OSDN Git Service

ツイート,DMの削除をTwitterApiクラスに移行
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Drawing;
37 using System.Globalization;
38 using System.IO;
39 using System.Linq;
40 using System.Media;
41 using System.Net;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Text;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
49 using OpenTween.Api;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.OpenTweenCustomControl;
53 using OpenTween.Thumbnail;
54
55 namespace OpenTween
56 {
57     public partial class TweenMain : OTBaseForm
58     {
59         //各種設定
60         private Size _mySize;           //画面サイズ
61         private Point _myLoc;           //画面位置
62         private int _mySpDis;           //区切り位置
63         private int _mySpDis2;          //発言欄区切り位置
64         private int _mySpDis3;          //プレビュー区切り位置
65         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
66         private bool _iconCol;          //1列表示の時true(48サイズのとき)
67
68         //雑多なフラグ類
69         private bool _initial;         //true:起動時処理中
70         private bool _initialLayout = true;
71         private bool _ignoreConfigSave;         //true:起動時処理中
72         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
73         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
74         private Point _tabMouseDownPoint;
75         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
76         private readonly object _syncObject = new object();    //ロック用
77
78         private const string detailHtmlFormatHeaderMono = 
79             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
80             + "<style type=\"text/css\"><!-- "
81             + "body, p, pre {margin: 0;} "
82             + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
83             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
84             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
85             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
86             + ".quote-tweet.reply {border-color: #f33;} "
87             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
88             + "--></style>"
89             + "</head><body><pre>";
90         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
91         private const string detailHtmlFormatHeaderColor = 
92             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
93             + "<style type=\"text/css\"><!-- "
94             + "body, p, pre {margin: 0;} "
95             + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
96             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
97             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
98             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
99             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
100             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
101             + "--></style>"
102             + "</head><body><p>";
103         private const string detailHtmlFormatFooterColor = "</p></body></html>";
104         private string detailHtmlFormatHeader;
105         private string detailHtmlFormatFooter;
106
107         private bool _myStatusError = false;
108         private bool _myStatusOnline = false;
109         private bool soundfileListup = false;
110         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
111
112         //設定ファイル関連
113         //private SettingToConfig _cfg; //旧
114         private SettingLocal _cfgLocal;
115         private SettingCommon _cfgCommon;
116
117         //twitter解析部
118         private Twitter tw = new Twitter();
119         private TwitterApi twitterApi = new TwitterApi();
120
121         //Growl呼び出し部
122         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123
124         //サブ画面インスタンス
125         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
126         private OpenURL UrlDialog = new OpenURL();
127         public AtIdSupplement AtIdSupl;     //@id補助
128         public AtIdSupplement HashSupl;    //Hashtag補助
129         public HashtagManage HashMgr;
130         private EventViewerDialog evtDialog;
131
132         //表示フォント、色、アイコン
133         private Font _fntUnread;            //未読用フォント
134         private Color _clUnread;            //未読用文字色
135         private Font _fntReaded;            //既読用フォント
136         private Color _clReaded;            //既読用文字色
137         private Color _clFav;               //Fav用文字色
138         private Color _clOWL;               //片思い用文字色
139         private Color _clRetweet;               //Retweet用文字色
140         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
141         private Font _fntDetail;            //発言詳細部用フォント
142         private Color _clDetail;              //発言詳細部用色
143         private Color _clDetailLink;          //発言詳細部用リンク文字色
144         private Color _clDetailBackcolor;     //発言詳細部用背景色
145         private Color _clSelf;              //自分の発言用背景色
146         private Color _clAtSelf;            //自分宛返信用背景色
147         private Color _clTarget;            //選択発言者の他の発言用背景色
148         private Color _clAtTarget;          //選択発言中の返信先用背景色
149         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
150         private Color _clAtTo;              //選択発言の唯一@先
151         private Color _clListBackcolor;       //リスト部通常発言背景色
152         private Color _clInputBackcolor;      //入力欄背景色
153         private Color _clInputFont;           //入力欄文字色
154         private Font _fntInputFont;           //入力欄フォント
155         private ImageCache IconCache;        //アイコン画像リスト
156         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
157         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
158         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
159         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
160         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
161         private Icon MainIcon;              //Main.ico           画面左上のアイコン
162         private Icon ReplyIcon;               //5g
163         private Icon ReplyIconBlink;          //6g
164
165         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
166
167         private PostClass _anchorPost;
168         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
169
170         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
171         private int _hisIdx;                  //発言履歴カレントインデックス
172
173         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
174         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175
176         //時速表示用
177         private List<DateTime> _postTimestamps = new List<DateTime>();
178         private List<DateTime> _favTimestamps = new List<DateTime>();
179         private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
180         private int _tlCount;
181
182         // 以下DrawItem関連
183         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
184         private SolidBrush _brsBackColorMine;
185         private SolidBrush _brsBackColorAt;
186         private SolidBrush _brsBackColorYou;
187         private SolidBrush _brsBackColorAtYou;
188         private SolidBrush _brsBackColorAtFromTarget;
189         private SolidBrush _brsBackColorAtTo;
190         private SolidBrush _brsBackColorNone;
191         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
192         private StringFormat sfTab = new StringFormat();
193
194         //////////////////////////////////////////////////////////////////////////////////////////////////////////
195         private TabInformations _statuses;
196
197         /// <summary>
198         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
199         /// </summary>
200         /// <remarks>
201         /// キャッシュクリアのために null が代入されることがあるため、
202         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
203         /// 一旦ローカル変数に代入してから参照すること。
204         /// </remarks>
205         private ListViewItemCache _listItemCache = null;
206
207         internal class ListViewItemCache
208         {
209             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
210             public ListView TargetList { get; set; }
211
212             /// <summary>キャッシュする範囲の開始インデックス</summary>
213             public int StartIndex { get; set; }
214
215             /// <summary>キャッシュする範囲の終了インデックス</summary>
216             public int EndIndex { get; set; }
217
218             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
219             public ListViewItem[] ListItem { get; set; }
220
221             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
222             public PostClass[] Post { get; set; }
223
224             /// <summary>キャッシュされたアイテムの件数</summary>
225             public int Count
226                 => this.EndIndex - this.StartIndex + 1;
227
228             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
229             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
230             public bool Contains(int index)
231                 => index >= this.StartIndex && index <= this.EndIndex;
232
233             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
234             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
235             public bool IsSupersetOf(int rangeStart, int rangeEnd)
236                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
237
238             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
239             /// <returns>取得に成功すれば true、それ以外は false</returns>
240             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
241             {
242                 if (this.Contains(index))
243                 {
244                     item = this.ListItem[index - this.StartIndex];
245                     post = this.Post[index - this.StartIndex];
246                     return true;
247                 }
248                 else
249                 {
250                     item = null;
251                     post = null;
252                     return false;
253                 }
254             }
255         }
256
257         private TabPage _curTab;
258         private int _curItemIndex;
259         private DetailsListView _curList;
260         private PostClass _curPost;
261         private bool _isColumnChanged = false;
262
263         private const int MAX_WORKER_THREADS = 20;
264         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
265         private CancellationTokenSource workerCts = new CancellationTokenSource();
266
267         private int UnreadCounter = -1;
268         private int UnreadAtCounter = -1;
269
270         private string[] ColumnOrgText = new string[9];
271         private string[] ColumnText = new string[9];
272
273         private bool _DoFavRetweetFlags = false;
274         private bool osResumed = false;
275
276         //////////////////////////////////////////////////////////////////////////////////////////////////////////
277         private string _postBrowserStatusText = "";
278
279         private bool _colorize = false;
280
281         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
282
283         private ImageListViewItem displayItem;
284
285         private string recommendedStatusFooter;
286
287         //URL短縮のUndo用
288         private struct urlUndo
289         {
290             public string Before;
291             public string After;
292         }
293
294         private List<urlUndo> urlUndoBuffer = null;
295
296         private struct ReplyChain
297         {
298             public long OriginalId;
299             public long InReplyToId;
300             public TabPage OriginalTab;
301
302             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
303             {
304                 this.OriginalId = originalId;
305                 this.InReplyToId = inReplyToId;
306                 this.OriginalTab = originalTab;
307             }
308         }
309
310         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
311         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
312
313         //検索処理タイプ
314         private enum SEARCHTYPE
315         {
316             DialogSearch,
317             NextSearch,
318             PrevSearch,
319         }
320
321         private class PostingStatus
322         {
323             public string status = "";
324             public long? inReplyToId = null;
325             public string inReplyToName = null;
326             public string imageService = "";      //画像投稿サービス名
327             public IMediaItem[] mediaItems = null;
328             public PostingStatus()
329             {
330             }
331             public PostingStatus(string status, long? replyToId, string replyToName)
332             {
333                 this.status = status;
334                 this.inReplyToId = replyToId;
335                 this.inReplyToName = replyToName;
336             }
337         }
338
339         private void TweenMain_Activated(object sender, EventArgs e)
340         {
341             //画面がアクティブになったら、発言欄の背景色戻す
342             if (StatusText.Focused)
343             {
344                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
345             }
346         }
347
348         private bool disposed = false;
349
350         /// <summary>
351         /// 使用中のリソースをすべてクリーンアップします。
352         /// </summary>
353         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
354         protected override void Dispose(bool disposing)
355         {
356             base.Dispose(disposing);
357
358             if (this.disposed)
359                 return;
360
361             if (disposing)
362             {
363                 this.components?.Dispose();
364
365                 //後始末
366                 SearchDialog.Dispose();
367                 UrlDialog.Dispose();
368                 NIconAt?.Dispose();
369                 NIconAtRed?.Dispose();
370                 NIconAtSmoke?.Dispose();
371                 foreach (var iconRefresh in this.NIconRefresh)
372                 {
373                     iconRefresh?.Dispose();
374                 }
375                 TabIcon?.Dispose();
376                 MainIcon?.Dispose();
377                 ReplyIcon?.Dispose();
378                 ReplyIconBlink?.Dispose();
379                 _listViewImageList.Dispose();
380                 _brsHighLight.Dispose();
381                 _brsBackColorMine?.Dispose();
382                 _brsBackColorAt?.Dispose();
383                 _brsBackColorYou?.Dispose();
384                 _brsBackColorAtYou?.Dispose();
385                 _brsBackColorAtFromTarget?.Dispose();
386                 _brsBackColorAtTo?.Dispose();
387                 _brsBackColorNone?.Dispose();
388                 _brsDeactiveSelection?.Dispose();
389                 //sf.Dispose();
390                 sfTab.Dispose();
391
392                 this.workerCts.Cancel();
393
394                 if (IconCache != null)
395                 {
396                     this.IconCache.CancelAsync();
397                     this.IconCache.Dispose();
398                 }
399
400                 this.thumbnailTokenSource?.Dispose();
401
402                 this.tw.Dispose();
403                 this.twitterApi.Dispose();
404                 this._hookGlobalHotkey.Dispose();
405             }
406
407             // 終了時にRemoveHandlerしておかないとメモリリークする
408             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
409             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
410
411             this.disposed = true;
412         }
413
414         private void LoadIcons()
415         {
416             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
417             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
418
419             // ウィンドウ左上のアイコン
420             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
421
422             // タブ見出し未読表示アイコン
423             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
424
425             // タスクトレイ: 通常時アイコン
426             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
427
428             // タスクトレイ: エラー時アイコン
429             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
430
431             // タスクトレイ: オフライン時アイコン
432             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
433
434             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
435             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
436             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
437
438             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
439             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
440             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
441             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
442             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
443
444             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
445
446             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
447             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
448             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
449             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
450             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
451
452             if (iconReply != null && iconReplyBlink != null)
453             {
454                 this.ReplyIcon = iconReply;
455                 this.ReplyIconBlink = iconReplyBlink;
456             }
457             else
458             {
459                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
460                 this.ReplyIconBlink = this.NIconAt;
461             }
462
463             if (iconRefresh1 == null)
464             {
465                 this.NIconRefresh = new[] {
466                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
467                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
468                 };
469             }
470             else if (iconRefresh2 == null)
471             {
472                 this.NIconRefresh = new[] { iconRefresh1 };
473             }
474             else if (iconRefresh3 == null)
475             {
476                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
477             }
478             else if (iconRefresh4 == null)
479             {
480                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
481             }
482             else // iconRefresh1 から iconRefresh4 まで全て揃っている
483             {
484                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
485             }
486         }
487
488         private Icon LoadIcon(string filePath)
489         {
490             if (!File.Exists(filePath))
491                 return null;
492
493             try
494             {
495                 return new Icon(filePath);
496             }
497             catch (Exception)
498             {
499                 return null;
500             }
501         }
502
503         private void InitColumns(ListView list, bool startup)
504         {
505             this.InitColumnText();
506
507             ColumnHeader[] columns = null;
508             try
509             {
510                 if (this._iconCol)
511                 {
512                     columns = new[]
513                     {
514                         new ColumnHeader(), // アイコン
515                         new ColumnHeader(), // 本文
516                     };
517
518                     columns[0].Text = this.ColumnText[0];
519                     columns[1].Text = this.ColumnText[2];
520
521                     if (startup)
522                     {
523                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
524
525                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
526                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
527                         columns[0].DisplayIndex = 0;
528                         columns[1].DisplayIndex = 1;
529                     }
530                     else
531                     {
532                         var idx = 0;
533                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
534                         {
535                             columns[idx].Width = curListColumn.Width;
536                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
537                             idx++;
538                         }
539                     }
540                 }
541                 else
542                 {
543                     columns = new[]
544                     {
545                         new ColumnHeader(), // アイコン
546                         new ColumnHeader(), // ニックネーム
547                         new ColumnHeader(), // 本文
548                         new ColumnHeader(), // 日付
549                         new ColumnHeader(), // ユーザID
550                         new ColumnHeader(), // 未読
551                         new ColumnHeader(), // マーク&プロテクト
552                         new ColumnHeader(), // ソース
553                     };
554
555                     foreach (var i in Enumerable.Range(0, columns.Length))
556                         columns[i].Text = this.ColumnText[i];
557
558                     if (startup)
559                     {
560                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
561
562                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
563                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
564                         columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
565                         columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
566                         columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
567                         columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
568                         columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
569                         columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
570
571                         var displayIndex = new[] {
572                             this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
573                             this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
574                             this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
575                             this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
576                         };
577
578                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
579                         {
580                             columns[i].DisplayIndex = displayIndex[i];
581                         }
582                     }
583                     else
584                     {
585                         var idx = 0;
586                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
587                         {
588                             columns[idx].Width = curListColumn.Width;
589                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
590                             idx++;
591                         }
592                     }
593                 }
594
595                 list.Columns.AddRange(columns);
596
597                 columns = null;
598             }
599             finally
600             {
601                 if (columns != null)
602                 {
603                     foreach (var column in columns)
604                         column?.Dispose();
605                 }
606             }
607         }
608
609         private void InitColumnText()
610         {
611             ColumnText[0] = "";
612             ColumnText[1] = Properties.Resources.AddNewTabText2;
613             ColumnText[2] = Properties.Resources.AddNewTabText3;
614             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
615             ColumnText[4] = Properties.Resources.AddNewTabText5;
616             ColumnText[5] = "";
617             ColumnText[6] = "";
618             ColumnText[7] = "Source";
619
620             ColumnOrgText[0] = "";
621             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
622             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
623             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
624             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
625             ColumnOrgText[5] = "";
626             ColumnOrgText[6] = "";
627             ColumnOrgText[7] = "Source";
628
629             int c = 0;
630             switch (_statuses.SortMode)
631             {
632                 case ComparerMode.Nickname:  //ニックネーム
633                     c = 1;
634                     break;
635                 case ComparerMode.Data:  //本文
636                     c = 2;
637                     break;
638                 case ComparerMode.Id:  //時刻=発言Id
639                     c = 3;
640                     break;
641                 case ComparerMode.Name:  //名前
642                     c = 4;
643                     break;
644                 case ComparerMode.Source:  //Source
645                     c = 7;
646                     break;
647             }
648
649             if (_iconCol)
650             {
651                 if (_statuses.SortOrder == SortOrder.Descending)
652                 {
653                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
654                     ColumnText[2] = ColumnOrgText[2] + "▾";
655                 }
656                 else
657                 {
658                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
659                     ColumnText[2] = ColumnOrgText[2] + "▴";
660                 }
661             }
662             else
663             {
664                 if (_statuses.SortOrder == SortOrder.Descending)
665                 {
666                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
667                     ColumnText[c] = ColumnOrgText[c] + "▾";
668                 }
669                 else
670                 {
671                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
672                     ColumnText[c] = ColumnOrgText[c] + "▴";
673                 }
674             }
675         }
676
677         private void InitializeTraceFrag()
678         {
679 #if DEBUG
680             TraceOutToolStripMenuItem.Checked = true;
681             MyCommon.TraceFlag = true;
682 #endif
683             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
684             {
685                 TraceOutToolStripMenuItem.Checked = true;
686                 MyCommon.TraceFlag = true;
687             }
688         }
689
690         private void TweenMain_Load(object sender, EventArgs e)
691         {
692             _ignoreConfigSave = true;
693             this.Visible = false;
694
695             if (MyApplication.StartupOptions.ContainsKey("d"))
696                 MyCommon.TraceFlag = true;
697
698             InitializeTraceFrag();
699
700             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
701
702             new InternetSecurityManager(PostBrowser);
703             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
704
705             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
706             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
707
708             Regex.CacheSize = 100;
709
710             //発言保持クラス
711             _statuses = TabInformations.GetInstance();
712
713             //アイコン設定
714             LoadIcons();
715             this.Icon = MainIcon;              //メインフォーム(TweenMain)
716             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
717             TabImage.Images.Add(TabIcon);    //タブ見出し
718
719             //<<<<<<<<<設定関連>>>>>>>>>
720             ////設定読み出し
721             LoadConfig();
722
723             // 現在の DPI と設定保存時の DPI との比を取得する
724             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
725
726             // UIフォント設定
727             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
728             if (fontUIGlobal != null)
729             {
730                 OTBaseForm.GlobalFont = fontUIGlobal;
731                 this.Font = fontUIGlobal;
732             }
733
734             //不正値チェック
735             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
736             {
737                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
738                     this._cfgCommon.TimelinePeriod = 15;
739
740                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
741                     this._cfgCommon.ReplyPeriod = 15;
742
743                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
744                     this._cfgCommon.DMPeriod = 15;
745
746                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
747                     this._cfgCommon.PubSearchPeriod = 30;
748
749                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
750                     this._cfgCommon.UserTimelinePeriod = 15;
751
752                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
753                     this._cfgCommon.ListsPeriod = 15;
754             }
755
756             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
757                 this._cfgCommon.CountApi = 60;
758             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
759                 this._cfgCommon.CountApiReply = 40;
760
761             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
762                 this._cfgCommon.MoreCountApi = 200;
763             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
764                 this._cfgCommon.FirstCountApi = 100;
765
766             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
767                 this._cfgCommon.FavoritesCountApi = 40;
768             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
769                 this._cfgCommon.ListCountApi = 100;
770             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
771                 this._cfgCommon.SearchCountApi = 100;
772             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
773                 this._cfgCommon.UserTimelineCountApi = 20;
774
775             //廃止サービスが選択されていた場合ux.nuへ読み替え
776             if (this._cfgCommon.AutoShortUrlFirst < 0)
777                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
778
779             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
780
781             //認証関連
782             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
783             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
784             this.twitterApi.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserId, this._cfgCommon.UserName);
785
786             _initial = true;
787
788             Networking.Initialize();
789
790             bool saveRequired = false;
791             bool firstRun = false;
792
793             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
794             if (string.IsNullOrEmpty(tw.Username))
795             {
796                 saveRequired = true;
797                 firstRun = true;
798
799                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
800                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
801                     string.IsNullOrEmpty(tw.Username))
802                 {
803                     Application.Exit();  //強制終了
804                     return;
805                 }
806             }
807
808             //Twitter用通信クラス初期化
809             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
810             Networking.SetWebProxy(this._cfgLocal.ProxyType,
811                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
812                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
813             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
814
815             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
816             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818             tw.TrackWord = this._cfgCommon.TrackWord;
819             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820             tw.AllAtReply = this._cfgCommon.AllAtReply;
821             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
825
826             // アクセストークンが有効であるか確認する
827             // ここが Twitter API への最初のアクセスになるようにすること
828             try
829             {
830                 this.tw.VerifyCredentials();
831             }
832             catch (WebApiException ex)
833             {
834                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
836             }
837
838             //サムネイル関連の初期化
839             //プロキシ設定等の通信まわりの初期化が済んでから処理する
840             ThumbnailGenerator.InitializeGenerator();
841
842             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
845
846             Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
847                 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
848                     this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
849
850             //画像投稿サービス
851             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
852
853             //ハッシュタグ/@id関連
854             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
855             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
856             HashMgr = new HashtagManage(HashSupl,
857                                     _cfgCommon.HashTags.ToArray(),
858                                     _cfgCommon.HashSelected,
859                                     _cfgCommon.HashIsPermanent,
860                                     _cfgCommon.HashIsHead,
861                                     _cfgCommon.HashIsNotAddToAtReply);
862             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
863
864             //アイコンリスト作成
865             this.IconCache = new ImageCache();
866
867             //フォント&文字色&背景色保持
868             _fntUnread = this._cfgLocal.FontUnread;
869             _clUnread = this._cfgLocal.ColorUnread;
870             _fntReaded = this._cfgLocal.FontRead;
871             _clReaded = this._cfgLocal.ColorRead;
872             _clFav = this._cfgLocal.ColorFav;
873             _clOWL = this._cfgLocal.ColorOWL;
874             _clRetweet = this._cfgLocal.ColorRetweet;
875             _fntDetail = this._cfgLocal.FontDetail;
876             _clDetail = this._cfgLocal.ColorDetail;
877             _clDetailLink = this._cfgLocal.ColorDetailLink;
878             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
879             _clSelf = this._cfgLocal.ColorSelf;
880             _clAtSelf = this._cfgLocal.ColorAtSelf;
881             _clTarget = this._cfgLocal.ColorTarget;
882             _clAtTarget = this._cfgLocal.ColorAtTarget;
883             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
884             _clAtTo = this._cfgLocal.ColorAtTo;
885             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
886             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
887             _clInputFont = this._cfgLocal.ColorInputFont;
888             _fntInputFont = this._cfgLocal.FontInputFont;
889
890             _brsBackColorMine = new SolidBrush(_clSelf);
891             _brsBackColorAt = new SolidBrush(_clAtSelf);
892             _brsBackColorYou = new SolidBrush(_clTarget);
893             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
894             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
895             _brsBackColorAtTo = new SolidBrush(_clAtTo);
896             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
897             _brsBackColorNone = new SolidBrush(_clListBackcolor);
898
899             // StringFormatオブジェクトへの事前設定
900             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
901             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
902             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
903             sfTab.Alignment = StringAlignment.Center;
904             sfTab.LineAlignment = StringAlignment.Center;
905
906             InitDetailHtmlFormat();
907
908             //Regex statregex = new Regex("^0*");
909             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
910
911             _history.Add(new PostingStatus());
912             _hisIdx = 0;
913             this.inReplyTo = null;
914
915             //各種ダイアログ設定
916             SearchDialog.Owner = this;
917             UrlDialog.Owner = this;
918
919             //新着バルーン通知のチェック状態設定
920             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
921             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
922
923             //新着取得時のリストスクロールをするか。trueならスクロールしない
924             ListLockMenuItem.Checked = _cfgCommon.ListLock;
925             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
926             //サウンド再生(タブ別設定より優先)
927             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
928             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
929
930             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
931             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
932
933             //ウィンドウ設定
934             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
935             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
936             _myLoc = _cfgLocal.FormLocation;
937             //タイトルバー領域
938             if (this.WindowState != FormWindowState.Minimized)
939             {
940                 this.DesktopLocation = _cfgLocal.FormLocation;
941                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
942                 bool outOfScreen = true;
943                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
944                 {
945                     foreach (Screen scr in Screen.AllScreens)
946                     {
947                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
948                         {
949                             outOfScreen = false;
950                             break;
951                         }
952                     }
953                     if (outOfScreen)
954                     {
955                         this.DesktopLocation = new Point(0, 0);
956                         _myLoc = this.DesktopLocation;
957                     }
958                 }
959             }
960             this.TopMost = this._cfgCommon.AlwaysTop;
961             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
962             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
963             if (_cfgLocal.PreviewDistance == -1)
964             {
965                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
966                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
967                 _cfgLocal.PreviewDistance = _mySpDis3;
968             }
969             else
970             {
971                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
972             }
973             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
974             //this.Tween_ClientSizeChanged(this, null);
975             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
976             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
977             //入力欄
978             StatusText.Font = _fntInputFont;
979             StatusText.ForeColor = _clInputFont;
980
981             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
982             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
983             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
984
985             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
986             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
987
988             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
989             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
990
991             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
992             if (this._cfgCommon.UnreadManage == false)
993             {
994                 ReadedStripMenuItem.Enabled = false;
995                 UnreadStripMenuItem.Enabled = false;
996             }
997
998             //発言詳細部の初期化
999             NameLabel.Text = "";
1000             DateTimeLabel.Text = "";
1001             SourceLinkLabel.Text = "";
1002
1003             //リンク先URL表示部の初期化(画面左下)
1004             StatusLabelUrl.Text = "";
1005             //状態表示部の初期化(画面右下)
1006             StatusLabel.Text = "";
1007             StatusLabel.AutoToolTip = false;
1008             StatusLabel.ToolTipText = "";
1009             //文字カウンタ初期化
1010             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1011
1012             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1013             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1014             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1015             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1016
1017             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1018             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1019             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1020             this.SplitContainer2.Panel2.AccessibleName = "";
1021
1022             ////////////////////////////////////////////////////////////////////////////////
1023             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1024             var mode = ComparerMode.Id;
1025             switch (_cfgCommon.SortColumn)
1026             {
1027                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1028                 case 5:
1029                 case 6:
1030                     //ソートしない
1031                     mode = ComparerMode.Id;  //Idソートに読み替え
1032                     break;
1033                 case 1:  //ニックネーム
1034                     mode = ComparerMode.Nickname;
1035                     break;
1036                 case 2:  //本文
1037                     mode = ComparerMode.Data;
1038                     break;
1039                 case 3:  //時刻=発言Id
1040                     mode = ComparerMode.Id;
1041                     break;
1042                 case 4:  //名前
1043                     mode = ComparerMode.Name;
1044                     break;
1045                 case 7:  //Source
1046                     mode = ComparerMode.Source;
1047                     break;
1048             }
1049             _statuses.SetSortMode(mode, sortOrder);
1050             ////////////////////////////////////////////////////////////////////////////////
1051
1052             ApplyListViewIconSize(this._cfgCommon.IconSize);
1053
1054             //<<<<<<<<タブ関連>>>>>>>
1055             // タブの位置を調整する
1056             SetTabAlignment();
1057
1058             //デフォルトタブの存在チェック、ない場合には追加
1059             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1060             {
1061                 TabClass tab;
1062                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1063                 {
1064                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1065                 }
1066                 else
1067                 {
1068                     tab.TabType = MyCommon.TabUsageType.Home;
1069                 }
1070             }
1071             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1072             {
1073                 TabClass tab;
1074                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1075                 {
1076                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1077                 }
1078                 else
1079                 {
1080                     tab.TabType = MyCommon.TabUsageType.Mentions;
1081                 }
1082             }
1083             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1084             {
1085                 TabClass tab;
1086                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1087                 {
1088                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1089                 }
1090                 else
1091                 {
1092                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1093                 }
1094             }
1095             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1096             {
1097                 TabClass tab;
1098                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1099                 {
1100                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1101                 }
1102                 else
1103                 {
1104                     tab.TabType = MyCommon.TabUsageType.Favorites;
1105                 }
1106             }
1107             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1108             {
1109                 TabClass tab;
1110                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1111                 {
1112                     _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1113                 }
1114                 else
1115                 {
1116                     tab.TabType = MyCommon.TabUsageType.Mute;
1117                 }
1118             }
1119
1120             foreach (var tab in _statuses.Tabs.Values)
1121             {
1122                 // ミュートタブは表示しない
1123                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1124                     continue;
1125
1126                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1127                 {
1128                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1129                 }
1130                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1131                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1132             }
1133
1134             _curTab = ListTab.SelectedTab;
1135             _curItemIndex = -1;
1136             _curList = (DetailsListView)_curTab.Tag;
1137
1138             if (this._cfgCommon.TabIconDisp)
1139             {
1140                 ListTab.DrawMode = TabDrawMode.Normal;
1141             }
1142             else
1143             {
1144                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1145                 ListTab.DrawItem += ListTab_DrawItem;
1146                 ListTab.ImageList = null;
1147             }
1148
1149             if (this._cfgCommon.HotkeyEnabled)
1150             {
1151                 //////グローバルホットキーの登録
1152                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1153                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1154                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1155                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1156                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1157                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1158                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1159                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1160                     modKey |= HookGlobalHotkey.ModKeys.Win;
1161
1162                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1163             }
1164
1165             if (this._cfgCommon.IsUseNotifyGrowl)
1166                 gh.RegisterGrowl();
1167
1168             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1169
1170             SetMainWindowTitle();
1171             SetNotifyIconText();
1172
1173             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1174             {
1175                 this.Visible = true;
1176             }
1177
1178             //タイマー設定
1179             TimerTimeline.AutoReset = true;
1180             TimerTimeline.SynchronizingObject = this;
1181             //Recent取得間隔
1182             TimerTimeline.Interval = 1000;
1183             TimerTimeline.Enabled = true;
1184             //更新中アイコンアニメーション間隔
1185             TimerRefreshIcon.Interval = 200;
1186             TimerRefreshIcon.Enabled = true;
1187
1188             _ignoreConfigSave = false;
1189             this.TweenMain_Resize(null, null);
1190             if (saveRequired) SaveConfigsAll(false);
1191
1192             foreach (var ua in this._cfgCommon.UserAccounts)
1193             {
1194                 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1195                 {
1196                     ua.UserId = tw.UserId;
1197                     break;
1198                 }
1199             }
1200
1201             if (firstRun)
1202             {
1203                 // 初回起動時だけ右下のメニューを目立たせる
1204                 HashStripSplitButton.ShowDropDown();
1205             }
1206         }
1207
1208         private void InitDetailHtmlFormat()
1209         {
1210             if (this._cfgCommon.IsMonospace)
1211             {
1212                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1213                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1214             }
1215             else
1216             {
1217                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1218                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1219             }
1220
1221             detailHtmlFormatHeader = detailHtmlFormatHeader
1222                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1223                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1224                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1225                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1226                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1227                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1228         }
1229
1230         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1231         {
1232             string txt;
1233             try
1234             {
1235                 txt = ListTab.TabPages[e.Index].Text;
1236             }
1237             catch (Exception)
1238             {
1239                 return;
1240             }
1241
1242             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1243             if (e.State == DrawItemState.Selected)
1244             {
1245                 e.DrawFocusRectangle();
1246             }
1247             Brush fore;
1248             try
1249             {
1250                 if (_statuses.Tabs[txt].UnreadCount > 0)
1251                     fore = Brushes.Red;
1252                 else
1253                     fore = System.Drawing.SystemBrushes.ControlText;
1254             }
1255             catch (Exception)
1256             {
1257                 fore = System.Drawing.SystemBrushes.ControlText;
1258             }
1259             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1260         }
1261
1262         private void LoadConfig()
1263         {
1264             _cfgCommon = SettingCommon.Load();
1265             SettingCommon.Instance = this._cfgCommon;
1266             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1267             {
1268                 _cfgCommon.UserAccounts = new List<UserAccount>();
1269                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1270                 {
1271                     UserAccount account = new UserAccount();
1272                     account.Username = _cfgCommon.UserName;
1273                     account.UserId = _cfgCommon.UserId;
1274                     account.Token = _cfgCommon.Token;
1275                     account.TokenSecret = _cfgCommon.TokenSecret;
1276
1277                     _cfgCommon.UserAccounts.Add(account);
1278                 }
1279             }
1280
1281             _cfgLocal = SettingLocal.Load();
1282
1283             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1284             if (_cfgLocal.ScaleDimension.IsEmpty)
1285                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1286
1287             List<TabClass> tabs = SettingTabs.Load().Tabs;
1288             foreach (TabClass tb in tabs)
1289             {
1290                 try
1291                 {
1292                     tb.FilterModified = false;
1293                     _statuses.Tabs.Add(tb.TabName, tb);
1294                 }
1295                 catch (Exception)
1296                 {
1297                     tb.TabName = _statuses.MakeTabName("MyTab");
1298                     _statuses.Tabs.Add(tb.TabName, tb);
1299                 }
1300             }
1301             if (_statuses.Tabs.Count == 0)
1302             {
1303                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1304                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1305                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1306                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1307             }
1308         }
1309
1310         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1311         {
1312             if (!TimerTimeline.Enabled) return;
1313             ResetTimers = e;
1314         }
1315
1316         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1317
1318         private static int homeCounter = 0;
1319         private static int mentionCounter = 0;
1320         private static int dmCounter = 0;
1321         private static int pubSearchCounter = 0;
1322         private static int userTimelineCounter = 0;
1323         private static int listsCounter = 0;
1324         private static int usCounter = 0;
1325         private static int ResumeWait = 0;
1326         private static int refreshFollowers = 0;
1327
1328         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1329         {
1330             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1331             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1332             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1333             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1334             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1335             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1336             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1337             Interlocked.Increment(ref refreshFollowers);
1338
1339             var refreshTasks = new List<Task>();
1340
1341             ////タイマー初期化
1342             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1343             {
1344                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1345                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1346                     refreshTasks.Add(this.GetHomeTimelineAsync());
1347                 ResetTimers.Timeline = false;
1348             }
1349             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1350             {
1351                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1352                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1353                     refreshTasks.Add(this.GetReplyAsync());
1354                 ResetTimers.Reply = false;
1355             }
1356             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1357             {
1358                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1359                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1360                     refreshTasks.Add(this.GetDirectMessagesAsync());
1361                 ResetTimers.DirectMessage = false;
1362             }
1363             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1364             {
1365                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1366                 if (!ResetTimers.PublicSearch)
1367                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1368                 ResetTimers.PublicSearch = false;
1369             }
1370             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1371             {
1372                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1373                 if (!ResetTimers.UserTimeline)
1374                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1375                 ResetTimers.UserTimeline = false;
1376             }
1377             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1378             {
1379                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1380                 if (!ResetTimers.Lists)
1381                     refreshTasks.Add(this.GetListTimelineAllAsync());
1382                 ResetTimers.Lists = false;
1383             }
1384             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1385             {
1386                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1387                 if (this._isActiveUserstream)
1388                     this.RefreshTimeline();
1389                 ResetTimers.UserStream = false;
1390             }
1391             if (refreshFollowers > 6 * 3600)
1392             {
1393                 Interlocked.Exchange(ref refreshFollowers, 0);
1394                 refreshTasks.AddRange(new[]
1395                 {
1396                     this.doGetFollowersMenu(),
1397                     this.RefreshNoRetweetIdsAsync(),
1398                     this.RefreshTwitterConfigurationAsync(),
1399                 });
1400             }
1401             if (osResumed)
1402             {
1403                 Interlocked.Increment(ref ResumeWait);
1404                 if (ResumeWait > 30)
1405                 {
1406                     osResumed = false;
1407                     Interlocked.Exchange(ref ResumeWait, 0);
1408                     refreshTasks.AddRange(new[]
1409                     {
1410                         this.GetHomeTimelineAsync(),
1411                         this.GetReplyAsync(),
1412                         this.GetDirectMessagesAsync(),
1413                         this.GetPublicSearchAllAsync(),
1414                         this.GetUserTimelineAllAsync(),
1415                         this.GetListTimelineAllAsync(),
1416                         this.doGetFollowersMenu(),
1417                         this.RefreshTwitterConfigurationAsync(),
1418                     });
1419                 }
1420             }
1421
1422             await Task.WhenAll(refreshTasks);
1423         }
1424
1425         private void RefreshTimeline()
1426         {
1427             // 現在表示中のタブのスクロール位置を退避
1428             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1429
1430             // 各タブのリスト上の選択位置などを退避
1431             var listSelections = this.SaveListViewSelection();
1432
1433             //更新確定
1434             PostClass[] notifyPosts;
1435             string soundFile;
1436             int addCount;
1437             bool newMentionOrDm;
1438             bool isDelete;
1439             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1440
1441             if (MyCommon._endingFlag) return;
1442
1443             //リストに反映&選択状態復元
1444             try
1445             {
1446                 foreach (TabPage tab in ListTab.TabPages)
1447                 {
1448                     DetailsListView lst = (DetailsListView)tab.Tag;
1449                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1450                     if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1451                     {
1452                         using (ControlTransaction.Update(lst))
1453                         {
1454                             if (lst.Equals(_curList))
1455                             {
1456                                 this.PurgeListViewItemCache();
1457                             }
1458                             try
1459                             {
1460                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1461                             }
1462                             catch (Exception)
1463                             {
1464                                 //アイコン描画不具合あり?
1465                             }
1466
1467                             // 選択位置などを復元
1468                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1469                         }
1470                     }
1471                     if (tabInfo.UnreadCount > 0)
1472                         if (this._cfgCommon.TabIconDisp)
1473                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1474                 }
1475                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1476             }
1477             catch (Exception)
1478             {
1479                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1480                 //throw;
1481             }
1482
1483             // スクロール位置を復元
1484             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1485
1486             //新着通知
1487             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1488
1489             SetMainWindowTitle();
1490             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1491
1492             HashSupl.AddRangeItem(tw.GetHashList());
1493
1494         }
1495
1496         internal struct ListViewScroll
1497         {
1498             public ScrollLockMode ScrollLockMode { get; set; }
1499             public long? TopItemStatusId { get; set; }
1500         }
1501
1502         internal enum ScrollLockMode
1503         {
1504             /// <summary>固定しない</summary>
1505             None,
1506
1507             /// <summary>最上部に固定する</summary>
1508             FixedToTop,
1509
1510             /// <summary>最下部に固定する</summary>
1511             FixedToBottom,
1512
1513             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1514             FixedToItem,
1515         }
1516
1517         /// <summary>
1518         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1519         /// </summary>
1520         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1521         {
1522             var listScroll = new ListViewScroll
1523             {
1524                 ScrollLockMode = this.GetScrollLockMode(listView),
1525             };
1526
1527             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1528             {
1529                 var topItem = listView.TopItem;
1530                 if (topItem != null)
1531                     listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1532             }
1533
1534             return listScroll;
1535         }
1536
1537         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1538         {
1539             if (this._statuses.SortMode == ComparerMode.Id)
1540             {
1541                 if (this._statuses.SortOrder == SortOrder.Ascending)
1542                 {
1543                     // Id昇順
1544                     if (this.ListLockMenuItem.Checked)
1545                         return ScrollLockMode.None;
1546
1547                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1548
1549                     // 一番下に表示されているアイテム
1550                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1551                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1552                         return ScrollLockMode.FixedToBottom;
1553                     else
1554                         return ScrollLockMode.None;
1555                 }
1556                 else
1557                 {
1558                     // Id降順
1559                     if (this.ListLockMenuItem.Checked)
1560                         return ScrollLockMode.FixedToItem;
1561
1562                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1563                     var topItem = listView.TopItem;
1564                     if (topItem == null || topItem.Index == 0)
1565                         return ScrollLockMode.FixedToTop;
1566                     else
1567                         return ScrollLockMode.FixedToItem;
1568                 }
1569             }
1570             else
1571             {
1572                 return ScrollLockMode.FixedToItem;
1573             }
1574         }
1575
1576         internal struct ListViewSelection
1577         {
1578             public long[] SelectedStatusIds { get; set; }
1579             public long? SelectionMarkStatusId { get; set; }
1580             public long? FocusedStatusId { get; set; }
1581         }
1582
1583         /// <summary>
1584         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1585         /// </summary>
1586         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1587         {
1588             var listsDict = new Dictionary<string, ListViewSelection>();
1589
1590             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1591             {
1592                 var listView = (DetailsListView)tabPage.Tag;
1593                 var tab = _statuses.Tabs[tabPage.Text];
1594
1595                 ListViewSelection listStatus;
1596                 if (listView.VirtualListSize != 0)
1597                 {
1598                     listStatus = new ListViewSelection
1599                     {
1600                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1601                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1602                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1603                     };
1604                 }
1605                 else
1606                 {
1607                     listStatus = new ListViewSelection
1608                     {
1609                         SelectedStatusIds = new long[0],
1610                         SelectionMarkStatusId = null,
1611                         FocusedStatusId = null,
1612                     };
1613                 }
1614
1615                 listsDict[tab.TabName] = listStatus;
1616             }
1617
1618             return listsDict;
1619         }
1620
1621         private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1622         {
1623             var selectedIndices = listView.SelectedIndices;
1624             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1625                 return tab.GetId(selectedIndices);
1626             else
1627                 return null;
1628         }
1629
1630         private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1631         {
1632             var focusedItem = listView.FocusedItem;
1633
1634             return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1635         }
1636
1637         private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1638         {
1639             var selectionMarkIndex = listView.SelectionMark;
1640
1641             return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1642         }
1643
1644         /// <summary>
1645         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1646         /// </summary>
1647         private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1648         {
1649             if (listView.VirtualListSize == 0)
1650                 return;
1651
1652             switch (listScroll.ScrollLockMode)
1653             {
1654                 case ScrollLockMode.FixedToTop:
1655                     listView.EnsureVisible(0);
1656                     break;
1657                 case ScrollLockMode.FixedToBottom:
1658                     listView.EnsureVisible(listView.VirtualListSize - 1);
1659                     break;
1660                 case ScrollLockMode.FixedToItem:
1661                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1662                     if (topIndex != -1)
1663                         listView.TopItem = listView.Items[topIndex];
1664                     break;
1665                 case ScrollLockMode.None:
1666                 default:
1667                     break;
1668             }
1669         }
1670
1671         /// <summary>
1672         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1673         /// </summary>
1674         private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1675         {
1676             // status_id から ListView 上のインデックスに変換
1677             int[] selectedIndices = null;
1678             if (listSelection.SelectedStatusIds != null)
1679                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1680
1681             var focusedIndex = -1;
1682             if (listSelection.FocusedStatusId != null)
1683                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1684
1685             var selectionMarkIndex = -1;
1686             if (listSelection.SelectionMarkStatusId != null)
1687                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1688
1689             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1690         }
1691
1692         private bool BalloonRequired()
1693         {
1694             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1695             ev.Eventtype = MyCommon.EVENTTYPE.None;
1696
1697             return BalloonRequired(ev);
1698         }
1699
1700         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1701         {
1702             if (type == MyCommon.EVENTTYPE.None)
1703                 return true;
1704
1705             if (!this._cfgCommon.EventNotifyEnabled)
1706                 return false;
1707
1708             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1709         }
1710
1711         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1712         {
1713             if (!ev.IsMe)
1714                 return true;
1715
1716             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1717         }
1718
1719         private bool BalloonRequired(Twitter.FormattedEvent ev)
1720         {
1721             if (this._initial)
1722                 return false;
1723
1724             if (NativeMethods.IsScreenSaverRunning())
1725                 return false;
1726
1727             // 「新着通知」が無効
1728             if (!this.NewPostPopMenuItem.Checked)
1729             {
1730                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1731                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1732                     return false;
1733             }
1734
1735             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1736             if (this._cfgCommon.LimitBalloon)
1737             {
1738                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1739                     return false;
1740             }
1741
1742             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1743         }
1744
1745         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1746         {
1747             if (this._cfgCommon.ReadOwnPost)
1748             {
1749                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1750                     return;
1751             }
1752
1753             //新着通知
1754             if (BalloonRequired())
1755             {
1756                 if (notifyPosts != null && notifyPosts.Length > 0)
1757                 {
1758                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1759                     if (this._cfgCommon.IsUseNotifyGrowl)
1760                     {
1761                         StringBuilder sb = new StringBuilder();
1762                         bool reply = false;
1763                         bool dm = false;
1764
1765                         foreach (PostClass post in notifyPosts)
1766                         {
1767                             if (!(notifyPosts.Length > 3))
1768                             {
1769                                 sb.Clear();
1770                                 reply = false;
1771                                 dm = false;
1772                             }
1773                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1774                             if (post.IsDm) dm = true;
1775                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1776                             switch (this._cfgCommon.NameBalloon)
1777                             {
1778                                 case MyCommon.NameBalloonEnum.UserID:
1779                                     sb.Append(post.ScreenName).Append(" : ");
1780                                     break;
1781                                 case MyCommon.NameBalloonEnum.NickName:
1782                                     sb.Append(post.Nickname).Append(" : ");
1783                                     break;
1784                             }
1785                             sb.Append(post.TextFromApi);
1786                             if (notifyPosts.Length > 3)
1787                             {
1788                                 if (notifyPosts.Last() != post) continue;
1789                             }
1790
1791                             StringBuilder title = new StringBuilder();
1792                             GrowlHelper.NotifyType nt;
1793                             if (this._cfgCommon.DispUsername)
1794                             {
1795                                 title.Append(tw.Username);
1796                                 title.Append(" - ");
1797                             }
1798                             else
1799                             {
1800                                 //title.Clear();
1801                             }
1802                             if (dm)
1803                             {
1804                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1805                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1806                                 title.Append(Application.ProductName);
1807                                 title.Append(" [DM] ");
1808                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1809                                 nt = GrowlHelper.NotifyType.DirectMessage;
1810                             }
1811                             else if (reply)
1812                             {
1813                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1814                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1815                                 title.Append(Application.ProductName);
1816                                 title.Append(" [Reply!] ");
1817                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1818                                 nt = GrowlHelper.NotifyType.Reply;
1819                             }
1820                             else
1821                             {
1822                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1823                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1824                                 title.Append(Application.ProductName);
1825                                 title.Append(" ");
1826                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1827                                 nt = GrowlHelper.NotifyType.Notify;
1828                             }
1829                             string bText = sb.ToString();
1830                             if (string.IsNullOrEmpty(bText)) return;
1831
1832                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1833                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1834                         }
1835                     }
1836                     else
1837                     {
1838                         StringBuilder sb = new StringBuilder();
1839                         bool reply = false;
1840                         bool dm = false;
1841                         foreach (PostClass post in notifyPosts)
1842                         {
1843                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1844                             if (post.IsDm) dm = true;
1845                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1846                             switch (this._cfgCommon.NameBalloon)
1847                             {
1848                                 case MyCommon.NameBalloonEnum.UserID:
1849                                     sb.Append(post.ScreenName).Append(" : ");
1850                                     break;
1851                                 case MyCommon.NameBalloonEnum.NickName:
1852                                     sb.Append(post.Nickname).Append(" : ");
1853                                     break;
1854                             }
1855                             sb.Append(post.TextFromApi);
1856
1857                         }
1858                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1859                         StringBuilder title = new StringBuilder();
1860                         ToolTipIcon ntIcon;
1861                         if (this._cfgCommon.DispUsername)
1862                         {
1863                             title.Append(tw.Username);
1864                             title.Append(" - ");
1865                         }
1866                         else
1867                         {
1868                             //title.Clear();
1869                         }
1870                         if (dm)
1871                         {
1872                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1873                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1874                             ntIcon = ToolTipIcon.Warning;
1875                             title.Append(Application.ProductName);
1876                             title.Append(" [DM] ");
1877                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1878                         }
1879                         else if (reply)
1880                         {
1881                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1882                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1883                             ntIcon = ToolTipIcon.Warning;
1884                             title.Append(Application.ProductName);
1885                             title.Append(" [Reply!] ");
1886                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1887                         }
1888                         else
1889                         {
1890                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1891                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1892                             ntIcon = ToolTipIcon.Info;
1893                             title.Append(Application.ProductName);
1894                             title.Append(" ");
1895                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1896                         }
1897                         string bText = sb.ToString();
1898                         if (string.IsNullOrEmpty(bText)) return;
1899                         //NotifyIcon1.BalloonTipText = sb.ToString();
1900                         //NotifyIcon1.ShowBalloonTip(500);
1901                         NotifyIcon1.BalloonTipTitle = title.ToString();
1902                         NotifyIcon1.BalloonTipText = bText;
1903                         NotifyIcon1.BalloonTipIcon = ntIcon;
1904                         NotifyIcon1.ShowBalloonTip(500);
1905                     }
1906                 }
1907             }
1908
1909             //サウンド再生
1910             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1911             {
1912                 try
1913                 {
1914                     string dir = Application.StartupPath;
1915                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1916                     {
1917                         dir = Path.Combine(dir, "Sounds");
1918                     }
1919                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1920                     {
1921                         player.Play();
1922                     }
1923                 }
1924                 catch (Exception)
1925                 {
1926                 }
1927             }
1928
1929             //mentions新着時に画面ブリンク
1930             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1931             {
1932                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1933             }
1934         }
1935
1936         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1937         {
1938             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1939
1940             _curItemIndex = _curList.SelectedIndices[0];
1941             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1942
1943             try
1944             {
1945                 this._curPost = GetCurTabPost(_curItemIndex);
1946             }
1947             catch (ArgumentException)
1948             {
1949                 return;
1950             }
1951
1952             this.PushSelectPostChain();
1953
1954             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1955             //キャッシュの書き換え
1956             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1957
1958             ColorizeList();
1959             _colorize = true;
1960         }
1961
1962         private void ChangeCacheStyleRead(bool Read, int Index)
1963         {
1964             var tabInfo = _statuses.Tabs[_curTab.Text];
1965             //Read:true=既読 false=未読
1966             //未読管理していなかったら既読として扱う
1967             if (!tabInfo.UnreadManage ||
1968                !this._cfgCommon.UnreadManage) Read = true;
1969
1970             var listCache = this._listItemCache;
1971             if (listCache == null)
1972                 return;
1973
1974             // キャッシュに含まれていないアイテムは対象外
1975             ListViewItem itm;
1976             PostClass post;
1977             if (!listCache.TryGetValue(Index, out itm, out post))
1978                 return;
1979
1980             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1981         }
1982
1983         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1984         {
1985             Font fnt;
1986             //フォント
1987             if (Read)
1988             {
1989                 fnt = _fntReaded;
1990                 Item.SubItems[5].Text = "";
1991             }
1992             else
1993             {
1994                 fnt = _fntUnread;
1995                 Item.SubItems[5].Text = "★";
1996             }
1997             //文字色
1998             Color cl;
1999             if (Post.IsFav)
2000                 cl = _clFav;
2001             else if (Post.RetweetedId != null)
2002                 cl = _clRetweet;
2003             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2004                 cl = _clOWL;
2005             else if (Read || !this._cfgCommon.UseUnreadStyle)
2006                 cl = _clReaded;
2007             else
2008                 cl = _clUnread;
2009
2010             if (DList == null || Item.Index == -1)
2011             {
2012                 Item.ForeColor = cl;
2013                 if (this._cfgCommon.UseUnreadStyle)
2014                     Item.Font = fnt;
2015             }
2016             else
2017             {
2018                 DList.Update();
2019                 if (this._cfgCommon.UseUnreadStyle)
2020                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2021                 else
2022                     DList.ChangeItemForeColor(Item.Index, cl);
2023                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2024             }
2025         }
2026
2027         private void ColorizeList()
2028         {
2029             //Index:更新対象のListviewItem.Index。Colorを返す。
2030             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2031             PostClass _post;
2032             if (_anchorFlag)
2033                 _post = _anchorPost;
2034             else
2035                 _post = _curPost;
2036
2037             if (_post == null) return;
2038
2039             var listCache = this._listItemCache;
2040             if (listCache == null)
2041                 return;
2042
2043             var index = listCache.StartIndex;
2044             foreach (var cachedPost in listCache.Post)
2045             {
2046                 var backColor = this.JudgeColor(_post, cachedPost);
2047                 this._curList.ChangeItemBackColor(index++, backColor);
2048             }
2049         }
2050
2051         private void ColorizeList(ListViewItem Item, int Index)
2052         {
2053             //Index:更新対象のListviewItem.Index。Colorを返す。
2054             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2055             PostClass _post;
2056             if (_anchorFlag)
2057                 _post = _anchorPost;
2058             else
2059                 _post = _curPost;
2060
2061             PostClass tPost = GetCurTabPost(Index);
2062
2063             if (_post == null) return;
2064
2065             if (Item.Index == -1)
2066                 Item.BackColor = JudgeColor(_post, tPost);
2067             else
2068                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2069         }
2070
2071         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2072         {
2073             Color cl;
2074             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2075                 //@先
2076                 cl = _clAtTo;
2077             else if (TargetPost.IsMe)
2078                 //自分=発言者
2079                 cl = _clSelf;
2080             else if (TargetPost.IsReply)
2081                 //自分宛返信
2082                 cl = _clAtSelf;
2083             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2084                 //返信先
2085                 cl = _clAtFromTarget;
2086             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2087                 //その人への返信
2088                 cl = _clAtTarget;
2089             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2090                 //発言者
2091                 cl = _clTarget;
2092             else
2093                 //その他
2094                 cl = _clListBackcolor;
2095
2096             return cl;
2097         }
2098
2099         private async void PostButton_Click(object sender, EventArgs e)
2100         {
2101             if (StatusText.Text.Trim().Length == 0)
2102             {
2103                 if (!ImageSelector.Enabled)
2104                 {
2105                     await this.DoRefresh();
2106                     return;
2107                 }
2108             }
2109
2110             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2111             {
2112                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2113                                                                "Retweet",
2114                                                                MessageBoxButtons.YesNoCancel,
2115                                                                MessageBoxIcon.Question);
2116                 switch (rtResult)
2117                 {
2118                     case DialogResult.Yes:
2119                         StatusText.Text = "";
2120                         await this.doReTweetOfficial(false);
2121                         return;
2122                     case DialogResult.Cancel:
2123                         return;
2124                 }
2125             }
2126
2127             var inReplyToStatusId = this.inReplyTo?.Item1;
2128             var inReplyToScreenName = this.inReplyTo?.Item2;
2129             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2130
2131             if (this._cfgCommon.Nicoms)
2132             {
2133                 StatusText.SelectionStart = StatusText.Text.Length;
2134                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2135             }
2136             //if (SettingDialog.UrlConvertAuto)
2137             //{
2138             //    StatusText.SelectionStart = StatusText.Text.Length;
2139             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2140             //}
2141             //else if (SettingDialog.Nicoms)
2142             //{
2143             //    StatusText.SelectionStart = StatusText.Text.Length;
2144             //    UrlConvert(UrlConverter.Nicoms);
2145             //}
2146             StatusText.SelectionStart = StatusText.Text.Length;
2147             CheckReplyTo(StatusText.Text);
2148
2149             var statusText = this.FormatStatusText(this.StatusText.Text);
2150
2151             if (this.GetRestStatusCount(statusText) < 0)
2152             {
2153                 // 文字数制限を超えているが強制的に投稿するか
2154                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2155                 if (ret != DialogResult.OK)
2156                     return;
2157             }
2158
2159             var status = new PostingStatus();
2160             status.status = statusText;
2161
2162             status.inReplyToId = this.inReplyTo?.Item1;
2163             status.inReplyToName = this.inReplyTo?.Item2;
2164             if (ImageSelector.Visible)
2165             {
2166                 //画像投稿
2167                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2168                     return;
2169             }
2170
2171             this.inReplyTo = null;
2172             StatusText.Text = "";
2173             _history.Add(new PostingStatus());
2174             _hisIdx = _history.Count - 1;
2175             if (!ToolStripFocusLockMenuItem.Checked)
2176                 ((Control)ListTab.SelectedTab.Tag).Focus();
2177             urlUndoBuffer = null;
2178             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2179
2180             //Google検索(試験実装)
2181             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2182             {
2183                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2184                 await this.OpenUriInBrowserAsync(tmp);
2185             }
2186
2187             await this.PostMessageAsync(status);
2188         }
2189
2190         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2191         {
2192             MyCommon._endingFlag = true;
2193             this.Close();
2194         }
2195
2196         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2197         {
2198             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2199             {
2200                 //_endingFlag=false:フォームの×ボタン
2201                 e.Cancel = true;
2202                 this.Visible = false;
2203             }
2204             else
2205             {
2206                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2207                 _ignoreConfigSave = true;
2208                 MyCommon._endingFlag = true;
2209                 TimerTimeline.Enabled = false;
2210                 TimerRefreshIcon.Enabled = false;
2211             }
2212         }
2213
2214         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2215         {
2216             this.Visible = true;
2217             if (this.WindowState == FormWindowState.Minimized)
2218             {
2219                 this.WindowState = FormWindowState.Normal;
2220             }
2221             this.Activate();
2222             this.BringToFront();
2223         }
2224
2225         private static int errorCount = 0;
2226
2227         private static bool CheckAccountValid()
2228         {
2229             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2230             {
2231                 errorCount += 1;
2232                 if (errorCount > 5)
2233                 {
2234                     errorCount = 0;
2235                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2236                     return true;
2237                 }
2238                 return false;
2239             }
2240             errorCount = 0;
2241             return true;
2242         }
2243
2244         private Task GetHomeTimelineAsync()
2245         {
2246             return this.GetHomeTimelineAsync(loadMore: false);
2247         }
2248
2249         private async Task GetHomeTimelineAsync(bool loadMore)
2250         {
2251             await this.workerSemaphore.WaitAsync();
2252
2253             try
2254             {
2255                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2256
2257                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2258             }
2259             catch (WebApiException ex)
2260             {
2261                 this._myStatusError = true;
2262                 this.StatusLabel.Text = ex.Message;
2263             }
2264             finally
2265             {
2266                 this.workerSemaphore.Release();
2267             }
2268         }
2269
2270         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2271         {
2272             if (ct.IsCancellationRequested)
2273                 return;
2274
2275             if (!CheckAccountValid())
2276                 throw new WebApiException("Auth error. Check your account");
2277
2278             bool read;
2279             if (!this._cfgCommon.UnreadManage)
2280                 read = true;
2281             else
2282                 read = this._initial && this._cfgCommon.Read;
2283
2284             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2285
2286             await Task.Run(() =>
2287             {
2288                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2289
2290                 // 新着時未読クリア
2291                 if (this._cfgCommon.ReadOldPosts)
2292                     this._statuses.SetReadHomeTab();
2293
2294                 var addCount = this._statuses.DistributePosts();
2295
2296                 if (!this._initial)
2297                     this.UpdateTimelineSpeed(addCount);
2298             });
2299
2300             if (ct.IsCancellationRequested)
2301                 return;
2302
2303             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2304
2305             this.RefreshTimeline();
2306         }
2307
2308         /// <summary>
2309         /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2310         /// </summary>
2311         /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2312         private void UpdateTimelineSpeed(int addCount)
2313         {
2314             var now = DateTime.Now;
2315             this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2316
2317             var removeKeys = new List<DateTime>();
2318             var oneHour = TimeSpan.FromHours(1);
2319             var tlCount = 0;
2320             foreach (var pair in this._tlTimestamps)
2321             {
2322                 if (now - pair.Key > oneHour)
2323                     removeKeys.Add(pair.Key);
2324                 else
2325                     tlCount += pair.Value;
2326             }
2327             Interlocked.Exchange(ref this._tlCount, tlCount);
2328
2329             int _;
2330             foreach (var key in removeKeys)
2331                 this._tlTimestamps.TryRemove(key, out _);
2332         }
2333
2334         private Task GetReplyAsync()
2335         {
2336             return this.GetReplyAsync(loadMore: false);
2337         }
2338
2339         private async Task GetReplyAsync(bool loadMore)
2340         {
2341             await this.workerSemaphore.WaitAsync();
2342
2343             try
2344             {
2345                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2346
2347                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2348             }
2349             catch (WebApiException ex)
2350             {
2351                 this._myStatusError = true;
2352                 this.StatusLabel.Text = ex.Message;
2353             }
2354             finally
2355             {
2356                 this.workerSemaphore.Release();
2357             }
2358         }
2359
2360         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2361         {
2362             if (ct.IsCancellationRequested)
2363                 return;
2364
2365             if (!CheckAccountValid())
2366                 throw new WebApiException("Auth error. Check your account");
2367
2368             bool read;
2369             if (!this._cfgCommon.UnreadManage)
2370                 read = true;
2371             else
2372                 read = this._initial && this._cfgCommon.Read;
2373
2374             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2375
2376             await Task.Run(() =>
2377             {
2378                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2379
2380                 this._statuses.DistributePosts();
2381             });
2382
2383             if (ct.IsCancellationRequested)
2384                 return;
2385
2386             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2387
2388             this.RefreshTimeline();
2389         }
2390
2391         private Task GetDirectMessagesAsync()
2392         {
2393             return this.GetDirectMessagesAsync(loadMore: false);
2394         }
2395
2396         private async Task GetDirectMessagesAsync(bool loadMore)
2397         {
2398             await this.workerSemaphore.WaitAsync();
2399
2400             try
2401             {
2402                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2403
2404                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2405             }
2406             catch (WebApiException ex)
2407             {
2408                 this._myStatusError = true;
2409                 this.StatusLabel.Text = ex.Message;
2410             }
2411             finally
2412             {
2413                 this.workerSemaphore.Release();
2414             }
2415         }
2416
2417         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2418         {
2419             if (ct.IsCancellationRequested)
2420                 return;
2421
2422             if (!CheckAccountValid())
2423                 throw new WebApiException("Auth error. Check your account");
2424
2425             bool read;
2426             if (!this._cfgCommon.UnreadManage)
2427                 read = true;
2428             else
2429                 read = this._initial && this._cfgCommon.Read;
2430
2431             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2432
2433             await Task.Run(() =>
2434             {
2435                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2436                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2437
2438                 this._statuses.DistributePosts();
2439             });
2440
2441             if (ct.IsCancellationRequested)
2442                 return;
2443
2444             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2445
2446             this.RefreshTimeline();
2447         }
2448
2449         private Task GetFavoritesAsync()
2450         {
2451             return this.GetFavoritesAsync(loadMore: false);
2452         }
2453
2454         private async Task GetFavoritesAsync(bool loadMore)
2455         {
2456             await this.workerSemaphore.WaitAsync();
2457
2458             try
2459             {
2460                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2461
2462                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2463             }
2464             catch (WebApiException ex)
2465             {
2466                 this._myStatusError = true;
2467                 this.StatusLabel.Text = ex.Message;
2468             }
2469             finally
2470             {
2471                 this.workerSemaphore.Release();
2472             }
2473         }
2474
2475         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2476         {
2477             if (ct.IsCancellationRequested)
2478                 return;
2479
2480             if (!CheckAccountValid())
2481                 throw new WebApiException("Auth error. Check your account");
2482
2483             bool read;
2484             if (!this._cfgCommon.UnreadManage)
2485                 read = true;
2486             else
2487                 read = this._initial && this._cfgCommon.Read;
2488
2489             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2490
2491             await Task.Run(() =>
2492             {
2493                 this.tw.GetFavoritesApi(read, loadMore);
2494
2495                 this._statuses.DistributePosts();
2496             });
2497
2498             if (ct.IsCancellationRequested)
2499                 return;
2500
2501             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2502
2503             this.RefreshTimeline();
2504         }
2505
2506         private Task GetPublicSearchAllAsync()
2507         {
2508             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2509
2510             return this.GetPublicSearchAsync(tabs, loadMore: false);
2511         }
2512
2513         private Task GetPublicSearchAsync(TabClass tab)
2514         {
2515             return this.GetPublicSearchAsync(tab, loadMore: false);
2516         }
2517
2518         private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2519         {
2520             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2521         }
2522
2523         private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2524         {
2525             await this.workerSemaphore.WaitAsync();
2526
2527             try
2528             {
2529                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2530
2531                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2532             }
2533             catch (WebApiException ex)
2534             {
2535                 this._myStatusError = true;
2536                 this.StatusLabel.Text = ex.Message;
2537             }
2538             finally
2539             {
2540                 this.workerSemaphore.Release();
2541             }
2542         }
2543
2544         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2545         {
2546             if (ct.IsCancellationRequested)
2547                 return;
2548
2549             if (!CheckAccountValid())
2550                 throw new WebApiException("Auth error. Check your account");
2551
2552             bool read;
2553             if (!this._cfgCommon.UnreadManage)
2554                 read = true;
2555             else
2556                 read = this._initial && this._cfgCommon.Read;
2557
2558             p.Report("Search refreshing...");
2559
2560             await Task.Run(() =>
2561             {
2562                 WebApiException lastException = null;
2563
2564                 foreach (var tab in tabs)
2565                 {
2566                     try
2567                     {
2568                         if (string.IsNullOrEmpty(tab.SearchWords))
2569                             continue;
2570
2571                         this.tw.GetSearch(read, tab, false);
2572
2573                         if (loadMore)
2574                             this.tw.GetSearch(read, tab, true);
2575                     }
2576                     catch (WebApiException ex)
2577                     {
2578                         lastException = ex;
2579                     }
2580                 }
2581
2582                 this._statuses.DistributePosts();
2583
2584                 if (lastException != null)
2585                     throw new WebApiException(lastException.Message, lastException);
2586             });
2587
2588             if (ct.IsCancellationRequested)
2589                 return;
2590
2591             p.Report("Search refreshed");
2592
2593             this.RefreshTimeline();
2594         }
2595
2596         private Task GetUserTimelineAllAsync()
2597         {
2598             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2599
2600             return this.GetUserTimelineAsync(tabs, loadMore: false);
2601         }
2602
2603         private Task GetUserTimelineAsync(TabClass tab)
2604         {
2605             return this.GetUserTimelineAsync(tab, loadMore: false);
2606         }
2607
2608         private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2609         {
2610             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2611         }
2612
2613         private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2614         {
2615             await this.workerSemaphore.WaitAsync();
2616
2617             try
2618             {
2619                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2620
2621                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2622             }
2623             catch (WebApiException ex)
2624             {
2625                 this._myStatusError = true;
2626                 this.StatusLabel.Text = ex.Message;
2627             }
2628             finally
2629             {
2630                 this.workerSemaphore.Release();
2631             }
2632         }
2633
2634         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2635         {
2636             if (ct.IsCancellationRequested)
2637                 return;
2638
2639             if (!CheckAccountValid())
2640                 throw new WebApiException("Auth error. Check your account");
2641
2642             bool read;
2643             if (!this._cfgCommon.UnreadManage)
2644                 read = true;
2645             else
2646                 read = this._initial && this._cfgCommon.Read;
2647
2648             p.Report("UserTimeline refreshing...");
2649
2650             await Task.Run(() =>
2651             {
2652                 WebApiException lastException = null;
2653
2654                 foreach (var tab in tabs)
2655                 {
2656                     try
2657                     {
2658                         if (string.IsNullOrEmpty(tab.User))
2659                             continue;
2660
2661                         this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2662                     }
2663                     catch (WebApiException ex)
2664                     {
2665                         lastException = ex;
2666                     }
2667                 }
2668
2669                 this._statuses.DistributePosts();
2670
2671                 if (lastException != null)
2672                     throw new WebApiException(lastException.Message, lastException);
2673             });
2674
2675             if (ct.IsCancellationRequested)
2676                 return;
2677
2678             p.Report("UserTimeline refreshed");
2679
2680             this.RefreshTimeline();
2681         }
2682
2683         private Task GetListTimelineAllAsync()
2684         {
2685             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2686
2687             return this.GetListTimelineAsync(tabs, loadMore: false);
2688         }
2689
2690         private Task GetListTimelineAsync(TabClass tab)
2691         {
2692             return this.GetListTimelineAsync(tab, loadMore: false);
2693         }
2694
2695         private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2696         {
2697             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2698         }
2699
2700         private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2701         {
2702             await this.workerSemaphore.WaitAsync();
2703
2704             try
2705             {
2706                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2707
2708                 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2709             }
2710             catch (WebApiException ex)
2711             {
2712                 this._myStatusError = true;
2713                 this.StatusLabel.Text = ex.Message;
2714             }
2715             finally
2716             {
2717                 this.workerSemaphore.Release();
2718             }
2719         }
2720
2721         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2722         {
2723             if (ct.IsCancellationRequested)
2724                 return;
2725
2726             if (!CheckAccountValid())
2727                 throw new WebApiException("Auth error. Check your account");
2728
2729             bool read;
2730             if (!this._cfgCommon.UnreadManage)
2731                 read = true;
2732             else
2733                 read = this._initial && this._cfgCommon.Read;
2734
2735             p.Report("List refreshing...");
2736
2737             await Task.Run(() =>
2738             {
2739                 WebApiException lastException = null;
2740
2741                 foreach (var tab in tabs)
2742                 {
2743                     try
2744                     {
2745                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2746                             continue;
2747
2748                         this.tw.GetListStatus(read, tab, loadMore, this._initial);
2749                     }
2750                     catch (WebApiException ex)
2751                     {
2752                         lastException = ex;
2753                     }
2754                 }
2755
2756                 this._statuses.DistributePosts();
2757
2758                 if (lastException != null)
2759                     throw new WebApiException(lastException.Message, lastException);
2760             });
2761
2762             if (ct.IsCancellationRequested)
2763                 return;
2764
2765             p.Report("List refreshed");
2766
2767             this.RefreshTimeline();
2768         }
2769
2770         private async Task GetRelatedTweetsAsync(TabClass tab)
2771         {
2772             await this.workerSemaphore.WaitAsync();
2773
2774             try
2775             {
2776                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2777
2778                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2779             }
2780             catch (WebApiException ex)
2781             {
2782                 this._myStatusError = true;
2783                 this.StatusLabel.Text = ex.Message;
2784             }
2785             finally
2786             {
2787                 this.workerSemaphore.Release();
2788             }
2789         }
2790
2791         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2792         {
2793             if (ct.IsCancellationRequested)
2794                 return;
2795
2796             if (!CheckAccountValid())
2797                 throw new WebApiException("Auth error. Check your account");
2798
2799             bool read;
2800             if (!this._cfgCommon.UnreadManage)
2801                 read = true;
2802             else
2803                 read = this._initial && this._cfgCommon.Read;
2804
2805             p.Report("Related refreshing...");
2806
2807             await Task.Run(() =>
2808             {
2809                 this.tw.GetRelatedResult(read, tab);
2810
2811                 this._statuses.DistributePosts();
2812             });
2813
2814             if (ct.IsCancellationRequested)
2815                 return;
2816
2817             p.Report("Related refreshed");
2818
2819             this.RefreshTimeline();
2820
2821             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2822                 .FirstOrDefault(x => x.Text == tab.TabName);
2823
2824             if (tabPage != null)
2825             {
2826                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2827
2828                 var listView = (DetailsListView)tabPage.Tag;
2829                 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2830
2831                 if (index != -1 && index < listView.Items.Count)
2832                 {
2833                     listView.SelectedIndices.Add(index);
2834                     listView.Items[index].Focused = true;
2835                 }
2836             }
2837         }
2838
2839         private async Task FavAddAsync(long statusId, TabClass tab)
2840         {
2841             await this.workerSemaphore.WaitAsync();
2842
2843             try
2844             {
2845                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2846
2847                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2848             }
2849             catch (WebApiException ex)
2850             {
2851                 this._myStatusError = true;
2852                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2853             }
2854             finally
2855             {
2856                 this.workerSemaphore.Release();
2857             }
2858         }
2859
2860         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2861         {
2862             if (ct.IsCancellationRequested)
2863                 return;
2864
2865             if (!CheckAccountValid())
2866                 throw new WebApiException("Auth error. Check your account");
2867
2868             PostClass post;
2869             if (!tab.Posts.TryGetValue(statusId, out post))
2870                 return;
2871
2872             if (post.IsFav)
2873                 return;
2874
2875             await Task.Run(async () =>
2876             {
2877                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2878
2879                 try
2880                 {
2881                     await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2882                         .IgnoreResponse()
2883                         .ConfigureAwait(false);
2884
2885                     if (this._cfgCommon.RestrictFavCheck)
2886                     {
2887                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2888                             .ConfigureAwait(false);
2889
2890                         if (status.Favorited != true)
2891                             throw new WebApiException("NG(Restricted?)");
2892                     }
2893
2894                     this._favTimestamps.Add(DateTime.Now);
2895
2896                     // TLでも取得済みならfav反映
2897                     if (this._statuses.ContainsKey(statusId))
2898                     {
2899                         var postTl = this._statuses[statusId];
2900                         postTl.IsFav = true;
2901
2902                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2903                         favTab.AddPostQueue(statusId, postTl.IsRead);
2904                     }
2905
2906                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2907                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2908                     {
2909                         if (tb.Contains(statusId))
2910                             tb.Posts[statusId].IsFav = true;
2911                     }
2912
2913                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2914                 }
2915                 catch (WebApiException)
2916                 {
2917                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2918                     throw;
2919                 }
2920
2921                 // 時速表示用
2922                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2923                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2924                 {
2925                     if (this._favTimestamps[i] < oneHour)
2926                         this._favTimestamps.RemoveAt(i);
2927                 }
2928
2929                 this._statuses.DistributePosts();
2930             });
2931
2932             if (ct.IsCancellationRequested)
2933                 return;
2934
2935             this.RefreshTimeline();
2936
2937             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2938             {
2939                 using (ControlTransaction.Update(this._curList))
2940                 {
2941                     var idx = tab.IndexOf(statusId);
2942                     if (idx != -1)
2943                         this.ChangeCacheStyleRead(post.IsRead, idx);
2944                 }
2945
2946                 if (statusId == this._curPost.StatusId)
2947                     await this.DispSelectedPost(true); // 選択アイテム再表示
2948             }
2949         }
2950
2951         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2952         {
2953             await this.workerSemaphore.WaitAsync();
2954
2955             try
2956             {
2957                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2958
2959                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2960             }
2961             catch (WebApiException ex)
2962             {
2963                 this._myStatusError = true;
2964                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2965             }
2966             finally
2967             {
2968                 this.workerSemaphore.Release();
2969             }
2970         }
2971
2972         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2973         {
2974             if (ct.IsCancellationRequested)
2975                 return;
2976
2977             if (!CheckAccountValid())
2978                 throw new WebApiException("Auth error. Check your account");
2979
2980             var successIds = new List<long>();
2981
2982             await Task.Run(async () =>
2983             {
2984                 //スレッド処理はしない
2985                 var allCount = 0;
2986                 var failedCount = 0;
2987                 foreach (var statusId in statusIds)
2988                 {
2989                     allCount++;
2990
2991                     var post = tab.Posts[statusId];
2992
2993                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2994
2995                     if (!post.IsFav)
2996                         continue;
2997
2998                     try
2999                     {
3000                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3001                             .IgnoreResponse()
3002                             .ConfigureAwait(false);
3003                     }
3004                     catch (WebApiException)
3005                     {
3006                         failedCount++;
3007                         continue;
3008                     }
3009
3010                     successIds.Add(statusId);
3011                     post.IsFav = false; // リスト再描画必要
3012
3013                     if (this._statuses.ContainsKey(statusId))
3014                     {
3015                         this._statuses[statusId].IsFav = false;
3016                     }
3017
3018                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
3019                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
3020                     {
3021                         if (tb.Contains(statusId))
3022                             tb.Posts[statusId].IsFav = false;
3023                     }
3024                 }
3025             });
3026
3027             if (ct.IsCancellationRequested)
3028                 return;
3029
3030             this.RemovePostFromFavTab(successIds.ToArray());
3031
3032             this.RefreshTimeline();
3033
3034             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3035             {
3036                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3037                 {
3038                     // 色変えは不要
3039                 }
3040                 else
3041                 {
3042                     using (ControlTransaction.Update(this._curList))
3043                     {
3044                         foreach (var statusId in successIds)
3045                         {
3046                             var idx = tab.IndexOf(statusId);
3047                             if (idx == -1)
3048                                 continue;
3049
3050                             var post = tab.Posts[statusId];
3051                             this.ChangeCacheStyleRead(post.IsRead, idx);
3052                         }
3053                     }
3054
3055                     if (successIds.Contains(this._curPost.StatusId))
3056                         await this.DispSelectedPost(true); // 選択アイテム再表示
3057                 }
3058             }
3059         }
3060
3061         private async Task PostMessageAsync(PostingStatus status)
3062         {
3063             await this.workerSemaphore.WaitAsync();
3064
3065             try
3066             {
3067                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3068
3069                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3070             }
3071             catch (WebApiException ex)
3072             {
3073                 this._myStatusError = true;
3074                 this.StatusLabel.Text = ex.Message;
3075             }
3076             finally
3077             {
3078                 this.workerSemaphore.Release();
3079             }
3080         }
3081
3082         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3083         {
3084             if (ct.IsCancellationRequested)
3085                 return;
3086
3087             if (!CheckAccountValid())
3088                 throw new WebApiException("Auth error. Check your account");
3089
3090             p.Report("Posting...");
3091
3092             var errMsg = "";
3093
3094             try
3095             {
3096                 await Task.Run(async () =>
3097                 {
3098                     if (status.mediaItems == null || status.mediaItems.Length == 0)
3099                     {
3100                         this.tw.PostStatus(status.status, status.inReplyToId);
3101                     }
3102                     else
3103                     {
3104                         var service = ImageSelector.GetService(status.imageService);
3105                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3106                             .ConfigureAwait(false);
3107                     }
3108                 });
3109
3110                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3111             }
3112             catch (WebApiException ex)
3113             {
3114                 // 処理は中断せずエラーの表示のみ行う
3115                 errMsg = ex.Message;
3116                 p.Report(errMsg);
3117                 this._myStatusError = true;
3118             }
3119             finally
3120             {
3121                 // 使い終わった MediaItem は破棄する
3122                 if (status.mediaItems != null)
3123                 {
3124                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3125                     {
3126                         disposableItem.Dispose();
3127                     }
3128                 }
3129             }
3130
3131             if (ct.IsCancellationRequested)
3132                 return;
3133
3134             if (!string.IsNullOrEmpty(errMsg) &&
3135                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3136                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3137             {
3138                 var ret = MessageBox.Show(
3139                     string.Format(
3140                         "{0}   --->   [ " + errMsg + " ]" + Environment.NewLine +
3141                         "\"" + status.status + "\"" + Environment.NewLine +
3142                         "{1}",
3143                         Properties.Resources.StatusUpdateFailed1,
3144                         Properties.Resources.StatusUpdateFailed2),
3145                     "Failed to update status",
3146                     MessageBoxButtons.RetryCancel,
3147                     MessageBoxIcon.Question);
3148
3149                 if (ret == DialogResult.Retry)
3150                 {
3151                     await this.PostMessageAsync(status);
3152                 }
3153                 else
3154                 {
3155                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3156                     if (this.ToolStripFocusLockMenuItem.Checked)
3157                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3158                 }
3159                 return;
3160             }
3161
3162             this._postTimestamps.Add(DateTime.Now);
3163
3164             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3165             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3166             {
3167                 if (this._postTimestamps[i] < oneHour)
3168                     this._postTimestamps.RemoveAt(i);
3169             }
3170
3171             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3172             {
3173                 this.HashMgr.ClearHashtag();
3174                 this.HashStripSplitButton.Text = "#[-]";
3175                 this.HashToggleMenuItem.Checked = false;
3176                 this.HashToggleToolStripMenuItem.Checked = false;
3177             }
3178
3179             this.SetMainWindowTitle();
3180
3181             if (this._cfgCommon.PostAndGet)
3182             {
3183                 if (this._isActiveUserstream)
3184                     this.RefreshTimeline();
3185                 else
3186                     await this.GetHomeTimelineAsync();
3187             }
3188         }
3189
3190         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3191         {
3192             await this.workerSemaphore.WaitAsync();
3193
3194             try
3195             {
3196                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3197
3198                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3199             }
3200             catch (WebApiException ex)
3201             {
3202                 this._myStatusError = true;
3203                 this.StatusLabel.Text = ex.Message;
3204             }
3205             finally
3206             {
3207                 this.workerSemaphore.Release();
3208             }
3209         }
3210
3211         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3212         {
3213             if (ct.IsCancellationRequested)
3214                 return;
3215
3216             if (!CheckAccountValid())
3217                 throw new WebApiException("Auth error. Check your account");
3218
3219             bool read;
3220             if (!this._cfgCommon.UnreadManage)
3221                 read = true;
3222             else
3223                 read = this._initial && this._cfgCommon.Read;
3224
3225             p.Report("Posting...");
3226
3227             await Task.Run(() =>
3228             {
3229                 foreach (var statusId in statusIds)
3230                 {
3231                     this.tw.PostRetweet(statusId, read);
3232                 }
3233             });
3234
3235             if (ct.IsCancellationRequested)
3236                 return;
3237
3238             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3239
3240             this._postTimestamps.Add(DateTime.Now);
3241
3242             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3243             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3244             {
3245                 if (this._postTimestamps[i] < oneHour)
3246                     this._postTimestamps.RemoveAt(i);
3247             }
3248
3249             if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3250                 await this.GetHomeTimelineAsync();
3251         }
3252
3253         private async Task RefreshFollowerIdsAsync()
3254         {
3255             await this.workerSemaphore.WaitAsync();
3256             try
3257             {
3258                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3259
3260                 await Task.Run(() => tw.RefreshFollowerIds());
3261
3262                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3263
3264                 this.RefreshTimeline();
3265                 this.PurgeListViewItemCache();
3266                 this._curList?.Refresh();
3267             }
3268             catch (WebApiException ex)
3269             {
3270                 this.StatusLabel.Text = ex.Message;
3271             }
3272             finally
3273             {
3274                 this.workerSemaphore.Release();
3275             }
3276         }
3277
3278         private async Task RefreshNoRetweetIdsAsync()
3279         {
3280             await this.workerSemaphore.WaitAsync();
3281             try
3282             {
3283                 await Task.Run(() => tw.RefreshNoRetweetIds());
3284
3285                 this.StatusLabel.Text = "NoRetweetIds refreshed";
3286             }
3287             catch (WebApiException ex)
3288             {
3289                 this.StatusLabel.Text = ex.Message;
3290             }
3291             finally
3292             {
3293                 this.workerSemaphore.Release();
3294             }
3295         }
3296
3297         private async Task RefreshBlockIdsAsync()
3298         {
3299             await this.workerSemaphore.WaitAsync();
3300             try
3301             {
3302                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3303
3304                 await Task.Run(() => tw.RefreshBlockIds());
3305
3306                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3307             }
3308             catch (WebApiException ex)
3309             {
3310                 this.StatusLabel.Text = ex.Message;
3311             }
3312             finally
3313             {
3314                 this.workerSemaphore.Release();
3315             }
3316         }
3317
3318         private async Task RefreshTwitterConfigurationAsync()
3319         {
3320             await this.workerSemaphore.WaitAsync();
3321             try
3322             {
3323                 await Task.Run(() => tw.RefreshConfiguration());
3324
3325                 if (this.tw.Configuration.PhotoSizeLimit != 0)
3326                 {
3327                     foreach (var service in this.ImageSelector.GetServices())
3328                     {
3329                         service.UpdateTwitterConfiguration(this.tw.Configuration);
3330                     }
3331                 }
3332
3333                 this.PurgeListViewItemCache();
3334
3335                 this._curList?.Refresh();
3336             }
3337             catch (WebApiException ex)
3338             {
3339                 this.StatusLabel.Text = ex.Message;
3340             }
3341             finally
3342             {
3343                 this.workerSemaphore.Release();
3344             }
3345         }
3346
3347         private async Task RefreshMuteUserIdsAsync()
3348         {
3349             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3350
3351             try
3352             {
3353                 await tw.RefreshMuteUserIdsAsync();
3354             }
3355             catch (WebApiException ex)
3356             {
3357                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3358                 return;
3359             }
3360
3361             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3362         }
3363
3364         private void RemovePostFromFavTab(Int64[] ids)
3365         {
3366             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3367             string favTabName = favTab.TabName;
3368             int fidx = 0;
3369             if (_curTab.Text.Equals(favTabName))
3370             {
3371                 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3372             }
3373
3374             foreach (long i in ids)
3375             {
3376                 try
3377                 {
3378                     _statuses.RemoveFavPost(i);
3379                 }
3380                 catch (Exception)
3381                 {
3382                     continue;
3383                 }
3384             }
3385             if (_curTab != null && _curTab.Text.Equals(favTabName))
3386             {
3387                 this.PurgeListViewItemCache();
3388                 _curPost = null;
3389                 //_curItemIndex = -1;
3390             }
3391             foreach (TabPage tp in ListTab.TabPages)
3392             {
3393                 if (tp.Text == favTabName)
3394                 {
3395                     ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3396                     break;
3397                 }
3398             }
3399             if (_curTab.Text.Equals(favTabName))
3400             {
3401                 do
3402                 {
3403                     _curList.SelectedIndices.Clear();
3404                 }
3405                 while (_curList.SelectedIndices.Count > 0);
3406
3407                 if (favTab.AllCount > 0)
3408                 {
3409                     if (favTab.AllCount - 1 > fidx && fidx > -1)
3410                     {
3411                         _curList.SelectedIndices.Add(fidx);
3412                     }
3413                     else
3414                     {
3415                         _curList.SelectedIndices.Add(favTab.AllCount - 1);
3416                     }
3417                     if (_curList.SelectedIndices.Count > 0)
3418                     {
3419                         _curList.EnsureVisible(_curList.SelectedIndices[0]);
3420                         _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3421                     }
3422                 }
3423             }
3424         }
3425
3426         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3427         {
3428             if (e.Button == MouseButtons.Left)
3429             {
3430                 this.Visible = true;
3431                 if (this.WindowState == FormWindowState.Minimized)
3432                 {
3433                     this.WindowState = _formWindowState;
3434                 }
3435                 this.Activate();
3436                 this.BringToFront();
3437             }
3438         }
3439
3440         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3441         {
3442             switch (this._cfgCommon.ListDoubleClickAction)
3443             {
3444                 case 0:
3445                     MakeReplyOrDirectStatus();
3446                     break;
3447                 case 1:
3448                     await this.FavoriteChange(true);
3449                     break;
3450                 case 2:
3451                     if (_curPost != null)
3452                         await this.ShowUserStatus(_curPost.ScreenName, false);
3453                     break;
3454                 case 3:
3455                     ShowUserTimeline();
3456                     break;
3457                 case 4:
3458                     ShowRelatedStatusesMenuItem_Click(null, null);
3459                     break;
3460                 case 5:
3461                     MoveToHomeToolStripMenuItem_Click(null, null);
3462                     break;
3463                 case 6:
3464                     StatusOpenMenuItem_Click(null, null);
3465                     break;
3466                 case 7:
3467                     //動作なし
3468                     break;
3469             }
3470         }
3471
3472         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3473         {
3474             await this.FavoriteChange(true);
3475         }
3476
3477         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3478         {
3479             await this.FavoriteChange(false);
3480         }
3481
3482
3483         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3484         {
3485             await this.FavoritesRetweetOfficial();
3486         }
3487
3488         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3489         {
3490             await this.FavoritesRetweetUnofficial();
3491         }
3492
3493         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3494         {
3495             TabClass tab;
3496             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3497                 return;
3498
3499             //trueでFavAdd,falseでFavRemove
3500             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3501                 || !this.ExistCurrentPost) return;
3502
3503             if (this._curList.SelectedIndices.Count > 1)
3504             {
3505                 if (FavAdd)
3506                 {
3507                     // 複数ツイートの一括ふぁぼは禁止
3508                     // https://support.twitter.com/articles/76915#favoriting
3509                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3510                     _DoFavRetweetFlags = false;
3511                     return;
3512                 }
3513                 else
3514                 {
3515                     if (multiFavoriteChangeDialogEnable)
3516                     {
3517                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3518                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3519                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3520
3521                         if (confirm == DialogResult.Cancel)
3522                             return;
3523                     }
3524                 }
3525             }
3526
3527             if (FavAdd)
3528             {
3529                 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3530                 if (selectedPost.IsFav)
3531                 {
3532                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3533                     return;
3534                 }
3535
3536                 await this.FavAddAsync(selectedPost.StatusId, tab);
3537             }
3538             else
3539             {
3540                 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3541                     .Select(x => this.GetCurTabPost(x))
3542                     .Where(x => x.IsFav);
3543
3544                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3545                 if (statusIds.Length == 0)
3546                 {
3547                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3548                     return;
3549                 }
3550
3551                 await this.FavRemoveAsync(statusIds, tab);
3552             }
3553         }
3554
3555         private PostClass GetCurTabPost(int Index)
3556         {
3557             var listCache = this._listItemCache;
3558             if (listCache != null)
3559             {
3560                 ListViewItem item;
3561                 PostClass post;
3562                 if (listCache.TryGetValue(Index, out item, out post))
3563                     return post;
3564             }
3565
3566             return _statuses.Tabs[_curTab.Text][Index];
3567         }
3568
3569         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3570         {
3571             if (_curList.SelectedIndices.Count > 0)
3572                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3573             else if (_curList.SelectedIndices.Count == 0)
3574                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3575         }
3576
3577         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3578         {
3579             if (_curList.SelectedIndices.Count > 0)
3580                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3581         }
3582
3583         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3584         {
3585             if ((!_initialLayout) && this.Visible)
3586             {
3587                 if (this.WindowState == FormWindowState.Normal)
3588                 {
3589                     _mySize = this.ClientSize;
3590                     _mySpDis = this.SplitContainer1.SplitterDistance;
3591                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3592                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3593                     ModifySettingLocal = true;
3594                 }
3595             }
3596         }
3597
3598         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3599         {
3600             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3601             if (comparerMode == null)
3602                 return;
3603
3604             this.SetSortColumn(comparerMode.Value);
3605         }
3606
3607         /// <summary>
3608         /// 列インデックスからソートを行う ComparerMode を求める
3609         /// </summary>
3610         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3611         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3612         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3613         {
3614             if (this._iconCol)
3615                 return ComparerMode.Id;
3616
3617             switch (columnIndex)
3618             {
3619                 case 1: // ニックネーム
3620                     return ComparerMode.Nickname;
3621                 case 2: // 本文
3622                     return ComparerMode.Data;
3623                 case 3: // 時刻=発言Id
3624                     return ComparerMode.Id;
3625                 case 4: // 名前
3626                     return ComparerMode.Name;
3627                 case 7: // Source
3628                     return ComparerMode.Source;
3629                 default:
3630                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3631                     return null;
3632             }
3633         }
3634
3635         /// <summary>
3636         /// 発言一覧の指定した位置の列でソートする
3637         /// </summary>
3638         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3639         private void SetSortColumnByDisplayIndex(int columnIndex)
3640         {
3641             // 表示上の列の位置から ColumnHeader を求める
3642             var col = this._curList.Columns.Cast<ColumnHeader>()
3643                 .Where(x => x.DisplayIndex == columnIndex)
3644                 .FirstOrDefault();
3645
3646             if (col == null)
3647                 return;
3648
3649             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3650             if (comparerMode == null)
3651                 return;
3652
3653             this.SetSortColumn(comparerMode.Value);
3654         }
3655
3656         /// <summary>
3657         /// 発言一覧の最後列の項目でソートする
3658         /// </summary>
3659         private void SetSortLastColumn()
3660         {
3661             // 表示上の最後列にある ColumnHeader を求める
3662             var col = this._curList.Columns.Cast<ColumnHeader>()
3663                 .OrderByDescending(x => x.DisplayIndex)
3664                 .First();
3665
3666             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3667             if (comparerMode == null)
3668                 return;
3669
3670             this.SetSortColumn(comparerMode.Value);
3671         }
3672
3673         /// <summary>
3674         /// 発言一覧を指定された ComparerMode に基づいてソートする
3675         /// </summary>
3676         private void SetSortColumn(ComparerMode sortColumn)
3677         {
3678             if (this._cfgCommon.SortOrderLock)
3679                 return;
3680
3681             this._statuses.ToggleSortOrder(sortColumn);
3682             this.InitColumnText();
3683
3684             var list = this._curList;
3685             if (_iconCol)
3686             {
3687                 list.Columns[0].Text = this.ColumnText[0];
3688                 list.Columns[1].Text = this.ColumnText[2];
3689             }
3690             else
3691             {
3692                 for (var i = 0; i <= 7; i++)
3693                 {
3694                     list.Columns[i].Text = this.ColumnText[i];
3695                 }
3696             }
3697
3698             this.PurgeListViewItemCache();
3699
3700             var tab = this._statuses.Tabs[this._curTab.Text];
3701             if (tab.AllCount > 0 && this._curPost != null)
3702             {
3703                 var idx = tab.IndexOf(this._curPost.StatusId);
3704                 if (idx > -1)
3705                 {
3706                     this.SelectListItem(list, idx);
3707                     list.EnsureVisible(idx);
3708                 }
3709             }
3710             list.Refresh();
3711
3712             this.ModifySettingCommon = true;
3713         }
3714
3715         private void TweenMain_LocationChanged(object sender, EventArgs e)
3716         {
3717             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3718             {
3719                 _myLoc = this.DesktopLocation;
3720                 ModifySettingLocal = true;
3721             }
3722         }
3723
3724         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3725         {
3726             if (ListTab.SelectedTab == null) return;
3727             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3728             if (!this.ExistCurrentPost)
3729             {
3730                 ReplyStripMenuItem.Enabled = false;
3731                 ReplyAllStripMenuItem.Enabled = false;
3732                 DMStripMenuItem.Enabled = false;
3733                 ShowProfileMenuItem.Enabled = false;
3734                 ShowUserTimelineContextMenuItem.Enabled = false;
3735                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3736                 MoveToFavToolStripMenuItem.Enabled = false;
3737                 TabMenuItem.Enabled = false;
3738                 IDRuleMenuItem.Enabled = false;
3739                 SourceRuleMenuItem.Enabled = false;
3740                 ReadedStripMenuItem.Enabled = false;
3741                 UnreadStripMenuItem.Enabled = false;
3742             }
3743             else
3744             {
3745                 ShowProfileMenuItem.Enabled = true;
3746                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3747                 ReplyStripMenuItem.Enabled = true;
3748                 ReplyAllStripMenuItem.Enabled = true;
3749                 DMStripMenuItem.Enabled = true;
3750                 ShowUserTimelineContextMenuItem.Enabled = true;
3751                 MoveToFavToolStripMenuItem.Enabled = true;
3752                 TabMenuItem.Enabled = true;
3753                 IDRuleMenuItem.Enabled = true;
3754                 SourceRuleMenuItem.Enabled = true;
3755                 ReadedStripMenuItem.Enabled = true;
3756                 UnreadStripMenuItem.Enabled = true;
3757             }
3758             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3759             {
3760                 FavAddToolStripMenuItem.Enabled = false;
3761                 FavRemoveToolStripMenuItem.Enabled = false;
3762                 StatusOpenMenuItem.Enabled = false;
3763                 FavorareMenuItem.Enabled = false;
3764                 ShowRelatedStatusesMenuItem.Enabled = false;
3765
3766                 ReTweetStripMenuItem.Enabled = false;
3767                 ReTweetUnofficialStripMenuItem.Enabled = false;
3768                 QuoteStripMenuItem.Enabled = false;
3769                 FavoriteRetweetContextMenu.Enabled = false;
3770                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3771             }
3772             else
3773             {
3774                 FavAddToolStripMenuItem.Enabled = true;
3775                 FavRemoveToolStripMenuItem.Enabled = true;
3776                 StatusOpenMenuItem.Enabled = true;
3777                 FavorareMenuItem.Enabled = true;
3778                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3779
3780                 if (_curPost.IsMe)
3781                 {
3782                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3783                     ReTweetUnofficialStripMenuItem.Enabled = true;
3784                     QuoteStripMenuItem.Enabled = true;
3785                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3786                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3787                 }
3788                 else
3789                 {
3790                     if (_curPost.IsProtect)
3791                     {
3792                         ReTweetStripMenuItem.Enabled = false;
3793                         ReTweetUnofficialStripMenuItem.Enabled = false;
3794                         QuoteStripMenuItem.Enabled = false;
3795                         FavoriteRetweetContextMenu.Enabled = false;
3796                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3797                     }
3798                     else
3799                     {
3800                         ReTweetStripMenuItem.Enabled = true;
3801                         ReTweetUnofficialStripMenuItem.Enabled = true;
3802                         QuoteStripMenuItem.Enabled = true;
3803                         FavoriteRetweetContextMenu.Enabled = true;
3804                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3805                     }
3806                 }
3807             }
3808             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3809             //{
3810             //    RefreshMoreStripMenuItem.Enabled = true;
3811             //}
3812             //else
3813             //{
3814             //    RefreshMoreStripMenuItem.Enabled = false;
3815             //}
3816             if (!this.ExistCurrentPost
3817                 || _curPost.InReplyToStatusId == null)
3818             {
3819                 RepliedStatusOpenMenuItem.Enabled = false;
3820             }
3821             else
3822             {
3823                 RepliedStatusOpenMenuItem.Enabled = true;
3824             }
3825             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3826             {
3827                 MoveToRTHomeMenuItem.Enabled = false;
3828             }
3829             else
3830             {
3831                 MoveToRTHomeMenuItem.Enabled = true;
3832             }
3833
3834             if (this.ExistCurrentPost)
3835             {
3836                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3837                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3838                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3839                 else
3840                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3841             }
3842         }
3843
3844         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3845         {
3846             MakeReplyOrDirectStatus(false, true);
3847         }
3848
3849         private void DMStripMenuItem_Click(object sender, EventArgs e)
3850         {
3851             MakeReplyOrDirectStatus(false, false);
3852         }
3853
3854         private async Task doStatusDelete()
3855         {
3856             if (this._curTab == null || this._curList == null)
3857                 return;
3858
3859             if (this._curList.SelectedIndices.Count == 0)
3860                 return;
3861
3862             var posts = this._curList.SelectedIndices.Cast<int>()
3863                 .Select(x => this.GetCurTabPost(x))
3864                 .ToArray();
3865
3866             // 選択されたツイートの中に削除可能なものが一つでもあるか
3867             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3868                 return;
3869
3870             var ret = MessageBox.Show(this,
3871                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3872                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3873                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3874
3875             if (ret != DialogResult.OK)
3876                 return;
3877
3878             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3879
3880             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3881             {
3882                 Exception lastException = null;
3883                 foreach (var post in posts)
3884                 {
3885                     if (!post.CanDeleteBy(this.tw.UserId))
3886                         continue;
3887
3888                     try
3889                     {
3890                         if (post.IsDm)
3891                         {
3892                             await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3893                                 .IgnoreResponse();
3894                         }
3895                         else
3896                         {
3897                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3898                                 // 他人に RT された自分のツイート
3899                                 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3900                                     .IgnoreResponse();
3901                             else
3902                                 // 自分のツイート or 自分が RT したツイート
3903                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3904                                     .IgnoreResponse();
3905                         }
3906                     }
3907                     catch (WebApiException ex)
3908                     {
3909                         lastException = ex;
3910                         continue;
3911                     }
3912
3913                     this._statuses.RemovePost(post.StatusId);
3914                 }
3915
3916                 if (lastException == null)
3917                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3918                 else
3919                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3920
3921                 this.PurgeListViewItemCache();
3922                 this._curPost = null;
3923                 this._curItemIndex = -1;
3924
3925                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3926                 {
3927                     var listView = (DetailsListView)tabPage.Tag;
3928                     var tab = this._statuses.Tabs[tabPage.Text];
3929
3930                     using (ControlTransaction.Update(listView))
3931                     {
3932                         listView.VirtualListSize = tab.AllCount;
3933
3934                         if (tabPage == this._curTab)
3935                         {
3936                             listView.SelectedIndices.Clear();
3937
3938                             if (tab.AllCount != 0)
3939                             {
3940                                 int selectedIndex;
3941                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3942                                     selectedIndex = focusedIndex;
3943                                 else
3944                                     selectedIndex = tab.AllCount - 1;
3945
3946                                 listView.SelectedIndices.Add(selectedIndex);
3947                                 listView.EnsureVisible(selectedIndex);
3948                                 listView.FocusedItem = listView.Items[selectedIndex];
3949                             }
3950                         }
3951                     }
3952
3953                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3954                     {
3955                         if (tabPage.ImageIndex == 0)
3956                             tabPage.ImageIndex = -1; // タブアイコン
3957                     }
3958                 }
3959
3960                 if (!this._cfgCommon.TabIconDisp)
3961                     this.ListTab.Refresh();
3962             }
3963         }
3964
3965         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3966         {
3967             await this.doStatusDelete();
3968         }
3969
3970         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3971         {
3972             using (ControlTransaction.Update(this._curList))
3973             {
3974                 foreach (int idx in _curList.SelectedIndices)
3975                 {
3976                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3977                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3978                     ChangeCacheStyleRead(true, idx);
3979                 }
3980                 ColorizeList();
3981             }
3982             foreach (TabPage tb in ListTab.TabPages)
3983             {
3984                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3985                 {
3986                     if (this._cfgCommon.TabIconDisp)
3987                     {
3988                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3989                     }
3990                 }
3991             }
3992             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3993         }
3994
3995         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3996         {
3997             using (ControlTransaction.Update(this._curList))
3998             {
3999                 foreach (int idx in _curList.SelectedIndices)
4000                 {
4001                     var post = this._statuses.Tabs[this._curTab.Text][idx];
4002                     this._statuses.SetReadAllTab(post.StatusId, read: false);
4003                     ChangeCacheStyleRead(false, idx);
4004                 }
4005                 ColorizeList();
4006             }
4007             foreach (TabPage tb in ListTab.TabPages)
4008             {
4009                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4010                 {
4011                     if (this._cfgCommon.TabIconDisp)
4012                     {
4013                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4014                     }
4015                 }
4016             }
4017             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4018         }
4019
4020         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4021         {
4022             await this.DoRefresh();
4023         }
4024
4025         private async Task DoRefresh()
4026         {
4027             if (_curTab != null)
4028             {
4029                 TabClass tab;
4030                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4031                     return;
4032
4033                 switch (_statuses.Tabs[_curTab.Text].TabType)
4034                 {
4035                     case MyCommon.TabUsageType.Mentions:
4036                         await this.GetReplyAsync();
4037                         break;
4038                     case MyCommon.TabUsageType.DirectMessage:
4039                         await this.GetDirectMessagesAsync();
4040                         break;
4041                     case MyCommon.TabUsageType.Favorites:
4042                         await this.GetFavoritesAsync();
4043                         break;
4044                     //case MyCommon.TabUsageType.Profile:
4045                         //// TODO
4046                     case MyCommon.TabUsageType.PublicSearch:
4047                         //// TODO
4048                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4049                         await this.GetPublicSearchAsync(tab);
4050                         break;
4051                     case MyCommon.TabUsageType.UserTimeline:
4052                         await this.GetUserTimelineAsync(tab);
4053                         break;
4054                     case MyCommon.TabUsageType.Lists:
4055                         //// TODO
4056                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4057                         await this.GetListTimelineAsync(tab);
4058                         break;
4059                     default:
4060                         await this.GetHomeTimelineAsync();
4061                         break;
4062                 }
4063             }
4064             else
4065             {
4066                 await this.GetHomeTimelineAsync();
4067             }
4068         }
4069
4070         private async Task DoRefreshMore()
4071         {
4072             //ページ指定をマイナス1に
4073             if (_curTab != null)
4074             {
4075                 TabClass tab;
4076                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4077                     return;
4078
4079                 switch (_statuses.Tabs[_curTab.Text].TabType)
4080                 {
4081                     case MyCommon.TabUsageType.Mentions:
4082                         await this.GetReplyAsync(loadMore: true);
4083                         break;
4084                     case MyCommon.TabUsageType.DirectMessage:
4085                         await this.GetDirectMessagesAsync(loadMore: true);
4086                         break;
4087                     case MyCommon.TabUsageType.Favorites:
4088                         await this.GetFavoritesAsync(loadMore: true);
4089                         break;
4090                     case MyCommon.TabUsageType.Profile:
4091                         //// TODO
4092                         break;
4093                     case MyCommon.TabUsageType.PublicSearch:
4094                         // TODO
4095                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4096                         await this.GetPublicSearchAsync(tab, loadMore: true);
4097                         break;
4098                     case MyCommon.TabUsageType.UserTimeline:
4099                         await this.GetUserTimelineAsync(tab, loadMore: true);
4100                         break;
4101                     case MyCommon.TabUsageType.Lists:
4102                         //// TODO
4103                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4104                         await this.GetListTimelineAsync(tab, loadMore: true);
4105                         break;
4106                     default:
4107                         await this.GetHomeTimelineAsync(loadMore: true);
4108                         break;
4109                 }
4110             }
4111             else
4112             {
4113                 await this.GetHomeTimelineAsync(loadMore: true);
4114             }
4115         }
4116
4117         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4118         {
4119             DialogResult result = DialogResult.Abort;
4120
4121             using (var settingDialog = new AppendSettingDialog())
4122             {
4123                 settingDialog.Icon = this.MainIcon;
4124                 settingDialog.Owner = this;
4125                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4126                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4127
4128                 settingDialog.tw = this.tw;
4129                 settingDialog.twitterApi = this.twitterApi;
4130
4131                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4132
4133                 try
4134                 {
4135                     result = settingDialog.ShowDialog(this);
4136                 }
4137                 catch (Exception)
4138                 {
4139                     return DialogResult.Abort;
4140                 }
4141
4142                 if (result == DialogResult.OK)
4143                 {
4144                     lock (_syncObject)
4145                     {
4146                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4147                     }
4148                 }
4149             }
4150
4151             return result;
4152         }
4153
4154         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4155         {
4156             // 設定画面表示前のユーザー情報
4157             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4158
4159             var oldIconSz = this._cfgCommon.IconSize;
4160
4161             if (ShowSettingDialog() == DialogResult.OK)
4162             {
4163                 lock (_syncObject)
4164                 {
4165                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4166                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4167                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4168                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4169                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4170                     HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4171
4172                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4173                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4174                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4175                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4176                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4177
4178                     ImageSelector.Reset(tw, this.tw.Configuration);
4179
4180                     try
4181                     {
4182                         if (this._cfgCommon.TabIconDisp)
4183                         {
4184                             ListTab.DrawItem -= ListTab_DrawItem;
4185                             ListTab.DrawMode = TabDrawMode.Normal;
4186                             ListTab.ImageList = this.TabImage;
4187                         }
4188                         else
4189                         {
4190                             ListTab.DrawItem -= ListTab_DrawItem;
4191                             ListTab.DrawItem += ListTab_DrawItem;
4192                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4193                             ListTab.ImageList = null;
4194                         }
4195                     }
4196                     catch (Exception ex)
4197                     {
4198                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4199                         ex.Data["IsTerminatePermission"] = false;
4200                         throw;
4201                     }
4202
4203                     try
4204                     {
4205                         if (!this._cfgCommon.UnreadManage)
4206                         {
4207                             ReadedStripMenuItem.Enabled = false;
4208                             UnreadStripMenuItem.Enabled = false;
4209                             if (this._cfgCommon.TabIconDisp)
4210                             {
4211                                 foreach (TabPage myTab in ListTab.TabPages)
4212                                 {
4213                                     myTab.ImageIndex = -1;
4214                                 }
4215                             }
4216                         }
4217                         else
4218                         {
4219                             ReadedStripMenuItem.Enabled = true;
4220                             UnreadStripMenuItem.Enabled = true;
4221                         }
4222                     }
4223                     catch (Exception ex)
4224                     {
4225                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4226                         ex.Data["IsTerminatePermission"] = false;
4227                         throw;
4228                     }
4229
4230                     // タブの表示位置の決定
4231                     SetTabAlignment();
4232
4233                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4234
4235                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4236                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4237                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4238
4239                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4240                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4241                     _fntUnread = this._cfgLocal.FontUnread;
4242                     _clUnread = this._cfgLocal.ColorUnread;
4243                     _fntReaded = this._cfgLocal.FontRead;
4244                     _clReaded = this._cfgLocal.ColorRead;
4245                     _clFav = this._cfgLocal.ColorFav;
4246                     _clOWL = this._cfgLocal.ColorOWL;
4247                     _clRetweet = this._cfgLocal.ColorRetweet;
4248                     _fntDetail = this._cfgLocal.FontDetail;
4249                     _clDetail = this._cfgLocal.ColorDetail;
4250                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4251                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4252                     _clSelf = this._cfgLocal.ColorSelf;
4253                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4254                     _clTarget = this._cfgLocal.ColorTarget;
4255                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4256                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4257                     _clAtTo = this._cfgLocal.ColorAtTo;
4258                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4259                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4260                     _clInputFont = this._cfgLocal.ColorInputFont;
4261                     _fntInputFont = this._cfgLocal.FontInputFont;
4262                     _brsBackColorMine.Dispose();
4263                     _brsBackColorAt.Dispose();
4264                     _brsBackColorYou.Dispose();
4265                     _brsBackColorAtYou.Dispose();
4266                     _brsBackColorAtFromTarget.Dispose();
4267                     _brsBackColorAtTo.Dispose();
4268                     _brsBackColorNone.Dispose();
4269                     _brsBackColorMine = new SolidBrush(_clSelf);
4270                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4271                     _brsBackColorYou = new SolidBrush(_clTarget);
4272                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4273                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4274                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4275                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4276
4277                     try
4278                     {
4279                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4280                         StatusText.Font = _fntInputFont;
4281                         StatusText.ForeColor = _clInputFont;
4282                     }
4283                     catch (Exception ex)
4284                     {
4285                         MessageBox.Show(ex.Message);
4286                     }
4287
4288                     try
4289                     {
4290                         InitDetailHtmlFormat();
4291                     }
4292                     catch (Exception ex)
4293                     {
4294                         ex.Data["Instance"] = "Font";
4295                         ex.Data["IsTerminatePermission"] = false;
4296                         throw;
4297                     }
4298
4299                     try
4300                     {
4301                         foreach (TabPage tb in ListTab.TabPages)
4302                         {
4303                             if (this._cfgCommon.TabIconDisp)
4304                             {
4305                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4306                                     tb.ImageIndex = -1;
4307                                 else
4308                                     tb.ImageIndex = 0;
4309                             }
4310                         }
4311                     }
4312                     catch (Exception ex)
4313                     {
4314                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4315                         ex.Data["IsTerminatePermission"] = false;
4316                         throw;
4317                     }
4318
4319                     try
4320                     {
4321                         var oldIconCol = _iconCol;
4322
4323                         if (this._cfgCommon.IconSize != oldIconSz)
4324                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4325
4326                         foreach (TabPage tp in ListTab.TabPages)
4327                         {
4328                             DetailsListView lst = (DetailsListView)tp.Tag;
4329
4330                             using (ControlTransaction.Update(lst))
4331                             {
4332                                 lst.GridLines = this._cfgCommon.ShowGrid;
4333                                 lst.Font = _fntReaded;
4334                                 lst.BackColor = _clListBackcolor;
4335
4336                                 if (_iconCol != oldIconCol)
4337                                     ResetColumns(lst);
4338                             }
4339                         }
4340                     }
4341                     catch (Exception ex)
4342                     {
4343                         ex.Data["Instance"] = "ListView(IconSize)";
4344                         ex.Data["IsTerminatePermission"] = false;
4345                         throw;
4346                     }
4347
4348                     SetMainWindowTitle();
4349                     SetNotifyIconText();
4350
4351                     this.PurgeListViewItemCache();
4352                     _curList?.Refresh();
4353                     ListTab.Refresh();
4354
4355                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4356                     if (this._cfgCommon.HotkeyEnabled)
4357                     {
4358                         ///グローバルホットキーの登録。設定で変更可能にするかも
4359                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4360                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4361                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4362                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4363                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4364                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4365                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4366                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4367                             modKey |= HookGlobalHotkey.ModKeys.Win;
4368
4369                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4370                     }
4371
4372                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4373                     try
4374                     {
4375                         StatusText_TextChanged(null, null);
4376                     }
4377                     catch (Exception)
4378                     {
4379                     }
4380                 }
4381             }
4382             else
4383             {
4384                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4385                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4386                 this.twitterApi.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.UserId, oldUser.Username);
4387             }
4388
4389             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4390
4391             this.TopMost = this._cfgCommon.AlwaysTop;
4392             SaveConfigsAll(false);
4393
4394             if (tw.Username != oldUser.Username)
4395                 await this.doGetFollowersMenu();
4396         }
4397
4398         /// <summary>
4399         /// タブの表示位置を設定する
4400         /// </summary>
4401         private void SetTabAlignment()
4402         {
4403             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4404             if (ListTab.Alignment == newAlignment) return;
4405
4406             // 各タブのリスト上の選択位置などを退避
4407             var listSelections = this.SaveListViewSelection();
4408
4409             ListTab.Alignment = newAlignment;
4410
4411             foreach (TabPage tab in ListTab.TabPages)
4412             {
4413                 DetailsListView lst = (DetailsListView)tab.Tag;
4414                 TabClass tabInfo = _statuses.Tabs[tab.Text];
4415                 using (ControlTransaction.Update(lst))
4416                 {
4417                     // 選択位置などを復元
4418                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4419                 }
4420             }
4421         }
4422
4423         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4424         {
4425             // アイコンサイズの再設定
4426             _iconCol = false;
4427             switch (iconSz)
4428             {
4429                 case MyCommon.IconSizes.IconNone:
4430                     _iconSz = 0;
4431                     break;
4432                 case MyCommon.IconSizes.Icon16:
4433                     _iconSz = 16;
4434                     break;
4435                 case MyCommon.IconSizes.Icon24:
4436                     _iconSz = 26;
4437                     break;
4438                 case MyCommon.IconSizes.Icon48:
4439                     _iconSz = 48;
4440                     break;
4441                 case MyCommon.IconSizes.Icon48_2:
4442                     _iconSz = 48;
4443                     _iconCol = true;
4444                     break;
4445             }
4446
4447             if (_iconSz > 0)
4448             {
4449                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4450                 _listViewImageList.ImageSize = new Size(
4451                     1,
4452                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4453             }
4454             else
4455             {
4456                 _listViewImageList.ImageSize = new Size(1, 1);
4457             }
4458         }
4459
4460         private void ResetColumns(DetailsListView list)
4461         {
4462             using (ControlTransaction.Update(list))
4463             using (ControlTransaction.Layout(list, false))
4464             {
4465                 // カラムヘッダの再設定
4466                 list.ColumnClick -= MyList_ColumnClick;
4467                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4468                 list.ColumnReordered -= MyList_ColumnReordered;
4469                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4470
4471                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4472                 list.Columns.Clear();
4473                 cols.ForEach(col => col.Dispose());
4474                 cols.Clear();
4475
4476                 InitColumns(list, true);
4477
4478                 list.ColumnClick += MyList_ColumnClick;
4479                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4480                 list.ColumnReordered += MyList_ColumnReordered;
4481                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4482             }
4483         }
4484
4485         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4486         {
4487             if (e.Url.AbsoluteUri != "about:blank")
4488             {
4489                 await this.DispSelectedPost();
4490                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4491             }
4492         }
4493
4494         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4495         {
4496             if (e.Url.Scheme == "data")
4497             {
4498                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4499             }
4500             else if (e.Url.AbsoluteUri != "about:blank")
4501             {
4502                 e.Cancel = true;
4503                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4504                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4505             }
4506         }
4507
4508         public void AddNewTabForSearch(string searchWord)
4509         {
4510             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4511             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4512             {
4513                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4514                 {
4515                     foreach (TabPage tp in ListTab.TabPages)
4516                     {
4517                         if (tb.TabName == tp.Text)
4518                         {
4519                             ListTab.SelectedTab = tp;
4520                             return;
4521                         }
4522                     }
4523                 }
4524             }
4525             //ユニークなタブ名生成
4526             string tabName = searchWord;
4527             for (int i = 0; i <= 100; i++)
4528             {
4529                 if (_statuses.ContainsTab(tabName))
4530                     tabName += "_";
4531                 else
4532                     break;
4533             }
4534             //タブ追加
4535             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4536             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4537             //追加したタブをアクティブに
4538             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4539             //検索条件の設定
4540             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4541             cmb.Items.Add(searchWord);
4542             cmb.Text = searchWord;
4543             SaveConfigsTabs();
4544             //検索実行
4545             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4546         }
4547
4548         private void ShowUserTimeline()
4549         {
4550             if (!this.ExistCurrentPost) return;
4551             AddNewTabForUserTimeline(_curPost.ScreenName);
4552         }
4553
4554         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4555         {
4556             if (e.KeyCode == Keys.Escape)
4557             {
4558                 TabPage relTp = ListTab.SelectedTab;
4559                 RemoveSpecifiedTab(relTp.Text, false);
4560                 SaveConfigsTabs();
4561                 e.SuppressKeyPress = true;
4562             }
4563         }
4564
4565         public void AddNewTabForUserTimeline(string user)
4566         {
4567             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4568             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4569             {
4570                 if (tb.User == user)
4571                 {
4572                     foreach (TabPage tp in ListTab.TabPages)
4573                     {
4574                         if (tb.TabName == tp.Text)
4575                         {
4576                             ListTab.SelectedTab = tp;
4577                             return;
4578                         }
4579                     }
4580                 }
4581             }
4582             //ユニークなタブ名生成
4583             string tabName = "user:" + user;
4584             while (_statuses.ContainsTab(tabName))
4585             {
4586                 tabName += "_";
4587             }
4588             //タブ追加
4589             _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4590             var tab = this._statuses.Tabs[tabName];
4591             tab.User = user;
4592             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4593             //追加したタブをアクティブに
4594             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4595             SaveConfigsTabs();
4596             //検索実行
4597             this.GetUserTimelineAsync(tab);
4598         }
4599
4600         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4601         {
4602             //重複チェック
4603             foreach (TabPage tb in ListTab.TabPages)
4604             {
4605                 if (tb.Text == tabName) return false;
4606             }
4607
4608             //新規タブ名チェック
4609             if (tabName == Properties.Resources.AddNewTabText1) return false;
4610
4611             //タブタイプ重複チェック
4612             if (!startup)
4613             {
4614                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4615                    tabType == MyCommon.TabUsageType.Favorites ||
4616                    tabType == MyCommon.TabUsageType.Home ||
4617                    tabType == MyCommon.TabUsageType.Mentions ||
4618                    tabType == MyCommon.TabUsageType.Related)
4619                 {
4620                     if (_statuses.GetTabByType(tabType) != null) return false;
4621                 }
4622             }
4623
4624             var _tabPage = new TabPage();
4625             var _listCustom = new DetailsListView();
4626
4627             int cnt = ListTab.TabPages.Count;
4628
4629             ///ToDo:Create and set controls follow tabtypes
4630
4631             using (ControlTransaction.Update(_listCustom))
4632             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4633             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4634             using (ControlTransaction.Layout(this.SplitContainer1, false))
4635             using (ControlTransaction.Layout(this.ListTab, false))
4636             using (ControlTransaction.Layout(this))
4637             using (ControlTransaction.Layout(_tabPage, false))
4638             {
4639                 _tabPage.Controls.Add(_listCustom);
4640
4641                 /// UserTimeline関連
4642                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4643                 {
4644                     var label = new Label();
4645                     label.Dock = DockStyle.Top;
4646                     label.Name = "labelUser";
4647                     label.TabIndex = 0;
4648                     if (tabType == MyCommon.TabUsageType.Lists)
4649                     {
4650                         label.Text = listInfo.ToString();
4651                     }
4652                     else
4653                     {
4654                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4655                     }
4656                     label.TextAlign = ContentAlignment.MiddleLeft;
4657                     using (ComboBox tmpComboBox = new ComboBox())
4658                     {
4659                         label.Height = tmpComboBox.Height;
4660                     }
4661                     _tabPage.Controls.Add(label);
4662                 }
4663                 /// 検索関連の準備
4664                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4665                 {
4666                     var pnl = new Panel();
4667
4668                     var lbl = new Label();
4669                     var cmb = new ComboBox();
4670                     var btn = new Button();
4671                     var cmbLang = new ComboBox();
4672
4673                     using (ControlTransaction.Layout(pnl, false))
4674                     {
4675                         pnl.Controls.Add(cmb);
4676                         pnl.Controls.Add(cmbLang);
4677                         pnl.Controls.Add(btn);
4678                         pnl.Controls.Add(lbl);
4679                         pnl.Name = "panelSearch";
4680                         pnl.TabIndex = 0;
4681                         pnl.Dock = DockStyle.Top;
4682                         pnl.Height = cmb.Height;
4683                         pnl.Enter += SearchControls_Enter;
4684                         pnl.Leave += SearchControls_Leave;
4685
4686                         cmb.Text = "";
4687                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4688                         cmb.Dock = DockStyle.Fill;
4689                         cmb.Name = "comboSearch";
4690                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4691                         cmb.ImeMode = ImeMode.NoControl;
4692                         cmb.TabStop = false;
4693                         cmb.TabIndex = 1;
4694                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4695                         cmb.KeyDown += SearchComboBox_KeyDown;
4696
4697                         cmbLang.Text = "";
4698                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4699                         cmbLang.Dock = DockStyle.Right;
4700                         cmbLang.Width = 50;
4701                         cmbLang.Name = "comboLang";
4702                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4703                         cmbLang.TabStop = false;
4704                         cmbLang.TabIndex = 2;
4705                         cmbLang.Items.Add("");
4706                         cmbLang.Items.Add("ja");
4707                         cmbLang.Items.Add("en");
4708                         cmbLang.Items.Add("ar");
4709                         cmbLang.Items.Add("da");
4710                         cmbLang.Items.Add("nl");
4711                         cmbLang.Items.Add("fa");
4712                         cmbLang.Items.Add("fi");
4713                         cmbLang.Items.Add("fr");
4714                         cmbLang.Items.Add("de");
4715                         cmbLang.Items.Add("hu");
4716                         cmbLang.Items.Add("is");
4717                         cmbLang.Items.Add("it");
4718                         cmbLang.Items.Add("no");
4719                         cmbLang.Items.Add("pl");
4720                         cmbLang.Items.Add("pt");
4721                         cmbLang.Items.Add("ru");
4722                         cmbLang.Items.Add("es");
4723                         cmbLang.Items.Add("sv");
4724                         cmbLang.Items.Add("th");
4725
4726                         lbl.Text = "Search(C-S-f)";
4727                         lbl.Name = "label1";
4728                         lbl.Dock = DockStyle.Left;
4729                         lbl.Width = 90;
4730                         lbl.Height = cmb.Height;
4731                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4732                         lbl.TabIndex = 0;
4733
4734                         btn.Text = "Search";
4735                         btn.Name = "buttonSearch";
4736                         btn.UseVisualStyleBackColor = true;
4737                         btn.Dock = DockStyle.Right;
4738                         btn.TabStop = false;
4739                         btn.TabIndex = 3;
4740                         btn.Click += SearchButton_Click;
4741
4742                         TabClass tab;
4743                         if (_statuses.Tabs.TryGetValue(tabName, out tab))
4744                         {
4745                             if (!string.IsNullOrEmpty(tab.SearchWords))
4746                             {
4747                                 cmb.Items.Add(tab.SearchWords);
4748                                 cmb.Text = tab.SearchWords;
4749                             }
4750
4751                             cmbLang.Text = tab.SearchLang;
4752                         }
4753
4754                         _tabPage.Controls.Add(pnl);
4755                     }
4756                 }
4757
4758                 _tabPage.Tag = _listCustom;
4759                 this.ListTab.Controls.Add(_tabPage);
4760
4761                 _tabPage.Location = new Point(4, 4);
4762                 _tabPage.Name = "CTab" + cnt.ToString();
4763                 _tabPage.Size = new Size(380, 260);
4764                 _tabPage.TabIndex = 2 + cnt;
4765                 _tabPage.Text = tabName;
4766                 _tabPage.UseVisualStyleBackColor = true;
4767                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4768
4769                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4770                 _listCustom.TabIndex = 1;
4771                 _listCustom.AllowColumnReorder = true;
4772                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4773                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4774                 _listCustom.Dock = DockStyle.Fill;
4775                 _listCustom.FullRowSelect = true;
4776                 _listCustom.HideSelection = false;
4777                 _listCustom.Location = new Point(0, 0);
4778                 _listCustom.Margin = new Padding(0);
4779                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4780                 _listCustom.ShowItemToolTips = true;
4781                 _listCustom.Size = new Size(380, 260);
4782                 _listCustom.UseCompatibleStateImageBehavior = false;
4783                 _listCustom.View = View.Details;
4784                 _listCustom.OwnerDraw = true;
4785                 _listCustom.VirtualMode = true;
4786                 _listCustom.Font = _fntReaded;
4787                 _listCustom.BackColor = _clListBackcolor;
4788
4789                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4790                 _listCustom.AllowDrop = true;
4791
4792                 _listCustom.SmallImageList = _listViewImageList;
4793
4794                 InitColumns(_listCustom, startup);
4795
4796                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4797                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4798                 _listCustom.ColumnClick += MyList_ColumnClick;
4799                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4800                 _listCustom.DragDrop += TweenMain_DragDrop;
4801                 _listCustom.DragEnter += TweenMain_DragEnter;
4802                 _listCustom.DragOver += TweenMain_DragOver;
4803                 _listCustom.DrawItem += MyList_DrawItem;
4804                 _listCustom.MouseClick += MyList_MouseClick;
4805                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4806                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4807                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4808                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4809                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4810                 _listCustom.HScrolled += MyList_HScrolled;
4811             }
4812
4813             return true;
4814         }
4815
4816         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4817         {
4818             var tabInfo = _statuses.GetTabByName(TabName);
4819             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4820
4821             if (confirm)
4822             {
4823                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4824                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4825                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4826                 {
4827                     return false;
4828                 }
4829             }
4830
4831             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4832             if (_tabPage == null) return false;
4833
4834             SetListProperty();   //他のタブに列幅等を反映
4835
4836             //オブジェクトインスタンスの削除
4837             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4838             _tabPage.Tag = null;
4839
4840             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4841             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4842             using (ControlTransaction.Layout(this.SplitContainer1, false))
4843             using (ControlTransaction.Layout(this.ListTab, false))
4844             using (ControlTransaction.Layout(this))
4845             using (ControlTransaction.Layout(_tabPage, false))
4846             {
4847                 if (this.ListTab.SelectedTab == _tabPage)
4848                 {
4849                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4850                     this._beforeSelectedTab = null;
4851                 }
4852                 this.ListTab.Controls.Remove(_tabPage);
4853
4854                 // 後付けのコントロールを破棄
4855                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4856                 {
4857                     using (Control label = _tabPage.Controls["labelUser"])
4858                     {
4859                         _tabPage.Controls.Remove(label);
4860                     }
4861                 }
4862                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4863                 {
4864                     using (Control pnl = _tabPage.Controls["panelSearch"])
4865                     {
4866                         pnl.Enter -= SearchControls_Enter;
4867                         pnl.Leave -= SearchControls_Leave;
4868                         _tabPage.Controls.Remove(pnl);
4869
4870                         foreach (Control ctrl in pnl.Controls)
4871                         {
4872                             if (ctrl.Name == "buttonSearch")
4873                             {
4874                                 ctrl.Click -= SearchButton_Click;
4875                             }
4876                             else if (ctrl.Name == "comboSearch")
4877                             {
4878                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4879                             }
4880                             pnl.Controls.Remove(ctrl);
4881                             ctrl.Dispose();
4882                         }
4883                     }
4884                 }
4885
4886                 _tabPage.Controls.Remove(_listCustom);
4887
4888                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4889                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4890                 _listCustom.ColumnClick -= MyList_ColumnClick;
4891                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4892                 _listCustom.DragDrop -= TweenMain_DragDrop;
4893                 _listCustom.DragEnter -= TweenMain_DragEnter;
4894                 _listCustom.DragOver -= TweenMain_DragOver;
4895                 _listCustom.DrawItem -= MyList_DrawItem;
4896                 _listCustom.MouseClick -= MyList_MouseClick;
4897                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4898                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4899                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4900                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4901                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4902                 _listCustom.HScrolled -= MyList_HScrolled;
4903
4904                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4905                 _listCustom.Columns.Clear();
4906                 cols.ForEach(col => col.Dispose());
4907                 cols.Clear();
4908
4909                 _listCustom.ContextMenuStrip = null;
4910                 _listCustom.ColumnHeaderContextMenuStrip = null;
4911                 _listCustom.Font = null;
4912
4913                 _listCustom.SmallImageList = null;
4914                 _listCustom.ListViewItemSorter = null;
4915
4916                 //キャッシュのクリア
4917                 if (_curTab.Equals(_tabPage))
4918                 {
4919                     _curTab = null;
4920                     _curItemIndex = -1;
4921                     _curList = null;
4922                     _curPost = null;
4923                 }
4924                 this.PurgeListViewItemCache();
4925             }
4926
4927             _tabPage.Dispose();
4928             _listCustom.Dispose();
4929             _statuses.RemoveTab(TabName);
4930
4931             foreach (TabPage tp in ListTab.TabPages)
4932             {
4933                 DetailsListView lst = (DetailsListView)tp.Tag;
4934                 var count = _statuses.Tabs[tp.Text].AllCount;
4935                 if (lst.VirtualListSize != count)
4936                 {
4937                     lst.VirtualListSize = count;
4938                 }
4939             }
4940
4941             return true;
4942         }
4943
4944         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4945         {
4946             this.PurgeListViewItemCache();
4947             _beforeSelectedTab = e.TabPage;
4948         }
4949
4950         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4951         {
4952             //タブのD&D
4953
4954             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4955             {
4956                 string tn = "";
4957                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4958                 if (!dragEnableRectangle.Contains(e.Location))
4959                 {
4960                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4961                     tn = ListTab.SelectedTab.Text;
4962                 }
4963
4964                 if (string.IsNullOrEmpty(tn)) return;
4965
4966                 foreach (TabPage tb in ListTab.TabPages)
4967                 {
4968                     if (tb.Text == tn)
4969                     {
4970                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4971                         break;
4972                     }
4973                 }
4974             }
4975             else
4976             {
4977                 _tabDrag = false;
4978             }
4979
4980             Point cpos = new Point(e.X, e.Y);
4981             for (int i = 0; i < ListTab.TabPages.Count; i++)
4982             {
4983                 Rectangle rect = ListTab.GetTabRect(i);
4984                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4985                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4986                 {
4987                     _rclickTabName = ListTab.TabPages[i].Text;
4988                     break;
4989                 }
4990             }
4991         }
4992
4993         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4994         {
4995             //_curList.Refresh();
4996             SetMainWindowTitle();
4997             SetStatusLabelUrl();
4998             SetApiStatusLabel();
4999             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
5000             TabMenuControl(ListTab.SelectedTab.Text);
5001             this.PushSelectPostChain();
5002             await DispSelectedPost();
5003         }
5004
5005         private void SetListProperty()
5006         {
5007             //削除などで見つからない場合は処理せず
5008             if (_curList == null) return;
5009             if (!_isColumnChanged) return;
5010
5011             int[] dispOrder = new int[_curList.Columns.Count];
5012             for (int i = 0; i < _curList.Columns.Count; i++)
5013             {
5014                 for (int j = 0; j < _curList.Columns.Count; j++)
5015                 {
5016                     if (_curList.Columns[j].DisplayIndex == i)
5017                     {
5018                         dispOrder[i] = j;
5019                         break;
5020                     }
5021                 }
5022             }
5023
5024             //列幅、列並びを他のタブに設定
5025             foreach (TabPage tb in ListTab.TabPages)
5026             {
5027                 if (!tb.Equals(_curTab))
5028                 {
5029                     if (tb.Tag != null && tb.Controls.Count > 0)
5030                     {
5031                         DetailsListView lst = (DetailsListView)tb.Tag;
5032                         for (int i = 0; i < lst.Columns.Count; i++)
5033                         {
5034                             lst.Columns[dispOrder[i]].DisplayIndex = i;
5035                             lst.Columns[i].Width = _curList.Columns[i].Width;
5036                         }
5037                     }
5038                 }
5039             }
5040
5041             _isColumnChanged = false;
5042         }
5043
5044         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5045         {
5046             try
5047             {
5048                 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5049                     || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5050                     || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5051                 {
5052                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5053                 }
5054                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5055                 {
5056                     SetStatusLabelUrl();
5057                 }
5058             }
5059             catch (Exception)
5060             {
5061             }
5062         }
5063
5064         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5065         {
5066             if (e.KeyChar == '@')
5067             {
5068                 if (!this._cfgCommon.UseAtIdSupplement) return;
5069                 //@マーク
5070                 int cnt = AtIdSupl.ItemCount;
5071                 ShowSuplDialog(StatusText, AtIdSupl);
5072                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5073                 e.Handled = true;
5074             }
5075             else if (e.KeyChar == '#')
5076             {
5077                 if (!this._cfgCommon.UseHashSupplement) return;
5078                 ShowSuplDialog(StatusText, HashSupl);
5079                 e.Handled = true;
5080             }
5081         }
5082
5083         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5084         {
5085             ShowSuplDialog(owner, dialog, 0, "");
5086         }
5087
5088         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5089         {
5090             ShowSuplDialog(owner, dialog, offset, "");
5091         }
5092
5093         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5094         {
5095             dialog.StartsWith = startswith;
5096             if (dialog.Visible)
5097             {
5098                 dialog.Focus();
5099             }
5100             else
5101             {
5102                 dialog.ShowDialog();
5103             }
5104             this.TopMost = this._cfgCommon.AlwaysTop;
5105             int selStart = owner.SelectionStart;
5106             string fHalf = "";
5107             string eHalf = "";
5108             if (dialog.DialogResult == DialogResult.OK)
5109             {
5110                 if (!string.IsNullOrEmpty(dialog.inputText))
5111                 {
5112                     if (selStart > 0)
5113                     {
5114                         fHalf = owner.Text.Substring(0, selStart - offset);
5115                     }
5116                     if (selStart < owner.Text.Length)
5117                     {
5118                         eHalf = owner.Text.Substring(selStart);
5119                     }
5120                     owner.Text = fHalf + dialog.inputText + eHalf;
5121                     owner.SelectionStart = selStart + dialog.inputText.Length;
5122                 }
5123             }
5124             else
5125             {
5126                 if (selStart > 0)
5127                 {
5128                     fHalf = owner.Text.Substring(0, selStart);
5129                 }
5130                 if (selStart < owner.Text.Length)
5131                 {
5132                     eHalf = owner.Text.Substring(selStart);
5133                 }
5134                 owner.Text = fHalf + eHalf;
5135                 if (selStart > 0)
5136                 {
5137                     owner.SelectionStart = selStart;
5138                 }
5139             }
5140             owner.Focus();
5141         }
5142
5143         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5144         {
5145             //スペースキーで未読ジャンプ
5146             if (!e.Alt && !e.Control && !e.Shift)
5147             {
5148                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5149                 {
5150                     bool isSpace = false;
5151                     foreach (char c in StatusText.Text.ToCharArray())
5152                     {
5153                         if (c == ' ' || c == ' ')
5154                         {
5155                             isSpace = true;
5156                         }
5157                         else
5158                         {
5159                             isSpace = false;
5160                             break;
5161                         }
5162                     }
5163                     if (isSpace)
5164                     {
5165                         e.Handled = true;
5166                         StatusText.Text = "";
5167                         JumpUnreadMenuItem_Click(null, null);
5168                     }
5169                 }
5170             }
5171             this.StatusText_TextChanged(null, null);
5172         }
5173
5174         private void StatusText_TextChanged(object sender, EventArgs e)
5175         {
5176             //文字数カウント
5177             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5178             lblLen.Text = pLen.ToString();
5179             if (pLen < 0)
5180             {
5181                 StatusText.ForeColor = Color.Red;
5182             }
5183             else
5184             {
5185                 StatusText.ForeColor = _clInputFont;
5186             }
5187             if (string.IsNullOrEmpty(StatusText.Text))
5188             {
5189                 this.inReplyTo = null;
5190             }
5191         }
5192
5193         /// <summary>
5194         /// ツイート投稿前のフッター付与などの前処理を行います
5195         /// </summary>
5196         private string FormatStatusText(string statusText)
5197         {
5198             statusText = statusText.Replace("\r\n", "\n");
5199
5200             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5201             {
5202                 // URLと全角文字の切り離し
5203                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5204             }
5205
5206             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5207             {
5208                 // 文中の全角スペースを半角スペース1個にする
5209                 statusText = statusText.Replace(" ", " ");
5210             }
5211
5212             // DM の場合はこれ以降の処理を行わない
5213             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5214                 return statusText;
5215
5216             bool disableFooter;
5217             if (this._cfgCommon.PostShiftEnter)
5218             {
5219                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5220             }
5221             else
5222             {
5223                 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5224                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5225                 else
5226                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5227             }
5228
5229             if (statusText.Contains("RT @"))
5230                 disableFooter = true;
5231
5232             var header = "";
5233             var footer = "";
5234
5235             var hashtag = this.HashMgr.UseHash;
5236             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5237             {
5238                 if (HashMgr.IsHead)
5239                     header = HashMgr.UseHash + " ";
5240                 else
5241                     footer = " " + HashMgr.UseHash;
5242             }
5243
5244             if (!disableFooter)
5245             {
5246                 if (this._cfgLocal.UseRecommendStatus)
5247                 {
5248                     // 推奨ステータスを使用する
5249                     footer += this.recommendedStatusFooter;
5250                 }
5251                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5252                 {
5253                     // テキストボックスに入力されている文字列を使用する
5254                     footer += " " + this._cfgLocal.StatusText.Trim();
5255                 }
5256             }
5257
5258             statusText = header + statusText + footer;
5259
5260             if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5261             {
5262                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5263                 // 参照: https://support.twitter.com/articles/14020
5264
5265                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5266                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
5267                 {
5268                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5269                     statusText = '\u200b' + statusText;
5270                 }
5271             }
5272
5273             return statusText;
5274         }
5275
5276         /// <summary>
5277         /// 投稿欄に表示する入力可能な文字数を計算します
5278         /// </summary>
5279         private int GetRestStatusCount(string statusText)
5280         {
5281             //文字数カウント
5282             var remainCount = this.tw.GetTextLengthRemain(statusText);
5283
5284             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5285             {
5286                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5287             }
5288
5289             return remainCount;
5290         }
5291
5292         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5293         {
5294             if (sender != this._curList)
5295                 return;
5296
5297             var listCache = this._listItemCache;
5298             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5299             {
5300                 // If the newly requested cache is a subset of the old cache,
5301                 // no need to rebuild everything, so do nothing.
5302                 return;
5303             }
5304
5305             // Now we need to rebuild the cache.
5306             this.CreateCache(e.StartIndex, e.EndIndex);
5307         }
5308
5309         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5310         {
5311             var listCache = this._listItemCache;
5312             if (listCache != null && listCache.TargetList == sender)
5313             {
5314                 ListViewItem item;
5315                 PostClass cacheItemPost;
5316                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5317                 {
5318                     e.Item = item;
5319                     return;
5320                 }
5321             }
5322
5323             // A cache miss, so create a new ListViewItem and pass it back.
5324             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5325             try
5326             {
5327                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5328             }
5329             catch (Exception)
5330             {
5331                 // 不正な要求に対する間に合わせの応答
5332                 string[] sitem = {"", "", "", "", "", "", "", ""};
5333                 e.Item = new ImageListViewItem(sitem);
5334             }
5335         }
5336
5337         private void CreateCache(int startIndex, int endIndex)
5338         {
5339             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5340
5341             if (tabInfo.AllCount == 0)
5342                 return;
5343
5344             // キャッシュ要求(要求範囲±30を作成)
5345             startIndex = Math.Max(startIndex - 30, 0);
5346             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5347
5348             var cacheLength = endIndex - startIndex + 1;
5349
5350             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5351             var listItems = Enumerable.Range(0, cacheLength)
5352                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5353                 .ToArray();
5354
5355             var listCache = new ListViewItemCache
5356             {
5357                 TargetList = this._curList,
5358                 StartIndex = startIndex,
5359                 EndIndex = endIndex,
5360                 Post = posts,
5361                 ListItem = listItems,
5362             };
5363
5364             Interlocked.Exchange(ref this._listItemCache, listCache);
5365         }
5366
5367         /// <summary>
5368         /// DetailsListView のための ListViewItem のキャッシュを消去する
5369         /// </summary>
5370         private void PurgeListViewItemCache()
5371         {
5372             Interlocked.Exchange(ref this._listItemCache, null);
5373         }
5374
5375         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5376         {
5377             StringBuilder mk = new StringBuilder();
5378             //if (Post.IsDeleted) mk.Append("×");
5379             //if (Post.IsMark) mk.Append("♪");
5380             //if (Post.IsProtect) mk.Append("Ю");
5381             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5382             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5383             ImageListViewItem itm;
5384             if (Post.RetweetedId == null)
5385             {
5386                 string[] sitem= {"",
5387                                  Post.Nickname,
5388                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5389                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5390                                  Post.ScreenName,
5391                                  "",
5392                                  mk.ToString(),
5393                                  Post.Source};
5394                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5395             }
5396             else
5397             {
5398                 string[] sitem = {"",
5399                                   Post.Nickname,
5400                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5401                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5402                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5403                                   "",
5404                                   mk.ToString(),
5405                                   Post.Source};
5406                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5407             }
5408             itm.StateIndex = Post.StateIndex;
5409
5410             bool read = Post.IsRead;
5411             //未読管理していなかったら既読として扱う
5412             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5413             ChangeItemStyleRead(read, itm, Post, null);
5414             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5415             return itm;
5416         }
5417
5418         /// <summary>
5419         /// 全てのタブの振り分けルールを反映し直します
5420         /// </summary>
5421         private void ApplyPostFilters()
5422         {
5423             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5424             {
5425                 this.PurgeListViewItemCache();
5426                 this._curPost = null;
5427                 this._curItemIndex = -1;
5428                 this._statuses.FilterAll();
5429
5430                 foreach (TabPage tabPage in this.ListTab.TabPages)
5431                 {
5432                     var tab = this._statuses.Tabs[tabPage.Text];
5433
5434                     var listview = (DetailsListView)tabPage.Tag;
5435                     using (ControlTransaction.Update(listview))
5436                     {
5437                         listview.VirtualListSize = tab.AllCount;
5438                     }
5439
5440                     if (this._cfgCommon.TabIconDisp)
5441                     {
5442                         if (tab.UnreadCount > 0)
5443                             tabPage.ImageIndex = 0;
5444                         else
5445                             tabPage.ImageIndex = -1;
5446                     }
5447                 }
5448
5449                 if (!this._cfgCommon.TabIconDisp)
5450                     this.ListTab.Refresh();
5451
5452                 SetMainWindowTitle();
5453                 SetStatusLabelUrl();
5454             }
5455         }
5456
5457         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5458         {
5459             e.DrawDefault = true;
5460         }
5461
5462         private void MyList_HScrolled(object sender, EventArgs e)
5463         {
5464             DetailsListView listView = (DetailsListView)sender;
5465             listView.Refresh();
5466         }
5467
5468         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5469         {
5470             if (e.State == 0) return;
5471             e.DrawDefault = false;
5472
5473             SolidBrush brs2 = null;
5474             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5475             {
5476                 if (e.Item.BackColor == _clSelf)
5477                     brs2 = _brsBackColorMine;
5478                 else if (e.Item.BackColor == _clAtSelf)
5479                     brs2 = _brsBackColorAt;
5480                 else if (e.Item.BackColor == _clTarget)
5481                     brs2 = _brsBackColorYou;
5482                 else if (e.Item.BackColor == _clAtTarget)
5483                     brs2 = _brsBackColorAtYou;
5484                 else if (e.Item.BackColor == _clAtFromTarget)
5485                     brs2 = _brsBackColorAtFromTarget;
5486                 else if (e.Item.BackColor == _clAtTo)
5487                     brs2 = _brsBackColorAtTo;
5488                 else
5489                     brs2 = _brsBackColorNone;
5490             }
5491             else
5492             {
5493                 //選択中の行
5494                 if (((Control)sender).Focused)
5495                     brs2 = _brsHighLight;
5496                 else
5497                     brs2 = _brsDeactiveSelection;
5498             }
5499             e.Graphics.FillRectangle(brs2, e.Bounds);
5500             e.DrawFocusRectangle();
5501             this.DrawListViewItemIcon(e);
5502         }
5503
5504         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5505         {
5506             if (e.ItemState == 0) return;
5507
5508             if (e.ColumnIndex > 0)
5509             {
5510                 //アイコン以外の列
5511                 RectangleF rct = e.Bounds;
5512                 rct.Width = e.Header.Width;
5513                 int fontHeight = e.Item.Font.Height;
5514                 if (_iconCol)
5515                 {
5516                     rct.Y += fontHeight;
5517                     rct.Height -= fontHeight;
5518                 }
5519
5520                 int heightDiff;
5521                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5522
5523                 //if (heightDiff > fontHeight * 0.7)
5524                 //{
5525                 //    rct.Height += fontHeight;
5526                 //    drawLineCount += 1;
5527                 //}
5528
5529                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5530                 if (!_iconCol && drawLineCount <= 1)
5531                 {
5532                     //rct.Inflate(0, heightDiff / -2);
5533                     //rct.Height += fontHeight / 2;
5534                 }
5535                 else if (heightDiff < fontHeight * 0.7)
5536                 {
5537                     //最終行が70%以上欠けていたら、最終行は表示しない
5538                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5539                     rct.Height = (fontHeight * drawLineCount) - 1;
5540                 }
5541                 else
5542                 {
5543                     drawLineCount += 1;
5544                 }
5545
5546                 //if (!_iconCol && drawLineCount > 1)
5547                 //{
5548                 //    rct.Y += fontHeight * 0.2;
5549                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5550                 //}
5551
5552                 if (rct.Width > 0)
5553                 {
5554                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5555                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5556                         _clUnread;
5557
5558                     if (_iconCol)
5559                     {
5560                         Rectangle rctB = e.Bounds;
5561                         rctB.Width = e.Header.Width;
5562                         rctB.Height = fontHeight;
5563
5564                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5565                         {
5566                             TextRenderer.DrawText(e.Graphics,
5567                                                     e.Item.SubItems[2].Text,
5568                                                     e.Item.Font,
5569                                                     Rectangle.Round(rct),
5570                                                     color,
5571                                                     TextFormatFlags.WordBreak |
5572                                                     TextFormatFlags.EndEllipsis |
5573                                                     TextFormatFlags.GlyphOverhangPadding |
5574                                                     TextFormatFlags.NoPrefix);
5575                             TextRenderer.DrawText(e.Graphics,
5576                                                     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 + "]",
5577                                                     fnt,
5578                                                     rctB,
5579                                                     color,
5580                                                     TextFormatFlags.SingleLine |
5581                                                     TextFormatFlags.EndEllipsis |
5582                                                     TextFormatFlags.GlyphOverhangPadding |
5583                                                     TextFormatFlags.NoPrefix);
5584                         }
5585                     }
5586                     else if (drawLineCount == 1)
5587                     {
5588                         TextRenderer.DrawText(e.Graphics,
5589                                                 e.SubItem.Text,
5590                                                 e.Item.Font,
5591                                                 Rectangle.Round(rct),
5592                                                 color,
5593                                                 TextFormatFlags.SingleLine |
5594                                                 TextFormatFlags.EndEllipsis |
5595                                                 TextFormatFlags.GlyphOverhangPadding |
5596                                                 TextFormatFlags.NoPrefix |
5597                                                 TextFormatFlags.VerticalCenter);
5598                     }
5599                     else
5600                     {
5601                         TextRenderer.DrawText(e.Graphics,
5602                                                 e.SubItem.Text,
5603                                                 e.Item.Font,
5604                                                 Rectangle.Round(rct),
5605                                                 color,
5606                                                 TextFormatFlags.WordBreak |
5607                                                 TextFormatFlags.EndEllipsis |
5608                                                 TextFormatFlags.GlyphOverhangPadding |
5609                                                 TextFormatFlags.NoPrefix);
5610                     }
5611                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5612                 }
5613             }
5614         }
5615
5616         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5617         {
5618             if (_iconSz == 0) return;
5619
5620             ImageListViewItem item = (ImageListViewItem)e.Item;
5621
5622             //e.Bounds.Leftが常に0を指すから自前で計算
5623             Rectangle itemRect = item.Bounds;
5624             var col0 = e.Item.ListView.Columns[0];
5625             itemRect.Width = col0.Width;
5626
5627             if (col0.DisplayIndex > 0)
5628             {
5629                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5630                 {
5631                     if (clm.DisplayIndex < col0.DisplayIndex)
5632                         itemRect.X += clm.Width;
5633                 }
5634             }
5635
5636             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5637             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5638             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5639
5640             Rectangle iconRect;
5641             var img = item.Image;
5642             if (img != null)
5643             {
5644                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5645                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5646
5647                 if (iconRect.Width > 0)
5648                 {
5649                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5650                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5651                     try
5652                     {
5653                         e.Graphics.DrawImage(img.Image, iconRect);
5654                     }
5655                     catch (ArgumentException)
5656                     {
5657                         item.RefreshImageAsync();
5658                     }
5659                 }
5660             }
5661             else
5662             {
5663                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5664                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5665
5666                 item.GetImageAsync();
5667             }
5668
5669             if (item.StateIndex > -1)
5670             {
5671                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5672                 if (stateRect.Width > 0)
5673                 {
5674                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5675                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5676                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5677                 }
5678             }
5679         }
5680
5681         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5682         {
5683             base.ScaleControl(factor, specified);
5684
5685             ScaleChildControl(this.TabImage, factor);
5686
5687             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5688             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5689
5690             foreach (var listview in listviews)
5691             {
5692                 ScaleChildControl(listview, factor);
5693             }
5694         }
5695
5696         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5697         //{
5698         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5699         //    if (item.StateImageIndex > -1)
5700         //    {
5701         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5702         //        //Rectangle itemRect = item.Bounds;
5703         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5704
5705         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5706         //        //{
5707         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5708         //        //    {
5709         //        //        itemRect.X += clm.Width;
5710         //        //    }
5711         //        //}
5712
5713         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5714         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5715
5716         //        if (rct.Width > 0)
5717         //        {
5718         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5719         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5720         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5721         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5722         //        }
5723         //    }
5724         //}
5725
5726         private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5727         {
5728             var tab = this._statuses.Tabs[this._curTab.Text];
5729
5730             if (tab.AllCount == 0)
5731             {
5732                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5733                 return;
5734             }
5735
5736             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5737
5738             int startIndex;
5739             switch (searchType)
5740             {
5741                 case SEARCHTYPE.NextSearch: // 次を検索
5742                     if (selectedIndex != -1)
5743                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5744                     else
5745                         startIndex = 0;
5746                     break;
5747                 case SEARCHTYPE.PrevSearch: // 前を検索
5748                     if (selectedIndex != -1)
5749                         startIndex = Math.Max(selectedIndex - 1, 0);
5750                     else
5751                         startIndex = tab.AllCount - 1;
5752                     break;
5753                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5754                 default:
5755                     if (selectedIndex != -1)
5756                         startIndex = selectedIndex;
5757                     else
5758                         startIndex = 0;
5759                     break;
5760             }
5761
5762             Func<string, bool> stringComparer;
5763             try
5764             {
5765                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5766             }
5767             catch (ArgumentException)
5768             {
5769                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5770                 return;
5771             }
5772
5773             var reverse = searchType == SEARCHTYPE.PrevSearch;
5774             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5775                 .DefaultIfEmpty(-1).First();
5776
5777             if (foundIndex == -1)
5778             {
5779                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5780                 return;
5781             }
5782
5783             this.SelectListItem(this._curList, foundIndex);
5784             this._curList.EnsureVisible(foundIndex);
5785         }
5786
5787         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5788         {
5789             // 検索メニュー
5790             this.ShowSearchDialog();
5791         }
5792
5793         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5794         {
5795             var previousSearch = this.SearchDialog.ResultOptions;
5796             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5797             {
5798                 this.SearchDialog.Reset();
5799                 this.ShowSearchDialog();
5800                 return;
5801             }
5802
5803             // 次を検索
5804             this.DoTabSearch(
5805                 previousSearch.Query,
5806                 previousSearch.CaseSensitive,
5807                 previousSearch.UseRegex,
5808                 SEARCHTYPE.NextSearch);
5809         }
5810
5811         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5812         {
5813             var previousSearch = this.SearchDialog.ResultOptions;
5814             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5815             {
5816                 this.SearchDialog.Reset();
5817                 this.ShowSearchDialog();
5818                 return;
5819             }
5820
5821             // 前を検索
5822             this.DoTabSearch(
5823                 previousSearch.Query,
5824                 previousSearch.CaseSensitive,
5825                 previousSearch.UseRegex,
5826                 SEARCHTYPE.PrevSearch);
5827         }
5828
5829         /// <summary>
5830         /// 検索ダイアログを表示し、検索を実行します
5831         /// </summary>
5832         private void ShowSearchDialog()
5833         {
5834             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5835             {
5836                 this.TopMost = this._cfgCommon.AlwaysTop;
5837                 return;
5838             }
5839             this.TopMost = this._cfgCommon.AlwaysTop;
5840
5841             var searchOptions = this.SearchDialog.ResultOptions;
5842             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5843             {
5844                 if (searchOptions.NewTab)
5845                 {
5846                     var tabName = Properties.Resources.SearchResults_TabName;
5847
5848                     try
5849                     {
5850                         tabName = this._statuses.MakeTabName(tabName);
5851                     }
5852                     catch (TabException ex)
5853                     {
5854                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5855                     }
5856
5857                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5858                     this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5859
5860                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5861
5862                     Func<string, bool> stringComparer;
5863                     try
5864                     {
5865                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5866                     }
5867                     catch (ArgumentException)
5868                     {
5869                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5870                         return;
5871                     }
5872
5873                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5874                     if (foundIndices.Length == 0)
5875                     {
5876                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5877                         return;
5878                     }
5879
5880                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5881
5882                     var resultTab = this._statuses.Tabs[tabName];
5883                     foreach (var post in foundPosts)
5884                     {
5885                         resultTab.AddPostToInnerStorage(post);
5886                     }
5887
5888                     this._statuses.DistributePosts();
5889                     this.RefreshTimeline();
5890
5891                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5892                         .First(x => x.Text == tabName);
5893
5894                     this.ListTab.SelectedTab = tabPage;
5895                 }
5896                 else
5897                 {
5898                     this.DoTabSearch(
5899                         searchOptions.Query,
5900                         searchOptions.CaseSensitive,
5901                         searchOptions.UseRegex,
5902                         SEARCHTYPE.DialogSearch);
5903                 }
5904             }
5905             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5906             {
5907                 this.AddNewTabForSearch(searchOptions.Query);
5908             }
5909         }
5910
5911         /// <summary>発言検索に使用するメソッドを生成します</summary>
5912         /// <exception cref="ArgumentException">
5913         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5914         /// </exception>
5915         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5916         {
5917             if (useRegex)
5918             {
5919                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5920                 var regex = new Regex(query, regexOption);
5921
5922                 return x => regex.IsMatch(x);
5923             }
5924             else
5925             {
5926                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5927
5928                 return x => x.IndexOf(query, comparisonType) != -1;
5929             }
5930         }
5931
5932         private void AboutMenuItem_Click(object sender, EventArgs e)
5933         {
5934             using (TweenAboutBox about = new TweenAboutBox())
5935             {
5936                 about.ShowDialog(this);
5937             }
5938             this.TopMost = this._cfgCommon.AlwaysTop;
5939         }
5940
5941         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5942         {
5943             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5944             int idx = -1;
5945             DetailsListView lst = null;
5946
5947             if (ImageSelector.Enabled)
5948                 return;
5949
5950             //現在タブから最終タブまで探索
5951             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5952             {
5953                 //未読Index取得
5954                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5955                 if (idx > -1)
5956                 {
5957                     ListTab.SelectedIndex = i;
5958                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5959                     //_curTab = ListTab.TabPages[i];
5960                     break;
5961                 }
5962             }
5963
5964             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5965             if (idx == -1 && bgnIdx > 0)
5966             {
5967                 for (int i = 0; i < bgnIdx; i++)
5968                 {
5969                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5970                     if (idx > -1)
5971                     {
5972                         ListTab.SelectedIndex = i;
5973                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5974                         //_curTab = ListTab.TabPages[i];
5975                         break;
5976                     }
5977                 }
5978             }
5979
5980             //全部調べたが未読見つからず→先頭タブの最新発言へ
5981             if (idx == -1)
5982             {
5983                 ListTab.SelectedIndex = 0;
5984                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5985                 //_curTab = ListTab.TabPages[0];
5986                 if (_statuses.SortOrder == SortOrder.Ascending)
5987                     idx = lst.VirtualListSize - 1;
5988                 else
5989                     idx = 0;
5990             }
5991
5992             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5993             {
5994                 SelectListItem(lst, idx);
5995                 if (_statuses.SortMode == ComparerMode.Id)
5996                 {
5997                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5998                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5999                     {
6000                         MoveTop();
6001                     }
6002                     else
6003                     {
6004                         lst.EnsureVisible(idx);
6005                     }
6006                 }
6007                 else
6008                 {
6009                     lst.EnsureVisible(idx);
6010                 }
6011             }
6012             lst.Focus();
6013         }
6014
6015         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6016         {
6017             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6018             {
6019                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6020                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6021             }
6022         }
6023
6024         private async void FavorareMenuItem_Click(object sender, EventArgs e)
6025         {
6026             if (_curList.SelectedIndices.Count > 0)
6027             {
6028                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6029                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6030             }
6031         }
6032
6033         private async void VerUpMenuItem_Click(object sender, EventArgs e)
6034         {
6035             await this.CheckNewVersion(false);
6036         }
6037
6038         private void RunTweenUp()
6039         {
6040             ProcessStartInfo pinfo = new ProcessStartInfo();
6041             pinfo.UseShellExecute = true;
6042             pinfo.WorkingDirectory = MyCommon.settingPath;
6043             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6044             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6045             try
6046             {
6047                 Process.Start(pinfo);
6048             }
6049             catch (Exception)
6050             {
6051                 MessageBox.Show("Failed to execute TweenUp3.exe.");
6052             }
6053         }
6054
6055         public class VersionInfo
6056         {
6057             public Version Version { get; set; }
6058             public Uri DownloadUri { get; set; }
6059             public string ReleaseNote { get; set; }
6060         }
6061
6062         /// <summary>
6063         /// OpenTween の最新バージョンの情報を取得します
6064         /// </summary>
6065         public async Task<VersionInfo> GetVersionInfoAsync()
6066         {
6067             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6068                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6069
6070             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6071                 .ConfigureAwait(false);
6072
6073             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6074             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6075
6076             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6077             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6078
6079             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6080
6081             return new VersionInfo
6082             {
6083                 Version = Version.Parse(msgHeader[0]),
6084                 DownloadUri = new Uri(msgHeader[1]),
6085                 ReleaseNote = msgBody,
6086             };
6087         }
6088
6089         private async Task CheckNewVersion(bool startup = false)
6090         {
6091             if (ApplicationSettings.VersionInfoUrl == null)
6092                 return; // 更新チェック無効化
6093
6094             try
6095             {
6096                 var versionInfo = await this.GetVersionInfoAsync();
6097
6098                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6099                 {
6100                     // 更新不要
6101                     if (!startup)
6102                     {
6103                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6104                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6105                         msgtext = MyCommon.ReplaceAppName(msgtext);
6106
6107                         MessageBox.Show(msgtext,
6108                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6109                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6110                     }
6111                     return;
6112                 }
6113
6114                 using (var dialog = new UpdateDialog())
6115                 {
6116                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6117                         MyCommon.GetReadableVersion(versionInfo.Version));
6118                     dialog.DetailsText = versionInfo.ReleaseNote;
6119
6120                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6121                     {
6122                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6123                     }
6124                 }
6125             }
6126             catch (Exception)
6127             {
6128                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6129                 if (!startup)
6130                 {
6131                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6132                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6133                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6134                 }
6135             }
6136         }
6137
6138         private async Task Colorize()
6139         {
6140             _colorize = false;
6141             await this.DispSelectedPost();
6142             //件数関連の場合、タイトル即時書き換え
6143             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6144                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6145                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6146                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6147             {
6148                 SetMainWindowTitle();
6149             }
6150             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6151             foreach (TabPage tb in ListTab.TabPages)
6152             {
6153                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6154                 {
6155                     if (this._cfgCommon.TabIconDisp)
6156                     {
6157                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6158                     }
6159                 }
6160             }
6161             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6162         }
6163
6164         public string createDetailHtml(string orgdata)
6165         {
6166             if (this._cfgLocal.UseTwemoji)
6167                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6168
6169             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6170         }
6171
6172         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6173         {
6174             if (sender.Equals(displayItem))
6175             {
6176                 this.ClearUserPicture();
6177
6178                 var img = displayItem.Image;
6179                 try
6180                 {
6181                     if (img != null)
6182                         img = await img.CloneAsync();
6183
6184                     UserPicture.Image = img;
6185                 }
6186                 catch (Exception)
6187                 {
6188                     UserPicture.ShowErrorImage();
6189                 }
6190             }
6191         }
6192
6193         private Task DispSelectedPost()
6194         {
6195             return this.DispSelectedPost(false);
6196         }
6197
6198         private PostClass displayPost = new PostClass();
6199
6200         /// <summary>
6201         /// サムネイル表示に使用する CancellationToken の生成元
6202         /// </summary>
6203         private CancellationTokenSource thumbnailTokenSource = null;
6204
6205         private async Task DispSelectedPost(bool forceupdate)
6206         {
6207             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6208                 return;
6209
6210             var oldDisplayPost = this.displayPost;
6211             this.displayPost = this._curPost;
6212
6213             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6214                 return;
6215
6216             if (displayItem != null)
6217             {
6218                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6219                 displayItem = null;
6220             }
6221             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6222             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6223
6224             using (ControlTransaction.Update(this.TableLayoutPanel1))
6225             {
6226                 SourceLinkLabel.Text = this._curPost.Source;
6227                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6228                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6229
6230                 string nameText;
6231                 if (_curPost.IsDm)
6232                 {
6233                     if (_curPost.IsOwl)
6234                         nameText = "DM FROM <- ";
6235                     else
6236                         nameText = "DM TO -> ";
6237                 }
6238                 else
6239                 {
6240                     nameText = "";
6241                 }
6242                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6243                 if (_curPost.RetweetedId != null)
6244                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6245
6246                 NameLabel.Text = nameText;
6247                 NameLabel.Tag = _curPost.ScreenName;
6248
6249                 var nameForeColor = SystemColors.ControlText;
6250                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6251                     nameForeColor = this._clOWL;
6252                 if (_curPost.RetweetedId != null)
6253                     nameForeColor = this._clRetweet;
6254                 if (_curPost.IsFav)
6255                     nameForeColor = this._clFav;
6256                 NameLabel.ForeColor = nameForeColor;
6257
6258                 this.ClearUserPicture();
6259
6260                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6261                 {
6262                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6263                     try
6264                     {
6265                         UserPicture.Image = image?.Clone();
6266                     }
6267                     catch (Exception)
6268                     {
6269                         UserPicture.ShowErrorImage();
6270                     }
6271                 }
6272
6273                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6274             }
6275
6276             if (DumpPostClassToolStripMenuItem.Checked)
6277             {
6278                 StringBuilder sb = new StringBuilder(512);
6279
6280                 sb.Append("-----Start PostClass Dump<br>");
6281                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6282                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6283                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6284                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6285                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6286                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6287                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6288                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6289                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6290                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6291                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6292                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6293                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6294                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6295                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6296
6297                 foreach (string nm in _curPost.ReplyToList)
6298                 {
6299                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6300                 }
6301
6302                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6303                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6304                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6305                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6306                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6307                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6308                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6309                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6310                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6311                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6312
6313                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6314                 if (_curPost.Media.Count > 0)
6315                 {
6316                     for (int i = 0; i < _curPost.Media.Count; i++)
6317                     {
6318                         var info = _curPost.Media[i];
6319                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6320                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6321                     }
6322                 }
6323                 sb.Append("-----End PostClass Dump<br>");
6324
6325                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6326                 return;
6327             }
6328
6329             var loadTasks = new List<Task>();
6330
6331             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6332             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6333             if (_curPost.StatusId != oldDisplayPost.StatusId)
6334             {
6335                 using (ControlTransaction.Update(this.PostBrowser))
6336                 {
6337                     this.PostBrowser.DocumentText =
6338                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6339
6340                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6341                 }
6342
6343                 this.SplitContainer3.Panel2Collapsed = true;
6344
6345                 if (this._cfgCommon.PreviewEnable)
6346                 {
6347                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6348                     oldTokenSource?.Cancel();
6349
6350                     var token = this.thumbnailTokenSource.Token;
6351                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6352                 }
6353
6354                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6355             }
6356
6357             try
6358             {
6359                 await Task.WhenAll(loadTasks);
6360             }
6361             catch (OperationCanceledException) { }
6362         }
6363
6364         /// <summary>
6365         /// 発言詳細欄のツイートURLを展開する
6366         /// </summary>
6367         private async Task AppendQuoteTweetAsync(PostClass post)
6368         {
6369             var quoteStatusIds = post.QuoteStatusIds;
6370             if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6371                 return;
6372
6373             // 「読み込み中」テキストを表示
6374             var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6375
6376             var loadingReplyHtml = string.Empty;
6377             if (post.InReplyToStatusId != null)
6378                 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6379
6380             var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6381
6382             using (ControlTransaction.Update(this.PostBrowser))
6383                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6384
6385             // 引用ツイートを読み込み
6386             var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6387
6388             if (post.InReplyToStatusId != null)
6389                 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6390
6391             var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6392
6393             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6394             if (this._curPost != post || this._curPost.IsDeleted)
6395                 return;
6396
6397             body = post.Text + string.Concat(quoteHtmls);
6398
6399             using (ControlTransaction.Update(this.PostBrowser))
6400                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6401         }
6402
6403         private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6404         {
6405             PostClass post = this._statuses[statusId];
6406             if (post == null)
6407             {
6408                 try
6409                 {
6410                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6411                         .ConfigureAwait(false);
6412                 }
6413                 catch (WebApiException ex)
6414                 {
6415                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message), isReply);
6416                 }
6417
6418                 post.IsRead = true;
6419                 if (!this._statuses.AddQuoteTweet(post))
6420                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6421             }
6422
6423             return FormatQuoteTweetHtml(post, isReply);
6424         }
6425
6426         internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6427         {
6428             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6429                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6430                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6431                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6432
6433             return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6434         }
6435
6436         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6437         {
6438             var blockClassName = "quote-tweet";
6439
6440             if (isReply)
6441                 blockClassName += " reply";
6442
6443             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6444                 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6445                 "</a>";
6446         }
6447
6448         /// <summary>
6449         /// 指定されたHTMLからリンクを除去します
6450         /// </summary>
6451         internal static string StripLinkTagHtml(string html)
6452         {
6453             // a 要素はネストされていない前提の正規表現パターン
6454             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6455         }
6456
6457         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6458         {
6459             await this.OpenApplicationWebsite();
6460         }
6461
6462         private async Task OpenApplicationWebsite()
6463         {
6464             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6465         }
6466
6467         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6468         {
6469             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6470         }
6471
6472         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6473         {
6474             if (ListTab.SelectedTab != null)
6475             {
6476                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6477                 {
6478                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6479                     if (pnl.Controls["comboSearch"].Focused ||
6480                         pnl.Controls["comboLang"].Focused ||
6481                         pnl.Controls["buttonSearch"].Focused) return;
6482                 }
6483
6484                 if (e.Control || e.Shift || e.Alt)
6485                     this._anchorFlag = false;
6486
6487                 Task asyncTask;
6488                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6489                 {
6490                     e.Handled = true;
6491                     e.SuppressKeyPress = true;
6492                 }
6493
6494                 if (asyncTask != null)
6495                     await asyncTask;
6496             }
6497         }
6498
6499         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6500
6501         private void InitializeShortcuts()
6502         {
6503             this.shortcutCommands = new[]
6504             {
6505                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6506                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6507                     .FocusedOn(FocusedControl.ListTab)
6508                     .Do(() => SendKeys.Send("{DOWN}")),
6509
6510                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6511                     .FocusedOn(FocusedControl.ListTab)
6512                     .Do(() => SendKeys.Send("{UP}")),
6513
6514                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6515                     .FocusedOn(FocusedControl.ListTab)
6516                     .Do(() => SendKeys.Send("{PGDN}")),
6517
6518                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6519                     .FocusedOn(FocusedControl.ListTab)
6520                     .Do(() => SendKeys.Send("{PGUP}")),
6521
6522                 ShortcutCommand.Create(Keys.F1)
6523                     .Do(() => this.OpenApplicationWebsite()),
6524
6525                 ShortcutCommand.Create(Keys.F3)
6526                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6527
6528                 ShortcutCommand.Create(Keys.F5)
6529                     .Do(() => this.DoRefresh()),
6530
6531                 ShortcutCommand.Create(Keys.F6)
6532                     .Do(() => this.GetReplyAsync()),
6533
6534                 ShortcutCommand.Create(Keys.F7)
6535                     .Do(() => this.GetDirectMessagesAsync()),
6536
6537                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6538                     .NotFocusedOn(FocusedControl.StatusText)
6539                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6540
6541                 ShortcutCommand.Create(Keys.G)
6542                     .NotFocusedOn(FocusedControl.StatusText)
6543                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6544
6545                 ShortcutCommand.Create(Keys.Right, Keys.N)
6546                     .FocusedOn(FocusedControl.ListTab)
6547                     .Do(() => this.GoRelPost(forward: true)),
6548
6549                 ShortcutCommand.Create(Keys.Left, Keys.P)
6550                     .FocusedOn(FocusedControl.ListTab)
6551                     .Do(() => this.GoRelPost(forward: false)),
6552
6553                 ShortcutCommand.Create(Keys.OemPeriod)
6554                     .FocusedOn(FocusedControl.ListTab)
6555                     .Do(() => this.GoAnchor()),
6556
6557                 ShortcutCommand.Create(Keys.I)
6558                     .FocusedOn(FocusedControl.ListTab)
6559                     .OnlyWhen(() => this.StatusText.Enabled)
6560                     .Do(() => this.StatusText.Focus()),
6561
6562                 ShortcutCommand.Create(Keys.Enter)
6563                     .FocusedOn(FocusedControl.ListTab)
6564                     .Do(() => this.MakeReplyOrDirectStatus()),
6565
6566                 ShortcutCommand.Create(Keys.R)
6567                     .FocusedOn(FocusedControl.ListTab)
6568                     .Do(() => this.DoRefresh()),
6569
6570                 ShortcutCommand.Create(Keys.L)
6571                     .FocusedOn(FocusedControl.ListTab)
6572                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6573
6574                 ShortcutCommand.Create(Keys.H)
6575                     .FocusedOn(FocusedControl.ListTab)
6576                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6577
6578                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6579                     .FocusedOn(FocusedControl.ListTab)
6580                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6581
6582                 ShortcutCommand.Create(Keys.S)
6583                     .FocusedOn(FocusedControl.ListTab)
6584                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6585
6586                 ShortcutCommand.Create(Keys.A)
6587                     .FocusedOn(FocusedControl.ListTab)
6588                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6589
6590                 // ] in_reply_to参照元へ戻る
6591                 ShortcutCommand.Create(Keys.Oem4)
6592                     .FocusedOn(FocusedControl.ListTab)
6593                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6594
6595                 // [ in_reply_toへジャンプ
6596                 ShortcutCommand.Create(Keys.Oem6)
6597                     .FocusedOn(FocusedControl.ListTab)
6598                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6599
6600                 ShortcutCommand.Create(Keys.Escape)
6601                     .FocusedOn(FocusedControl.ListTab)
6602                     .Do(() => {
6603                         this._anchorFlag = false;
6604                         if (ListTab.SelectedTab != null)
6605                         {
6606                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6607                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6608                             {
6609                                 var relTp = ListTab.SelectedTab;
6610                                 RemoveSpecifiedTab(relTp.Text, false);
6611                                 SaveConfigsTabs();
6612                             }
6613                         }
6614                     }),
6615
6616                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6617                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6618                     .FocusedOn(FocusedControl.ListTab)
6619                     .Do(() => this._anchorFlag = false, preventDefault: false),
6620
6621                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6622                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6623                     .FocusedOn(FocusedControl.PostBrowser)
6624                     .Do(() => { }),
6625
6626                 ShortcutCommand.Create(Keys.Control | Keys.R)
6627                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6628
6629                 ShortcutCommand.Create(Keys.Control | Keys.D)
6630                     .Do(() => this.doStatusDelete()),
6631
6632                 ShortcutCommand.Create(Keys.Control | Keys.M)
6633                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6634
6635                 ShortcutCommand.Create(Keys.Control | Keys.S)
6636                     .Do(() => this.FavoriteChange(FavAdd: true)),
6637
6638                 ShortcutCommand.Create(Keys.Control | Keys.I)
6639                     .Do(() => this.doRepliedStatusOpen()),
6640
6641                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6642                     .Do(() => this.doQuoteOfficial()),
6643
6644                 ShortcutCommand.Create(Keys.Control | Keys.B)
6645                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6646
6647                 ShortcutCommand.Create(Keys.Control | Keys.T)
6648                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6649
6650                 ShortcutCommand.Create(Keys.Control | Keys.L)
6651                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6652
6653                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6654                     .NotFocusedOn(FocusedControl.PostBrowser)
6655                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6656
6657                 ShortcutCommand.Create(Keys.Control | Keys.F)
6658                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6659
6660                 ShortcutCommand.Create(Keys.Control | Keys.U)
6661                     .Do(() => this.ShowUserTimeline()),
6662
6663                 ShortcutCommand.Create(Keys.Control | Keys.H)
6664                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6665
6666                 ShortcutCommand.Create(Keys.Control | Keys.G)
6667                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6668
6669                 ShortcutCommand.Create(Keys.Control | Keys.O)
6670                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6671
6672                 ShortcutCommand.Create(Keys.Control | Keys.E)
6673                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6674
6675                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6676                     .FocusedOn(FocusedControl.ListTab)
6677                     .Do(() => this._colorize = true, preventDefault: false),
6678
6679                 ShortcutCommand.Create(Keys.Control | Keys.N)
6680                     .FocusedOn(FocusedControl.ListTab)
6681                     .Do(() => this.GoNextTab(forward: true)),
6682
6683                 ShortcutCommand.Create(Keys.Control | Keys.P)
6684                     .FocusedOn(FocusedControl.ListTab)
6685                     .Do(() => this.GoNextTab(forward: false)),
6686
6687                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6688                     .FocusedOn(FocusedControl.ListTab)
6689                     .Do(() => this.CopyStot()),
6690
6691                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6692                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6693                     .FocusedOn(FocusedControl.ListTab)
6694                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6695                     .Do(() => this.ListTab.SelectedIndex = 0),
6696
6697                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6698                     .FocusedOn(FocusedControl.ListTab)
6699                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6700                     .Do(() => this.ListTab.SelectedIndex = 1),
6701
6702                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6703                     .FocusedOn(FocusedControl.ListTab)
6704                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6705                     .Do(() => this.ListTab.SelectedIndex = 2),
6706
6707                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6708                     .FocusedOn(FocusedControl.ListTab)
6709                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6710                     .Do(() => this.ListTab.SelectedIndex = 3),
6711
6712                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6713                     .FocusedOn(FocusedControl.ListTab)
6714                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6715                     .Do(() => this.ListTab.SelectedIndex = 4),
6716
6717                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6718                     .FocusedOn(FocusedControl.ListTab)
6719                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6720                     .Do(() => this.ListTab.SelectedIndex = 5),
6721
6722                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6723                     .FocusedOn(FocusedControl.ListTab)
6724                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6725                     .Do(() => this.ListTab.SelectedIndex = 6),
6726
6727                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6728                     .FocusedOn(FocusedControl.ListTab)
6729                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6730                     .Do(() => this.ListTab.SelectedIndex = 7),
6731
6732                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6733                     .FocusedOn(FocusedControl.ListTab)
6734                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6735
6736                 ShortcutCommand.Create(Keys.Control | Keys.A)
6737                     .FocusedOn(FocusedControl.StatusText)
6738                     .Do(() => this.StatusText.SelectAll()),
6739
6740                 ShortcutCommand.Create(Keys.Control | Keys.V)
6741                     .FocusedOn(FocusedControl.StatusText)
6742                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6743
6744                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6745                     .FocusedOn(FocusedControl.StatusText)
6746                     .Do(() => {
6747                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6748                         {
6749                             var inReplyToStatusId = this.inReplyTo?.Item1;
6750                             var inReplyToScreenName = this.inReplyTo?.Item2;
6751                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6752                         }
6753                         _hisIdx -= 1;
6754                         if (_hisIdx < 0) _hisIdx = 0;
6755
6756                         var historyItem = this._history[this._hisIdx];
6757                         StatusText.Text = historyItem.status;
6758                         StatusText.SelectionStart = StatusText.Text.Length;
6759                         if (historyItem.inReplyToId != null)
6760                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6761                         else
6762                             this.inReplyTo = null;
6763                     }),
6764
6765                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6766                     .FocusedOn(FocusedControl.StatusText)
6767                     .Do(() => {
6768                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6769                         {
6770                             var inReplyToStatusId = this.inReplyTo?.Item1;
6771                             var inReplyToScreenName = this.inReplyTo?.Item2;
6772                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6773                         }
6774                         _hisIdx += 1;
6775                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6776
6777                         var historyItem = this._history[this._hisIdx];
6778                         StatusText.Text = historyItem.status;
6779                         StatusText.SelectionStart = StatusText.Text.Length;
6780                         if (historyItem.inReplyToId != null)
6781                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6782                         else
6783                             this.inReplyTo = null;
6784                     }),
6785
6786                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6787                     .FocusedOn(FocusedControl.StatusText)
6788                     .Do(() => {
6789                         if (ListTab.SelectedIndex == 0)
6790                         {
6791                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6792                         }
6793                         else
6794                         {
6795                             ListTab.SelectedIndex -= 1;
6796                         }
6797                         StatusText.Focus();
6798                     }),
6799
6800                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6801                     .FocusedOn(FocusedControl.StatusText)
6802                     .Do(() => {
6803                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6804                         {
6805                             ListTab.SelectedIndex = 0;
6806                         }
6807                         else
6808                         {
6809                             ListTab.SelectedIndex += 1;
6810                         }
6811                         StatusText.Focus();
6812                     }),
6813
6814                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6815                     .FocusedOn(FocusedControl.PostBrowser)
6816                     .Do(() => {
6817                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6818                         MultiLineMenuItem_Click(null, null);
6819                     }),
6820
6821                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6822                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6823
6824                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6825                     .Do(() => this.DoRefreshMore()),
6826
6827                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6828                     .Do(() => this.GetReplyAsync(loadMore: true)),
6829
6830                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6831                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6832
6833                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6834                     .NotFocusedOn(FocusedControl.StatusText)
6835                     .Do(() => this.DoRefreshMore()),
6836
6837                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6838                     .FocusedOn(FocusedControl.ListTab)
6839                     .Do(() => this.GoTopEnd(GoTop: true)),
6840
6841                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6842                     .FocusedOn(FocusedControl.ListTab)
6843                     .Do(() => this.GoTopEnd(GoTop: false)),
6844
6845                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6846                     .FocusedOn(FocusedControl.ListTab)
6847                     .Do(() => this.GoMiddle()),
6848
6849                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6850                     .FocusedOn(FocusedControl.ListTab)
6851                     .Do(() => this.GoLast()),
6852
6853                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6854                     .FocusedOn(FocusedControl.ListTab)
6855                     .Do(() => this.MoveMiddle()),
6856
6857                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6858                     .FocusedOn(FocusedControl.ListTab)
6859                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6860
6861                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6862                     .FocusedOn(FocusedControl.ListTab)
6863                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6864
6865                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6866                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6867                     .FocusedOn(FocusedControl.ListTab)
6868                     .Do(() => this.GoFav(forward: true)),
6869
6870                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6871                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6872                     .FocusedOn(FocusedControl.ListTab)
6873                     .Do(() => this.GoFav(forward: false)),
6874
6875                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6876                     .FocusedOn(FocusedControl.ListTab)
6877                     .Do(() => this.GoBackSelectPostChain()),
6878
6879                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6880                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6881
6882                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6883                     .OnlyWhen(() => this._curPost != null)
6884                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6885
6886                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6887                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6888
6889                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6890                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6891
6892                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6893                     .Do(() => this.PageDownPostBrowser(forward: false)),
6894
6895                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6896                     .Do(() => this.PageDownPostBrowser(forward: true)),
6897
6898                 // 別タブの同じ書き込みへ(ALT+←/→)
6899                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6900                     .FocusedOn(FocusedControl.ListTab)
6901                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6902
6903                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6904                     .FocusedOn(FocusedControl.ListTab)
6905                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6906
6907                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6908                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6909
6910                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6911                     .Do(() => this.CopyIdUri()),
6912
6913                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6914                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6915                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6916                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6917
6918                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6919                     .Do(() => this.FavoriteChange(FavAdd: false)),
6920
6921                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6922                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6923
6924                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6925                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6926
6927                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6928                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6929
6930                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6931                     .Do(() => this.doMoveToRTHome()),
6932
6933                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6934                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6935
6936                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6937                     .FocusedOn(FocusedControl.StatusText)
6938                     .Do(() => {
6939                         if (_curList != null && _curList.VirtualListSize != 0 &&
6940                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6941                         {
6942                             var idx = _curList.SelectedIndices[0] - 1;
6943                             SelectListItem(_curList, idx);
6944                             _curList.EnsureVisible(idx);
6945                         }
6946                     }),
6947
6948                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6949                     .FocusedOn(FocusedControl.StatusText)
6950                     .Do(() => {
6951                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6952                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6953                         {
6954                             var idx = _curList.SelectedIndices[0] + 1;
6955                             SelectListItem(_curList, idx);
6956                             _curList.EnsureVisible(idx);
6957                         }
6958                     }),
6959
6960                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6961                     .FocusedOn(FocusedControl.StatusText)
6962                     .Do(() => {
6963                         if (StatusText.SelectionStart > 0)
6964                         {
6965                             int endidx = StatusText.SelectionStart - 1;
6966                             string startstr = "";
6967                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6968                             {
6969                                 char c = StatusText.Text[i];
6970                                 if (Char.IsLetterOrDigit(c) || c == '_')
6971                                 {
6972                                     continue;
6973                                 }
6974                                 if (c == '@')
6975                                 {
6976                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6977                                     int cnt = AtIdSupl.ItemCount;
6978                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6979                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6980                                 }
6981                                 else if (c == '#')
6982                                 {
6983                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6984                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6985                                 }
6986                                 else
6987                                 {
6988                                     break;
6989                                 }
6990                             }
6991                         }
6992                     }),
6993
6994                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6995                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6996                     .FocusedOn(FocusedControl.ListTab)
6997                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6998
6999                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7000                     .FocusedOn(FocusedControl.ListTab)
7001                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
7002
7003                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7004                     .FocusedOn(FocusedControl.ListTab)
7005                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
7006
7007                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7008                     .FocusedOn(FocusedControl.ListTab)
7009                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
7010
7011                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7012                     .FocusedOn(FocusedControl.ListTab)
7013                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
7014
7015                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7016                     .FocusedOn(FocusedControl.ListTab)
7017                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
7018
7019                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7020                     .FocusedOn(FocusedControl.ListTab)
7021                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
7022
7023                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7024                     .FocusedOn(FocusedControl.ListTab)
7025                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
7026
7027                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7028                     .FocusedOn(FocusedControl.ListTab)
7029                     .Do(() => this.SetSortLastColumn()),
7030
7031                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7032                     .Do(() => this.FavoritesRetweetOfficial()),
7033
7034                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7035                     .Do(() => this.FavoritesRetweetUnofficial()),
7036
7037                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7038                     .Do(() => this.OpenUserAppointUrl()),
7039
7040                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7041                     .FocusedOn(FocusedControl.PostBrowser)
7042                     .Do(() => this.doReTweetUnofficial()),
7043
7044                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7045                     .OnlyWhen(() => this.ExistCurrentPost)
7046                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
7047
7048                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7049                     .Do(() => this.doReTweetUnofficial()),
7050
7051                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7052                     .Do(() => this.CopyUserId()),
7053
7054                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7055                     .Do(() => this.tweetThumbnail1.ScrollUp()),
7056
7057                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7058                     .Do(() => this.tweetThumbnail1.ScrollDown()),
7059
7060                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7061                     .FocusedOn(FocusedControl.ListTab)
7062                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7063                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7064             };
7065         }
7066
7067         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7068         {
7069             // Task を返す非同期処理があれば asyncTask に代入する
7070             asyncTask = null;
7071
7072             // ShortcutCommand に対応しているコマンドはここで処理される
7073             foreach (var command in this.shortcutCommands)
7074             {
7075                 if (command.IsMatch(keyData, focusedOn))
7076                 {
7077                     asyncTask = command.RunCommand();
7078                     return command.PreventDefault;
7079                 }
7080             }
7081
7082             return false;
7083         }
7084
7085         private void ScrollDownPostBrowser(bool forward)
7086         {
7087             var doc = PostBrowser.Document;
7088             if (doc == null) return;
7089
7090             var tags = doc.GetElementsByTagName("html");
7091             if (tags.Count > 0)
7092             {
7093                 if (forward)
7094                     tags[0].ScrollTop += this._fntDetail.Height;
7095                 else
7096                     tags[0].ScrollTop -= this._fntDetail.Height;
7097             }
7098         }
7099
7100         private void PageDownPostBrowser(bool forward)
7101         {
7102             var doc = PostBrowser.Document;
7103             if (doc == null) return;
7104
7105             var tags = doc.GetElementsByTagName("html");
7106             if (tags.Count > 0)
7107             {
7108                 if (forward)
7109                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7110                 else
7111                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7112             }
7113         }
7114
7115         private void GoNextTab(bool forward)
7116         {
7117             int idx = ListTab.SelectedIndex;
7118             if (forward)
7119             {
7120                 idx += 1;
7121                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7122             }
7123             else
7124             {
7125                 idx -= 1;
7126                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7127             }
7128             ListTab.SelectedIndex = idx;
7129         }
7130
7131         private void CopyStot()
7132         {
7133             string clstr = "";
7134             StringBuilder sb = new StringBuilder();
7135             bool IsProtected = false;
7136             bool isDm = false;
7137             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7138             foreach (int idx in _curList.SelectedIndices)
7139             {
7140                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7141                 if (post.IsProtect)
7142                 {
7143                     IsProtected = true;
7144                     continue;
7145                 }
7146                 if (post.IsDeleted) continue;
7147                 if (!isDm)
7148                 {
7149                     if (post.RetweetedId != null)
7150                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7151                     else
7152                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7153                 }
7154                 else
7155                 {
7156                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7157                 }
7158             }
7159             if (IsProtected)
7160             {
7161                 MessageBox.Show(Properties.Resources.CopyStotText1);
7162             }
7163             if (sb.Length > 0)
7164             {
7165                 clstr = sb.ToString();
7166                 try
7167                 {
7168                     Clipboard.SetDataObject(clstr, false, 5, 100);
7169                 }
7170                 catch (Exception ex)
7171                 {
7172                     MessageBox.Show(ex.Message);
7173                 }
7174             }
7175         }
7176
7177         private void CopyIdUri()
7178         {
7179             string clstr = "";
7180             StringBuilder sb = new StringBuilder();
7181             if (this._curTab == null) return;
7182             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7183             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7184             foreach (int idx in _curList.SelectedIndices)
7185             {
7186                 var post = _statuses.Tabs[_curTab.Text][idx];
7187                 sb.Append(MyCommon.GetStatusUrl(post));
7188                 sb.Append(Environment.NewLine);
7189             }
7190             if (sb.Length > 0)
7191             {
7192                 clstr = sb.ToString();
7193                 try
7194                 {
7195                     Clipboard.SetDataObject(clstr, false, 5, 100);
7196                 }
7197                 catch (Exception ex)
7198                 {
7199                     MessageBox.Show(ex.Message);
7200                 }
7201             }
7202         }
7203
7204         private void GoFav(bool forward)
7205         {
7206             if (_curList.VirtualListSize == 0) return;
7207             int fIdx = 0;
7208             int toIdx = 0;
7209             int stp = 1;
7210
7211             if (forward)
7212             {
7213                 if (_curList.SelectedIndices.Count == 0)
7214                 {
7215                     fIdx = 0;
7216                 }
7217                 else
7218                 {
7219                     fIdx = _curList.SelectedIndices[0] + 1;
7220                     if (fIdx > _curList.VirtualListSize - 1) return;
7221                 }
7222                 toIdx = _curList.VirtualListSize;
7223                 stp = 1;
7224             }
7225             else
7226             {
7227                 if (_curList.SelectedIndices.Count == 0)
7228                 {
7229                     fIdx = _curList.VirtualListSize - 1;
7230                 }
7231                 else
7232                 {
7233                     fIdx = _curList.SelectedIndices[0] - 1;
7234                     if (fIdx < 0) return;
7235                 }
7236                 toIdx = -1;
7237                 stp = -1;
7238             }
7239
7240             for (int idx = fIdx; idx != toIdx; idx += stp)
7241             {
7242                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7243                 {
7244                     SelectListItem(_curList, idx);
7245                     _curList.EnsureVisible(idx);
7246                     break;
7247                 }
7248             }
7249         }
7250
7251         private void GoSamePostToAnotherTab(bool left)
7252         {
7253             if (_curList.VirtualListSize == 0) return;
7254             int fIdx = 0;
7255             int toIdx = 0;
7256             int stp = 1;
7257             long targetId = 0;
7258
7259             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7260             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7261
7262             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7263
7264             if (left)
7265             {
7266                 // 左のタブへ
7267                 if (ListTab.SelectedIndex == 0)
7268                 {
7269                     return;
7270                 }
7271                 else
7272                 {
7273                     fIdx = ListTab.SelectedIndex - 1;
7274                 }
7275                 toIdx = -1;
7276                 stp = -1;
7277             }
7278             else
7279             {
7280                 // 右のタブへ
7281                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7282                 {
7283                     return;
7284                 }
7285                 else
7286                 {
7287                     fIdx = ListTab.SelectedIndex + 1;
7288                 }
7289                 toIdx = ListTab.TabCount;
7290                 stp = 1;
7291             }
7292
7293             bool found = false;
7294             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7295             {
7296                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7297                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7298                 {
7299                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7300                     {
7301                         ListTab.SelectedIndex = tabidx;
7302                         SelectListItem(_curList, idx);
7303                         _curList.EnsureVisible(idx);
7304                         found = true;
7305                         break;
7306                     }
7307                 }
7308                 if (found) break;
7309             }
7310         }
7311
7312         private void GoPost(bool forward)
7313         {
7314             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7315             int fIdx = 0;
7316             int toIdx = 0;
7317             int stp = 1;
7318
7319             if (forward)
7320             {
7321                 fIdx = _curList.SelectedIndices[0] + 1;
7322                 if (fIdx > _curList.VirtualListSize - 1) return;
7323                 toIdx = _curList.VirtualListSize;
7324                 stp = 1;
7325             }
7326             else
7327             {
7328                 fIdx = _curList.SelectedIndices[0] - 1;
7329                 if (fIdx < 0) return;
7330                 toIdx = -1;
7331                 stp = -1;
7332             }
7333
7334             string name = "";
7335             if (_curPost.RetweetedId == null)
7336             {
7337                 name = _curPost.ScreenName;
7338             }
7339             else
7340             {
7341                 name = _curPost.RetweetedBy;
7342             }
7343             for (int idx = fIdx; idx != toIdx; idx += stp)
7344             {
7345                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7346                 {
7347                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7348                     {
7349                         SelectListItem(_curList, idx);
7350                         _curList.EnsureVisible(idx);
7351                         break;
7352                     }
7353                 }
7354                 else
7355                 {
7356                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7357                     {
7358                         SelectListItem(_curList, idx);
7359                         _curList.EnsureVisible(idx);
7360                         break;
7361                     }
7362                 }
7363             }
7364         }
7365
7366         private void GoRelPost(bool forward)
7367         {
7368             if (_curList.SelectedIndices.Count == 0) return;
7369
7370             int fIdx = 0;
7371             int toIdx = 0;
7372             int stp = 1;
7373             if (forward)
7374             {
7375                 fIdx = _curList.SelectedIndices[0] + 1;
7376                 if (fIdx > _curList.VirtualListSize - 1) return;
7377                 toIdx = _curList.VirtualListSize;
7378                 stp = 1;
7379             }
7380             else
7381             {
7382                 fIdx = _curList.SelectedIndices[0] - 1;
7383                 if (fIdx < 0) return;
7384                 toIdx = -1;
7385                 stp = -1;
7386             }
7387
7388             if (!_anchorFlag)
7389             {
7390                 if (_curPost == null) return;
7391                 _anchorPost = _curPost;
7392                 _anchorFlag = true;
7393             }
7394             else
7395             {
7396                 if (_anchorPost == null) return;
7397             }
7398
7399             for (int idx = fIdx; idx != toIdx; idx += stp)
7400             {
7401                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402                 if (post.ScreenName == _anchorPost.ScreenName ||
7403                     post.RetweetedBy == _anchorPost.ScreenName ||
7404                     post.ScreenName == _anchorPost.RetweetedBy ||
7405                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7406                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7407                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7408                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7409                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7410                 {
7411                     SelectListItem(_curList, idx);
7412                     _curList.EnsureVisible(idx);
7413                     break;
7414                 }
7415             }
7416         }
7417
7418         private void GoAnchor()
7419         {
7420             if (_anchorPost == null) return;
7421             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7422             if (idx == -1) return;
7423
7424             SelectListItem(_curList, idx);
7425             _curList.EnsureVisible(idx);
7426         }
7427
7428         private void GoTopEnd(bool GoTop)
7429         {
7430             if (_curList.VirtualListSize == 0)
7431                 return;
7432
7433             ListViewItem _item;
7434             int idx;
7435
7436             if (GoTop)
7437             {
7438                 _item = _curList.GetItemAt(0, 25);
7439                 if (_item == null)
7440                     idx = 0;
7441                 else
7442                     idx = _item.Index;
7443             }
7444             else
7445             {
7446                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7447                 if (_item == null)
7448                     idx = _curList.VirtualListSize - 1;
7449                 else
7450                     idx = _item.Index;
7451             }
7452             SelectListItem(_curList, idx);
7453         }
7454
7455         private void GoMiddle()
7456         {
7457             if (_curList.VirtualListSize == 0)
7458                 return;
7459
7460             ListViewItem _item;
7461             int idx1;
7462             int idx2;
7463             int idx3;
7464
7465             _item = _curList.GetItemAt(0, 0);
7466             if (_item == null)
7467             {
7468                 idx1 = 0;
7469             }
7470             else
7471             {
7472                 idx1 = _item.Index;
7473             }
7474
7475             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7476             if (_item == null)
7477             {
7478                 idx2 = _curList.VirtualListSize - 1;
7479             }
7480             else
7481             {
7482                 idx2 = _item.Index;
7483             }
7484             idx3 = (idx1 + idx2) / 2;
7485
7486             SelectListItem(_curList, idx3);
7487         }
7488
7489         private void GoLast()
7490         {
7491             if (_curList.VirtualListSize == 0) return;
7492
7493             if (_statuses.SortOrder == SortOrder.Ascending)
7494             {
7495                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7496                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7497             }
7498             else
7499             {
7500                 SelectListItem(_curList, 0);
7501                 _curList.EnsureVisible(0);
7502             }
7503         }
7504
7505         private void MoveTop()
7506         {
7507             if (_curList.SelectedIndices.Count == 0) return;
7508             int idx = _curList.SelectedIndices[0];
7509             if (_statuses.SortOrder == SortOrder.Ascending)
7510             {
7511                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7512             }
7513             else
7514             {
7515                 _curList.EnsureVisible(0);
7516             }
7517             _curList.EnsureVisible(idx);
7518         }
7519
7520         private async Task GoInReplyToPostTree()
7521         {
7522             if (_curPost == null) return;
7523
7524             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7525
7526             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7527             {
7528                 try
7529                 {
7530                     var post = tw.GetStatusApi(false, _curPost.StatusId);
7531
7532                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7533                     _curPost.InReplyToUser = post.InReplyToUser;
7534                     _curPost.IsReply = post.IsReply;
7535                     this.PurgeListViewItemCache();
7536                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7537                 }
7538                 catch (WebApiException ex)
7539                 {
7540                     this.StatusLabel.Text = ex.Message;
7541                 }
7542             }
7543
7544             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7545
7546             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7547             {
7548                 replyChains = new Stack<ReplyChain>();
7549             }
7550             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7551
7552             int inReplyToIndex;
7553             string inReplyToTabName;
7554             long inReplyToId = _curPost.InReplyToStatusId.Value;
7555             string inReplyToUser = _curPost.InReplyToUser;
7556             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7557
7558             var inReplyToPosts = from tab in _statuses.Tabs.Values
7559                                  orderby tab != curTabClass
7560                                  from post in tab.Posts.Values
7561                                  where post.StatusId == inReplyToId
7562                                  let index = tab.IndexOf(post.StatusId)
7563                                  where index != -1
7564                                  select new {Tab = tab, Index = index};
7565
7566             var inReplyPost = inReplyToPosts.FirstOrDefault();
7567             if (inReplyPost == null)
7568             {
7569                 try
7570                 {
7571                     await Task.Run(() =>
7572                     {
7573                         var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7574                         post.IsRead = true;
7575
7576                         _statuses.AddPost(post);
7577                         _statuses.DistributePosts();
7578                     });
7579                 }
7580                 catch (WebApiException ex)
7581                 {
7582                     this.StatusLabel.Text = ex.Message;
7583                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7584                     return;
7585                 }
7586
7587                 this.RefreshTimeline();
7588
7589                 inReplyPost = inReplyToPosts.FirstOrDefault();
7590                 if (inReplyPost == null)
7591                 {
7592                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7593                     return;
7594                 }
7595             }
7596             inReplyToTabName = inReplyPost.Tab.TabName;
7597             inReplyToIndex = inReplyPost.Index;
7598
7599             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7600             DetailsListView listView = (DetailsListView)tabPage.Tag;
7601
7602             if (_curTab != tabPage)
7603             {
7604                 this.ListTab.SelectTab(tabPage);
7605             }
7606
7607             this.SelectListItem(listView, inReplyToIndex);
7608             listView.EnsureVisible(inReplyToIndex);
7609         }
7610
7611         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7612         {
7613             if (_curPost == null) return;
7614
7615             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7616             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7617
7618             if (parallel)
7619             {
7620                 if (_curPost.InReplyToStatusId != null)
7621                 {
7622                     var posts = from t in _statuses.Tabs
7623                                 from p in t.Value.Posts
7624                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7625                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7626                                 where indexOf > -1
7627                                 orderby isForward ? indexOf : indexOf * -1
7628                                 orderby t.Value != curTabClass
7629                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7630                     try
7631                     {
7632                         var postList = posts.ToList();
7633                         for (int i = postList.Count - 1; i >= 0; i--)
7634                         {
7635                             int index = i;
7636                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7637                             {
7638                                 postList.RemoveAt(index);
7639                             }
7640                         }
7641                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7642                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7643                         if (post == null) post = postList.First();
7644                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7645                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7646                         SelectListItem(listView, post.Index);
7647                         listView.EnsureVisible(post.Index);
7648                     }
7649                     catch (InvalidOperationException)
7650                     {
7651                         return;
7652                     }
7653                 }
7654             }
7655             else
7656             {
7657                 if (replyChains == null || replyChains.Count < 1)
7658                 {
7659                     var posts = from t in _statuses.Tabs
7660                                 from p in t.Value.Posts
7661                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7662                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7663                                 where indexOf > -1
7664                                 orderby indexOf
7665                                 orderby t.Value != curTabClass
7666                                 select new {Tab = t.Value, Index = indexOf};
7667                     try
7668                     {
7669                         var post = posts.First();
7670                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7671                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7672                         SelectListItem(listView, post.Index);
7673                         listView.EnsureVisible(post.Index);
7674                     }
7675                     catch (InvalidOperationException)
7676                     {
7677                         return;
7678                     }
7679                 }
7680                 else
7681                 {
7682                     ReplyChain chainHead = replyChains.Pop();
7683                     if (chainHead.InReplyToId == _curPost.StatusId)
7684                     {
7685                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7686                         if (idx == -1)
7687                         {
7688                             replyChains = null;
7689                         }
7690                         else
7691                         {
7692                             try
7693                             {
7694                                 ListTab.SelectTab(chainHead.OriginalTab);
7695                             }
7696                             catch (Exception)
7697                             {
7698                                 replyChains = null;
7699                             }
7700                             SelectListItem(_curList, idx);
7701                             _curList.EnsureVisible(idx);
7702                         }
7703                     }
7704                     else
7705                     {
7706                         replyChains = null;
7707                         this.GoBackInReplyToPostTree(parallel);
7708                     }
7709                 }
7710             }
7711         }
7712
7713         private void GoBackSelectPostChain()
7714         {
7715             if (this.selectPostChains.Count > 1)
7716             {
7717                 var idx = -1;
7718                 TabPage tp = null;
7719
7720                 do
7721                 {
7722                     try
7723                     {
7724                         this.selectPostChains.Pop();
7725                         var tabPostPair = this.selectPostChains.Peek();
7726
7727                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7728
7729                         if (tabPostPair.Item2 != null)
7730                         {
7731                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7732                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7733                         }
7734
7735                         tp = tabPostPair.Item1;
7736
7737                         this.selectPostChains.Pop();
7738                     }
7739                     catch (InvalidOperationException)
7740                     {
7741                     }
7742
7743                     break;
7744                 }
7745                 while (this.selectPostChains.Count > 1);
7746
7747                 if (tp == null)
7748                 {
7749                     //状態がおかしいので処理を中断
7750                     //履歴が残り1つであればクリアしておく
7751                     if (this.selectPostChains.Count == 1)
7752                         this.selectPostChains.Clear();
7753                     return;
7754                 }
7755
7756                 DetailsListView lst = (DetailsListView)tp.Tag;
7757                 this.ListTab.SelectedTab = tp;
7758                 if (idx > -1)
7759                 {
7760                     SelectListItem(lst, idx);
7761                     lst.EnsureVisible(idx);
7762                 }
7763                 lst.Focus();
7764             }
7765         }
7766
7767         private void PushSelectPostChain()
7768         {
7769             int count = this.selectPostChains.Count;
7770             if (count > 0)
7771             {
7772                 var p = this.selectPostChains.Peek();
7773                 if (p.Item1 == this._curTab)
7774                 {
7775                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7776                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7777                 }
7778             }
7779             if (count >= 2500) TrimPostChain();
7780             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7781         }
7782
7783         private void TrimPostChain()
7784         {
7785             if (this.selectPostChains.Count <= 2000) return;
7786             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7787             for (int i = 0; i < 2000; i++)
7788             {
7789                 p.Push(this.selectPostChains.Pop());
7790             }
7791             this.selectPostChains.Clear();
7792             for (int i = 0; i < 2000; i++)
7793             {
7794                 this.selectPostChains.Push(p.Pop());
7795             }
7796         }
7797
7798         private bool GoStatus(long statusId)
7799         {
7800             if (statusId == 0) return false;
7801             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7802             {
7803                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7804                 {
7805                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7806                     ListTab.SelectedIndex = tabidx;
7807                     SelectListItem(_curList, idx);
7808                     _curList.EnsureVisible(idx);
7809                     return true;
7810                 }
7811             }
7812             return false;
7813         }
7814
7815         private bool GoDirectMessage(long statusId)
7816         {
7817             if (statusId == 0) return false;
7818             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7819             {
7820                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7821                 {
7822                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7823                     ListTab.SelectedIndex = tabidx;
7824                     SelectListItem(_curList, idx);
7825                     _curList.EnsureVisible(idx);
7826                     return true;
7827                 }
7828             }
7829             return false;
7830         }
7831
7832         private void MyList_MouseClick(object sender, MouseEventArgs e)
7833         {
7834             _anchorFlag = false;
7835         }
7836
7837         private void StatusText_Enter(object sender, EventArgs e)
7838         {
7839             // フォーカスの戻り先を StatusText に設定
7840             this.Tag = StatusText;
7841             StatusText.BackColor = _clInputBackcolor;
7842         }
7843
7844         public Color InputBackColor
7845         {
7846             get { return _clInputBackcolor; }
7847             set { _clInputBackcolor = value; }
7848         }
7849
7850         private void StatusText_Leave(object sender, EventArgs e)
7851         {
7852             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7853             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7854             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7855         }
7856
7857         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7858         {
7859             Task asyncTask;
7860             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7861             {
7862                 e.Handled = true;
7863                 e.SuppressKeyPress = true;
7864             }
7865
7866             this.StatusText_TextChanged(null, null);
7867
7868             if (asyncTask != null)
7869                 await asyncTask;
7870         }
7871
7872         private void SaveConfigsAll(bool ifModified)
7873         {
7874             if (!ifModified)
7875             {
7876                 SaveConfigsCommon();
7877                 SaveConfigsLocal();
7878                 SaveConfigsTabs();
7879                 SaveConfigsAtId();
7880             }
7881             else
7882             {
7883                 if (ModifySettingCommon) SaveConfigsCommon();
7884                 if (ModifySettingLocal) SaveConfigsLocal();
7885                 if (ModifySettingAtId) SaveConfigsAtId();
7886             }
7887         }
7888
7889         private void SaveConfigsAtId()
7890         {
7891             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7892
7893             ModifySettingAtId = false;
7894             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7895             cfgAtId.Save();
7896         }
7897
7898         private void SaveConfigsCommon()
7899         {
7900             if (_ignoreConfigSave) return;
7901
7902             ModifySettingCommon = false;
7903             lock (_syncObject)
7904             {
7905                 _cfgCommon.UserName = tw.Username;
7906                 _cfgCommon.UserId = tw.UserId;
7907                 _cfgCommon.Password = tw.Password;
7908                 _cfgCommon.Token = tw.AccessToken;
7909                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7910
7911                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7912                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7913                 {
7914                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7915                 }
7916
7917                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7918                 switch (_statuses.SortMode)
7919                 {
7920                     case ComparerMode.Nickname:  //ニックネーム
7921                         _cfgCommon.SortColumn = 1;
7922                         break;
7923                     case ComparerMode.Data:  //本文
7924                         _cfgCommon.SortColumn = 2;
7925                         break;
7926                     case ComparerMode.Id:  //時刻=発言Id
7927                         _cfgCommon.SortColumn = 3;
7928                         break;
7929                     case ComparerMode.Name:  //名前
7930                         _cfgCommon.SortColumn = 4;
7931                         break;
7932                     case ComparerMode.Source:  //Source
7933                         _cfgCommon.SortColumn = 7;
7934                         break;
7935                 }
7936
7937                 _cfgCommon.HashTags = HashMgr.HashHistories;
7938                 if (HashMgr.IsPermanent)
7939                 {
7940                     _cfgCommon.HashSelected = HashMgr.UseHash;
7941                 }
7942                 else
7943                 {
7944                     _cfgCommon.HashSelected = "";
7945                 }
7946                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7947                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7948                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7949                 if (ToolStripFocusLockMenuItem != null &&
7950                         ToolStripFocusLockMenuItem.IsDisposed == false)
7951                 {
7952                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7953                 }
7954                 _cfgCommon.TrackWord = tw.TrackWord;
7955                 _cfgCommon.AllAtReply = tw.AllAtReply;
7956                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7957                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7958
7959                 _cfgCommon.Save();
7960             }
7961         }
7962
7963         private void SaveConfigsLocal()
7964         {
7965             if (_ignoreConfigSave) return;
7966             lock (_syncObject)
7967             {
7968                 ModifySettingLocal = false;
7969                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7970                 _cfgLocal.FormSize = _mySize;
7971                 _cfgLocal.FormLocation = _myLoc;
7972                 _cfgLocal.SplitterDistance = _mySpDis;
7973                 _cfgLocal.PreviewDistance = _mySpDis3;
7974                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7975                 _cfgLocal.StatusTextHeight = _mySpDis2;
7976
7977                 _cfgLocal.FontUnread = _fntUnread;
7978                 _cfgLocal.ColorUnread = _clUnread;
7979                 _cfgLocal.FontRead = _fntReaded;
7980                 _cfgLocal.ColorRead = _clReaded;
7981                 _cfgLocal.FontDetail = _fntDetail;
7982                 _cfgLocal.ColorDetail = _clDetail;
7983                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7984                 _cfgLocal.ColorDetailLink = _clDetailLink;
7985                 _cfgLocal.ColorFav = _clFav;
7986                 _cfgLocal.ColorOWL = _clOWL;
7987                 _cfgLocal.ColorRetweet = _clRetweet;
7988                 _cfgLocal.ColorSelf = _clSelf;
7989                 _cfgLocal.ColorAtSelf = _clAtSelf;
7990                 _cfgLocal.ColorTarget = _clTarget;
7991                 _cfgLocal.ColorAtTarget = _clAtTarget;
7992                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7993                 _cfgLocal.ColorAtTo = _clAtTo;
7994                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7995                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7996                 _cfgLocal.ColorInputFont = _clInputFont;
7997                 _cfgLocal.FontInputFont = _fntInputFont;
7998
7999                 if (_ignoreConfigSave) return;
8000                 _cfgLocal.Save();
8001             }
8002         }
8003
8004         private void SaveConfigsTabs()
8005         {
8006             SettingTabs tabSetting = new SettingTabs();
8007             for (int i = 0; i < ListTab.TabPages.Count; i++)
8008             {
8009                 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8010                 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8011                     tabSetting.Tabs.Add(tab);
8012             }
8013             tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8014             tabSetting.Save();
8015         }
8016
8017         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8018         {
8019             string inputText;
8020             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8021             if (ret != DialogResult.OK)
8022                 return;
8023
8024             var match = Twitter.StatusUrlRegex.Match(inputText);
8025             if (!match.Success)
8026             {
8027                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8028                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8029                 return;
8030             }
8031
8032             try
8033             {
8034                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8035                 await this.OpenRelatedTab(statusId);
8036             }
8037             catch (TabException ex)
8038             {
8039                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8040             }
8041         }
8042
8043         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8044         {
8045             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8046                     Properties.Resources.SaveLogMenuItem_ClickText2,
8047                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8048             if (rslt == DialogResult.Cancel) return;
8049
8050             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8051             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8052             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8053             SaveFileDialog1.FilterIndex = 0;
8054             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8055             SaveFileDialog1.RestoreDirectory = true;
8056
8057             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8058             {
8059                 if (!SaveFileDialog1.ValidateNames) return;
8060                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8061                 {
8062                     if (rslt == DialogResult.Yes)
8063                     {
8064                         //All
8065                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8066                         {
8067                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8068                             string protect = "";
8069                             if (post.IsProtect) protect = "Protect";
8070                             sw.WriteLine(post.Nickname + "\t" +
8071                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8072                                      post.CreatedAt.ToString() + "\t" +
8073                                      post.ScreenName + "\t" +
8074                                      post.StatusId.ToString() + "\t" +
8075                                      post.ImageUrl + "\t" +
8076                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8077                                      protect);
8078                         }
8079                     }
8080                     else
8081                     {
8082                         foreach (int idx in _curList.SelectedIndices)
8083                         {
8084                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8085                             string protect = "";
8086                             if (post.IsProtect) protect = "Protect";
8087                             sw.WriteLine(post.Nickname + "\t" +
8088                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8089                                      post.CreatedAt.ToString() + "\t" +
8090                                      post.ScreenName + "\t" +
8091                                      post.StatusId.ToString() + "\t" +
8092                                      post.ImageUrl + "\t" +
8093                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8094                                      protect);
8095                         }
8096                     }
8097                 }
8098             }
8099             this.TopMost = this._cfgCommon.AlwaysTop;
8100         }
8101
8102         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8103         {
8104             Task asyncTask;
8105             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8106             if (KeyRes)
8107             {
8108                 e.IsInputKey = true;
8109             }
8110             else
8111             {
8112                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8113                 {
8114                     var shortcut = (Shortcut)e.KeyData;
8115                     switch (shortcut)
8116                     {
8117                         case Shortcut.CtrlA:
8118                         case Shortcut.CtrlC:
8119                         case Shortcut.CtrlIns:
8120                             // 既定の動作を有効にする
8121                             break;
8122                         default:
8123                             // その他のショートカットキーは無効にする
8124                             e.IsInputKey = true;
8125                             break;
8126                     }
8127                 }
8128             }
8129
8130             if (asyncTask != null)
8131                 await asyncTask;
8132         }
8133         public bool TabRename(ref string tabName)
8134         {
8135             //タブ名変更
8136             string newTabText = null;
8137             using (InputTabName inputName = new InputTabName())
8138             {
8139                 inputName.TabName = tabName;
8140                 inputName.ShowDialog();
8141                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8142                 newTabText = inputName.TabName;
8143             }
8144             this.TopMost = this._cfgCommon.AlwaysTop;
8145             if (!string.IsNullOrEmpty(newTabText))
8146             {
8147                 //新タブ名存在チェック
8148                 for (int i = 0; i < ListTab.TabCount; i++)
8149                 {
8150                     if (ListTab.TabPages[i].Text == newTabText)
8151                     {
8152                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8153                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8154                         return false;
8155                     }
8156                 }
8157                 //タブ名を変更
8158                 for (int i = 0; i < ListTab.TabCount; i++)
8159                 {
8160                     if (ListTab.TabPages[i].Text == tabName)
8161                     {
8162                         ListTab.TabPages[i].Text = newTabText;
8163                         break;
8164                     }
8165                 }
8166                 _statuses.RenameTab(tabName, newTabText);
8167
8168                 SaveConfigsCommon();
8169                 SaveConfigsTabs();
8170                 _rclickTabName = newTabText;
8171                 tabName = newTabText;
8172                 return true;
8173             }
8174             else
8175             {
8176                 return false;
8177             }
8178         }
8179
8180         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8181         {
8182             if (e.Button == MouseButtons.Middle)
8183             {
8184                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8185                 {
8186                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8187                     {
8188                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8189                         this.SaveConfigsTabs();
8190                         break;
8191                     }
8192                 }
8193             }
8194         }
8195
8196         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8197         {
8198             string tn = ListTab.SelectedTab.Text;
8199             TabRename(ref tn);
8200         }
8201
8202         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8203         {
8204             if (this._cfgCommon.TabMouseLock) return;
8205             Point cpos = new Point(e.X, e.Y);
8206             if (e.Button == MouseButtons.Left)
8207             {
8208                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8209                 {
8210                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8211                     {
8212                         _tabDrag = true;
8213                         _tabMouseDownPoint = e.Location;
8214                         break;
8215                     }
8216                 }
8217             }
8218             else
8219             {
8220                 _tabDrag = false;
8221             }
8222         }
8223
8224         private void ListTab_DragEnter(object sender, DragEventArgs e)
8225         {
8226             if (e.Data.GetDataPresent(typeof(TabPage)))
8227                 e.Effect = DragDropEffects.Move;
8228             else
8229                 e.Effect = DragDropEffects.None;
8230         }
8231
8232         private void ListTab_DragDrop(object sender, DragEventArgs e)
8233         {
8234             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8235
8236             _tabDrag = false;
8237             string tn = "";
8238             bool bef = false;
8239             Point cpos = new Point(e.X, e.Y);
8240             Point spos = ListTab.PointToClient(cpos);
8241             int i;
8242             for (i = 0; i < ListTab.TabPages.Count; i++)
8243             {
8244                 Rectangle rect = ListTab.GetTabRect(i);
8245                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8246                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8247                 {
8248                     tn = ListTab.TabPages[i].Text;
8249                     if (spos.X <= (rect.Left + rect.Right) / 2)
8250                         bef = true;
8251                     else
8252                         bef = false;
8253
8254                     break;
8255                 }
8256             }
8257
8258             //タブのないところにドロップ->最後尾へ移動
8259             if (string.IsNullOrEmpty(tn))
8260             {
8261                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8262                 bef = false;
8263                 i = ListTab.TabPages.Count - 1;
8264             }
8265
8266             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8267             if (tp.Text == tn) return;
8268
8269             ReOrderTab(tp.Text, tn, bef);
8270         }
8271
8272         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8273         {
8274             var baseIndex = this.GetTabPageIndex(baseTabText);
8275             if (baseIndex == -1)
8276                 return;
8277
8278             var targetIndex = this.GetTabPageIndex(targetTabText);
8279             if (targetIndex == -1)
8280                 return;
8281
8282             using (ControlTransaction.Layout(this.ListTab))
8283             {
8284                 var mTp = this.ListTab.TabPages[targetIndex];
8285                 this.ListTab.TabPages.Remove(mTp);
8286
8287                 if (targetIndex < baseIndex)
8288                     baseIndex--;
8289
8290                 if (isBeforeBaseTab)
8291                     ListTab.TabPages.Insert(baseIndex, mTp);
8292                 else
8293                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8294             }
8295
8296             SaveConfigsTabs();
8297         }
8298
8299         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8300         {
8301             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8302             //isReply:true=@,false=DM
8303             if (!StatusText.Enabled) return;
8304             if (_curList == null) return;
8305             if (_curTab == null) return;
8306             if (!this.ExistCurrentPost) return;
8307
8308             // 複数あてリプライはReplyではなく通常ポスト
8309             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8310             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8311             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8312
8313             if (_curList.SelectedIndices.Count > 0)
8314             {
8315                 // アイテムが1件以上選択されている
8316                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8317                 {
8318                     // 単独ユーザー宛リプライまたはDM
8319                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8320                     {
8321                         // ダイレクトメッセージ
8322                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8323                         StatusText.SelectionStart = StatusText.Text.Length;
8324                         StatusText.Focus();
8325                         this.inReplyTo = null;
8326                         return;
8327                     }
8328                     if (string.IsNullOrEmpty(StatusText.Text))
8329                     {
8330                         //空の場合
8331
8332                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8333                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8334
8335                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8336                         var inReplyToScreenName = this._curPost.ScreenName;
8337                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8338                     }
8339                     else
8340                     {
8341                         //何か入力済の場合
8342
8343                         if (isAuto)
8344                         {
8345                             //1件選んでEnter or DoubleClick
8346                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8347                             {
8348                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8349                                 {
8350                                     //返信先書き換え
8351                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8352                                     var inReplyToScreenName = this._curPost.ScreenName;
8353                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8354                                 }
8355                                 return;
8356                             }
8357                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8358                             {
8359                                 //文頭@以外
8360                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8361                                 {
8362                                     // 複数リプライ
8363                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8364                                     this.inReplyTo = null;
8365                                 }
8366                                 else
8367                                 {
8368                                     // 単独リプライ
8369                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8370                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8371                                     var inReplyToScreenName = this._curPost.ScreenName;
8372                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8373                                 }
8374                             }
8375                             else
8376                             {
8377                                 //文頭@
8378                                 // 複数リプライ
8379                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8380                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8381                                 this.inReplyTo = null;
8382                             }
8383                         }
8384                         else
8385                         {
8386                             //1件選んでCtrl-Rの場合(返信先操作せず)
8387                             int sidx = StatusText.SelectionStart;
8388                             string id = "@" + _curPost.ScreenName + " ";
8389                             if (sidx > 0)
8390                             {
8391                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8392                                 {
8393                                     id = " " + id;
8394                                 }
8395                             }
8396                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8397                             sidx += id.Length;
8398                             //if (StatusText.Text.StartsWith("@"))
8399                             //{
8400                             //    //複数リプライ
8401                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8402                             //    sidx += 5 + _curPost.ScreenName.Length;
8403                             //}
8404                             //else
8405                             //{
8406                             //    // 複数リプライ
8407                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8408                             //    sidx += 3 + _curPost.ScreenName.Length;
8409                             //}
8410                             StatusText.SelectionStart = sidx;
8411                             StatusText.Focus();
8412                             //_reply_to_id = 0;
8413                             //_reply_to_name = null;
8414                             return;
8415                         }
8416                     }
8417                 }
8418                 else
8419                 {
8420                     // 複数リプライ
8421                     if (!isAuto && !isReply) return;
8422
8423                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8424
8425                     if (isAuto)
8426                     {
8427                         //Enter or DoubleClick
8428
8429                         string sTxt = StatusText.Text;
8430                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8431                         {
8432                             sTxt = ". " + sTxt;
8433                             this.inReplyTo = null;
8434                         }
8435                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8436                         {
8437                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8438                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8439                             {
8440                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8441                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8442                             }
8443                         }
8444                         StatusText.Text = sTxt;
8445                     }
8446                     else
8447                     {
8448                         //C-S-r or C-r
8449                         if (_curList.SelectedIndices.Count > 1)
8450                         {
8451                             //複数ポスト選択
8452
8453                             string ids = "";
8454                             int sidx = StatusText.SelectionStart;
8455                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8456                             {
8457                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8458                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8459                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8460                                 {
8461                                     ids += "@" + post.ScreenName + " ";
8462                                 }
8463                                 if (isAll)
8464                                 {
8465                                     foreach (string nm in post.ReplyToList)
8466                                     {
8467                                         if (!ids.Contains("@" + nm + " ") &&
8468                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8469                                         {
8470                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8471                                             if (m.Success)
8472                                                 ids += "@" + m.Result("${id}") + " ";
8473                                             else
8474                                                 ids += "@" + nm + " ";
8475                                         }
8476                                     }
8477                                 }
8478                             }
8479                             if (ids.Length == 0) return;
8480                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8481                             {
8482                                 StatusText.Text = ". " + StatusText.Text;
8483                                 sidx += 2;
8484                                 this.inReplyTo = null;
8485                             }
8486                             if (sidx > 0)
8487                             {
8488                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8489                                 {
8490                                     ids = " " + ids;
8491                                 }
8492                             }
8493                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8494                             sidx += ids.Length;
8495                             //if (StatusText.Text.StartsWith("@"))
8496                             //{
8497                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8498                             //    sidx += 2 + ids.Length;
8499                             //}
8500                             //else
8501                             //{
8502                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8503                             //    sidx += 1 + ids.Length;
8504                             //}
8505                             StatusText.SelectionStart = sidx;
8506                             StatusText.Focus();
8507                             return;
8508                         }
8509                         else
8510                         {
8511                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8512
8513                             string ids = "";
8514                             int sidx = StatusText.SelectionStart;
8515                             PostClass post = _curPost;
8516                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8517                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8518                             {
8519                                 ids += "@" + post.ScreenName + " ";
8520                             }
8521                             foreach (string nm in post.ReplyToList)
8522                             {
8523                                 if (!ids.Contains("@" + nm + " ") &&
8524                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8525                                 {
8526                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8527                                     if (m.Success)
8528                                         ids += "@" + m.Result("${id}") + " ";
8529                                     else
8530                                         ids += "@" + nm + " ";
8531                                 }
8532                             }
8533                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8534                             {
8535                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8536                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8537                                 {
8538                                     ids += "@" + post.RetweetedBy + " ";
8539                                 }
8540                             }
8541                             if (ids.Length == 0) return;
8542                             if (string.IsNullOrEmpty(StatusText.Text))
8543                             {
8544                                 //未入力の場合のみ返信先付加
8545                                 StatusText.Text = ids;
8546                                 StatusText.SelectionStart = ids.Length;
8547                                 StatusText.Focus();
8548
8549                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8550                                 var inReplyToScreenName = this._curPost.ScreenName;
8551                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8552                                 return;
8553                             }
8554
8555                             if (sidx > 0)
8556                             {
8557                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8558                                 {
8559                                     ids = " " + ids;
8560                                 }
8561                             }
8562                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8563                             sidx += ids.Length;
8564                             StatusText.SelectionStart = sidx;
8565                             StatusText.Focus();
8566                             return;
8567                         }
8568                     }
8569                 }
8570                 StatusText.SelectionStart = StatusText.Text.Length;
8571                 StatusText.Focus();
8572             }
8573         }
8574
8575         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8576         {
8577             _tabDrag = false;
8578         }
8579
8580         private static int iconCnt = 0;
8581         private static int blinkCnt = 0;
8582         private static bool blink = false;
8583         private static bool idle = false;
8584
8585         private async Task RefreshTasktrayIcon()
8586         {
8587             if (_colorize)
8588                 await this.Colorize();
8589
8590             if (!TimerRefreshIcon.Enabled) return;
8591             //Static usCheckCnt As int = 0
8592
8593             //Static iconDlListTopItem As ListViewItem = null
8594
8595             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8596             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8597             //else
8598             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8599             //
8600             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8601
8602             iconCnt += 1;
8603             blinkCnt += 1;
8604             //usCheckCnt += 1;
8605
8606             //if (usCheckCnt > 300)    //1min
8607             //{
8608             //    usCheckCnt = 0;
8609             //    if (!this.IsReceivedUserStream)
8610             //    {
8611             //        TraceOut("ReconnectUserStream");
8612             //        tw.ReconnectUserStream();
8613             //    }
8614             //}
8615
8616             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8617
8618             if (iconCnt >= this.NIconRefresh.Length)
8619             {
8620                 iconCnt = 0;
8621             }
8622             if (blinkCnt > 10)
8623             {
8624                 blinkCnt = 0;
8625                 //未保存の変更を保存
8626                 SaveConfigsAll(true);
8627             }
8628
8629             if (busy)
8630             {
8631                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8632                 idle = false;
8633                 _myStatusError = false;
8634                 return;
8635             }
8636
8637             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8638             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8639             {
8640                 if (blinkCnt > 0) return;
8641                 blink = !blink;
8642                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8643                 {
8644                     NotifyIcon1.Icon = ReplyIcon;
8645                 }
8646                 else
8647                 {
8648                     NotifyIcon1.Icon = ReplyIconBlink;
8649                 }
8650                 idle = false;
8651                 return;
8652             }
8653
8654             if (idle) return;
8655             idle = true;
8656             //優先度:エラー→オフライン→アイドル
8657             //エラーは更新アイコンでクリアされる
8658             if (_myStatusError)
8659             {
8660                 NotifyIcon1.Icon = NIconAtRed;
8661                 return;
8662             }
8663             if (_myStatusOnline)
8664             {
8665                 NotifyIcon1.Icon = NIconAt;
8666             }
8667             else
8668             {
8669                 NotifyIcon1.Icon = NIconAtSmoke;
8670             }
8671         }
8672
8673         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8674         {
8675             //200ms
8676             await this.RefreshTasktrayIcon();
8677         }
8678
8679         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8680         {
8681             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8682             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8683             {
8684                 if (ListTab != null && ListTab.SelectedTab != null)
8685                     _rclickTabName = ListTab.SelectedTab.Text;
8686                 else
8687                     return;
8688             }
8689
8690             if (_statuses == null) return;
8691             if (_statuses.Tabs == null) return;
8692
8693             TabClass tb = _statuses.Tabs[_rclickTabName];
8694             if (tb == null) return;
8695
8696             NotifyDispMenuItem.Checked = tb.Notify;
8697             this.NotifyTbMenuItem.Checked = tb.Notify;
8698
8699             soundfileListup = true;
8700             SoundFileComboBox.Items.Clear();
8701             this.SoundFileTbComboBox.Items.Clear();
8702             SoundFileComboBox.Items.Add("");
8703             this.SoundFileTbComboBox.Items.Add("");
8704             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8705             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8706             {
8707                 oDir = oDir.GetDirectories("Sounds")[0];
8708             }
8709             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8710             {
8711                 SoundFileComboBox.Items.Add(oFile.Name);
8712                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8713             }
8714             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8715             if (idx == -1) idx = 0;
8716             SoundFileComboBox.SelectedIndex = idx;
8717             this.SoundFileTbComboBox.SelectedIndex = idx;
8718             soundfileListup = false;
8719             UreadManageMenuItem.Checked = tb.UnreadManage;
8720             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8721
8722             TabMenuControl(_rclickTabName);
8723         }
8724
8725         private void TabMenuControl(string tabName)
8726         {
8727             var tabInfo = _statuses.GetTabByName(tabName);
8728
8729             this.FilterEditMenuItem.Enabled = true;
8730             this.EditRuleTbMenuItem.Enabled = true;
8731
8732             if (tabInfo.IsDefaultTabType)
8733             {
8734                 this.ProtectTabMenuItem.Enabled = false;
8735                 this.ProtectTbMenuItem.Enabled = false;
8736             }
8737             else
8738             {
8739                 this.ProtectTabMenuItem.Enabled = true;
8740                 this.ProtectTbMenuItem.Enabled = true;
8741             }
8742
8743             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8744             {
8745                 this.ProtectTabMenuItem.Checked = true;
8746                 this.ProtectTbMenuItem.Checked = true;
8747                 this.DeleteTabMenuItem.Enabled = false;
8748                 this.DeleteTbMenuItem.Enabled = false;
8749             }
8750             else
8751             {
8752                 this.ProtectTabMenuItem.Checked = false;
8753                 this.ProtectTbMenuItem.Checked = false;
8754                 this.DeleteTabMenuItem.Enabled = true;
8755                 this.DeleteTbMenuItem.Enabled = true;
8756             }
8757         }
8758
8759         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8760         {
8761             var checkState = ((ToolStripMenuItem)sender).Checked;
8762
8763             // チェック状態を同期
8764             this.ProtectTbMenuItem.Checked = checkState;
8765             this.ProtectTabMenuItem.Checked = checkState;
8766
8767             // ロック中はタブの削除を無効化
8768             this.DeleteTabMenuItem.Enabled = !checkState;
8769             this.DeleteTbMenuItem.Enabled = !checkState;
8770
8771             if (string.IsNullOrEmpty(_rclickTabName)) return;
8772             _statuses.Tabs[_rclickTabName].Protected = checkState;
8773
8774             SaveConfigsTabs();
8775         }
8776
8777         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8778         {
8779             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8781
8782             if (string.IsNullOrEmpty(_rclickTabName)) return;
8783             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8784
8785             SaveConfigsTabs();
8786         }
8787
8788         public void ChangeTabUnreadManage(string tabName, bool isManage)
8789         {
8790             var idx = this.GetTabPageIndex(tabName);
8791             if (idx == -1)
8792                 return;
8793
8794             _statuses.Tabs[tabName].UnreadManage = isManage;
8795             if (this._cfgCommon.TabIconDisp)
8796             {
8797                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8798                     ListTab.TabPages[idx].ImageIndex = 0;
8799                 else
8800                     ListTab.TabPages[idx].ImageIndex = -1;
8801             }
8802
8803             if (_curTab.Text == tabName)
8804             {
8805                 this.PurgeListViewItemCache();
8806                 _curList.Refresh();
8807             }
8808
8809             SetMainWindowTitle();
8810             SetStatusLabelUrl();
8811             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8812         }
8813
8814         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8815         {
8816             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8817             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8818
8819             if (string.IsNullOrEmpty(_rclickTabName)) return;
8820
8821             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8822
8823             SaveConfigsTabs();
8824         }
8825
8826         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8827         {
8828             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8829
8830             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8831
8832             SaveConfigsTabs();
8833         }
8834
8835         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8836         {
8837             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8838
8839             RemoveSpecifiedTab(_rclickTabName, true);
8840             SaveConfigsTabs();
8841         }
8842
8843         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8844         {
8845             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8846
8847             using (var fltDialog = new FilterDialog())
8848             {
8849                 fltDialog.Owner = this;
8850                 fltDialog.SetCurrent(_rclickTabName);
8851                 fltDialog.ShowDialog(this);
8852             }
8853             this.TopMost = this._cfgCommon.AlwaysTop;
8854
8855             this.ApplyPostFilters();
8856             SaveConfigsTabs();
8857         }
8858
8859         private void AddTabMenuItem_Click(object sender, EventArgs e)
8860         {
8861             string tabName = null;
8862             MyCommon.TabUsageType tabUsage;
8863             using (InputTabName inputName = new InputTabName())
8864             {
8865                 inputName.TabName = _statuses.MakeTabName("MyTab");
8866                 inputName.IsShowUsage = true;
8867                 inputName.ShowDialog();
8868                 if (inputName.DialogResult == DialogResult.Cancel) return;
8869                 tabName = inputName.TabName;
8870                 tabUsage = inputName.Usage;
8871             }
8872             this.TopMost = this._cfgCommon.AlwaysTop;
8873             if (!string.IsNullOrEmpty(tabName))
8874             {
8875                 //List対応
8876                 ListElement list = null;
8877                 if (tabUsage == MyCommon.TabUsageType.Lists)
8878                 {
8879                     using (ListAvailable listAvail = new ListAvailable())
8880                     {
8881                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8882                         if (listAvail.SelectedList == null) return;
8883                         list = listAvail.SelectedList;
8884                     }
8885                 }
8886                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8887                 {
8888                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8889                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8890                 }
8891                 else
8892                 {
8893                     //成功
8894                     SaveConfigsTabs();
8895                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8896                     {
8897                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8898                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8899                     }
8900                     if (tabUsage == MyCommon.TabUsageType.Lists)
8901                     {
8902                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8903                         var tab = this._statuses.Tabs[this._curTab.Text];
8904                         this.GetListTimelineAsync(tab);
8905                     }
8906                 }
8907             }
8908         }
8909
8910         private void TabMenuItem_Click(object sender, EventArgs e)
8911         {
8912             using (var fltDialog = new FilterDialog())
8913             {
8914                 fltDialog.Owner = this;
8915
8916                 //選択発言を元にフィルタ追加
8917                 foreach (int idx in _curList.SelectedIndices)
8918                 {
8919                     string tabName;
8920                     //タブ選択(or追加)
8921                     if (!SelectTab(out tabName)) return;
8922
8923                     fltDialog.SetCurrent(tabName);
8924                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8925                     {
8926                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8927                     }
8928                     else
8929                     {
8930                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8931                     }
8932                     fltDialog.ShowDialog(this);
8933                     this.TopMost = this._cfgCommon.AlwaysTop;
8934                 }
8935             }
8936
8937             this.ApplyPostFilters();
8938             SaveConfigsTabs();
8939             if (this.ListTab.SelectedTab != null &&
8940                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8941             {
8942                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8943             }
8944         }
8945
8946         protected override bool ProcessDialogKey(Keys keyData)
8947         {
8948             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8949             if ((keyData & Keys.KeyCode) == Keys.Enter)
8950             {
8951                 if (StatusText.Focused)
8952                 {
8953                     bool _NewLine = false;
8954                     bool _Post = false;
8955
8956                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8957                     {
8958                         if (StatusText.Multiline)
8959                         {
8960                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8961
8962                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8963                         }
8964                         else
8965                         {
8966                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8967                         }
8968
8969                     }
8970                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8971                     {
8972                         if (StatusText.Multiline)
8973                         {
8974                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8975
8976                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8977                         }
8978                         else
8979                         {
8980                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8981                         }
8982
8983                     }
8984                     else //Enter投稿時
8985                     {
8986                         if (StatusText.Multiline)
8987                         {
8988                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8989
8990                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8991                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8992                         }
8993                         else
8994                         {
8995                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8996                                 (((keyData & Keys.Control) != Keys.Control) &&
8997                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8998                         }
8999                     }
9000
9001                     if (_NewLine)
9002                     {
9003                         int pos1 = StatusText.SelectionStart;
9004                         if (StatusText.SelectionLength > 0)
9005                         {
9006                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
9007                         }
9008                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
9009                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
9010                         return true;
9011                     }
9012                     else if (_Post)
9013                     {
9014                         PostButton_Click(null, null);
9015                         return true;
9016                     }
9017                 }
9018                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9019                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9020                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9021                 {
9022                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9023                     return true;
9024                 }
9025             }
9026
9027             return base.ProcessDialogKey(keyData);
9028         }
9029
9030         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9031         {
9032             MakeReplyOrDirectStatus(false, true, true);
9033         }
9034
9035         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9036         {
9037             string tabName;
9038
9039             //未選択なら処理終了
9040             if (_curList.SelectedIndices.Count == 0) return;
9041
9042             //タブ選択(or追加)
9043             if (!SelectTab(out tabName)) return;
9044
9045             var tab = this._statuses.Tabs[tabName];
9046
9047             bool mv;
9048             bool mk;
9049             if (tab.TabType != MyCommon.TabUsageType.Mute)
9050             {
9051                 this.MoveOrCopy(out mv, out mk);
9052             }
9053             else
9054             {
9055                 // ミュートタブでは常に MoveMatches を true にする
9056                 mv = true;
9057                 mk = false;
9058             }
9059
9060             List<string> ids = new List<string>();
9061             foreach (int idx in _curList.SelectedIndices)
9062             {
9063                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9064                 if (!ids.Contains(post.ScreenName))
9065                 {
9066                     PostFilterRule fc = new PostFilterRule();
9067                     ids.Add(post.ScreenName);
9068                     if (post.RetweetedId == null)
9069                     {
9070                         fc.FilterName = post.ScreenName;
9071                     }
9072                     else
9073                     {
9074                         fc.FilterName = post.RetweetedBy;
9075                     }
9076                     fc.UseNameField = true;
9077                     fc.MoveMatches = mv;
9078                     fc.MarkMatches = mk;
9079                     fc.UseRegex = false;
9080                     fc.FilterByUrl = false;
9081                     tab.AddFilter(fc);
9082                 }
9083             }
9084             if (ids.Count != 0)
9085             {
9086                 List<string> atids = new List<string>();
9087                 foreach (string id in ids)
9088                 {
9089                     atids.Add("@" + id);
9090                 }
9091                 int cnt = AtIdSupl.ItemCount;
9092                 AtIdSupl.AddRangeItem(atids.ToArray());
9093                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9094             }
9095
9096             this.ApplyPostFilters();
9097             SaveConfigsTabs();
9098         }
9099
9100         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9101         {
9102             if (this._curList.SelectedIndices.Count == 0)
9103                 return;
9104
9105             // タブ選択ダイアログを表示(or追加)
9106             string tabName;
9107             if (!this.SelectTab(out tabName))
9108                 return;
9109
9110             var currentTab = this._statuses.Tabs[this._curTab.Text];
9111             var filterTab = this._statuses.Tabs[tabName];
9112
9113             bool mv;
9114             bool mk;
9115             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9116             {
9117                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9118                 this.MoveOrCopy(out mv, out mk);
9119             }
9120             else
9121             {
9122                 // ミュートタブでは常に MoveMatches を true にする
9123                 mv = true;
9124                 mk = false;
9125             }
9126
9127             // 振り分けルールに追加するSource
9128             var sources = new HashSet<string>();
9129
9130             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9131             {
9132                 var post = currentTab[idx];
9133                 var filterSource = post.Source;
9134
9135                 if (sources.Add(filterSource))
9136                 {
9137                     var filter = new PostFilterRule
9138                     {
9139                         FilterSource = filterSource,
9140                         MoveMatches = mv,
9141                         MarkMatches = mk,
9142                         UseRegex = false,
9143                         FilterByUrl = false,
9144                     };
9145                     filterTab.AddFilter(filter);
9146                 }
9147             }
9148
9149             this.ApplyPostFilters();
9150             this.SaveConfigsTabs();
9151         }
9152
9153         private bool SelectTab(out string tabName)
9154         {
9155             do
9156             {
9157                 tabName = null;
9158
9159                 //振り分け先タブ選択
9160                 using (var dialog = new TabsDialog(_statuses))
9161                 {
9162                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9163
9164                     var selectedTab = dialog.SelectedTab;
9165                     tabName = selectedTab == null ? null : selectedTab.TabName;
9166                 }
9167
9168                 ListTab.SelectedTab.Focus();
9169                 //新規タブを選択→タブ作成
9170                 if (tabName == null)
9171                 {
9172                     using (InputTabName inputName = new InputTabName())
9173                     {
9174                         inputName.TabName = _statuses.MakeTabName("MyTab");
9175                         inputName.ShowDialog();
9176                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9177                         tabName = inputName.TabName;
9178                     }
9179                     this.TopMost = this._cfgCommon.AlwaysTop;
9180                     if (!string.IsNullOrEmpty(tabName))
9181                     {
9182                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9183                         {
9184                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9185                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9186                             //もう一度タブ名入力
9187                         }
9188                         else
9189                         {
9190                             return true;
9191                         }
9192                     }
9193                 }
9194                 else
9195                 {
9196                     //既存タブを選択
9197                     return true;
9198                 }
9199             }
9200             while (true);
9201         }
9202
9203         private void MoveOrCopy(out bool move, out bool mark)
9204         {
9205             {
9206                 //移動するか?
9207                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9208                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9209                     move = false;
9210                 else
9211                     move = true;
9212             }
9213             if (!move)
9214             {
9215                 //マークするか?
9216                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9217                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9218                     mark = true;
9219                 else
9220                     mark = false;
9221             }
9222             else
9223             {
9224                 mark = false;
9225             }
9226         }
9227         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9228         {
9229             this.CopyStot();
9230         }
9231
9232         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9233         {
9234             this.CopyIdUri();
9235         }
9236
9237         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9238         {
9239             if (StatusText.Focused)
9240             {
9241                 // 発言欄でのCtrl+A
9242                 StatusText.SelectAll();
9243             }
9244             else
9245             {
9246                 // ListView上でのCtrl+A
9247                 NativeMethods.SelectAllItems(this._curList);
9248             }
9249         }
9250
9251         private void MoveMiddle()
9252         {
9253             ListViewItem _item;
9254             int idx1;
9255             int idx2;
9256
9257             if (_curList.SelectedIndices.Count == 0) return;
9258
9259             int idx = _curList.SelectedIndices[0];
9260
9261             _item = _curList.GetItemAt(0, 25);
9262             if (_item == null)
9263                 idx1 = 0;
9264             else
9265                 idx1 = _item.Index;
9266
9267             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9268             if (_item == null)
9269                 idx2 = _curList.VirtualListSize - 1;
9270             else
9271                 idx2 = _item.Index;
9272
9273             idx -= Math.Abs(idx1 - idx2) / 2;
9274             if (idx < 0) idx = 0;
9275
9276             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9277             _curList.EnsureVisible(idx);
9278         }
9279
9280         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9281         {
9282             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9283                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9284                 .ToArray();
9285
9286             if (linkElements.Length > 0)
9287             {
9288                 UrlDialog.ClearUrl();
9289
9290                 string openUrlStr = "";
9291
9292                 if (linkElements.Length == 1)
9293                 {
9294                     // ツイートに含まれる URL が 1 つのみの場合
9295                     //   => OpenURL ダイアログを表示せずにリンクを開く
9296
9297                     string urlStr = "";
9298                     try
9299                     {
9300                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9301                     }
9302                     catch (ArgumentException)
9303                     {
9304                         //変なHTML?
9305                         return;
9306                     }
9307                     catch (Exception)
9308                     {
9309                         return;
9310                     }
9311                     if (string.IsNullOrEmpty(urlStr)) return;
9312                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9313
9314                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9315                     await this.OpenUriAsync(new Uri(openUrlStr));
9316                 }
9317                 else
9318                 {
9319                     // ツイートに含まれる URL が複数ある場合
9320                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9321
9322                     foreach (var linkElm in linkElements)
9323                     {
9324                         string urlStr = "";
9325                         string linkText = "";
9326                         string href = "";
9327                         try
9328                         {
9329                             urlStr = linkElm.GetAttribute("title");
9330                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9331                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9332                             linkText = linkElm.InnerText;
9333                         }
9334                         catch (ArgumentException)
9335                         {
9336                             //変なHTML?
9337                             return;
9338                         }
9339                         catch (Exception)
9340                         {
9341                             return;
9342                         }
9343                         if (string.IsNullOrEmpty(urlStr)) continue;
9344                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9345                     }
9346                     try
9347                     {
9348                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9349                         {
9350                             openUrlStr = UrlDialog.SelectedUrl;
9351
9352                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9353                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9354                         }
9355                     }
9356                     catch (Exception)
9357                     {
9358                         return;
9359                     }
9360                     this.TopMost = this._cfgCommon.AlwaysTop;
9361                 }
9362             }
9363         }
9364
9365         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9366         {
9367             if (string.IsNullOrEmpty(_rclickTabName)) return;
9368             ClearTab(_rclickTabName, true);
9369         }
9370
9371         private void ClearTab(string tabName, bool showWarning)
9372         {
9373             if (showWarning)
9374             {
9375                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9376                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9377                 {
9378                     return;
9379                 }
9380             }
9381
9382             _statuses.ClearTabIds(tabName);
9383             if (ListTab.SelectedTab.Text == tabName)
9384             {
9385                 _anchorPost = null;
9386                 _anchorFlag = false;
9387                 this.PurgeListViewItemCache();
9388                 _curItemIndex = -1;
9389                 _curPost = null;
9390             }
9391             foreach (TabPage tb in ListTab.TabPages)
9392             {
9393                 if (tb.Text == tabName)
9394                 {
9395                     tb.ImageIndex = -1;
9396                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9397                     break;
9398                 }
9399             }
9400             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9401
9402             SetMainWindowTitle();
9403             SetStatusLabelUrl();
9404         }
9405
9406         private static long followers = 0;
9407
9408         private void SetMainWindowTitle()
9409         {
9410             //メインウインドウタイトルの書き換え
9411             StringBuilder ttl = new StringBuilder(256);
9412             int ur = 0;
9413             int al = 0;
9414             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9415                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9416                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9417                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9418             {
9419                 foreach (var tab in _statuses.Tabs.Values)
9420                 {
9421                     ur += tab.UnreadCount;
9422                     al += tab.AllCount;
9423                 }
9424             }
9425
9426             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9427             ttl.Append(Application.ProductName);
9428             ttl.Append("  ");
9429             switch (this._cfgCommon.DispLatestPost)
9430             {
9431                 case MyCommon.DispTitleEnum.Ver:
9432                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9433                     break;
9434                 case MyCommon.DispTitleEnum.Post:
9435                     if (_history != null && _history.Count > 1)
9436                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9437                     break;
9438                 case MyCommon.DispTitleEnum.UnreadRepCount:
9439                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9440                     break;
9441                 case MyCommon.DispTitleEnum.UnreadAllCount:
9442                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9443                     break;
9444                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9445                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9446                     break;
9447                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9448                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9449                     break;
9450                 case MyCommon.DispTitleEnum.OwnStatus:
9451                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9452                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9453                     break;
9454             }
9455
9456             try
9457             {
9458                 this.Text = ttl.ToString();
9459             }
9460             catch (AccessViolationException)
9461             {
9462                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9463             }
9464         }
9465
9466         private string GetStatusLabelText()
9467         {
9468             //ステータス欄にカウント表示
9469             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9470             if (_statuses == null) return "";
9471             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9472             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9473             if (tbRep == null || tbDm == null) return "";
9474             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9475             int ur = 0;
9476             int al = 0;
9477             int tur = 0;
9478             int tal = 0;
9479             StringBuilder slbl = new StringBuilder(256);
9480             try
9481             {
9482                 foreach (var tab in _statuses.Tabs.Values)
9483                 {
9484                     ur += tab.UnreadCount;
9485                     al += tab.AllCount;
9486                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9487                     {
9488                         tur = tab.UnreadCount;
9489                         tal = tab.AllCount;
9490                     }
9491                 }
9492             }
9493             catch (Exception)
9494             {
9495                 return "";
9496             }
9497
9498             UnreadCounter = ur;
9499             UnreadAtCounter = urat;
9500
9501             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9502             if (this._cfgCommon.TimelinePeriod == 0)
9503             {
9504                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9505             }
9506             else
9507             {
9508                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9509             }
9510             return slbl.ToString();
9511         }
9512
9513         private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9514         {
9515             try
9516             {
9517                 if (this.InvokeRequired && !this.IsDisposed)
9518                 {
9519                     this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9520                 }
9521                 else
9522                 {
9523                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9524                     SetApiStatusLabel(endpointName);
9525                 }
9526             }
9527             catch (ObjectDisposedException)
9528             {
9529                 return;
9530             }
9531             catch (InvalidOperationException)
9532             {
9533                 return;
9534             }
9535         }
9536
9537         private void SetApiStatusLabel(string endpointName = null)
9538         {
9539             if (_curTab == null)
9540             {
9541                 this.toolStripApiGauge.ApiEndpoint = null;
9542             }
9543             else
9544             {
9545                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9546
9547                 if (endpointName == null)
9548                 {
9549                     // 表示中のタブに応じて更新
9550                     switch (tabType)
9551                     {
9552                         case MyCommon.TabUsageType.Home:
9553                         case MyCommon.TabUsageType.UserDefined:
9554                             endpointName = "/statuses/home_timeline";
9555                             break;
9556
9557                         case MyCommon.TabUsageType.Mentions:
9558                             endpointName = "/statuses/mentions_timeline";
9559                             break;
9560
9561                         case MyCommon.TabUsageType.Favorites:
9562                             endpointName = "/favorites/list";
9563                             break;
9564
9565                         case MyCommon.TabUsageType.DirectMessage:
9566                             endpointName = "/direct_messages";
9567                             break;
9568
9569                         case MyCommon.TabUsageType.UserTimeline:
9570                             endpointName = "/statuses/user_timeline";
9571                             break;
9572
9573                         case MyCommon.TabUsageType.Lists:
9574                             endpointName = "/lists/statuses";
9575                             break;
9576
9577                         case MyCommon.TabUsageType.PublicSearch:
9578                             endpointName = "/search/tweets";
9579                             break;
9580
9581                         case MyCommon.TabUsageType.Related:
9582                             endpointName = "/statuses/show/:id";
9583                             break;
9584
9585                         default:
9586                             break;
9587                     }
9588
9589                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9590                 }
9591                 else
9592                 {
9593                     // 表示中のタブに関連する endpoint であれば更新
9594                     var update = false;
9595
9596                     switch (endpointName)
9597                     {
9598                         case "/statuses/home_timeline":
9599                             update = tabType == MyCommon.TabUsageType.Home ||
9600                                      tabType == MyCommon.TabUsageType.UserDefined;
9601                             break;
9602
9603                         case "/statuses/mentions_timeline":
9604                             update = tabType == MyCommon.TabUsageType.Mentions;
9605                             break;
9606
9607                         case "/favorites/list":
9608                             update = tabType == MyCommon.TabUsageType.Favorites;
9609                             break;
9610
9611                         case "/direct_messages:":
9612                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9613                             break;
9614
9615                         case "/statuses/user_timeline":
9616                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9617                             break;
9618
9619                         case "/lists/statuses":
9620                             update = tabType == MyCommon.TabUsageType.Lists;
9621                             break;
9622
9623                         case "/search/tweets":
9624                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9625                             break;
9626
9627                         case "/statuses/show/:id":
9628                             update = tabType == MyCommon.TabUsageType.Related;
9629                             break;
9630
9631                         default:
9632                             break;
9633                     }
9634
9635                     if (update)
9636                     {
9637                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9638                     }
9639                 }
9640             }
9641         }
9642
9643         private void SetStatusLabelUrl()
9644         {
9645             StatusLabelUrl.Text = GetStatusLabelText();
9646         }
9647
9648         public void SetStatusLabel(string text)
9649         {
9650             StatusLabel.Text = text;
9651         }
9652
9653         private static StringBuilder ur = new StringBuilder(64);
9654
9655         private void SetNotifyIconText()
9656         {
9657             // タスクトレイアイコンのツールチップテキスト書き換え
9658             // Tween [未読/@]
9659             ur.Remove(0, ur.Length);
9660             if (this._cfgCommon.DispUsername)
9661             {
9662                 ur.Append(tw.Username);
9663                 ur.Append(" - ");
9664             }
9665             ur.Append(Application.ProductName);
9666 #if DEBUG
9667             ur.Append("(Debug Build)");
9668 #endif
9669             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9670             {
9671                 ur.Append(" [");
9672                 ur.Append(UnreadCounter);
9673                 ur.Append("/@");
9674                 ur.Append(UnreadAtCounter);
9675                 ur.Append("]");
9676             }
9677             NotifyIcon1.Text = ur.ToString();
9678         }
9679
9680         internal void CheckReplyTo(string StatusText)
9681         {
9682             MatchCollection m;
9683             //ハッシュタグの保存
9684             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9685             string hstr = "";
9686             foreach (Match hm in m)
9687             {
9688                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9689                 {
9690                     hstr += "#" + hm.Result("$3") + " ";
9691                     HashSupl.AddItem("#" + hm.Result("$3"));
9692                 }
9693             }
9694             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9695             {
9696                 hstr += HashMgr.UseHash;
9697             }
9698             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9699
9700             // 本当にリプライ先指定すべきかどうかの判定
9701             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9702
9703             if (this._cfgCommon.UseAtIdSupplement)
9704             {
9705                 int bCnt = AtIdSupl.ItemCount;
9706                 foreach (Match mid in m)
9707                 {
9708                     AtIdSupl.AddItem(mid.Result("${id}"));
9709                 }
9710                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9711             }
9712
9713             // リプライ先ステータスIDの指定がない場合は指定しない
9714             if (this.inReplyTo == null)
9715                 return;
9716
9717             // 通常Reply
9718             // 次の条件を満たす場合に in_reply_to_status_id 指定
9719             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9720             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9721             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9722
9723             if (m != null)
9724             {
9725                 var inReplyToScreenName = this.inReplyTo.Item2;
9726                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9727                 {
9728                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9729                 }
9730                 else
9731                 {
9732                     foreach (Match mid in m)
9733                     {
9734                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9735                     }
9736                 }
9737             }
9738
9739             this.inReplyTo = null;
9740         }
9741
9742         private void TweenMain_Resize(object sender, EventArgs e)
9743         {
9744             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9745             {
9746                 this.Visible = false;
9747             }
9748             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9749             {
9750                 // 現在の DPI と設定保存時の DPI との比を取得する
9751                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9752
9753                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9754                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9755                 this.DesktopLocation = _cfgLocal.FormLocation;
9756                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9757
9758                 // Splitterの位置設定
9759                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9760                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9761                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9762                 {
9763                     this.SplitContainer1.SplitterDistance = splitterDistance;
9764                 }
9765
9766                 //発言欄複数行
9767                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9768                 if (StatusText.Multiline)
9769                 {
9770                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9771                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9772                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9773                     {
9774                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9775                     }
9776                     StatusText.Height = statusTextHeight;
9777                 }
9778                 else
9779                 {
9780                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9781                     {
9782                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9783                     }
9784                 }
9785
9786                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9787                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9788                 {
9789                     this.SplitContainer3.SplitterDistance = previewDistance;
9790                 }
9791
9792                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9793                 this.SplitContainer3.Panel2Collapsed = true;
9794
9795                 _initialLayout = false;
9796             }
9797             if (this.WindowState != FormWindowState.Minimized)
9798             {
9799                 _formWindowState = this.WindowState;
9800             }
9801         }
9802
9803         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9804         {
9805             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9806             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9807             if (PlaySoundMenuItem.Checked)
9808             {
9809                 this._cfgCommon.PlaySound = true;
9810             }
9811             else
9812             {
9813                 this._cfgCommon.PlaySound = false;
9814             }
9815             ModifySettingCommon = true;
9816         }
9817
9818         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9819         {
9820             if (this._initialLayout)
9821                 return;
9822
9823             int splitterDistance;
9824             switch (this.WindowState)
9825             {
9826                 case FormWindowState.Normal:
9827                     splitterDistance = this.SplitContainer1.SplitterDistance;
9828                     break;
9829                 case FormWindowState.Maximized:
9830                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9831                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9832                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9833                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9834                     break;
9835                 default:
9836                     return;
9837             }
9838
9839             this._mySpDis = splitterDistance;
9840             this.ModifySettingLocal = true;
9841         }
9842
9843         private async Task doRepliedStatusOpen()
9844         {
9845             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9846             {
9847                 if (MyCommon.IsKeyDown(Keys.Shift))
9848                 {
9849                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9850                     return;
9851                 }
9852                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9853                 {
9854                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9855                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9856                 }
9857                 else
9858                 {
9859                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9860                     {
9861                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9862                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9863                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9864                         return;
9865                     }
9866                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9867                 }
9868             }
9869         }
9870
9871         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9872         {
9873             await this.doRepliedStatusOpen();
9874         }
9875
9876         /// <summary>
9877         /// UserPicture.Image に設定されている画像を破棄します。
9878         /// </summary>
9879         private void ClearUserPicture()
9880         {
9881             if (this.UserPicture.Image != null)
9882             {
9883                 var oldImage = this.UserPicture.Image;
9884                 this.UserPicture.Image = null;
9885                 oldImage.Dispose();
9886             }
9887         }
9888
9889         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9890         {
9891             //発言詳細のアイコン右クリック時のメニュー制御
9892             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9893             {
9894                 string name = _curPost.ImageUrl;
9895                 if (name != null && name.Length > 0)
9896                 {
9897                     int idx = name.LastIndexOf('/');
9898                     if (idx != -1)
9899                     {
9900                         name = Path.GetFileName(name.Substring(idx));
9901                         if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9902                         {
9903                             name = name.Replace("_normal", "");
9904                             this.IconNameToolStripMenuItem.Text = name;
9905                             this.IconNameToolStripMenuItem.Enabled = true;
9906                         }
9907                         else
9908                         {
9909                             this.IconNameToolStripMenuItem.Enabled = false;
9910                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9911                         }
9912                     }
9913                     else
9914                     {
9915                         this.IconNameToolStripMenuItem.Enabled = false;
9916                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9917                     }
9918
9919                     this.ReloadIconToolStripMenuItem.Enabled = true;
9920
9921                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9922                     {
9923                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9924                     }
9925                     else
9926                     {
9927                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9928                     }
9929                 }
9930                 else
9931                 {
9932                     this.IconNameToolStripMenuItem.Enabled = false;
9933                     this.ReloadIconToolStripMenuItem.Enabled = false;
9934                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9935                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9936                 }
9937             }
9938             else
9939             {
9940                 this.IconNameToolStripMenuItem.Enabled = false;
9941                 this.ReloadIconToolStripMenuItem.Enabled = false;
9942                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9943                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9944             }
9945             if (NameLabel.Tag != null)
9946             {
9947                 string id = (string)NameLabel.Tag;
9948                 if (id == tw.Username)
9949                 {
9950                     FollowToolStripMenuItem.Enabled = false;
9951                     UnFollowToolStripMenuItem.Enabled = false;
9952                     ShowFriendShipToolStripMenuItem.Enabled = false;
9953                     ShowUserStatusToolStripMenuItem.Enabled = true;
9954                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9955                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9956                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9957                 }
9958                 else
9959                 {
9960                     FollowToolStripMenuItem.Enabled = true;
9961                     UnFollowToolStripMenuItem.Enabled = true;
9962                     ShowFriendShipToolStripMenuItem.Enabled = true;
9963                     ShowUserStatusToolStripMenuItem.Enabled = true;
9964                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9965                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9966                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9967                 }
9968             }
9969             else
9970             {
9971                 FollowToolStripMenuItem.Enabled = false;
9972                 UnFollowToolStripMenuItem.Enabled = false;
9973                 ShowFriendShipToolStripMenuItem.Enabled = false;
9974                 ShowUserStatusToolStripMenuItem.Enabled = false;
9975                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9976                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9977                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9978             }
9979         }
9980
9981         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9982         {
9983             if (_curPost == null) return;
9984             string name = _curPost.ImageUrl;
9985             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9986         }
9987
9988         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9989         {
9990             if (this._curPost == null) return;
9991
9992             await this.UserPicture.SetImageFromTask(async () =>
9993             {
9994                 var imageUrl = this._curPost.ImageUrl;
9995
9996                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9997                     .ConfigureAwait(false);
9998
9999                 return await image.CloneAsync()
10000                     .ConfigureAwait(false);
10001             });
10002         }
10003
10004         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10005         {
10006             if (_curPost == null) return;
10007             string name = _curPost.ImageUrl;
10008             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10009
10010             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10011
10012             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10013             {
10014                 // STUB
10015             }
10016         }
10017
10018         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10019         {
10020             if (_curPost == null) return;
10021             string name = _curPost.ImageUrl;
10022
10023             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10024
10025             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10026             {
10027                 try
10028                 {
10029                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10030                     {
10031                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10032                         {
10033                             using (Graphics g = Graphics.FromImage(bmp2))
10034                             {
10035                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10036                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10037                             }
10038                             bmp2.Save(this.SaveFileDialog1.FileName);
10039                         }
10040                     }
10041                 }
10042                 catch (Exception)
10043                 {
10044                     //処理中にキャッシュアウトする可能性あり
10045                 }
10046             }
10047         }
10048
10049         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10050         {
10051             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10052             if (multiline != this.StatusText.Multiline)
10053             {
10054                 this.StatusText.Multiline = multiline;
10055                 MultiLineMenuItem.Checked = multiline;
10056                 ModifySettingLocal = true;
10057             }
10058         }
10059
10060         private void StatusText_MultilineChanged(object sender, EventArgs e)
10061         {
10062             if (this.StatusText.Multiline)
10063                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10064             else
10065                 this.StatusText.ScrollBars = ScrollBars.None;
10066
10067             ModifySettingLocal = true;
10068         }
10069
10070         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10071         {
10072             //発言欄複数行
10073             StatusText.Multiline = MultiLineMenuItem.Checked;
10074             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10075             if (MultiLineMenuItem.Checked)
10076             {
10077                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10078                     SplitContainer2.SplitterDistance = 0;
10079                 else
10080                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10081             }
10082             else
10083             {
10084                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10085             }
10086             ModifySettingLocal = true;
10087         }
10088
10089         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10090         {
10091             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10092             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10093
10094             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10095             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10096             //Appendix A.  Collected ABNF for URI
10097             //http://www.ietf.org/rfc/rfc3986.txt
10098
10099             string result = "";
10100
10101             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10102
10103             if (StatusText.SelectionLength > 0)
10104             {
10105                 string tmp = StatusText.SelectedText;
10106                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10107                 if (tmp.StartsWith("http"))
10108                 {
10109                     // 文字列が選択されている場合はその文字列について処理
10110
10111                     //nico.ms使用、nicovideoにマッチしたら変換
10112                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10113                     {
10114                         result = nicoms.Shorten(tmp);
10115                     }
10116                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10117                     {
10118                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10119                         try
10120                         {
10121                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10122                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10123                             result = resultUri.AbsoluteUri;
10124                         }
10125                         catch (WebApiException e)
10126                         {
10127                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10128                             return false;
10129                         }
10130                         catch (UriFormatException e)
10131                         {
10132                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10133                             return false;
10134                         }
10135                     }
10136                     else
10137                     {
10138                         return true;
10139                     }
10140
10141                     if (!string.IsNullOrEmpty(result))
10142                     {
10143                         urlUndo undotmp = new urlUndo();
10144
10145                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10146                         StatusText.SelectedText = result;
10147
10148                         //undoバッファにセット
10149                         undotmp.Before = tmp;
10150                         undotmp.After = result;
10151
10152                         if (urlUndoBuffer == null)
10153                         {
10154                             urlUndoBuffer = new List<urlUndo>();
10155                             UrlUndoToolStripMenuItem.Enabled = true;
10156                         }
10157
10158                         urlUndoBuffer.Add(undotmp);
10159                     }
10160                 }
10161             }
10162             else
10163             {
10164                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10165                                    @"(?<url>(?<protocol>https?://)" +
10166                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10167                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10168                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10169                 // 正規表現にマッチしたURL文字列をtinyurl化
10170                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10171                 {
10172                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10173                     string tmp = mt.Result("${url}");
10174                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10175                     urlUndo undotmp = new urlUndo();
10176
10177                     //選んだURLを選択(?)
10178                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10179
10180                     //nico.ms使用、nicovideoにマッチしたら変換
10181                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10182                     {
10183                         result = nicoms.Shorten(tmp);
10184                     }
10185                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10186                     {
10187                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10188                         try
10189                         {
10190                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10191                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10192                             result = resultUri.AbsoluteUri;
10193                         }
10194                         catch (HttpRequestException e)
10195                         {
10196                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10197                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10198                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10199
10200                             this.StatusLabel.Text = Converter_Type + ":" + message;
10201                             continue;
10202                         }
10203                         catch (WebApiException e)
10204                         {
10205                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10206                             continue;
10207                         }
10208                         catch (UriFormatException e)
10209                         {
10210                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10211                             continue;
10212                         }
10213                     }
10214                     else
10215                     {
10216                         continue;
10217                     }
10218
10219                     if (!string.IsNullOrEmpty(result))
10220                     {
10221                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10222                         StatusText.SelectedText = result;
10223                         //undoバッファにセット
10224                         undotmp.Before = mt.Result("${url}");
10225                         undotmp.After = result;
10226
10227                         if (urlUndoBuffer == null)
10228                         {
10229                             urlUndoBuffer = new List<urlUndo>();
10230                             UrlUndoToolStripMenuItem.Enabled = true;
10231                         }
10232
10233                         urlUndoBuffer.Add(undotmp);
10234                     }
10235                 }
10236             }
10237
10238             return true;
10239         }
10240
10241         private void doUrlUndo()
10242         {
10243             if (urlUndoBuffer != null)
10244             {
10245                 string tmp = StatusText.Text;
10246                 foreach (urlUndo data in urlUndoBuffer)
10247                 {
10248                     tmp = tmp.Replace(data.After, data.Before);
10249                 }
10250                 StatusText.Text = tmp;
10251                 urlUndoBuffer = null;
10252                 UrlUndoToolStripMenuItem.Enabled = false;
10253                 StatusText.SelectionStart = 0;
10254                 StatusText.SelectionLength = 0;
10255             }
10256         }
10257
10258         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10259         {
10260             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10261         }
10262
10263         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10264         {
10265             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10266         }
10267
10268         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10269         {
10270             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10271         }
10272
10273         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10274         {
10275             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10276         }
10277
10278         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10279         {
10280             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10281             {
10282                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10283                 Random rnd = new Random();
10284                 // 前回使用した短縮URLサービス以外を選択する
10285                 do
10286                 {
10287                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10288                 }
10289                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10290                 await UrlConvertAsync(svc);
10291             }
10292         }
10293
10294         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10295         {
10296             doUrlUndo();
10297         }
10298
10299         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10300         {
10301             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10302             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10303             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10304             ModifySettingCommon = true;
10305         }
10306
10307         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10308         {
10309             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10310             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10311             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10312             ModifySettingCommon = true;
10313         }
10314
10315         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10316         {
10317             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10318             MenuStrip1.Tag = new Object();
10319             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10320         }
10321
10322         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10323         {
10324             if (this.Tag != null) // 設定された戻り先へ遷移
10325             {
10326                 if (this.Tag == this.ListTab.SelectedTab)
10327                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10328                 else
10329                     ((Control)this.Tag).Select();
10330             }
10331             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10332             {
10333                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10334                 {
10335                     this.Tag = ListTab.SelectedTab.Tag;
10336                     ((Control)this.Tag).Select();
10337                 }
10338             }
10339             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10340             MenuStrip1.Tag = null;
10341         }
10342
10343         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10344         {
10345             DetailsListView lst = (DetailsListView)sender;
10346             if (_cfgLocal == null) return;
10347
10348             if (_iconCol)
10349             {
10350                 _cfgLocal.Width1 = lst.Columns[0].Width;
10351                 _cfgLocal.Width3 = lst.Columns[1].Width;
10352             }
10353             else
10354             {
10355                 int[] darr = new int[lst.Columns.Count];
10356                 for (int i = 0; i < lst.Columns.Count; i++)
10357                 {
10358                     darr[lst.Columns[i].DisplayIndex] = i;
10359                 }
10360                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10361
10362                 for (int i = 0; i < lst.Columns.Count; i++)
10363                 {
10364                     switch (darr[i])
10365                     {
10366                         case 0:
10367                             _cfgLocal.DisplayIndex1 = i;
10368                             break;
10369                         case 1:
10370                             _cfgLocal.DisplayIndex2 = i;
10371                             break;
10372                         case 2:
10373                             _cfgLocal.DisplayIndex3 = i;
10374                             break;
10375                         case 3:
10376                             _cfgLocal.DisplayIndex4 = i;
10377                             break;
10378                         case 4:
10379                             _cfgLocal.DisplayIndex5 = i;
10380                             break;
10381                         case 5:
10382                             _cfgLocal.DisplayIndex6 = i;
10383                             break;
10384                         case 6:
10385                             _cfgLocal.DisplayIndex7 = i;
10386                             break;
10387                         case 7:
10388                             _cfgLocal.DisplayIndex8 = i;
10389                             break;
10390                     }
10391                 }
10392                 _cfgLocal.Width1 = lst.Columns[0].Width;
10393                 _cfgLocal.Width2 = lst.Columns[1].Width;
10394                 _cfgLocal.Width3 = lst.Columns[2].Width;
10395                 _cfgLocal.Width4 = lst.Columns[3].Width;
10396                 _cfgLocal.Width5 = lst.Columns[4].Width;
10397                 _cfgLocal.Width6 = lst.Columns[5].Width;
10398                 _cfgLocal.Width7 = lst.Columns[6].Width;
10399                 _cfgLocal.Width8 = lst.Columns[7].Width;
10400             }
10401             ModifySettingLocal = true;
10402             _isColumnChanged = true;
10403         }
10404
10405         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10406         {
10407             DetailsListView lst = (DetailsListView)sender;
10408             if (_cfgLocal == null) return;
10409             if (_iconCol)
10410             {
10411                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10412                 {
10413                     _cfgLocal.Width1 = lst.Columns[0].Width;
10414                     ModifySettingLocal = true;
10415                     _isColumnChanged = true;
10416                 }
10417                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10418                 {
10419                     _cfgLocal.Width3 = lst.Columns[1].Width;
10420                     ModifySettingLocal = true;
10421                     _isColumnChanged = true;
10422                 }
10423             }
10424             else
10425             {
10426                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10427                 {
10428                     _cfgLocal.Width1 = lst.Columns[0].Width;
10429                     ModifySettingLocal = true;
10430                     _isColumnChanged = true;
10431                 }
10432                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10433                 {
10434                     _cfgLocal.Width2 = lst.Columns[1].Width;
10435                     ModifySettingLocal = true;
10436                     _isColumnChanged = true;
10437                 }
10438                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10439                 {
10440                     _cfgLocal.Width3 = lst.Columns[2].Width;
10441                     ModifySettingLocal = true;
10442                     _isColumnChanged = true;
10443                 }
10444                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10445                 {
10446                     _cfgLocal.Width4 = lst.Columns[3].Width;
10447                     ModifySettingLocal = true;
10448                     _isColumnChanged = true;
10449                 }
10450                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10451                 {
10452                     _cfgLocal.Width5 = lst.Columns[4].Width;
10453                     ModifySettingLocal = true;
10454                     _isColumnChanged = true;
10455                 }
10456                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10457                 {
10458                     _cfgLocal.Width6 = lst.Columns[5].Width;
10459                     ModifySettingLocal = true;
10460                     _isColumnChanged = true;
10461                 }
10462                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10463                 {
10464                     _cfgLocal.Width7 = lst.Columns[6].Width;
10465                     ModifySettingLocal = true;
10466                     _isColumnChanged = true;
10467                 }
10468                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10469                 {
10470                     _cfgLocal.Width8 = lst.Columns[7].Width;
10471                     ModifySettingLocal = true;
10472                     _isColumnChanged = true;
10473                 }
10474             }
10475             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10476             //if (changed)
10477             //{
10478             //    SaveConfigsLocal();
10479             //}
10480         }
10481
10482         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10483         {
10484             //発言詳細で「選択文字列をコピー」
10485             string _selText = this.PostBrowser.GetSelectedText();
10486             try
10487             {
10488                 Clipboard.SetDataObject(_selText, false, 5, 100);
10489             }
10490             catch (Exception ex)
10491             {
10492                 MessageBox.Show(ex.Message);
10493             }
10494         }
10495
10496         private async Task doSearchToolStrip(string url)
10497         {
10498             //発言詳細で「選択文字列で検索」(選択文字列取得)
10499             string _selText = this.PostBrowser.GetSelectedText();
10500
10501             if (_selText != null)
10502             {
10503                 if (url == Properties.Resources.SearchItem4Url)
10504                 {
10505                     //公式検索
10506                     AddNewTabForSearch(_selText);
10507                     return;
10508                 }
10509
10510                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10511                 await this.OpenUriInBrowserAsync(tmp);
10512             }
10513         }
10514
10515         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10516         {
10517             //発言詳細ですべて選択
10518             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10519         }
10520
10521         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10522         {
10523             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10524         }
10525
10526         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10527         {
10528             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10529         }
10530
10531         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10532         {
10533             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10534         }
10535
10536         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10537         {
10538             try
10539             {
10540                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10541                 {
10542                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10543                     {
10544                         var linkStr = link.GetAttribute("title");
10545                         if (string.IsNullOrEmpty(linkStr))
10546                             linkStr = link.GetAttribute("href");
10547
10548                         Clipboard.SetDataObject(linkStr, false, 5, 100);
10549                         return;
10550                     }
10551                 }
10552
10553                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10554             }
10555             catch (Exception ex)
10556             {
10557                 MessageBox.Show(ex.Message);
10558             }
10559         }
10560
10561         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10562         {
10563             // URLコピーの項目の表示/非表示
10564             if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10565             {
10566                 this._postBrowserStatusText = PostBrowser.StatusText;
10567                 string name = GetUserId();
10568                 UrlCopyContextMenuItem.Enabled = true;
10569                 if (name != null)
10570                 {
10571                     FollowContextMenuItem.Enabled = true;
10572                     RemoveContextMenuItem.Enabled = true;
10573                     FriendshipContextMenuItem.Enabled = true;
10574                     ShowUserStatusContextMenuItem.Enabled = true;
10575                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10576                     IdFilterAddMenuItem.Enabled = true;
10577                     ListManageUserContextToolStripMenuItem.Enabled = true;
10578                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10579                 }
10580                 else
10581                 {
10582                     FollowContextMenuItem.Enabled = false;
10583                     RemoveContextMenuItem.Enabled = false;
10584                     FriendshipContextMenuItem.Enabled = false;
10585                     ShowUserStatusContextMenuItem.Enabled = false;
10586                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10587                     IdFilterAddMenuItem.Enabled = false;
10588                     ListManageUserContextToolStripMenuItem.Enabled = false;
10589                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10590                 }
10591
10592                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10593                     UseHashtagMenuItem.Enabled = true;
10594                 else
10595                     UseHashtagMenuItem.Enabled = false;
10596             }
10597             else
10598             {
10599                 this._postBrowserStatusText = "";
10600                 UrlCopyContextMenuItem.Enabled = false;
10601                 FollowContextMenuItem.Enabled = false;
10602                 RemoveContextMenuItem.Enabled = false;
10603                 FriendshipContextMenuItem.Enabled = false;
10604                 ShowUserStatusContextMenuItem.Enabled = false;
10605                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10606                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10607                 UseHashtagMenuItem.Enabled = false;
10608                 IdFilterAddMenuItem.Enabled = false;
10609                 ListManageUserContextToolStripMenuItem.Enabled = false;
10610             }
10611             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10612             string _selText = this.PostBrowser.GetSelectedText();
10613             if (_selText == null)
10614             {
10615                 SelectionSearchContextMenuItem.Enabled = false;
10616                 SelectionCopyContextMenuItem.Enabled = false;
10617                 SelectionTranslationToolStripMenuItem.Enabled = false;
10618             }
10619             else
10620             {
10621                 SelectionSearchContextMenuItem.Enabled = true;
10622                 SelectionCopyContextMenuItem.Enabled = true;
10623                 SelectionTranslationToolStripMenuItem.Enabled = true;
10624             }
10625             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10626             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10627             bool fAllFlag = false;
10628             foreach (Match mu in ma)
10629             {
10630                 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10631                 {
10632                     fAllFlag = true;
10633                     break;
10634                 }
10635             }
10636             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10637
10638             if (_curPost == null)
10639                 TranslationToolStripMenuItem.Enabled = false;
10640             else
10641                 TranslationToolStripMenuItem.Enabled = true;
10642
10643             e.Cancel = false;
10644         }
10645
10646         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10647         {
10648             //発言詳細の選択文字列で現在のタブを検索
10649             string _selText = this.PostBrowser.GetSelectedText();
10650
10651             if (_selText != null)
10652             {
10653                 var searchOptions = new SearchWordDialog.SearchOptions(
10654                     SearchWordDialog.SearchType.Timeline,
10655                     _selText,
10656                     newTab: false,
10657                     caseSensitive: false,
10658                     useRegex: false);
10659
10660                 this.SearchDialog.ResultOptions = searchOptions;
10661
10662                 this.DoTabSearch(
10663                     searchOptions.Query,
10664                     searchOptions.CaseSensitive,
10665                     searchOptions.UseRegex,
10666                     SEARCHTYPE.NextSearch);
10667             }
10668         }
10669
10670         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10671         {
10672             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10673             ModifySettingLocal = true;
10674         }
10675
10676         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10677         {
10678             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10679             {
10680                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10681                 {
10682                     SelectMedia_DragDrop(e);
10683                 }
10684             }
10685             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10686             {
10687                 var url = GetUrlFromDataObject(e.Data);
10688
10689                 string appendText;
10690                 if (url.Item2 == null)
10691                     appendText = url.Item1;
10692                 else
10693                     appendText = url.Item2 + " " + url.Item1;
10694
10695                 if (this.StatusText.TextLength == 0)
10696                     this.StatusText.Text = appendText;
10697                 else
10698                     this.StatusText.Text += " " + appendText;
10699             }
10700             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10701             {
10702                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10703                 if (text != null)
10704                     this.StatusText.Text += text;
10705             }
10706             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10707             {
10708                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10709                 if (data != null) StatusText.Text += data;
10710             }
10711         }
10712
10713         /// <summary>
10714         /// IDataObject から URL とタイトルの対を取得します
10715         /// </summary>
10716         /// <remarks>
10717         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10718         /// </remarks>
10719         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10720         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10721         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10722         {
10723             if (data.GetDataPresent("text/x-moz-url"))
10724             {
10725                 // Firefox, Google Chrome で利用可能
10726                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10727
10728                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10729                 {
10730                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10731                     if (lines.Length < 2)
10732                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10733
10734                     return new Tuple<string, string>(lines[0], lines[1]);
10735                 }
10736             }
10737             else if (data.GetDataPresent("IESiteModeToUrl"))
10738             {
10739                 // Internet Exproler 用
10740                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10741
10742                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10743                 {
10744                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10745                     if (lines.Length < 2)
10746                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10747
10748                     return new Tuple<string, string>(lines[0], lines[1]);
10749                 }
10750             }
10751             else if (data.GetDataPresent("UniformResourceLocatorW"))
10752             {
10753                 // それ以外のブラウザ向け
10754
10755                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10756                 {
10757                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10758                     return new Tuple<string, string>(url, null);
10759                 }
10760             }
10761
10762             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10763         }
10764
10765         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10766         {
10767             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10768             {
10769                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10770                 {
10771                     SelectMedia_DragEnter(e);
10772                     return;
10773                 }
10774             }
10775             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10776             {
10777                 e.Effect = DragDropEffects.Copy;
10778                 return;
10779             }
10780             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10781             {
10782                 e.Effect = DragDropEffects.Copy;
10783                 return;
10784             }
10785             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10786             {
10787                 e.Effect = DragDropEffects.Copy;
10788                 return;
10789             }
10790
10791             e.Effect = DragDropEffects.None;
10792         }
10793
10794         private void TweenMain_DragOver(object sender, DragEventArgs e)
10795         {
10796         }
10797
10798         public bool IsNetworkAvailable()
10799         {
10800             bool nw = true;
10801             nw = MyCommon.IsNetworkAvailable();
10802             _myStatusOnline = nw;
10803             return nw;
10804         }
10805
10806         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10807         {
10808             var uriStr = uri.AbsoluteUri;
10809
10810             // OpenTween 内部で使用する URL
10811             if (uri.Authority == "opentween")
10812             {
10813                 await this.OpenInternalUriAsync(uri);
10814                 return;
10815             }
10816
10817             // ハッシュタグを含む Twitter 検索
10818             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10819             {
10820                 // ハッシュタグの場合は、タブで開く
10821                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10822                 var pos = unescapedQuery.IndexOf('#');
10823                 if (pos == -1) return;
10824
10825                 var hash = unescapedQuery.Substring(pos);
10826                 this.HashSupl.AddItem(hash);
10827                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10828                 this.AddNewTabForSearch(hash);
10829                 return;
10830             }
10831
10832             // ユーザープロフィールURL
10833             // フラグが立っている場合は設定と逆の動作をする
10834             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10835                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10836             {
10837                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10838                 if (userUriMatch.Success)
10839                 {
10840                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10841                     if (this.IsTwitterId(screenName))
10842                     {
10843                         this.AddNewTabForUserTimeline(screenName);
10844                         return;
10845                     }
10846                 }
10847             }
10848
10849             // どのパターンにも該当しないURL
10850             await this.OpenUriInBrowserAsync(uriStr);
10851         }
10852
10853         /// <summary>
10854         /// OpenTween 内部の機能を呼び出すための URL を開きます
10855         /// </summary>
10856         private async Task OpenInternalUriAsync(Uri uri)
10857         {
10858             // ツイートを開く (//opentween/status/:status_id)
10859             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10860             if (match.Success)
10861             {
10862                 var statusId = long.Parse(match.Groups[1].Value);
10863                 await this.OpenRelatedTab(statusId);
10864                 return;
10865             }
10866         }
10867
10868         public Task OpenUriInBrowserAsync(string UriString)
10869         {
10870             return Task.Run(() =>
10871             {
10872                 string myPath = UriString;
10873
10874                 try
10875                 {
10876                     var configBrowserPath = this._cfgLocal.BrowserPath;
10877                     if (!string.IsNullOrEmpty(configBrowserPath))
10878                     {
10879                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10880                         {
10881                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10882                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10883                             string arg = "";
10884                             if (sep < configBrowserPath.Length - 1)
10885                             {
10886                                 arg = configBrowserPath.Substring(sep + 1);
10887                             }
10888                             myPath = arg + " " + myPath;
10889                             System.Diagnostics.Process.Start(browserPath, myPath);
10890                         }
10891                         else
10892                         {
10893                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10894                         }
10895                     }
10896                     else
10897                     {
10898                         System.Diagnostics.Process.Start(myPath);
10899                     }
10900                 }
10901                 catch (Exception)
10902                 {
10903                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10904                 }
10905             });
10906         }
10907
10908         private void ListTabSelect(TabPage _tab)
10909         {
10910             SetListProperty();
10911
10912             this.PurgeListViewItemCache();
10913
10914             _curTab = _tab;
10915             _curList = (DetailsListView)_tab.Tag;
10916             if (_curList.SelectedIndices.Count > 0)
10917             {
10918                 _curItemIndex = _curList.SelectedIndices[0];
10919                 _curPost = GetCurTabPost(_curItemIndex);
10920             }
10921             else
10922             {
10923                 _curItemIndex = -1;
10924                 _curPost = null;
10925             }
10926
10927             _anchorPost = null;
10928             _anchorFlag = false;
10929
10930             if (_iconCol)
10931             {
10932                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10933             }
10934             else
10935             {
10936                 for (int i = 0; i < _curList.Columns.Count; i++)
10937                 {
10938                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10939                 }
10940             }
10941         }
10942
10943         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10944         {
10945             ListTabSelect(e.TabPage);
10946         }
10947
10948         private void SelectListItem(DetailsListView LView, int Index)
10949         {
10950             //単一
10951             Rectangle bnd = new Rectangle();
10952             bool flg = false;
10953             var item = LView.FocusedItem;
10954             if (item != null)
10955             {
10956                 bnd = item.Bounds;
10957                 flg = true;
10958             }
10959
10960             do
10961             {
10962                 LView.SelectedIndices.Clear();
10963             }
10964             while (LView.SelectedIndices.Count > 0);
10965             item = LView.Items[Index];
10966             item.Selected = true;
10967             item.Focused = true;
10968
10969             if (flg) LView.Invalidate(bnd);
10970         }
10971
10972         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10973         {
10974             //複数
10975             Rectangle bnd = new Rectangle();
10976             bool flg = false;
10977             var item = LView.FocusedItem;
10978             if (item != null)
10979             {
10980                 bnd = item.Bounds;
10981                 flg = true;
10982             }
10983
10984             if (Index != null)
10985             {
10986                 do
10987                 {
10988                     LView.SelectedIndices.Clear();
10989                 }
10990                 while (LView.SelectedIndices.Count > 0);
10991                 LView.SelectItems(Index);
10992             }
10993             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10994             {
10995                 LView.SelectionMark = selectionMarkIndex;
10996             }
10997             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10998             {
10999                 LView.Items[focusedIndex].Focused = true;
11000             }
11001             else if (Index != null && Index.Length != 0)
11002             {
11003                 LView.Items[Index.Last()].Focused = true;
11004             }
11005
11006             if (flg) LView.Invalidate(bnd);
11007         }
11008
11009         private void StartUserStream()
11010         {
11011             tw.NewPostFromStream += tw_NewPostFromStream;
11012             tw.UserStreamStarted += tw_UserStreamStarted;
11013             tw.UserStreamStopped += tw_UserStreamStopped;
11014             tw.PostDeleted += tw_PostDeleted;
11015             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11016
11017             MenuItemUserStream.Text = "&UserStream ■";
11018             MenuItemUserStream.Enabled = true;
11019             StopToolStripMenuItem.Text = "&Start";
11020             StopToolStripMenuItem.Enabled = true;
11021             if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11022         }
11023
11024         private async void TweenMain_Shown(object sender, EventArgs e)
11025         {
11026             try
11027             {
11028                 using (ControlTransaction.Update(this.PostBrowser))
11029                 {
11030                     PostBrowser.Url = new Uri("about:blank");
11031                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11032                 }
11033             }
11034             catch (Exception)
11035             {
11036             }
11037
11038             NotifyIcon1.Visible = true;
11039
11040             if (this.IsNetworkAvailable())
11041             {
11042                 StartUserStream();
11043
11044                 var loadTasks = new List<Task>
11045                 {
11046                     this.RefreshMuteUserIdsAsync(),
11047                     this.RefreshBlockIdsAsync(),
11048                     this.RefreshNoRetweetIdsAsync(),
11049                     this.RefreshTwitterConfigurationAsync(),
11050                     this.GetHomeTimelineAsync(),
11051                     this.GetReplyAsync(),
11052                     this.GetDirectMessagesAsync(),
11053                     this.GetPublicSearchAllAsync(),
11054                     this.GetUserTimelineAllAsync(),
11055                     this.GetListTimelineAllAsync(),
11056                 };
11057
11058                 if (this._cfgCommon.StartupFollowers)
11059                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11060
11061                 if (this._cfgCommon.GetFav)
11062                     loadTasks.Add(this.GetFavoritesAsync());
11063
11064                 var allTasks = Task.WhenAll(loadTasks);
11065
11066                 var i = 0;
11067                 while (true)
11068                 {
11069                     var timeout = Task.Delay(5000);
11070                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11071                         break;
11072
11073                     i += 1;
11074                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11075
11076                     if (MyCommon._endingFlag)
11077                         return;
11078                 }
11079
11080                 if (MyCommon._endingFlag) return;
11081
11082                 if (ApplicationSettings.VersionInfoUrl != null)
11083                 {
11084                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11085                     if (this._cfgCommon.StartupVersion)
11086                         await this.CheckNewVersion(true);
11087                 }
11088                 else
11089                 {
11090                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11091                     this.VerUpMenuItem.Enabled = false;
11092                     this.VerUpMenuItem.Available = false;
11093                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11094                 }
11095
11096                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11097                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11098                 {
11099                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11100                     SettingStripMenuItem_Click(null, null);
11101                 }
11102
11103                 // 取得失敗の場合は再試行する
11104                 var reloadTasks = new List<Task>();
11105
11106                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11107                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11108
11109                 if (!tw.GetNoRetweetSuccess)
11110                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11111
11112                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11113                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11114
11115                 await Task.WhenAll(reloadTasks);
11116             }
11117
11118             _initial = false;
11119
11120             TimerTimeline.Enabled = true;
11121         }
11122
11123         private async Task doGetFollowersMenu()
11124         {
11125             await this.RefreshFollowerIdsAsync();
11126             await this.DispSelectedPost(true);
11127         }
11128
11129         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11130         {
11131             await this.doGetFollowersMenu();
11132         }
11133
11134         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11135         {
11136             doReTweetUnofficial();
11137         }
11138
11139         private async Task doReTweetOfficial(bool isConfirm)
11140         {
11141             //公式RT
11142             if (this.ExistCurrentPost)
11143             {
11144                 if (_curPost.IsProtect)
11145                 {
11146                     MessageBox.Show("Protected.");
11147                     _DoFavRetweetFlags = false;
11148                     return;
11149                 }
11150                 if (_curList.SelectedIndices.Count > 15)
11151                 {
11152                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11153                     _DoFavRetweetFlags = false;
11154                     return;
11155                 }
11156                 else if (_curList.SelectedIndices.Count > 1)
11157                 {
11158                     string QuestionText = Properties.Resources.RetweetQuestion2;
11159                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11160                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11161                     {
11162                         case DialogResult.Cancel:
11163                         case DialogResult.No:
11164                             _DoFavRetweetFlags = false;
11165                             return;
11166                     }
11167                 }
11168                 else
11169                 {
11170                     if (_curPost.IsDm || _curPost.IsMe)
11171                     {
11172                         _DoFavRetweetFlags = false;
11173                         return;
11174                     }
11175                     if (!this._cfgCommon.RetweetNoConfirm)
11176                     {
11177                         string Questiontext = Properties.Resources.RetweetQuestion1;
11178                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11179                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11180                         {
11181                             _DoFavRetweetFlags = false;
11182                             return;
11183                         }
11184                     }
11185                 }
11186
11187                 var statusIds = new List<long>();
11188                 foreach (int idx in _curList.SelectedIndices)
11189                 {
11190                     PostClass post = GetCurTabPost(idx);
11191                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11192                         statusIds.Add(post.StatusId);
11193                 }
11194
11195                 await this.RetweetAsync(statusIds);
11196             }
11197         }
11198
11199         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11200         {
11201             await this.doReTweetOfficial(true);
11202         }
11203
11204         private async Task FavoritesRetweetOfficial()
11205         {
11206             if (!this.ExistCurrentPost) return;
11207             _DoFavRetweetFlags = true;
11208             var retweetTask = this.doReTweetOfficial(true);
11209             if (_DoFavRetweetFlags)
11210             {
11211                 _DoFavRetweetFlags = false;
11212                 var favoriteTask = this.FavoriteChange(true, false);
11213
11214                 await Task.WhenAll(retweetTask, favoriteTask);
11215             }
11216             else
11217             {
11218                 await retweetTask;
11219             }
11220         }
11221
11222         private async Task FavoritesRetweetUnofficial()
11223         {
11224             if (this.ExistCurrentPost && !_curPost.IsDm)
11225             {
11226                 _DoFavRetweetFlags = true;
11227                 var favoriteTask = this.FavoriteChange(true);
11228                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11229                 {
11230                     _DoFavRetweetFlags = false;
11231                     doReTweetUnofficial();
11232                 }
11233
11234                 await favoriteTask;
11235             }
11236         }
11237
11238         /// <summary>
11239         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11240         /// </summary>
11241         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11242         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11243         /// <returns>復元されたツイート本文</returns>
11244         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11245         {
11246             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11247
11248             // 通常の URL
11249             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11250             // メンション
11251             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11252             // ハッシュタグ
11253             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11254
11255             // <br> 除去
11256             if (multiline)
11257                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11258             else
11259                 statusHtml = statusHtml.Replace("<br>", " ");
11260
11261             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11262             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11263             statusHtml = statusHtml.Replace("&nbsp;", " ");
11264
11265             return WebUtility.HtmlDecode(statusHtml);
11266         }
11267
11268         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11269         {
11270             if (_curPost != null)
11271                 await this.DispSelectedPost(true);
11272         }
11273
11274         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11275         {
11276             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11277                 DebugModeToolStripMenuItem.Visible = true;
11278             else
11279                 DebugModeToolStripMenuItem.Visible = false;
11280         }
11281
11282         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11283         {
11284             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11285         }
11286
11287         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11288         {
11289             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11290         }
11291
11292         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11293         {
11294             if (TraceOutToolStripMenuItem.Checked)
11295                 MyCommon.TraceFlag = true;
11296             else
11297                 MyCommon.TraceFlag = false;
11298         }
11299
11300         private void TweenMain_Deactivate(object sender, EventArgs e)
11301         {
11302             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11303             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11304         }
11305
11306         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11307         {
11308             if (string.IsNullOrEmpty(_rclickTabName)) return;
11309             TabRename(ref _rclickTabName);
11310         }
11311
11312         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11313         {
11314             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11315         }
11316
11317         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11318         {
11319             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11320         }
11321
11322         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11323         {
11324             TwitterApiStatus apiStatus;
11325
11326             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11327             {
11328                 var cancellationToken = dialog.EnableCancellation();
11329
11330                 try
11331                 {
11332                     var task = Task.Run(() => this.tw.GetInfoApi());
11333                     apiStatus = await dialog.WaitForAsync(this, task);
11334                 }
11335                 catch (WebApiException)
11336                 {
11337                     apiStatus = null;
11338                 }
11339
11340                 if (cancellationToken.IsCancellationRequested)
11341                     return;
11342
11343                 if (apiStatus == null)
11344                 {
11345                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11346                     return;
11347                 }
11348             }
11349
11350             using (var apiDlg = new ApiInfoDialog())
11351             {
11352                 apiDlg.ShowDialog(this);
11353             }
11354         }
11355
11356         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11357         {
11358             var id = _curPost?.ScreenName ?? "";
11359
11360             await this.FollowCommand(id);
11361         }
11362
11363         private async Task FollowCommand(string id)
11364         {
11365             using (var inputName = new InputTabName())
11366             {
11367                 inputName.FormTitle = "Follow";
11368                 inputName.FormDescription = Properties.Resources.FRMessage1;
11369                 inputName.TabName = id;
11370
11371                 if (inputName.ShowDialog(this) != DialogResult.OK)
11372                     return;
11373                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11374                     return;
11375
11376                 id = inputName.TabName.Trim();
11377             }
11378
11379             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11380             {
11381                 try
11382                 {
11383                     var task = this.twitterApi.FriendshipsCreate(id);
11384                     await dialog.WaitForAsync(this, task);
11385                 }
11386                 catch (WebApiException ex)
11387                 {
11388                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11389                     return;
11390                 }
11391             }
11392
11393             MessageBox.Show(Properties.Resources.FRMessage3);
11394         }
11395
11396         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11397         {
11398             var id = _curPost?.ScreenName ?? "";
11399
11400             await this.RemoveCommand(id, false);
11401         }
11402
11403         private async Task RemoveCommand(string id, bool skipInput)
11404         {
11405             if (!skipInput)
11406             {
11407                 using (var inputName = new InputTabName())
11408                 {
11409                     inputName.FormTitle = "Unfollow";
11410                     inputName.FormDescription = Properties.Resources.FRMessage1;
11411                     inputName.TabName = id;
11412
11413                     if (inputName.ShowDialog(this) != DialogResult.OK)
11414                         return;
11415                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11416                         return;
11417
11418                     id = inputName.TabName.Trim();
11419                 }
11420             }
11421
11422             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11423             {
11424                 try
11425                 {
11426                     var task = this.twitterApi.FriendshipsDestroy(id);
11427                     await dialog.WaitForAsync(this, task);
11428                 }
11429                 catch (WebApiException ex)
11430                 {
11431                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11432                     return;
11433                 }
11434             }
11435
11436             MessageBox.Show(Properties.Resources.FRMessage3);
11437         }
11438
11439         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11440         {
11441             var id = _curPost?.ScreenName ?? "";
11442
11443             await this.ShowFriendship(id);
11444         }
11445
11446         private async Task ShowFriendship(string id)
11447         {
11448             using (var inputName = new InputTabName())
11449             {
11450                 inputName.FormTitle = "Show Friendships";
11451                 inputName.FormDescription = Properties.Resources.FRMessage1;
11452                 inputName.TabName = id;
11453
11454                 if (inputName.ShowDialog(this) != DialogResult.OK)
11455                     return;
11456                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11457                     return;
11458
11459                 id = inputName.TabName.Trim();
11460             }
11461
11462             bool isFollowing, isFollowed;
11463
11464             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11465             {
11466                 var cancellationToken = dialog.EnableCancellation();
11467
11468                 try
11469                 {
11470                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11471                     var friendship = await dialog.WaitForAsync(this, task);
11472
11473                     isFollowing = friendship.Relationship.Source.Following;
11474                     isFollowed = friendship.Relationship.Source.FollowedBy;
11475                 }
11476                 catch (WebApiException ex)
11477                 {
11478                     if (!cancellationToken.IsCancellationRequested)
11479                         MessageBox.Show(ex.Message);
11480                     return;
11481                 }
11482
11483                 if (cancellationToken.IsCancellationRequested)
11484                     return;
11485             }
11486
11487             string result = "";
11488             if (isFollowing)
11489             {
11490                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11491             }
11492             else
11493             {
11494                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11495             }
11496             if (isFollowed)
11497             {
11498                 result += Properties.Resources.GetFriendshipInfo3;
11499             }
11500             else
11501             {
11502                 result += Properties.Resources.GetFriendshipInfo4;
11503             }
11504             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11505             MessageBox.Show(result);
11506         }
11507
11508         private async Task ShowFriendship(string[] ids)
11509         {
11510             foreach (string id in ids)
11511             {
11512                 bool isFollowing, isFollowed;
11513
11514                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11515                 {
11516                     var cancellationToken = dialog.EnableCancellation();
11517
11518                     try
11519                     {
11520                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11521                         var friendship = await dialog.WaitForAsync(this, task);
11522
11523                         isFollowing = friendship.Relationship.Source.Following;
11524                         isFollowed = friendship.Relationship.Source.FollowedBy;
11525                     }
11526                     catch (WebApiException ex)
11527                     {
11528                         if (!cancellationToken.IsCancellationRequested)
11529                             MessageBox.Show(ex.Message);
11530                         return;
11531                     }
11532
11533                     if (cancellationToken.IsCancellationRequested)
11534                         return;
11535                 }
11536
11537                 string result = "";
11538                 string ff = "";
11539
11540                 ff = "  ";
11541                 if (isFollowing)
11542                 {
11543                     ff += Properties.Resources.GetFriendshipInfo1;
11544                 }
11545                 else
11546                 {
11547                     ff += Properties.Resources.GetFriendshipInfo2;
11548                 }
11549
11550                 ff += System.Environment.NewLine + "  ";
11551                 if (isFollowed)
11552                 {
11553                     ff += Properties.Resources.GetFriendshipInfo3;
11554                 }
11555                 else
11556                 {
11557                     ff += Properties.Resources.GetFriendshipInfo4;
11558                 }
11559                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11560                 if (isFollowing)
11561                 {
11562                     if (MessageBox.Show(
11563                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11564                         MessageBoxButtons.YesNo,
11565                         MessageBoxIcon.Question,
11566                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11567                     {
11568                         await this.RemoveCommand(id, true);
11569                     }
11570                 }
11571                 else
11572                 {
11573                     MessageBox.Show(result);
11574                 }
11575             }
11576         }
11577
11578         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11579         {
11580             await this.doShowUserStatus(tw.Username, false);
11581             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11582             //{
11583             //    doShowUserStatus(tw.Username, false);
11584             //}
11585             //else
11586             //{
11587             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11588             //    return;
11589             //}
11590         }
11591
11592         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11593         // URLから切り出した文字列を渡す
11594
11595         public bool IsTwitterId(string name)
11596         {
11597             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11598                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11599             else
11600                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11601         }
11602
11603         private string GetUserId()
11604         {
11605             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11606             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11607                 return m.Result("${ScreenName}");
11608             else
11609                 return null;
11610         }
11611
11612         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11613         {
11614             string name = GetUserId();
11615             if (name != null)
11616                 await this.FollowCommand(name);
11617         }
11618
11619         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11620         {
11621             string name = GetUserId();
11622             if (name != null)
11623                 await this.RemoveCommand(name, false);
11624         }
11625
11626         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11627         {
11628             string name = GetUserId();
11629             if (name != null)
11630                 await this.ShowFriendship(name);
11631         }
11632
11633         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11634         {
11635             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11636             List<string> ids = new List<string>();
11637             foreach (Match mu in ma)
11638             {
11639                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11640                 {
11641                     ids.Add(mu.Result("${ScreenName}"));
11642                 }
11643             }
11644
11645             await this.ShowFriendship(ids.ToArray());
11646         }
11647
11648         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11649         {
11650             string name = GetUserId();
11651             if (name != null)
11652                 await this.ShowUserStatus(name);
11653         }
11654
11655         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11656         {
11657             string name = GetUserId();
11658             if (name != null) AddNewTabForUserTimeline(name);
11659         }
11660
11661         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11662         {
11663             string name = GetUserId();
11664             if (name != null) AddNewTabForSearch("@" + name);
11665         }
11666
11667         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11668         {
11669             ModifySettingCommon = true;
11670         }
11671
11672         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11673         {
11674             ModifySettingCommon = true;
11675         }
11676
11677         private void doQuoteOfficial()
11678         {
11679             if (this.ExistCurrentPost)
11680             {
11681                 if (_curPost.IsDm ||
11682                     !StatusText.Enabled) return;
11683
11684                 if (_curPost.IsProtect)
11685                 {
11686                     MessageBox.Show("Protected.");
11687                     return;
11688                 }
11689
11690                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11691
11692                 this.inReplyTo = null;
11693
11694                 StatusText.SelectionStart = 0;
11695                 StatusText.Focus();
11696             }
11697         }
11698
11699         private void doReTweetUnofficial()
11700         {
11701             //RT @id:内容
11702             if (this.ExistCurrentPost)
11703             {
11704                 if (_curPost.IsDm || !StatusText.Enabled)
11705                     return;
11706
11707                 if (_curPost.IsProtect)
11708                 {
11709                     MessageBox.Show("Protected.");
11710                     return;
11711                 }
11712                 string rtdata = _curPost.Text;
11713                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11714
11715                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11716
11717                 // 投稿時に in_reply_to_status_id を付加する
11718                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11719                 var inReplyToScreenName = this._curPost.ScreenName;
11720                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11721
11722                 StatusText.SelectionStart = 0;
11723                 StatusText.Focus();
11724             }
11725         }
11726
11727         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11728         {
11729             doQuoteOfficial();
11730         }
11731
11732         private void SearchButton_Click(object sender, EventArgs e)
11733         {
11734             //公式検索
11735             Control pnl = ((Control)sender).Parent;
11736             if (pnl == null) return;
11737             string tbName = pnl.Parent.Text;
11738             TabClass tb = _statuses.Tabs[tbName];
11739             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11740             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11741             cmb.Text = cmb.Text.Trim();
11742             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11743             bool Quote = false;
11744             StringBuilder buf = new StringBuilder();
11745             char[] c = cmb.Text.ToCharArray();
11746             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11747             {
11748                 if (cnt > cmb.Text.Length - 4)
11749                 {
11750                     buf.Append(cmb.Text.Substring(cnt));
11751                     break;
11752                 }
11753                 if (c[cnt] == '"')
11754                 {
11755                     Quote = !Quote;
11756                 }
11757                 else
11758                 {
11759                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11760                     {
11761                         buf.Append(" OR ");
11762                         cnt += 3;
11763                         continue;
11764                     }
11765                 }
11766                 buf.Append(c[cnt]);
11767             }
11768             cmb.Text = buf.ToString();
11769
11770             var listView = (DetailsListView)pnl.Parent.Tag;
11771
11772             tb.SearchWords = cmb.Text;
11773             tb.SearchLang = cmbLang.Text;
11774             if (string.IsNullOrEmpty(cmb.Text))
11775             {
11776                 listView.Focus();
11777                 SaveConfigsTabs();
11778                 return;
11779             }
11780             if (tb.IsSearchQueryChanged)
11781             {
11782                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11783                 if (idx > -1) cmb.Items.RemoveAt(idx);
11784                 cmb.Items.Insert(0, tb.SearchWords);
11785                 cmb.Text = tb.SearchWords;
11786                 cmb.SelectAll();
11787                 this.PurgeListViewItemCache();
11788                 listView.VirtualListSize = 0;
11789                 _statuses.ClearTabIds(tbName);
11790                 SaveConfigsTabs();   //検索条件の保存
11791             }
11792
11793             this.GetPublicSearchAsync(tb);
11794             listView.Focus();
11795         }
11796
11797         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11798         {
11799             //もっと前を取得
11800             await this.DoRefreshMore();
11801         }
11802
11803         /// <summary>
11804         /// 指定されたタブのListTabにおける位置を返します
11805         /// </summary>
11806         /// <remarks>
11807         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11808         /// </remarks>
11809         public int GetTabPageIndex(string tabName)
11810         {
11811             var index = 0;
11812             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11813             {
11814                 if (tabPage.Text == tabName)
11815                     return index;
11816
11817                 index++;
11818             }
11819
11820             return -1;
11821         }
11822
11823         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11824         {
11825             if (_statuses.RemovedTab.Count == 0)
11826             {
11827                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11828                 return;
11829             }
11830             else
11831             {
11832                 DetailsListView listView = null;
11833
11834                 TabClass tb = _statuses.RemovedTab.Pop();
11835                 if (tb.TabType == MyCommon.TabUsageType.Related)
11836                 {
11837                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11838                     if (relatedTab != null)
11839                     {
11840                         // 関連発言なら既存のタブを置き換える
11841                         tb.TabName = relatedTab.TabName;
11842                         this.ClearTab(tb.TabName, false);
11843                         _statuses.Tabs[tb.TabName] = tb;
11844
11845                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11846                         {
11847                             var tabPage = ListTab.TabPages[i];
11848                             if (tb.TabName == tabPage.Text)
11849                             {
11850                                 listView = (DetailsListView)tabPage.Tag;
11851                                 ListTab.SelectedIndex = i;
11852                                 break;
11853                             }
11854                         }
11855                     }
11856                     else
11857                     {
11858                         const string TabName = "Related Tweets";
11859                         string renamed = TabName;
11860                         for (int i = 2; i <= 100; i++)
11861                         {
11862                             if (!_statuses.ContainsTab(renamed)) break;
11863                             renamed = TabName + i.ToString();
11864                         }
11865                         tb.TabName = renamed;
11866                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11867                         _statuses.Tabs.Add(renamed, tb);  // 後に
11868
11869                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11870                         listView = (DetailsListView)tabPage.Tag;
11871                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11872                     }
11873                 }
11874                 else
11875                 {
11876                     string renamed = tb.TabName;
11877                     for (int i = 1; i < int.MaxValue; i++)
11878                     {
11879                         if (!_statuses.ContainsTab(renamed)) break;
11880                         renamed = tb.TabName + "(" + i.ToString() + ")";
11881                     }
11882                     tb.TabName = renamed;
11883                     _statuses.Tabs.Add(renamed, tb);  // 先に
11884                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11885
11886                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11887                     listView = (DetailsListView)tabPage.Tag;
11888                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11889                 }
11890                 SaveConfigsTabs();
11891
11892                 if (listView != null)
11893                 {
11894                     using (ControlTransaction.Update(listView))
11895                     {
11896                         listView.VirtualListSize = tb.AllCount;
11897                     }
11898                 }
11899             }
11900         }
11901
11902         private async Task doMoveToRTHome()
11903         {
11904             if (_curList.SelectedIndices.Count > 0)
11905             {
11906                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11907                 if (post.RetweetedId != null)
11908                 {
11909                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11910                 }
11911             }
11912         }
11913
11914         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11915         {
11916             await this.doMoveToRTHome();
11917         }
11918
11919         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11920         {
11921             string name = GetUserId();
11922             if (name != null)
11923             {
11924                 string tabName;
11925
11926                 //未選択なら処理終了
11927                 if (_curList.SelectedIndices.Count == 0) return;
11928
11929                 //タブ選択(or追加)
11930                 if (!SelectTab(out tabName)) return;
11931
11932                 var tab = this._statuses.Tabs[tabName];
11933
11934                 bool mv;
11935                 bool mk;
11936                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11937                 {
11938                     this.MoveOrCopy(out mv, out mk);
11939                 }
11940                 else
11941                 {
11942                     // ミュートタブでは常に MoveMatches を true にする
11943                     mv = true;
11944                     mk = false;
11945                 }
11946
11947                 PostFilterRule fc = new PostFilterRule();
11948                 fc.FilterName = name;
11949                 fc.UseNameField = true;
11950                 fc.MoveMatches = mv;
11951                 fc.MarkMatches = mk;
11952                 fc.UseRegex = false;
11953                 fc.FilterByUrl = false;
11954                 tab.AddFilter(fc);
11955
11956                 this.ApplyPostFilters();
11957                 SaveConfigsTabs();
11958             }
11959         }
11960
11961         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11962         {
11963             string user;
11964
11965             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11966
11967             if (menuItem.Owner == this.ContextMenuPostBrowser)
11968             {
11969                 user = GetUserId();
11970                 if (user == null) return;
11971             }
11972             else if (this._curPost != null)
11973             {
11974                 user = this._curPost.ScreenName;
11975             }
11976             else
11977             {
11978                 return;
11979             }
11980
11981             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11982             {
11983                 try
11984                 {
11985                     this.tw.GetListsApi();
11986                 }
11987                 catch (WebApiException ex)
11988                 {
11989                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11990                     return;
11991                 }
11992             }
11993
11994             using (MyLists listSelectForm = new MyLists(user, this.tw))
11995             {
11996                 listSelectForm.ShowDialog(this);
11997             }
11998         }
11999
12000         private void SearchControls_Enter(object sender, EventArgs e)
12001         {
12002             Control pnl = (Control)sender;
12003             foreach (Control ctl in pnl.Controls)
12004             {
12005                 ctl.TabStop = true;
12006             }
12007         }
12008
12009         private void SearchControls_Leave(object sender, EventArgs e)
12010         {
12011             Control pnl = (Control)sender;
12012             foreach (Control ctl in pnl.Controls)
12013             {
12014                 ctl.TabStop = false;
12015             }
12016         }
12017
12018         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12019         {
12020             if (ListTab.SelectedTab != null)
12021             {
12022                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12023                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12024             }
12025         }
12026
12027         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12028         {
12029             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12030             if (m.Success)
12031             {
12032                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12033                 HashStripSplitButton.Text = HashMgr.UseHash;
12034                 HashToggleMenuItem.Checked = true;
12035                 HashToggleToolStripMenuItem.Checked = true;
12036                 //使用ハッシュタグとして設定
12037                 ModifySettingCommon = true;
12038             }
12039         }
12040
12041         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12042         {
12043             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12044         }
12045
12046         private void HashManageMenuItem_Click(object sender, EventArgs e)
12047         {
12048             DialogResult rslt = DialogResult.Cancel;
12049             try
12050             {
12051                 rslt = HashMgr.ShowDialog();
12052             }
12053             catch (Exception)
12054             {
12055                 return;
12056             }
12057             this.TopMost = this._cfgCommon.AlwaysTop;
12058             if (rslt == DialogResult.Cancel) return;
12059             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12060             {
12061                 HashStripSplitButton.Text = HashMgr.UseHash;
12062                 HashToggleMenuItem.Checked = true;
12063                 HashToggleToolStripMenuItem.Checked = true;
12064             }
12065             else
12066             {
12067                 HashStripSplitButton.Text = "#[-]";
12068                 HashToggleMenuItem.Checked = false;
12069                 HashToggleToolStripMenuItem.Checked = false;
12070             }
12071             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12072             //{
12073             //    int sidx = StatusText.SelectionStart;
12074             //    string hash = HashMgr.UseHash + " ";
12075             //    if (sidx > 0)
12076             //    {
12077             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12078             //            hash = " " + hash;
12079             //    }
12080             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12081             //    sidx += hash.Length;
12082             //    StatusText.SelectionStart = sidx;
12083             //    StatusText.Focus();
12084             //}
12085             ModifySettingCommon = true;
12086             this.StatusText_TextChanged(null, null);
12087         }
12088
12089         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12090         {
12091             HashMgr.ToggleHash();
12092             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12093             {
12094                 HashStripSplitButton.Text = HashMgr.UseHash;
12095                 HashToggleMenuItem.Checked = true;
12096                 HashToggleToolStripMenuItem.Checked = true;
12097             }
12098             else
12099             {
12100                 HashStripSplitButton.Text = "#[-]";
12101                 HashToggleMenuItem.Checked = false;
12102                 HashToggleToolStripMenuItem.Checked = false;
12103             }
12104             ModifySettingCommon = true;
12105             this.StatusText_TextChanged(null, null);
12106         }
12107
12108         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12109         {
12110             HashToggleMenuItem_Click(null, null);
12111         }
12112
12113         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12114         {
12115             if (ListTab.SelectedTab == null) return;
12116             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12117             if (!this.ExistCurrentPost)
12118             {
12119                 this.ReplyOpMenuItem.Enabled = false;
12120                 this.ReplyAllOpMenuItem.Enabled = false;
12121                 this.DmOpMenuItem.Enabled = false;
12122                 this.ShowProfMenuItem.Enabled = false;
12123                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12124                 this.ListManageMenuItem.Enabled = false;
12125                 this.OpenFavOpMenuItem.Enabled = false;
12126                 this.CreateTabRuleOpMenuItem.Enabled = false;
12127                 this.CreateIdRuleOpMenuItem.Enabled = false;
12128                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12129                 this.ReadOpMenuItem.Enabled = false;
12130                 this.UnreadOpMenuItem.Enabled = false;
12131             }
12132             else
12133             {
12134                 this.ReplyOpMenuItem.Enabled = true;
12135                 this.ReplyAllOpMenuItem.Enabled = true;
12136                 this.DmOpMenuItem.Enabled = true;
12137                 this.ShowProfMenuItem.Enabled = true;
12138                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12139                 this.ListManageMenuItem.Enabled = true;
12140                 this.OpenFavOpMenuItem.Enabled = true;
12141                 this.CreateTabRuleOpMenuItem.Enabled = true;
12142                 this.CreateIdRuleOpMenuItem.Enabled = true;
12143                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12144                 this.ReadOpMenuItem.Enabled = true;
12145                 this.UnreadOpMenuItem.Enabled = true;
12146             }
12147
12148             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12149             {
12150                 this.FavOpMenuItem.Enabled = false;
12151                 this.UnFavOpMenuItem.Enabled = false;
12152                 this.OpenStatusOpMenuItem.Enabled = false;
12153                 this.OpenFavotterOpMenuItem.Enabled = false;
12154                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12155                 this.RtOpMenuItem.Enabled = false;
12156                 this.RtUnOpMenuItem.Enabled = false;
12157                 this.QtOpMenuItem.Enabled = false;
12158                 this.FavoriteRetweetMenuItem.Enabled = false;
12159                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12160             }
12161             else
12162             {
12163                 this.FavOpMenuItem.Enabled = true;
12164                 this.UnFavOpMenuItem.Enabled = true;
12165                 this.OpenStatusOpMenuItem.Enabled = true;
12166                 this.OpenFavotterOpMenuItem.Enabled = true;
12167                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12168
12169                 if (_curPost.IsMe)
12170                 {
12171                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12172                     this.RtUnOpMenuItem.Enabled = true;
12173                     this.QtOpMenuItem.Enabled = true;
12174                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12175                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12176                 }
12177                 else
12178                 {
12179                     if (_curPost.IsProtect)
12180                     {
12181                         this.RtOpMenuItem.Enabled = false;
12182                         this.RtUnOpMenuItem.Enabled = false;
12183                         this.QtOpMenuItem.Enabled = false;
12184                         this.FavoriteRetweetMenuItem.Enabled = false;
12185                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12186                     }
12187                     else
12188                     {
12189                         this.RtOpMenuItem.Enabled = true;
12190                         this.RtUnOpMenuItem.Enabled = true;
12191                         this.QtOpMenuItem.Enabled = true;
12192                         this.FavoriteRetweetMenuItem.Enabled = true;
12193                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12194                     }
12195                 }
12196             }
12197
12198             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12199             {
12200                 this.RefreshPrevOpMenuItem.Enabled = true;
12201             }
12202             else
12203             {
12204                 this.RefreshPrevOpMenuItem.Enabled = false;
12205             }
12206             if (!this.ExistCurrentPost
12207                 || _curPost.InReplyToStatusId == null)
12208             {
12209                 OpenRepSourceOpMenuItem.Enabled = false;
12210             }
12211             else
12212             {
12213                 OpenRepSourceOpMenuItem.Enabled = true;
12214             }
12215             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12216             {
12217                 OpenRterHomeMenuItem.Enabled = false;
12218             }
12219             else
12220             {
12221                 OpenRterHomeMenuItem.Enabled = true;
12222             }
12223
12224             if (this.ExistCurrentPost)
12225             {
12226                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12227             }
12228         }
12229
12230         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12231         {
12232             ContextMenuTabProperty_Opening(sender, null);
12233         }
12234
12235         public Twitter TwitterInstance
12236         {
12237             get { return tw; }
12238         }
12239
12240         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12241         {
12242             if (this._initialLayout)
12243                 return;
12244
12245             int splitterDistance;
12246             switch (this.WindowState)
12247             {
12248                 case FormWindowState.Normal:
12249                     splitterDistance = this.SplitContainer3.SplitterDistance;
12250                     break;
12251                 case FormWindowState.Maximized:
12252                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12253                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12254                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12255                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12256                     break;
12257                 default:
12258                     return;
12259             }
12260
12261             this._mySpDis3 = splitterDistance;
12262             this.ModifySettingLocal = true;
12263         }
12264
12265         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12266         {
12267             if (_statuses.RemovedTab.Count == 0)
12268             {
12269                 UndoRemoveTabMenuItem.Enabled = false;
12270             }
12271             else
12272             {
12273                 UndoRemoveTabMenuItem.Enabled = true;
12274             }
12275             if (ListTab.SelectedTab != null)
12276             {
12277                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12278                     PublicSearchQueryMenuItem.Enabled = true;
12279                 else
12280                     PublicSearchQueryMenuItem.Enabled = false;
12281             }
12282             else
12283             {
12284                 PublicSearchQueryMenuItem.Enabled = false;
12285             }
12286             if (!this.ExistCurrentPost)
12287             {
12288                 this.CopySTOTMenuItem.Enabled = false;
12289                 this.CopyURLMenuItem.Enabled = false;
12290                 this.CopyUserIdStripMenuItem.Enabled = false;
12291             }
12292             else
12293             {
12294                 this.CopySTOTMenuItem.Enabled = true;
12295                 this.CopyURLMenuItem.Enabled = true;
12296                 this.CopyUserIdStripMenuItem.Enabled = true;
12297                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12298                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12299             }
12300         }
12301
12302         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12303         {
12304             SetNotifyIconText();
12305         }
12306
12307         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12308         {
12309             var id = _curPost?.ScreenName ?? "";
12310
12311             await this.ShowUserStatus(id);
12312         }
12313
12314         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12315         {
12316             TwitterUser user = null;
12317
12318             if (ShowInputDialog)
12319             {
12320                 using (var inputName = new InputTabName())
12321                 {
12322                     inputName.FormTitle = "Show UserStatus";
12323                     inputName.FormDescription = Properties.Resources.FRMessage1;
12324                     inputName.TabName = id;
12325
12326                     if (inputName.ShowDialog(this) != DialogResult.OK)
12327                         return;
12328                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12329                         return;
12330
12331                     id = inputName.TabName.Trim();
12332                 }
12333             }
12334
12335             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12336             {
12337                 var cancellationToken = dialog.EnableCancellation();
12338
12339                 try
12340                 {
12341                     var task = this.twitterApi.UsersShow(id);
12342                     user = await dialog.WaitForAsync(this, task);
12343                 }
12344                 catch (WebApiException ex)
12345                 {
12346                     if (!cancellationToken.IsCancellationRequested)
12347                         MessageBox.Show(ex.Message);
12348                     return;
12349                 }
12350
12351                 if (cancellationToken.IsCancellationRequested)
12352                     return;
12353             }
12354
12355             await this.doShowUserStatus(user);
12356         }
12357
12358         private async Task doShowUserStatus(TwitterUser user)
12359         {
12360             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12361             {
12362                 var showUserTask = userDialog.ShowUserAsync(user);
12363                 userDialog.ShowDialog(this);
12364
12365                 this.Activate();
12366                 this.BringToFront();
12367
12368                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12369                 await showUserTask;
12370             }
12371         }
12372
12373         private Task ShowUserStatus(string id, bool ShowInputDialog)
12374         {
12375             return this.doShowUserStatus(id, ShowInputDialog);
12376         }
12377
12378         private Task ShowUserStatus(string id)
12379         {
12380             return this.doShowUserStatus(id, true);
12381         }
12382
12383         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12384         {
12385             if (NameLabel.Tag != null)
12386             {
12387                 string id = (string)NameLabel.Tag;
12388                 if (id != tw.Username)
12389                 {
12390                     await this.FollowCommand(id);
12391                 }
12392             }
12393         }
12394
12395         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12396         {
12397             if (NameLabel.Tag != null)
12398             {
12399                 string id = (string)NameLabel.Tag;
12400                 if (id != tw.Username)
12401                 {
12402                     await this.RemoveCommand(id, false);
12403                 }
12404             }
12405         }
12406
12407         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12408         {
12409             if (NameLabel.Tag != null)
12410             {
12411                 string id = (string)NameLabel.Tag;
12412                 if (id != tw.Username)
12413                 {
12414                     await this.ShowFriendship(id);
12415                 }
12416             }
12417         }
12418
12419         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12420         {
12421             if (NameLabel.Tag != null)
12422             {
12423                 string id = (string)NameLabel.Tag;
12424                 await this.ShowUserStatus(id, false);
12425             }
12426         }
12427
12428         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12429         {
12430             if (NameLabel.Tag != null)
12431             {
12432                 string id = (string)NameLabel.Tag;
12433                 AddNewTabForUserTimeline(id);
12434             }
12435         }
12436
12437         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12438         {
12439             if (NameLabel.Tag != null)
12440             {
12441                 string id = (string)NameLabel.Tag;
12442                 AddNewTabForSearch("@" + id);
12443             }
12444         }
12445
12446         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12447         {
12448             if (_curPost != null)
12449             {
12450                 await this.ShowUserStatus(_curPost.ScreenName, false);
12451             }
12452         }
12453
12454         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12455         {
12456             if (!this.ExistCurrentPost)
12457                 return;
12458
12459             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12460             int retweetCount = 0;
12461
12462             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12463             {
12464                 var cancellationToken = dialog.EnableCancellation();
12465
12466                 try
12467                 {
12468                     var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12469                     retweetCount = await dialog.WaitForAsync(this, task);
12470                 }
12471                 catch (WebApiException ex)
12472                 {
12473                     if (!cancellationToken.IsCancellationRequested)
12474                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12475                     return;
12476                 }
12477
12478                 if (cancellationToken.IsCancellationRequested)
12479                     return;
12480             }
12481
12482             MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12483         }
12484
12485         private HookGlobalHotkey _hookGlobalHotkey;
12486         public TweenMain()
12487         {
12488             _hookGlobalHotkey = new HookGlobalHotkey(this);
12489
12490             // この呼び出しは、Windows フォーム デザイナで必要です。
12491             InitializeComponent();
12492
12493             // InitializeComponent() 呼び出しの後で初期化を追加します。
12494
12495             if (!this.DesignMode)
12496             {
12497                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12498                 this.StatusText.Dock = DockStyle.Fill;
12499             }
12500
12501             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12502             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12503             this.gh.NotifyClicked += GrowlHelper_Callback;
12504
12505             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12506             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12507
12508             this.ImageSelector.Visible = false;
12509             this.ImageSelector.Enabled = false;
12510             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12511
12512             this.ReplaceAppName();
12513             this.InitializeShortcuts();
12514         }
12515
12516         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12517         {
12518             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12519             {
12520                 //アイコン化
12521                 this.Visible = false;
12522             }
12523             else if (Form.ActiveForm == null)
12524             {
12525                 this.Visible = true;
12526                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12527                 this.Activate();
12528                 this.BringToFront();
12529                 this.StatusText.Focus();
12530             }
12531         }
12532
12533         private void UserPicture_MouseEnter(object sender, EventArgs e)
12534         {
12535             this.UserPicture.Cursor = Cursors.Hand;
12536         }
12537
12538         private void UserPicture_MouseLeave(object sender, EventArgs e)
12539         {
12540             this.UserPicture.Cursor = Cursors.Default;
12541         }
12542
12543         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12544         {
12545             if (NameLabel.Tag != null)
12546             {
12547                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12548             }
12549         }
12550
12551         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12552         {
12553             this.MultiLineMenuItem.PerformClick();
12554         }
12555
12556         public PostClass CurPost
12557         {
12558             get { return _curPost; }
12559         }
12560
12561 #region "画像投稿"
12562         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12563         {
12564             if (ImageSelector.Visible)
12565                 ImageSelector.EndSelection();
12566             else
12567                 ImageSelector.BeginSelection();
12568         }
12569
12570         private void SelectMedia_DragEnter(DragEventArgs e)
12571         {
12572             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12573             {
12574                 e.Effect = DragDropEffects.Copy;
12575                 return;
12576             }
12577             e.Effect = DragDropEffects.None;
12578         }
12579
12580         private void SelectMedia_DragDrop(DragEventArgs e)
12581         {
12582             this.Activate();
12583             this.BringToFront();
12584             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12585             StatusText.Focus();
12586         }
12587
12588         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12589         {
12590             TimelinePanel.Visible = false;
12591             TimelinePanel.Enabled = false;
12592         }
12593
12594         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12595         {
12596             TimelinePanel.Visible = true;
12597             TimelinePanel.Enabled = true;
12598             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12599         }
12600
12601         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12602         {
12603             this.AllowDrop = false;
12604         }
12605
12606         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12607         {
12608             this.AllowDrop = true;
12609         }
12610
12611         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12612         {
12613             if (ImageSelector.Visible)
12614             {
12615                 ModifySettingCommon = true;
12616                 SaveConfigsAll(true);
12617
12618                 if (ImageSelector.ServiceName.Equals("Twitter"))
12619                     this.StatusText_TextChanged(null, null);
12620             }
12621         }
12622
12623         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12624         {
12625             this.StatusText_TextChanged(null, null);
12626         }
12627
12628         /// <summary>
12629         /// StatusTextでCtrl+Vが押下された時の処理
12630         /// </summary>
12631         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12632         {
12633             if (Clipboard.ContainsText())
12634             {
12635                 // clipboardにテキストがある場合は貼り付け処理
12636                 this.StatusText.Paste(Clipboard.GetText());
12637             }
12638             else if (Clipboard.ContainsImage())
12639             {
12640                 // 画像があるので投稿処理を行う
12641                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12642                                    Properties.Resources.PostPictureWarn4,
12643                                    MessageBoxButtons.OKCancel,
12644                                    MessageBoxIcon.Question,
12645                                    MessageBoxDefaultButton.Button2)
12646                                == DialogResult.OK)
12647                 {
12648                     // clipboardから画像を取得
12649                     using (var image = Clipboard.GetImage())
12650                     {
12651                         this.ImageSelector.BeginSelection(image);
12652                     }
12653                 }
12654             }
12655         }
12656 #endregion
12657
12658         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12659         {
12660             using (ListManage form = new ListManage(tw))
12661             {
12662                 form.ShowDialog(this);
12663             }
12664         }
12665
12666         public bool ModifySettingCommon { get; set; }
12667         public bool ModifySettingLocal { get; set; }
12668         public bool ModifySettingAtId { get; set; }
12669
12670         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12671         {
12672             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12673             if (sourceUri != null && e.Button == MouseButtons.Left)
12674             {
12675                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12676             }
12677         }
12678
12679         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12680         {
12681             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12682             if (sourceUri != null)
12683             {
12684                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12685             }
12686         }
12687
12688         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12689         {
12690             SetStatusLabelUrl();
12691         }
12692
12693         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12694         {
12695             if (this.ExistCurrentPost && !_curPost.IsDm)
12696                 RtCountMenuItem.Enabled = true;
12697             else
12698                 RtCountMenuItem.Enabled = false;
12699
12700             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12701             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12702             //else
12703             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12704         }
12705
12706         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12707         {
12708             CopyUserId();
12709         }
12710
12711         private void CopyUserId()
12712         {
12713             if (_curPost == null) return;
12714             string clstr = _curPost.ScreenName;
12715             try
12716             {
12717                 Clipboard.SetDataObject(clstr, false, 5, 100);
12718             }
12719             catch (Exception ex)
12720             {
12721                 MessageBox.Show(ex.Message);
12722             }
12723         }
12724
12725         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12726         {
12727             if (this.ExistCurrentPost && !_curPost.IsDm)
12728             {
12729                 try
12730                 {
12731                     await this.OpenRelatedTab(this._curPost);
12732                 }
12733                 catch (TabException ex)
12734                 {
12735                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12736                 }
12737             }
12738         }
12739
12740         /// <summary>
12741         /// 指定されたツイートに対する関連発言タブを開きます
12742         /// </summary>
12743         /// <param name="statusId">表示するツイートのID</param>
12744         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12745         private async Task OpenRelatedTab(long statusId)
12746         {
12747             var post = this._statuses[statusId];
12748             if (post == null)
12749             {
12750                 try
12751                 {
12752                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12753                 }
12754                 catch (WebApiException ex)
12755                 {
12756                     this.StatusLabel.Text = ex.Message;
12757                     return;
12758                 }
12759             }
12760
12761             await this.OpenRelatedTab(post);
12762         }
12763
12764         /// <summary>
12765         /// 指定されたツイートに対する関連発言タブを開きます
12766         /// </summary>
12767         /// <param name="post">表示する対象となるツイート</param>
12768         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12769         private async Task OpenRelatedTab(PostClass post)
12770         {
12771             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12772             string tabName;
12773
12774             if (tabRelated == null)
12775             {
12776                 tabName = this._statuses.MakeTabName("Related Tweets");
12777
12778                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12779                 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12780
12781                 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12782                 tabRelated.UnreadManage = false;
12783                 tabRelated.Notify = false;
12784             }
12785             else
12786             {
12787                 tabName = tabRelated.TabName;
12788             }
12789
12790             tabRelated.RelationTargetPost = post;
12791             this.ClearTab(tabName, false);
12792
12793             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12794             {
12795                 var tabPage = this.ListTab.TabPages[i];
12796                 if (tabName == tabPage.Text)
12797                 {
12798                     this.ListTab.SelectedIndex = i;
12799                     break;
12800                 }
12801             }
12802
12803             await this.GetRelatedTweetsAsync(tabRelated);
12804         }
12805
12806         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12807         {
12808             StringBuilder buf = new StringBuilder();
12809             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12810             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12811             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12812             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12813             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12814         }
12815
12816         private void tw_UserIdChanged()
12817         {
12818             this.ModifySettingCommon = true;
12819         }
12820
12821 #region "Userstream"
12822         private bool _isActiveUserstream = false;
12823
12824         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12825         {
12826             try
12827             {
12828                 if (InvokeRequired && !IsDisposed)
12829                 {
12830                     Invoke((Action) (async () =>
12831                            {
12832                                _statuses.RemovePostReserve(e.StatusId);
12833                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12834                                {
12835                                    this.PurgeListViewItemCache();
12836                                    ((DetailsListView)_curTab.Tag).Update();
12837                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12838                                        await this.DispSelectedPost(true);
12839                                }
12840                            }));
12841                     return;
12842                 }
12843             }
12844             catch (ObjectDisposedException)
12845             {
12846                 return;
12847             }
12848             catch (InvalidOperationException)
12849             {
12850                 return;
12851             }
12852         }
12853
12854         private int userStreamsRefreshing = 0;
12855
12856         private async void tw_NewPostFromStream(object sender, EventArgs e)
12857         {
12858             if (this._cfgCommon.ReadOldPosts)
12859             {
12860                 _statuses.SetReadHomeTab(); //新着時未読クリア
12861             }
12862
12863             int rsltAddCount = _statuses.DistributePosts();
12864
12865             this.UpdateTimelineSpeed(rsltAddCount);
12866
12867             if (this._cfgCommon.UserstreamPeriod > 0) return;
12868
12869             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12870             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12871             {
12872                 try
12873                 {
12874                     await this.InvokeAsync(() => this.RefreshTimeline())
12875                         .ConfigureAwait(false);
12876                 }
12877                 finally
12878                 {
12879                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12880                 }
12881             }
12882         }
12883
12884         private void tw_UserStreamStarted(object sender, EventArgs e)
12885         {
12886             this._isActiveUserstream = true;
12887             try
12888             {
12889                 if (InvokeRequired && !IsDisposed)
12890                 {
12891                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12892                     return;
12893                 }
12894             }
12895             catch (ObjectDisposedException)
12896             {
12897                 return;
12898             }
12899             catch (InvalidOperationException)
12900             {
12901                 return;
12902             }
12903
12904             MenuItemUserStream.Text = "&UserStream ▶";
12905             MenuItemUserStream.Enabled = true;
12906             StopToolStripMenuItem.Text = "&Stop";
12907             StopToolStripMenuItem.Enabled = true;
12908
12909             StatusLabel.Text = "UserStream Started.";
12910         }
12911
12912         private void tw_UserStreamStopped(object sender, EventArgs e)
12913         {
12914             this._isActiveUserstream = false;
12915             try
12916             {
12917                 if (InvokeRequired && !IsDisposed)
12918                 {
12919                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12920                     return;
12921                 }
12922             }
12923             catch (ObjectDisposedException)
12924             {
12925                 return;
12926             }
12927             catch (InvalidOperationException)
12928             {
12929                 return;
12930             }
12931
12932             MenuItemUserStream.Text = "&UserStream ■";
12933             MenuItemUserStream.Enabled = true;
12934             StopToolStripMenuItem.Text = "&Start";
12935             StopToolStripMenuItem.Enabled = true;
12936
12937             StatusLabel.Text = "UserStream Stopped.";
12938         }
12939
12940         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12941         {
12942             try
12943             {
12944                 if (InvokeRequired && !IsDisposed)
12945                 {
12946                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12947                     return;
12948                 }
12949             }
12950             catch (ObjectDisposedException)
12951             {
12952                 return;
12953             }
12954             catch (InvalidOperationException)
12955             {
12956                 return;
12957             }
12958             var ev = e.EventData;
12959             StatusLabel.Text = "Event: " + ev.Event;
12960             //if (ev.Event == "favorite")
12961             //{
12962             //    NotifyFavorite(ev);
12963             //}
12964             NotifyEvent(ev);
12965             if (ev.Event == "favorite" || ev.Event == "unfavorite")
12966             {
12967                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12968                 {
12969                     this.PurgeListViewItemCache();
12970                     ((DetailsListView)_curTab.Tag).Update();
12971                 }
12972                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12973                 {
12974                     RemovePostFromFavTab(new long[] {ev.Id});
12975                 }
12976             }
12977         }
12978
12979         private void NotifyEvent(Twitter.FormattedEvent ev)
12980         {
12981             //新着通知 
12982             if (BalloonRequired(ev))
12983             {
12984                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12985                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12986                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12987                 StringBuilder title = new StringBuilder();
12988                 if (this._cfgCommon.DispUsername)
12989                 {
12990                     title.Append(tw.Username);
12991                     title.Append(" - ");
12992                 }
12993                 else
12994                 {
12995                     //title.Clear();
12996                 }
12997                 title.Append(Application.ProductName);
12998                 title.Append(" [");
12999                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13000                 title.Append("] by ");
13001                 if (!string.IsNullOrEmpty(ev.Username))
13002                 {
13003                     title.Append(ev.Username.ToString());
13004                 }
13005                 else
13006                 {
13007                     //title.Append("");
13008                 }
13009                 string text;
13010                 if (!string.IsNullOrEmpty(ev.Target))
13011                 {
13012                     //NotifyIcon1.BalloonTipText = ev.Target;
13013                     text = ev.Target;
13014                 }
13015                 else
13016                 {
13017                     //NotifyIcon1.BalloonTipText = " ";
13018                     text = " ";
13019                 }
13020                 //NotifyIcon1.ShowBalloonTip(500);
13021                 if (this._cfgCommon.IsUseNotifyGrowl)
13022                 {
13023                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13024                               ev.Id.ToString(), title.ToString(), text);
13025                 }
13026                 else
13027                 {
13028                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13029                     NotifyIcon1.BalloonTipTitle = title.ToString();
13030                     NotifyIcon1.BalloonTipText = text;
13031                     NotifyIcon1.ShowBalloonTip(500);
13032                 }
13033             }
13034
13035             //サウンド再生
13036             string snd = this._cfgCommon.EventSoundFile;
13037             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13038             {
13039                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13040                 {
13041                     try
13042                     {
13043                         string dir = Application.StartupPath;
13044                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13045                         {
13046                             dir = Path.Combine(dir, "Sounds");
13047                         }
13048                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13049                         {
13050                             player.Play();
13051                         }
13052                     }
13053                     catch (Exception)
13054                     {
13055                     }
13056                 }
13057             }
13058         }
13059
13060         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13061         {
13062             MenuItemUserStream.Enabled = false;
13063             if (StopRefreshAllMenuItem.Checked)
13064             {
13065                 StopRefreshAllMenuItem.Checked = false;
13066                 return;
13067             }
13068             if (this._isActiveUserstream)
13069             {
13070                 tw.StopUserStream();
13071             }
13072             else
13073             {
13074                 tw.StartUserStream();
13075             }
13076         }
13077
13078         private static string inputTrack = "";
13079
13080         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13081         {
13082             if (TrackToolStripMenuItem.Checked)
13083             {
13084                 using (InputTabName inputForm = new InputTabName())
13085                 {
13086                     inputForm.TabName = inputTrack;
13087                     inputForm.FormTitle = "Input track word";
13088                     inputForm.FormDescription = "Track word";
13089                     if (inputForm.ShowDialog() != DialogResult.OK)
13090                     {
13091                         TrackToolStripMenuItem.Checked = false;
13092                         return;
13093                     }
13094                     inputTrack = inputForm.TabName.Trim();
13095                 }
13096                 if (!inputTrack.Equals(tw.TrackWord))
13097                 {
13098                     tw.TrackWord = inputTrack;
13099                     this.ModifySettingCommon = true;
13100                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13101                     tw.ReconnectUserStream();
13102                 }
13103             }
13104             else
13105             {
13106                 tw.TrackWord = "";
13107                 tw.ReconnectUserStream();
13108             }
13109             this.ModifySettingCommon = true;
13110         }
13111
13112         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13113         {
13114             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13115             this.ModifySettingCommon = true;
13116             tw.ReconnectUserStream();
13117         }
13118
13119         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13120         {
13121             if (evtDialog == null || evtDialog.IsDisposed)
13122             {
13123                 evtDialog = null;
13124                 evtDialog = new EventViewerDialog();
13125                 evtDialog.Owner = this;
13126                 //親の中央に表示
13127                 Point pos = evtDialog.Location;
13128                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13129                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13130                 evtDialog.Location = pos;
13131             }
13132             evtDialog.EventSource = tw.StoredEvent;
13133             if (!evtDialog.Visible)
13134             {
13135                 evtDialog.Show(this);
13136             }
13137             else
13138             {
13139                 evtDialog.Activate();
13140             }
13141             this.TopMost = this._cfgCommon.AlwaysTop;
13142         }
13143 #endregion
13144
13145         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13146         {
13147             MyCommon._endingFlag = true;
13148             try
13149             {
13150                 this.Close();
13151                 Application.Restart();
13152             }
13153             catch (Exception)
13154             {
13155                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13156             }
13157         }
13158
13159         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13160         {
13161             if (!string.IsNullOrEmpty(tw.Username))
13162                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13163         }
13164
13165         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13166         {
13167             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13168         }
13169
13170         private async Task doTranslation(string str)
13171         {
13172             if (string.IsNullOrEmpty(str))
13173                 return;
13174
13175             var bing = new Bing();
13176             try
13177             {
13178                 var translatedText = await bing.TranslateAsync(str,
13179                     langFrom: null,
13180                     langTo: this._cfgCommon.TranslateLanguage);
13181
13182                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13183             }
13184             catch (HttpRequestException e)
13185             {
13186                 this.StatusLabel.Text = "Err:" + e.Message;
13187             }
13188             catch (OperationCanceledException)
13189             {
13190                 this.StatusLabel.Text = "Err:Timeout";
13191             }
13192         }
13193
13194         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13195         {
13196             if (!this.ExistCurrentPost)
13197                 return;
13198
13199             await this.doTranslation(this._curPost.TextFromApi);
13200         }
13201
13202         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13203         {
13204             var text = this.PostBrowser.GetSelectedText();
13205             await this.doTranslation(text);
13206         }
13207
13208         private bool ExistCurrentPost
13209         {
13210             get
13211             {
13212                 if (_curPost == null) return false;
13213                 if (_curPost.IsDeleted) return false;
13214                 return true;
13215             }
13216         }
13217
13218         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13219         {
13220             ShowUserTimeline();
13221         }
13222
13223         private string GetUserIdFromCurPostOrInput(string caption)
13224         {
13225             var id = _curPost?.ScreenName ?? "";
13226
13227             using (InputTabName inputName = new InputTabName())
13228             {
13229                 inputName.FormTitle = caption;
13230                 inputName.FormDescription = Properties.Resources.FRMessage1;
13231                 inputName.TabName = id;
13232                 if (inputName.ShowDialog() == DialogResult.OK &&
13233                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13234                 {
13235                     id = inputName.TabName.Trim();
13236                 }
13237                 else
13238                 {
13239                     id = "";
13240                 }
13241             }
13242             return id;
13243         }
13244
13245         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13246         {
13247             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13248             if (!string.IsNullOrEmpty(id))
13249             {
13250                 AddNewTabForUserTimeline(id);
13251             }
13252         }
13253
13254         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13255         {
13256             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13257             if (!string.IsNullOrEmpty(id))
13258             {
13259                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13260             }
13261         }
13262
13263         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13264         {
13265             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13266         }
13267
13268         private void TimelineRefreshEnableChange(bool isEnable)
13269         {
13270             if (isEnable)
13271             {
13272                 tw.StartUserStream();
13273             }
13274             else
13275             {
13276                 tw.StopUserStream();
13277             }
13278             TimerTimeline.Enabled = isEnable;
13279         }
13280
13281         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13282         {
13283             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13284         }
13285
13286         private async Task OpenUserAppointUrl()
13287         {
13288             if (this._cfgCommon.UserAppointUrl != null)
13289             {
13290                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13291                 {
13292                     if (_curPost != null)
13293                     {
13294                         string xUrl = this._cfgCommon.UserAppointUrl;
13295                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13296
13297                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13298                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13299
13300                         await this.OpenUriInBrowserAsync(xUrl);
13301                     }
13302                 }
13303                 else
13304                 {
13305                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13306                 }
13307             }
13308         }
13309
13310         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13311         {
13312             await this.OpenUserAppointUrl();
13313         }
13314
13315         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13316         {
13317             string selText = SourceLinkLabel.Text;
13318             try
13319             {
13320                 Clipboard.SetDataObject(selText, false, 5, 100);
13321             }
13322             catch (Exception ex)
13323             {
13324                 MessageBox.Show(ex.Message);
13325             }
13326         }
13327
13328         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13329         {
13330             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13331             try
13332             {
13333                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13334             }
13335             catch (Exception ex)
13336             {
13337                 MessageBox.Show(ex.Message);
13338             }
13339         }
13340
13341         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13342         {
13343             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13344             {
13345                 SourceCopyMenuItem.Enabled = false;
13346                 SourceUrlCopyMenuItem.Enabled = false;
13347             }
13348             else
13349             {
13350                 SourceCopyMenuItem.Enabled = true;
13351                 SourceUrlCopyMenuItem.Enabled = true;
13352             }
13353         }
13354
13355         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13356         {
13357             if (Form.ActiveForm == null)
13358             {
13359                 this.BeginInvoke((Action) (() =>
13360                 {
13361                     this.Visible = true;
13362                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13363                     this.Activate();
13364                     this.BringToFront();
13365                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13366                     {
13367                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13368                     }
13369                     else
13370                     {
13371                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13372                     }
13373                 }));
13374             }
13375         }
13376
13377         private void ReplaceAppName()
13378         {
13379             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13380             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13381         }
13382
13383         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13384         {
13385             this.SplitContainer3.Panel2Collapsed = false;
13386         }
13387
13388         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13389         {
13390             await this.OpenThumbnailPicture(e.Thumbnail);
13391         }
13392
13393         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13394         {
13395             await this.OpenUriInBrowserAsync(e.ImageUrl);
13396         }
13397
13398         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13399         {
13400             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13401
13402             await this.OpenUriInBrowserAsync(url);
13403         }
13404
13405         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13406         {
13407             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13408         }
13409
13410         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13411         {
13412             if (e.KeyCode == Keys.Space)
13413             {
13414                 this.JumpUnreadMenuItem_Click(null, null);
13415
13416                 e.SuppressKeyPress = true;
13417             }
13418         }
13419
13420         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13421         {
13422             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13423             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13424             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13425             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13426             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13427
13428             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13429         }
13430
13431         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13432         {
13433             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13434         }
13435
13436         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13437         {
13438             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13439         }
13440
13441         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13442         {
13443             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13444         }
13445
13446         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13447         {
13448             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13449         }
13450
13451         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13452         {
13453             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13454         }
13455
13456         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13457         {
13458             if (this._cfgCommon.IconSize == iconSize) return;
13459
13460             var oldIconCol = _iconCol;
13461
13462             this._cfgCommon.IconSize = iconSize;
13463             ApplyListViewIconSize(iconSize);
13464
13465             if (_iconCol != oldIconCol)
13466             {
13467                 foreach (TabPage tp in ListTab.TabPages)
13468                 {
13469                     ResetColumns((DetailsListView)tp.Tag);
13470                 }
13471             }
13472
13473             _curList?.Refresh();
13474
13475             ModifySettingCommon = true;
13476         }
13477
13478         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13479         {
13480             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13481             if (this._cfgCommon.SortOrderLock == state) return;
13482
13483             this._cfgCommon.SortOrderLock = state;
13484
13485             ModifySettingCommon = true;
13486         }
13487     }
13488 }