OSDN Git Service

短縮URLが生成されるまでの間に投稿欄のテキストが変更されるとエラーが発生する不具合を修正
[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.Runtime.InteropServices;
45 using System.Text;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
50 using OpenTween.Api;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
57
58 namespace OpenTween
59 {
60     public partial class TweenMain : OTBaseForm
61     {
62         //各種設定
63         private Size _mySize;           //画面サイズ
64         private Point _myLoc;           //画面位置
65         private int _mySpDis;           //区切り位置
66         private int _mySpDis2;          //発言欄区切り位置
67         private int _mySpDis3;          //プレビュー区切り位置
68         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69         private bool _iconCol;          //1列表示の時true(48サイズのとき)
70
71         //雑多なフラグ類
72         private bool _initial;         //true:起動時処理中
73         private bool _initialLayout = true;
74         private bool _ignoreConfigSave;         //true:起動時処理中
75         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77         private Point _tabMouseDownPoint;
78         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
79         private readonly object _syncObject = new object();    //ロック用
80
81         private const string detailHtmlFormatHeaderMono = 
82             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83             + "<style type=\"text/css\"><!-- "
84             + "body, p, pre {margin: 0;} "
85             + "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%);} "
86             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89             + ".quote-tweet.reply {border-color: #f33;} "
90             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
91             + "--></style>"
92             + "</head><body><pre>";
93         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94         private const string detailHtmlFormatHeaderColor = 
95             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96             + "<style type=\"text/css\"><!-- "
97             + "body, p, pre {margin: 0;} "
98             + "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%);} "
99             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
104             + "--></style>"
105             + "</head><body><p>";
106         private const string detailHtmlFormatFooterColor = "</p></body></html>";
107         private string detailHtmlFormatHeader;
108         private string detailHtmlFormatFooter;
109
110         private bool _myStatusError = false;
111         private bool _myStatusOnline = false;
112         private bool soundfileListup = false;
113         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
114
115         //twitter解析部
116         private TwitterApi twitterApi = new TwitterApi();
117         private Twitter tw;
118
119         //Growl呼び出し部
120         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
121
122         //サブ画面インスタンス
123         internal SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
124         private OpenURL UrlDialog = new OpenURL();
125         public AtIdSupplement AtIdSupl;     //@id補助
126         public AtIdSupplement HashSupl;    //Hashtag補助
127         public HashtagManage HashMgr;
128         private EventViewerDialog evtDialog;
129
130         //表示フォント、色、アイコン
131         private Font _fntUnread;            //未読用フォント
132         private Color _clUnread;            //未読用文字色
133         private Font _fntReaded;            //既読用フォント
134         private Color _clReaded;            //既読用文字色
135         private Color _clFav;               //Fav用文字色
136         private Color _clOWL;               //片思い用文字色
137         private Color _clRetweet;               //Retweet用文字色
138         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
139         private Font _fntDetail;            //発言詳細部用フォント
140         private Color _clDetail;              //発言詳細部用色
141         private Color _clDetailLink;          //発言詳細部用リンク文字色
142         private Color _clDetailBackcolor;     //発言詳細部用背景色
143         private Color _clSelf;              //自分の発言用背景色
144         private Color _clAtSelf;            //自分宛返信用背景色
145         private Color _clTarget;            //選択発言者の他の発言用背景色
146         private Color _clAtTarget;          //選択発言中の返信先用背景色
147         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
148         private Color _clAtTo;              //選択発言の唯一@先
149         private Color _clListBackcolor;       //リスト部通常発言背景色
150         private Color _clInputBackcolor;      //入力欄背景色
151         private Color _clInputFont;           //入力欄文字色
152         private Font _fntInputFont;           //入力欄フォント
153         private ImageCache IconCache;        //アイコン画像リスト
154         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
155         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
156         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
157         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
158         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
159         private Icon MainIcon;              //Main.ico           画面左上のアイコン
160         private Icon ReplyIcon;               //5g
161         private Icon ReplyIconBlink;          //6g
162
163         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
164
165         private PostClass _anchorPost;
166         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
167
168         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
169         private int _hisIdx;                  //発言履歴カレントインデックス
170
171         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
172         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
173
174         //時速表示用
175         private List<DateTime> _postTimestamps = new List<DateTime>();
176         private List<DateTime> _favTimestamps = new List<DateTime>();
177
178         // 以下DrawItem関連
179         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
180         private SolidBrush _brsBackColorMine;
181         private SolidBrush _brsBackColorAt;
182         private SolidBrush _brsBackColorYou;
183         private SolidBrush _brsBackColorAtYou;
184         private SolidBrush _brsBackColorAtFromTarget;
185         private SolidBrush _brsBackColorAtTo;
186         private SolidBrush _brsBackColorNone;
187         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
188         private StringFormat sfTab = new StringFormat();
189
190         //////////////////////////////////////////////////////////////////////////////////////////////////////////
191         private TabInformations _statuses;
192
193         /// <summary>
194         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
195         /// </summary>
196         /// <remarks>
197         /// キャッシュクリアのために null が代入されることがあるため、
198         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
199         /// 一旦ローカル変数に代入してから参照すること。
200         /// </remarks>
201         private ListViewItemCache _listItemCache = null;
202
203         internal class ListViewItemCache
204         {
205             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
206             public ListView TargetList { get; set; }
207
208             /// <summary>キャッシュする範囲の開始インデックス</summary>
209             public int StartIndex { get; set; }
210
211             /// <summary>キャッシュする範囲の終了インデックス</summary>
212             public int EndIndex { get; set; }
213
214             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
215             public ListViewItem[] ListItem { get; set; }
216
217             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
218             public PostClass[] Post { get; set; }
219
220             /// <summary>キャッシュされたアイテムの件数</summary>
221             public int Count
222                 => this.EndIndex - this.StartIndex + 1;
223
224             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
225             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
226             public bool Contains(int index)
227                 => index >= this.StartIndex && index <= this.EndIndex;
228
229             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
230             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
231             public bool IsSupersetOf(int rangeStart, int rangeEnd)
232                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
233
234             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
235             /// <returns>取得に成功すれば true、それ以外は false</returns>
236             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
237             {
238                 if (this.Contains(index))
239                 {
240                     item = this.ListItem[index - this.StartIndex];
241                     post = this.Post[index - this.StartIndex];
242                     return true;
243                 }
244                 else
245                 {
246                     item = null;
247                     post = null;
248                     return false;
249                 }
250             }
251         }
252
253         private TabPage _curTab;
254         private int _curItemIndex;
255         private DetailsListView _curList;
256         private PostClass _curPost;
257         private bool _isColumnChanged = false;
258
259         private const int MAX_WORKER_THREADS = 20;
260         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
261         private CancellationTokenSource workerCts = new CancellationTokenSource();
262         private IProgress<string> workerProgress;
263
264         private int UnreadCounter = -1;
265         private int UnreadAtCounter = -1;
266
267         private string[] ColumnOrgText = new string[9];
268         private string[] ColumnText = new string[9];
269
270         private bool _DoFavRetweetFlags = false;
271         private bool osResumed = false;
272
273         //////////////////////////////////////////////////////////////////////////////////////////////////////////
274         private bool _colorize = false;
275
276         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
277
278         private string recommendedStatusFooter;
279
280         //URL短縮のUndo用
281         private struct urlUndo
282         {
283             public string Before;
284             public string After;
285         }
286
287         private List<urlUndo> urlUndoBuffer = null;
288
289         private struct ReplyChain
290         {
291             public long OriginalId;
292             public long InReplyToId;
293             public TabPage OriginalTab;
294
295             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
296             {
297                 this.OriginalId = originalId;
298                 this.InReplyToId = inReplyToId;
299                 this.OriginalTab = originalTab;
300             }
301         }
302
303         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
304         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
305
306         //検索処理タイプ
307         internal enum SEARCHTYPE
308         {
309             DialogSearch,
310             NextSearch,
311             PrevSearch,
312         }
313
314         private class PostingStatus
315         {
316             public string status = "";
317             public long? inReplyToId = null;
318             public string inReplyToName = null;
319             public string imageService = "";      //画像投稿サービス名
320             public IMediaItem[] mediaItems = null;
321             public PostingStatus()
322             {
323             }
324             public PostingStatus(string status, long? replyToId, string replyToName)
325             {
326                 this.status = status;
327                 this.inReplyToId = replyToId;
328                 this.inReplyToName = replyToName;
329             }
330         }
331
332         private void TweenMain_Activated(object sender, EventArgs e)
333         {
334             //画面がアクティブになったら、発言欄の背景色戻す
335             if (StatusText.Focused)
336             {
337                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
338             }
339         }
340
341         private bool disposed = false;
342
343         /// <summary>
344         /// 使用中のリソースをすべてクリーンアップします。
345         /// </summary>
346         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
347         protected override void Dispose(bool disposing)
348         {
349             base.Dispose(disposing);
350
351             if (this.disposed)
352                 return;
353
354             if (disposing)
355             {
356                 this.components?.Dispose();
357
358                 //後始末
359                 SearchDialog.Dispose();
360                 UrlDialog.Dispose();
361                 NIconAt?.Dispose();
362                 NIconAtRed?.Dispose();
363                 NIconAtSmoke?.Dispose();
364                 foreach (var iconRefresh in this.NIconRefresh)
365                 {
366                     iconRefresh?.Dispose();
367                 }
368                 TabIcon?.Dispose();
369                 MainIcon?.Dispose();
370                 ReplyIcon?.Dispose();
371                 ReplyIconBlink?.Dispose();
372                 _listViewImageList.Dispose();
373                 _brsHighLight.Dispose();
374                 _brsBackColorMine?.Dispose();
375                 _brsBackColorAt?.Dispose();
376                 _brsBackColorYou?.Dispose();
377                 _brsBackColorAtYou?.Dispose();
378                 _brsBackColorAtFromTarget?.Dispose();
379                 _brsBackColorAtTo?.Dispose();
380                 _brsBackColorNone?.Dispose();
381                 _brsDeactiveSelection?.Dispose();
382                 //sf.Dispose();
383                 sfTab.Dispose();
384
385                 this.workerCts.Cancel();
386
387                 if (IconCache != null)
388                 {
389                     this.IconCache.CancelAsync();
390                     this.IconCache.Dispose();
391                 }
392
393                 this.thumbnailTokenSource?.Dispose();
394
395                 this.tw.Dispose();
396                 this.twitterApi.Dispose();
397                 this._hookGlobalHotkey.Dispose();
398             }
399
400             // 終了時にRemoveHandlerしておかないとメモリリークする
401             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
402             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
403
404             this.disposed = true;
405         }
406
407         private void LoadIcons()
408         {
409             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
410             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
411
412             // ウィンドウ左上のアイコン
413             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
414
415             // タブ見出し未読表示アイコン
416             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
417
418             // タスクトレイ: 通常時アイコン
419             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
420
421             // タスクトレイ: エラー時アイコン
422             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
423
424             // タスクトレイ: オフライン時アイコン
425             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
426
427             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
428             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
429             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
430
431             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
432             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
433             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
434             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
435             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
436
437             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
438
439             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
440             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
441             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
442             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
443             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
444
445             if (iconReply != null && iconReplyBlink != null)
446             {
447                 this.ReplyIcon = iconReply;
448                 this.ReplyIconBlink = iconReplyBlink;
449             }
450             else
451             {
452                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
453                 this.ReplyIconBlink = this.NIconAt;
454             }
455
456             if (iconRefresh1 == null)
457             {
458                 this.NIconRefresh = new[] {
459                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
460                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
461                 };
462             }
463             else if (iconRefresh2 == null)
464             {
465                 this.NIconRefresh = new[] { iconRefresh1 };
466             }
467             else if (iconRefresh3 == null)
468             {
469                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
470             }
471             else if (iconRefresh4 == null)
472             {
473                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
474             }
475             else // iconRefresh1 から iconRefresh4 まで全て揃っている
476             {
477                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
478             }
479         }
480
481         private Icon LoadIcon(string filePath)
482         {
483             if (!File.Exists(filePath))
484                 return null;
485
486             try
487             {
488                 return new Icon(filePath);
489             }
490             catch (Exception)
491             {
492                 return null;
493             }
494         }
495
496         private void InitColumns(ListView list, bool startup)
497         {
498             this.InitColumnText();
499
500             ColumnHeader[] columns = null;
501             try
502             {
503                 if (this._iconCol)
504                 {
505                     columns = new[]
506                     {
507                         new ColumnHeader(), // アイコン
508                         new ColumnHeader(), // 本文
509                     };
510
511                     columns[0].Text = this.ColumnText[0];
512                     columns[1].Text = this.ColumnText[2];
513
514                     if (startup)
515                     {
516                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
517
518                         columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
519                         columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
520                         columns[0].DisplayIndex = 0;
521                         columns[1].DisplayIndex = 1;
522                     }
523                     else
524                     {
525                         var idx = 0;
526                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
527                         {
528                             columns[idx].Width = curListColumn.Width;
529                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
530                             idx++;
531                         }
532                     }
533                 }
534                 else
535                 {
536                     columns = new[]
537                     {
538                         new ColumnHeader(), // アイコン
539                         new ColumnHeader(), // ニックネーム
540                         new ColumnHeader(), // 本文
541                         new ColumnHeader(), // 日付
542                         new ColumnHeader(), // ユーザID
543                         new ColumnHeader(), // 未読
544                         new ColumnHeader(), // マーク&プロテクト
545                         new ColumnHeader(), // ソース
546                     };
547
548                     foreach (var i in Enumerable.Range(0, columns.Length))
549                         columns[i].Text = this.ColumnText[i];
550
551                     if (startup)
552                     {
553                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
554
555                         columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
556                         columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
557                         columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
558                         columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
559                         columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
560                         columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
561                         columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
562                         columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
563
564                         var displayIndex = new[] {
565                             SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
566                             SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
567                             SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
568                             SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
569                         };
570
571                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
572                         {
573                             columns[i].DisplayIndex = displayIndex[i];
574                         }
575                     }
576                     else
577                     {
578                         var idx = 0;
579                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
580                         {
581                             columns[idx].Width = curListColumn.Width;
582                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
583                             idx++;
584                         }
585                     }
586                 }
587
588                 list.Columns.AddRange(columns);
589
590                 columns = null;
591             }
592             finally
593             {
594                 if (columns != null)
595                 {
596                     foreach (var column in columns)
597                         column?.Dispose();
598                 }
599             }
600         }
601
602         private void InitColumnText()
603         {
604             ColumnText[0] = "";
605             ColumnText[1] = Properties.Resources.AddNewTabText2;
606             ColumnText[2] = Properties.Resources.AddNewTabText3;
607             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
608             ColumnText[4] = Properties.Resources.AddNewTabText5;
609             ColumnText[5] = "";
610             ColumnText[6] = "";
611             ColumnText[7] = "Source";
612
613             ColumnOrgText[0] = "";
614             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
615             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
616             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
617             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
618             ColumnOrgText[5] = "";
619             ColumnOrgText[6] = "";
620             ColumnOrgText[7] = "Source";
621
622             int c = 0;
623             switch (_statuses.SortMode)
624             {
625                 case ComparerMode.Nickname:  //ニックネーム
626                     c = 1;
627                     break;
628                 case ComparerMode.Data:  //本文
629                     c = 2;
630                     break;
631                 case ComparerMode.Id:  //時刻=発言Id
632                     c = 3;
633                     break;
634                 case ComparerMode.Name:  //名前
635                     c = 4;
636                     break;
637                 case ComparerMode.Source:  //Source
638                     c = 7;
639                     break;
640             }
641
642             if (_iconCol)
643             {
644                 if (_statuses.SortOrder == SortOrder.Descending)
645                 {
646                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
647                     ColumnText[2] = ColumnOrgText[2] + "▾";
648                 }
649                 else
650                 {
651                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
652                     ColumnText[2] = ColumnOrgText[2] + "▴";
653                 }
654             }
655             else
656             {
657                 if (_statuses.SortOrder == SortOrder.Descending)
658                 {
659                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
660                     ColumnText[c] = ColumnOrgText[c] + "▾";
661                 }
662                 else
663                 {
664                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
665                     ColumnText[c] = ColumnOrgText[c] + "▴";
666                 }
667             }
668         }
669
670         private void InitializeTraceFrag()
671         {
672 #if DEBUG
673             TraceOutToolStripMenuItem.Checked = true;
674             MyCommon.TraceFlag = true;
675 #endif
676             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
677             {
678                 TraceOutToolStripMenuItem.Checked = true;
679                 MyCommon.TraceFlag = true;
680             }
681         }
682
683         private void TweenMain_Load(object sender, EventArgs e)
684         {
685             _ignoreConfigSave = true;
686             this.Visible = false;
687
688             if (MyApplication.StartupOptions.ContainsKey("d"))
689                 MyCommon.TraceFlag = true;
690
691             InitializeTraceFrag();
692
693             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
694
695             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
696             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
697
698             Regex.CacheSize = 100;
699
700             //発言保持クラス
701             _statuses = TabInformations.GetInstance();
702
703             //アイコン設定
704             LoadIcons();
705             this.Icon = MainIcon;              //メインフォーム(TweenMain)
706             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
707             TabImage.Images.Add(TabIcon);    //タブ見出し
708
709             //<<<<<<<<<設定関連>>>>>>>>>
710             ////設定読み出し
711             LoadConfig();
712
713             // 現在の DPI と設定保存時の DPI との比を取得する
714             var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
715
716             // UIフォント設定
717             var fontUIGlobal = SettingManager.Local.FontUIGlobal;
718             if (fontUIGlobal != null)
719             {
720                 OTBaseForm.GlobalFont = fontUIGlobal;
721                 this.Font = fontUIGlobal;
722             }
723
724             //不正値チェック
725             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
726             {
727                 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
728                     SettingManager.Common.TimelinePeriod = 15;
729
730                 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
731                     SettingManager.Common.ReplyPeriod = 15;
732
733                 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
734                     SettingManager.Common.DMPeriod = 15;
735
736                 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
737                     SettingManager.Common.PubSearchPeriod = 30;
738
739                 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
740                     SettingManager.Common.UserTimelinePeriod = 15;
741
742                 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
743                     SettingManager.Common.ListsPeriod = 15;
744             }
745
746             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
747                 SettingManager.Common.CountApi = 60;
748             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
749                 SettingManager.Common.CountApiReply = 40;
750
751             if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
752                 SettingManager.Common.MoreCountApi = 200;
753             if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
754                 SettingManager.Common.FirstCountApi = 100;
755
756             if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
757                 SettingManager.Common.FavoritesCountApi = 40;
758             if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
759                 SettingManager.Common.ListCountApi = 100;
760             if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
761                 SettingManager.Common.SearchCountApi = 100;
762             if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
763                 SettingManager.Common.UserTimelineCountApi = 20;
764
765             //廃止サービスが選択されていた場合ux.nuへ読み替え
766             if (SettingManager.Common.AutoShortUrlFirst < 0)
767                 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
768
769             TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
770             this.tw = new Twitter(this.twitterApi);
771
772             //認証関連
773             if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
774             tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
775
776             _initial = true;
777
778             Networking.Initialize();
779
780             bool saveRequired = false;
781             bool firstRun = false;
782
783             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
784             if (string.IsNullOrEmpty(tw.Username))
785             {
786                 saveRequired = true;
787                 firstRun = true;
788
789                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
790                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
791                     string.IsNullOrEmpty(tw.Username))
792                 {
793                     Application.Exit();  //強制終了
794                     return;
795                 }
796             }
797
798             //Twitter用通信クラス初期化
799             Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
800             Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
801             Networking.SetWebProxy(SettingManager.Local.ProxyType,
802                 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
803                 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
804             Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
805
806             TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
807             tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
808             tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
809             tw.TrackWord = SettingManager.Common.TrackWord;
810             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
811             tw.AllAtReply = SettingManager.Common.AllAtReply;
812             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
813             ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
814             ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
815             ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
816
817             // アクセストークンが有効であるか確認する
818             // ここが Twitter API への最初のアクセスになるようにすること
819             try
820             {
821                 this.tw.VerifyCredentials();
822             }
823             catch (WebApiException ex)
824             {
825                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
826                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
827             }
828
829             //サムネイル関連の初期化
830             //プロキシ設定等の通信まわりの初期化が済んでから処理する
831             ThumbnailGenerator.InitializeGenerator();
832
833             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
834             imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
835             imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
836
837             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
838
839             //画像投稿サービス
840             ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
841
842             //ハッシュタグ/@id関連
843             AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
844             HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
845             HashMgr = new HashtagManage(HashSupl,
846                                     SettingManager.Common.HashTags.ToArray(),
847                                     SettingManager.Common.HashSelected,
848                                     SettingManager.Common.HashIsPermanent,
849                                     SettingManager.Common.HashIsHead,
850                                     SettingManager.Common.HashIsNotAddToAtReply);
851             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
852
853             //アイコンリスト作成
854             this.IconCache = new ImageCache();
855             this.tweetDetailsView.IconCache = this.IconCache;
856
857             //フォント&文字色&背景色保持
858             _fntUnread = SettingManager.Local.FontUnread;
859             _clUnread = SettingManager.Local.ColorUnread;
860             _fntReaded = SettingManager.Local.FontRead;
861             _clReaded = SettingManager.Local.ColorRead;
862             _clFav = SettingManager.Local.ColorFav;
863             _clOWL = SettingManager.Local.ColorOWL;
864             _clRetweet = SettingManager.Local.ColorRetweet;
865             _fntDetail = SettingManager.Local.FontDetail;
866             _clDetail = SettingManager.Local.ColorDetail;
867             _clDetailLink = SettingManager.Local.ColorDetailLink;
868             _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
869             _clSelf = SettingManager.Local.ColorSelf;
870             _clAtSelf = SettingManager.Local.ColorAtSelf;
871             _clTarget = SettingManager.Local.ColorTarget;
872             _clAtTarget = SettingManager.Local.ColorAtTarget;
873             _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
874             _clAtTo = SettingManager.Local.ColorAtTo;
875             _clListBackcolor = SettingManager.Local.ColorListBackcolor;
876             _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
877             _clInputFont = SettingManager.Local.ColorInputFont;
878             _fntInputFont = SettingManager.Local.FontInputFont;
879
880             _brsBackColorMine = new SolidBrush(_clSelf);
881             _brsBackColorAt = new SolidBrush(_clAtSelf);
882             _brsBackColorYou = new SolidBrush(_clTarget);
883             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
884             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
885             _brsBackColorAtTo = new SolidBrush(_clAtTo);
886             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
887             _brsBackColorNone = new SolidBrush(_clListBackcolor);
888
889             // StringFormatオブジェクトへの事前設定
890             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
891             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
892             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
893             sfTab.Alignment = StringAlignment.Center;
894             sfTab.LineAlignment = StringAlignment.Center;
895
896             InitDetailHtmlFormat();
897
898             //Regex statregex = new Regex("^0*");
899             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
900
901             _history.Add(new PostingStatus());
902             _hisIdx = 0;
903             this.inReplyTo = null;
904
905             //各種ダイアログ設定
906             SearchDialog.Owner = this;
907             UrlDialog.Owner = this;
908
909             //新着バルーン通知のチェック状態設定
910             NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
911             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
912
913             //新着取得時のリストスクロールをするか。trueならスクロールしない
914             ListLockMenuItem.Checked = SettingManager.Common.ListLock;
915             this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
916             //サウンド再生(タブ別設定より優先)
917             this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
918             this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
919
920             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
921             this.ToolStripFocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
922
923             //ウィンドウ設定
924             this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
925             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
926             _myLoc = SettingManager.Local.FormLocation;
927             //タイトルバー領域
928             if (this.WindowState != FormWindowState.Minimized)
929             {
930                 this.DesktopLocation = SettingManager.Local.FormLocation;
931                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
932                 bool outOfScreen = true;
933                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
934                 {
935                     foreach (Screen scr in Screen.AllScreens)
936                     {
937                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
938                         {
939                             outOfScreen = false;
940                             break;
941                         }
942                     }
943                     if (outOfScreen)
944                     {
945                         this.DesktopLocation = new Point(0, 0);
946                         _myLoc = this.DesktopLocation;
947                     }
948                 }
949             }
950             this.TopMost = SettingManager.Common.AlwaysTop;
951             _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
952             _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
953             if (SettingManager.Local.PreviewDistance == -1)
954             {
955                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
956                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
957                 SettingManager.Local.PreviewDistance = _mySpDis3;
958             }
959             else
960             {
961                 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
962             }
963             MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
964             //this.Tween_ClientSizeChanged(this, null);
965             this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
966             this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
967             //入力欄
968             StatusText.Font = _fntInputFont;
969             StatusText.ForeColor = _clInputFont;
970
971             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
972             this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
973             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
974
975             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
976             SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
977
978             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
979             if (SettingManager.Common.UnreadManage == false)
980             {
981                 ReadedStripMenuItem.Enabled = false;
982                 UnreadStripMenuItem.Enabled = false;
983             }
984
985             //リンク先URL表示部の初期化(画面左下)
986             StatusLabelUrl.Text = "";
987             //状態表示部の初期化(画面右下)
988             StatusLabel.Text = "";
989             StatusLabel.AutoToolTip = false;
990             StatusLabel.ToolTipText = "";
991             //文字カウンタ初期化
992             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
993
994             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
995             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
996             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
997             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
998
999             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1000             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1001             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1002             this.SplitContainer2.Panel2.AccessibleName = "";
1003
1004             ////////////////////////////////////////////////////////////////////////////////
1005             var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1006             var mode = ComparerMode.Id;
1007             switch (SettingManager.Common.SortColumn)
1008             {
1009                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1010                 case 5:
1011                 case 6:
1012                     //ソートしない
1013                     mode = ComparerMode.Id;  //Idソートに読み替え
1014                     break;
1015                 case 1:  //ニックネーム
1016                     mode = ComparerMode.Nickname;
1017                     break;
1018                 case 2:  //本文
1019                     mode = ComparerMode.Data;
1020                     break;
1021                 case 3:  //時刻=発言Id
1022                     mode = ComparerMode.Id;
1023                     break;
1024                 case 4:  //名前
1025                     mode = ComparerMode.Name;
1026                     break;
1027                 case 7:  //Source
1028                     mode = ComparerMode.Source;
1029                     break;
1030             }
1031             _statuses.SetSortMode(mode, sortOrder);
1032             ////////////////////////////////////////////////////////////////////////////////
1033
1034             ApplyListViewIconSize(SettingManager.Common.IconSize);
1035
1036             //<<<<<<<<タブ関連>>>>>>>
1037             // タブの位置を調整する
1038             SetTabAlignment();
1039
1040             //デフォルトタブの存在チェック、ない場合には追加
1041             if (this._statuses.GetTabByType<HomeTabModel>() == null)
1042                 this._statuses.AddTab(new HomeTabModel());
1043
1044             if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1045                 this._statuses.AddTab(new MentionsTabModel());
1046
1047             if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1048                 this._statuses.AddTab(new DirectMessagesTabModel());
1049
1050             if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1051                 this._statuses.AddTab(new FavoritesTabModel());
1052
1053             if (this._statuses.GetTabByType<MuteTabModel>() == null)
1054                 this._statuses.AddTab(new MuteTabModel());
1055
1056             foreach (var tab in _statuses.Tabs.Values)
1057             {
1058                 // ミュートタブは表示しない
1059                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1060                     continue;
1061
1062                 if (!AddNewTab(tab, startup: true))
1063                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1064             }
1065
1066             _curTab = ListTab.SelectedTab;
1067             _curItemIndex = -1;
1068             _curList = (DetailsListView)_curTab.Tag;
1069
1070             if (SettingManager.Common.TabIconDisp)
1071             {
1072                 ListTab.DrawMode = TabDrawMode.Normal;
1073             }
1074             else
1075             {
1076                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1077                 ListTab.DrawItem += ListTab_DrawItem;
1078                 ListTab.ImageList = null;
1079             }
1080
1081             if (SettingManager.Common.HotkeyEnabled)
1082             {
1083                 //////グローバルホットキーの登録
1084                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1085                 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1086                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1087                 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1088                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1089                 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1090                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1091                 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1092                     modKey |= HookGlobalHotkey.ModKeys.Win;
1093
1094                 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1095             }
1096
1097             if (SettingManager.Common.IsUseNotifyGrowl)
1098                 gh.RegisterGrowl();
1099
1100             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1101
1102             SetMainWindowTitle();
1103             SetNotifyIconText();
1104
1105             if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1106             {
1107                 this.Visible = true;
1108             }
1109
1110             //タイマー設定
1111             TimerTimeline.AutoReset = true;
1112             TimerTimeline.SynchronizingObject = this;
1113             //Recent取得間隔
1114             TimerTimeline.Interval = 1000;
1115             TimerTimeline.Enabled = true;
1116             //更新中アイコンアニメーション間隔
1117             TimerRefreshIcon.Interval = 200;
1118             TimerRefreshIcon.Enabled = true;
1119
1120             _ignoreConfigSave = false;
1121             this.TweenMain_Resize(null, null);
1122             if (saveRequired) SaveConfigsAll(false);
1123
1124             foreach (var ua in SettingManager.Common.UserAccounts)
1125             {
1126                 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1127                 {
1128                     ua.UserId = tw.UserId;
1129                     break;
1130                 }
1131             }
1132
1133             if (firstRun)
1134             {
1135                 // 初回起動時だけ右下のメニューを目立たせる
1136                 HashStripSplitButton.ShowDropDown();
1137             }
1138         }
1139
1140         private void InitDetailHtmlFormat()
1141         {
1142             if (SettingManager.Common.IsMonospace)
1143             {
1144                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1145                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1146             }
1147             else
1148             {
1149                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1150                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1151             }
1152
1153             detailHtmlFormatHeader = detailHtmlFormatHeader
1154                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1155                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1156                     .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1157                     .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1158                     .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1159                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1160         }
1161
1162         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1163         {
1164             string txt;
1165             try
1166             {
1167                 txt = ListTab.TabPages[e.Index].Text;
1168             }
1169             catch (Exception)
1170             {
1171                 return;
1172             }
1173
1174             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1175             if (e.State == DrawItemState.Selected)
1176             {
1177                 e.DrawFocusRectangle();
1178             }
1179             Brush fore;
1180             try
1181             {
1182                 if (_statuses.Tabs[txt].UnreadCount > 0)
1183                     fore = Brushes.Red;
1184                 else
1185                     fore = System.Drawing.SystemBrushes.ControlText;
1186             }
1187             catch (Exception)
1188             {
1189                 fore = System.Drawing.SystemBrushes.ControlText;
1190             }
1191             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1192         }
1193
1194         private void LoadConfig()
1195         {
1196             SettingManager.Local = SettingManager.Local;
1197
1198             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1199             if (SettingManager.Local.ScaleDimension.IsEmpty)
1200                 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1201
1202             var tabSettings = SettingManager.Tabs;
1203             foreach (var tabSetting in tabSettings.Tabs)
1204             {
1205                 TabModel tab;
1206                 switch (tabSetting.TabType)
1207                 {
1208                     case MyCommon.TabUsageType.Home:
1209                         tab = new HomeTabModel(tabSetting.TabName);
1210                         break;
1211                     case MyCommon.TabUsageType.Mentions:
1212                         tab = new MentionsTabModel(tabSetting.TabName);
1213                         break;
1214                     case MyCommon.TabUsageType.DirectMessage:
1215                         tab = new DirectMessagesTabModel(tabSetting.TabName);
1216                         break;
1217                     case MyCommon.TabUsageType.Favorites:
1218                         tab = new FavoritesTabModel(tabSetting.TabName);
1219                         break;
1220                     case MyCommon.TabUsageType.UserDefined:
1221                         tab = new FilterTabModel(tabSetting.TabName);
1222                         break;
1223                     case MyCommon.TabUsageType.UserTimeline:
1224                         tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1225                         break;
1226                     case MyCommon.TabUsageType.PublicSearch:
1227                         tab = new PublicSearchTabModel(tabSetting.TabName)
1228                         {
1229                             SearchWords = tabSetting.SearchWords,
1230                             SearchLang = tabSetting.SearchLang,
1231                         };
1232                         break;
1233                     case MyCommon.TabUsageType.Lists:
1234                         tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1235                         break;
1236                     case MyCommon.TabUsageType.Mute:
1237                         tab = new MuteTabModel(tabSetting.TabName);
1238                         break;
1239                     default:
1240                         continue;
1241                 }
1242
1243                 tab.UnreadManage = tabSetting.UnreadManage;
1244                 tab.Protected = tabSetting.Protected;
1245                 tab.Notify = tabSetting.Notify;
1246                 tab.SoundFile = tabSetting.SoundFile;
1247
1248                 if (tab.IsDistributableTabType)
1249                 {
1250                     var filterTab = (FilterTabModel)tab;
1251                     filterTab.FilterArray = tabSetting.FilterArray;
1252                     filterTab.FilterModified = false;
1253                 }
1254
1255                 if (this._statuses.ContainsTab(tab.TabName))
1256                     tab.TabName = this._statuses.MakeTabName("MyTab");
1257
1258                 this._statuses.AddTab(tab);
1259             }
1260             if (_statuses.Tabs.Count == 0)
1261             {
1262                 _statuses.AddTab(new HomeTabModel());
1263                 _statuses.AddTab(new MentionsTabModel());
1264                 _statuses.AddTab(new DirectMessagesTabModel());
1265                 _statuses.AddTab(new FavoritesTabModel());
1266             }
1267         }
1268
1269         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1270         {
1271             if (!TimerTimeline.Enabled) return;
1272             ResetTimers = e;
1273         }
1274
1275         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1276
1277         private static int homeCounter = 0;
1278         private static int mentionCounter = 0;
1279         private static int dmCounter = 0;
1280         private static int pubSearchCounter = 0;
1281         private static int userTimelineCounter = 0;
1282         private static int listsCounter = 0;
1283         private static int usCounter = 0;
1284         private static int ResumeWait = 0;
1285         private static int refreshFollowers = 0;
1286
1287         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1288         {
1289             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1290             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1291             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1292             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1293             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1294             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1295             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1296             Interlocked.Increment(ref refreshFollowers);
1297
1298             var refreshTasks = new List<Task>();
1299
1300             ////タイマー初期化
1301             if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1302             {
1303                 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1304                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1305                     refreshTasks.Add(this.GetHomeTimelineAsync());
1306                 ResetTimers.Timeline = false;
1307             }
1308             if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1309             {
1310                 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1311                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1312                     refreshTasks.Add(this.GetReplyAsync());
1313                 ResetTimers.Reply = false;
1314             }
1315             if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1316             {
1317                 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1318                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1319                     refreshTasks.Add(this.GetDirectMessagesAsync());
1320                 ResetTimers.DirectMessage = false;
1321             }
1322             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1323             {
1324                 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1325                 if (!ResetTimers.PublicSearch)
1326                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1327                 ResetTimers.PublicSearch = false;
1328             }
1329             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1330             {
1331                 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1332                 if (!ResetTimers.UserTimeline)
1333                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1334                 ResetTimers.UserTimeline = false;
1335             }
1336             if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1337             {
1338                 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1339                 if (!ResetTimers.Lists)
1340                     refreshTasks.Add(this.GetListTimelineAllAsync());
1341                 ResetTimers.Lists = false;
1342             }
1343             if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1344             {
1345                 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1346                 if (this.tw.UserStreamActive)
1347                     this.RefreshTimeline();
1348                 ResetTimers.UserStream = false;
1349             }
1350             if (refreshFollowers > 6 * 3600)
1351             {
1352                 Interlocked.Exchange(ref refreshFollowers, 0);
1353                 refreshTasks.AddRange(new[]
1354                 {
1355                     this.doGetFollowersMenu(),
1356                     this.RefreshNoRetweetIdsAsync(),
1357                     this.RefreshTwitterConfigurationAsync(),
1358                 });
1359             }
1360             if (osResumed)
1361             {
1362                 Interlocked.Increment(ref ResumeWait);
1363                 if (ResumeWait > 30)
1364                 {
1365                     osResumed = false;
1366                     Interlocked.Exchange(ref ResumeWait, 0);
1367                     refreshTasks.AddRange(new[]
1368                     {
1369                         this.GetHomeTimelineAsync(),
1370                         this.GetReplyAsync(),
1371                         this.GetDirectMessagesAsync(),
1372                         this.GetPublicSearchAllAsync(),
1373                         this.GetUserTimelineAllAsync(),
1374                         this.GetListTimelineAllAsync(),
1375                         this.doGetFollowersMenu(),
1376                         this.RefreshTwitterConfigurationAsync(),
1377                     });
1378                 }
1379             }
1380
1381             await Task.WhenAll(refreshTasks);
1382         }
1383
1384         private void RefreshTimeline()
1385         {
1386             var curTabModel = this._statuses.Tabs[this._curTab.Text];
1387
1388             // 現在表示中のタブのスクロール位置を退避
1389             var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1390
1391             // 各タブのリスト上の選択位置などを退避
1392             var listSelections = this.SaveListViewSelection();
1393
1394             //更新確定
1395             PostClass[] notifyPosts;
1396             string soundFile;
1397             int addCount;
1398             bool newMentionOrDm;
1399             bool isDelete;
1400             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1401
1402             if (MyCommon._endingFlag) return;
1403
1404             // リストに反映&選択状態復元
1405             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1406             {
1407                 var listView = (DetailsListView)tabPage.Tag;
1408                 var tabModel = this._statuses.Tabs[tabPage.Text];
1409
1410                 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1411                 {
1412                     using (ControlTransaction.Update(listView))
1413                     {
1414                         if (listView == this._curList)
1415                             this.PurgeListViewItemCache();
1416
1417                         try
1418                         {
1419                             // リスト件数更新
1420                             listView.VirtualListSize = tabModel.AllCount;
1421                         }
1422                         catch (NullReferenceException ex)
1423                         {
1424                             // WinForms 内部で ListView.set_TopItem が発生させている例外
1425                             // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1426                             MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1427                         }
1428
1429                         // 選択位置などを復元
1430                         this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1431                     }
1432                 }
1433             }
1434
1435             if (addCount > 0)
1436             {
1437                 if (SettingManager.Common.TabIconDisp)
1438                 {
1439                     foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1440                     {
1441                         var tabModel = this._statuses.Tabs[tabPage.Text];
1442                         if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1443                             tabPage.ImageIndex = 0; // 未読アイコン
1444                     }
1445                 }
1446                 else
1447                 {
1448                     this.ListTab.Refresh();
1449                 }
1450             }
1451
1452             // スクロール位置を復元
1453             this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1454
1455             //新着通知
1456             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1457
1458             SetMainWindowTitle();
1459             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1460
1461             HashSupl.AddRangeItem(tw.GetHashList());
1462
1463         }
1464
1465         internal struct ListViewScroll
1466         {
1467             public ScrollLockMode ScrollLockMode { get; set; }
1468             public long? TopItemStatusId { get; set; }
1469         }
1470
1471         internal enum ScrollLockMode
1472         {
1473             /// <summary>固定しない</summary>
1474             None,
1475
1476             /// <summary>最上部に固定する</summary>
1477             FixedToTop,
1478
1479             /// <summary>最下部に固定する</summary>
1480             FixedToBottom,
1481
1482             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1483             FixedToItem,
1484         }
1485
1486         /// <summary>
1487         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1488         /// </summary>
1489         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1490         {
1491             var listScroll = new ListViewScroll
1492             {
1493                 ScrollLockMode = this.GetScrollLockMode(listView),
1494             };
1495
1496             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1497             {
1498                 var topItemIndex = listView.TopItem?.Index ?? -1;
1499                 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1500                     listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1501             }
1502
1503             return listScroll;
1504         }
1505
1506         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1507         {
1508             if (this._statuses.SortMode == ComparerMode.Id)
1509             {
1510                 if (this._statuses.SortOrder == SortOrder.Ascending)
1511                 {
1512                     // Id昇順
1513                     if (this.ListLockMenuItem.Checked)
1514                         return ScrollLockMode.None;
1515
1516                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1517
1518                     // 一番下に表示されているアイテム
1519                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1520                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1521                         return ScrollLockMode.FixedToBottom;
1522                     else
1523                         return ScrollLockMode.None;
1524                 }
1525                 else
1526                 {
1527                     // Id降順
1528                     if (this.ListLockMenuItem.Checked)
1529                         return ScrollLockMode.FixedToItem;
1530
1531                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1532                     var topItem = listView.TopItem;
1533                     if (topItem == null || topItem.Index == 0)
1534                         return ScrollLockMode.FixedToTop;
1535                     else
1536                         return ScrollLockMode.FixedToItem;
1537                 }
1538             }
1539             else
1540             {
1541                 return ScrollLockMode.FixedToItem;
1542             }
1543         }
1544
1545         internal struct ListViewSelection
1546         {
1547             public long[] SelectedStatusIds { get; set; }
1548             public long? SelectionMarkStatusId { get; set; }
1549             public long? FocusedStatusId { get; set; }
1550         }
1551
1552         /// <summary>
1553         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1554         /// </summary>
1555         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1556         {
1557             var listsDict = new Dictionary<string, ListViewSelection>();
1558
1559             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1560             {
1561                 var listView = (DetailsListView)tabPage.Tag;
1562                 var tab = _statuses.Tabs[tabPage.Text];
1563
1564                 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1565             }
1566
1567             return listsDict;
1568         }
1569
1570         /// <summary>
1571         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1572         /// </summary>
1573         private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1574         {
1575             if (listView.VirtualListSize == 0)
1576             {
1577                 return new ListViewSelection
1578                 {
1579                     SelectedStatusIds = new long[0],
1580                     SelectionMarkStatusId = null,
1581                     FocusedStatusId = null,
1582                 };
1583             }
1584
1585             return new ListViewSelection
1586             {
1587                 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1588                 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1589                 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1590             };
1591         }
1592
1593         private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1594         {
1595             var selectedIndices = listView.SelectedIndices;
1596             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1597                 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1598             else
1599                 return null;
1600         }
1601
1602         private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1603         {
1604             var index = listView.FocusedItem?.Index ?? -1;
1605
1606             return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1607         }
1608
1609         private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1610         {
1611             var index = listView.SelectionMark;
1612
1613             return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1614         }
1615
1616         /// <summary>
1617         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1618         /// </summary>
1619         private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1620         {
1621             if (listView.VirtualListSize == 0)
1622                 return;
1623
1624             switch (listScroll.ScrollLockMode)
1625             {
1626                 case ScrollLockMode.FixedToTop:
1627                     listView.EnsureVisible(0);
1628                     break;
1629                 case ScrollLockMode.FixedToBottom:
1630                     listView.EnsureVisible(listView.VirtualListSize - 1);
1631                     break;
1632                 case ScrollLockMode.FixedToItem:
1633                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1634                     if (topIndex != -1)
1635                         listView.TopItem = listView.Items[topIndex];
1636                     break;
1637                 case ScrollLockMode.None:
1638                 default:
1639                     break;
1640             }
1641         }
1642
1643         /// <summary>
1644         /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1645         /// </summary>
1646         private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1647         {
1648             // status_id から ListView 上のインデックスに変換
1649             int[] selectedIndices = null;
1650             if (listSelection.SelectedStatusIds != null)
1651                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1652
1653             var focusedIndex = -1;
1654             if (listSelection.FocusedStatusId != null)
1655                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1656
1657             var selectionMarkIndex = -1;
1658             if (listSelection.SelectionMarkStatusId != null)
1659                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1660
1661             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1662         }
1663
1664         private bool BalloonRequired()
1665         {
1666             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1667             ev.Eventtype = MyCommon.EVENTTYPE.None;
1668
1669             return BalloonRequired(ev);
1670         }
1671
1672         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1673         {
1674             if (type == MyCommon.EVENTTYPE.None)
1675                 return true;
1676
1677             if (!SettingManager.Common.EventNotifyEnabled)
1678                 return false;
1679
1680             return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1681         }
1682
1683         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1684         {
1685             if (!ev.IsMe)
1686                 return true;
1687
1688             return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1689         }
1690
1691         private bool BalloonRequired(Twitter.FormattedEvent ev)
1692         {
1693             if (this._initial)
1694                 return false;
1695
1696             if (NativeMethods.IsScreenSaverRunning())
1697                 return false;
1698
1699             // 「新着通知」が無効
1700             if (!this.NewPostPopMenuItem.Checked)
1701             {
1702                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1703                 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1704                     return false;
1705             }
1706
1707             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1708             if (SettingManager.Common.LimitBalloon)
1709             {
1710                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1711                     return false;
1712             }
1713
1714             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1715         }
1716
1717         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1718         {
1719             if (SettingManager.Common.ReadOwnPost)
1720             {
1721                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1722                     return;
1723             }
1724
1725             //新着通知
1726             if (BalloonRequired())
1727             {
1728                 if (notifyPosts != null && notifyPosts.Length > 0)
1729                 {
1730                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1731                     if (SettingManager.Common.IsUseNotifyGrowl)
1732                     {
1733                         StringBuilder sb = new StringBuilder();
1734                         bool reply = false;
1735                         bool dm = false;
1736
1737                         foreach (PostClass post in notifyPosts)
1738                         {
1739                             if (!(notifyPosts.Length > 3))
1740                             {
1741                                 sb.Clear();
1742                                 reply = false;
1743                                 dm = false;
1744                             }
1745                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1746                             if (post.IsDm) dm = true;
1747                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1748                             switch (SettingManager.Common.NameBalloon)
1749                             {
1750                                 case MyCommon.NameBalloonEnum.UserID:
1751                                     sb.Append(post.ScreenName).Append(" : ");
1752                                     break;
1753                                 case MyCommon.NameBalloonEnum.NickName:
1754                                     sb.Append(post.Nickname).Append(" : ");
1755                                     break;
1756                             }
1757                             sb.Append(post.TextFromApi);
1758                             if (notifyPosts.Length > 3)
1759                             {
1760                                 if (notifyPosts.Last() != post) continue;
1761                             }
1762
1763                             StringBuilder title = new StringBuilder();
1764                             GrowlHelper.NotifyType nt;
1765                             if (SettingManager.Common.DispUsername)
1766                             {
1767                                 title.Append(tw.Username);
1768                                 title.Append(" - ");
1769                             }
1770                             else
1771                             {
1772                                 //title.Clear();
1773                             }
1774                             if (dm)
1775                             {
1776                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1777                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1778                                 title.Append(Application.ProductName);
1779                                 title.Append(" [DM] ");
1780                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1781                                 nt = GrowlHelper.NotifyType.DirectMessage;
1782                             }
1783                             else if (reply)
1784                             {
1785                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1786                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1787                                 title.Append(Application.ProductName);
1788                                 title.Append(" [Reply!] ");
1789                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1790                                 nt = GrowlHelper.NotifyType.Reply;
1791                             }
1792                             else
1793                             {
1794                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1795                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1796                                 title.Append(Application.ProductName);
1797                                 title.Append(" ");
1798                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1799                                 nt = GrowlHelper.NotifyType.Notify;
1800                             }
1801                             string bText = sb.ToString();
1802                             if (string.IsNullOrEmpty(bText)) return;
1803
1804                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1805                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1806                         }
1807                     }
1808                     else
1809                     {
1810                         StringBuilder sb = new StringBuilder();
1811                         bool reply = false;
1812                         bool dm = false;
1813                         foreach (PostClass post in notifyPosts)
1814                         {
1815                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1816                             if (post.IsDm) dm = true;
1817                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1818                             switch (SettingManager.Common.NameBalloon)
1819                             {
1820                                 case MyCommon.NameBalloonEnum.UserID:
1821                                     sb.Append(post.ScreenName).Append(" : ");
1822                                     break;
1823                                 case MyCommon.NameBalloonEnum.NickName:
1824                                     sb.Append(post.Nickname).Append(" : ");
1825                                     break;
1826                             }
1827                             sb.Append(post.TextFromApi);
1828
1829                         }
1830                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1831                         StringBuilder title = new StringBuilder();
1832                         ToolTipIcon ntIcon;
1833                         if (SettingManager.Common.DispUsername)
1834                         {
1835                             title.Append(tw.Username);
1836                             title.Append(" - ");
1837                         }
1838                         else
1839                         {
1840                             //title.Clear();
1841                         }
1842                         if (dm)
1843                         {
1844                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1845                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1846                             ntIcon = ToolTipIcon.Warning;
1847                             title.Append(Application.ProductName);
1848                             title.Append(" [DM] ");
1849                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1850                         }
1851                         else if (reply)
1852                         {
1853                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1854                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1855                             ntIcon = ToolTipIcon.Warning;
1856                             title.Append(Application.ProductName);
1857                             title.Append(" [Reply!] ");
1858                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1859                         }
1860                         else
1861                         {
1862                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1863                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1864                             ntIcon = ToolTipIcon.Info;
1865                             title.Append(Application.ProductName);
1866                             title.Append(" ");
1867                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1868                         }
1869                         string bText = sb.ToString();
1870                         if (string.IsNullOrEmpty(bText)) return;
1871                         //NotifyIcon1.BalloonTipText = sb.ToString();
1872                         //NotifyIcon1.ShowBalloonTip(500);
1873                         NotifyIcon1.BalloonTipTitle = title.ToString();
1874                         NotifyIcon1.BalloonTipText = bText;
1875                         NotifyIcon1.BalloonTipIcon = ntIcon;
1876                         NotifyIcon1.ShowBalloonTip(500);
1877                     }
1878                 }
1879             }
1880
1881             //サウンド再生
1882             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1883             {
1884                 try
1885                 {
1886                     string dir = Application.StartupPath;
1887                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1888                     {
1889                         dir = Path.Combine(dir, "Sounds");
1890                     }
1891                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1892                     {
1893                         player.Play();
1894                     }
1895                 }
1896                 catch (Exception)
1897                 {
1898                 }
1899             }
1900
1901             //mentions新着時に画面ブリンク
1902             if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1903             {
1904                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1905             }
1906         }
1907
1908         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1909         {
1910             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1911
1912             _curItemIndex = _curList.SelectedIndices[0];
1913             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1914
1915             try
1916             {
1917                 this._curPost = GetCurTabPost(_curItemIndex);
1918             }
1919             catch (ArgumentException)
1920             {
1921                 return;
1922             }
1923
1924             this.PushSelectPostChain();
1925
1926             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1927             //キャッシュの書き換え
1928             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1929
1930             ColorizeList();
1931             _colorize = true;
1932         }
1933
1934         private void ChangeCacheStyleRead(bool Read, int Index)
1935         {
1936             var tabInfo = _statuses.Tabs[_curTab.Text];
1937             //Read:true=既読 false=未読
1938             //未読管理していなかったら既読として扱う
1939             if (!tabInfo.UnreadManage ||
1940                !SettingManager.Common.UnreadManage) Read = true;
1941
1942             var listCache = this._listItemCache;
1943             if (listCache == null)
1944                 return;
1945
1946             // キャッシュに含まれていないアイテムは対象外
1947             ListViewItem itm;
1948             PostClass post;
1949             if (!listCache.TryGetValue(Index, out itm, out post))
1950                 return;
1951
1952             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1953         }
1954
1955         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1956         {
1957             Font fnt;
1958             //フォント
1959             if (Read)
1960             {
1961                 fnt = _fntReaded;
1962                 Item.SubItems[5].Text = "";
1963             }
1964             else
1965             {
1966                 fnt = _fntUnread;
1967                 Item.SubItems[5].Text = "★";
1968             }
1969             //文字色
1970             Color cl;
1971             if (Post.IsFav)
1972                 cl = _clFav;
1973             else if (Post.RetweetedId != null)
1974                 cl = _clRetweet;
1975             else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1976                 cl = _clOWL;
1977             else if (Read || !SettingManager.Common.UseUnreadStyle)
1978                 cl = _clReaded;
1979             else
1980                 cl = _clUnread;
1981
1982             if (DList == null || Item.Index == -1)
1983             {
1984                 Item.ForeColor = cl;
1985                 if (SettingManager.Common.UseUnreadStyle)
1986                     Item.Font = fnt;
1987             }
1988             else
1989             {
1990                 DList.Update();
1991                 if (SettingManager.Common.UseUnreadStyle)
1992                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1993                 else
1994                     DList.ChangeItemForeColor(Item.Index, cl);
1995                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1996             }
1997         }
1998
1999         private void ColorizeList()
2000         {
2001             //Index:更新対象のListviewItem.Index。Colorを返す。
2002             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2003             PostClass _post;
2004             if (_anchorFlag)
2005                 _post = _anchorPost;
2006             else
2007                 _post = _curPost;
2008
2009             if (_post == null) return;
2010
2011             var listCache = this._listItemCache;
2012             if (listCache == null)
2013                 return;
2014
2015             var index = listCache.StartIndex;
2016             foreach (var cachedPost in listCache.Post)
2017             {
2018                 var backColor = this.JudgeColor(_post, cachedPost);
2019                 this._curList.ChangeItemBackColor(index++, backColor);
2020             }
2021         }
2022
2023         private void ColorizeList(ListViewItem Item, int Index)
2024         {
2025             //Index:更新対象のListviewItem.Index。Colorを返す。
2026             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2027             PostClass _post;
2028             if (_anchorFlag)
2029                 _post = _anchorPost;
2030             else
2031                 _post = _curPost;
2032
2033             PostClass tPost = GetCurTabPost(Index);
2034
2035             if (_post == null) return;
2036
2037             if (Item.Index == -1)
2038                 Item.BackColor = JudgeColor(_post, tPost);
2039             else
2040                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2041         }
2042
2043         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2044         {
2045             Color cl;
2046             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2047                 //@先
2048                 cl = _clAtTo;
2049             else if (TargetPost.IsMe)
2050                 //自分=発言者
2051                 cl = _clSelf;
2052             else if (TargetPost.IsReply)
2053                 //自分宛返信
2054                 cl = _clAtSelf;
2055             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2056                 //返信先
2057                 cl = _clAtFromTarget;
2058             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2059                 //その人への返信
2060                 cl = _clAtTarget;
2061             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2062                 //発言者
2063                 cl = _clTarget;
2064             else
2065                 //その他
2066                 cl = _clListBackcolor;
2067
2068             return cl;
2069         }
2070
2071         private async void PostButton_Click(object sender, EventArgs e)
2072         {
2073             if (StatusText.Text.Trim().Length == 0)
2074             {
2075                 if (!ImageSelector.Enabled)
2076                 {
2077                     await this.DoRefresh();
2078                     return;
2079                 }
2080             }
2081
2082             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2083             {
2084                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2085                                                                "Retweet",
2086                                                                MessageBoxButtons.YesNoCancel,
2087                                                                MessageBoxIcon.Question);
2088                 switch (rtResult)
2089                 {
2090                     case DialogResult.Yes:
2091                         StatusText.Text = "";
2092                         await this.doReTweetOfficial(false);
2093                         return;
2094                     case DialogResult.Cancel:
2095                         return;
2096                 }
2097             }
2098
2099             var inReplyToStatusId = this.inReplyTo?.Item1;
2100             var inReplyToScreenName = this.inReplyTo?.Item2;
2101             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2102
2103             if (SettingManager.Common.Nicoms)
2104             {
2105                 StatusText.SelectionStart = StatusText.Text.Length;
2106                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2107             }
2108             //if (SettingDialog.UrlConvertAuto)
2109             //{
2110             //    StatusText.SelectionStart = StatusText.Text.Length;
2111             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2112             //}
2113             //else if (SettingDialog.Nicoms)
2114             //{
2115             //    StatusText.SelectionStart = StatusText.Text.Length;
2116             //    UrlConvert(UrlConverter.Nicoms);
2117             //}
2118             StatusText.SelectionStart = StatusText.Text.Length;
2119             CheckReplyTo(StatusText.Text);
2120
2121             var statusText = this.FormatStatusText(this.StatusText.Text);
2122
2123             if (this.GetRestStatusCount(statusText) < 0)
2124             {
2125                 // 文字数制限を超えているが強制的に投稿するか
2126                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2127                 if (ret != DialogResult.OK)
2128                     return;
2129             }
2130
2131             var status = new PostingStatus();
2132             status.status = statusText;
2133
2134             status.inReplyToId = this.inReplyTo?.Item1;
2135             status.inReplyToName = this.inReplyTo?.Item2;
2136             if (ImageSelector.Visible)
2137             {
2138                 //画像投稿
2139                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2140                     return;
2141             }
2142
2143             this.inReplyTo = null;
2144             StatusText.Text = "";
2145             _history.Add(new PostingStatus());
2146             _hisIdx = _history.Count - 1;
2147             if (!ToolStripFocusLockMenuItem.Checked)
2148                 ((Control)ListTab.SelectedTab.Tag).Focus();
2149             urlUndoBuffer = null;
2150             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2151
2152             //Google検索(試験実装)
2153             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2154             {
2155                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2156                 await this.OpenUriInBrowserAsync(tmp);
2157             }
2158
2159             await this.PostMessageAsync(status);
2160         }
2161
2162         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2163         {
2164             MyCommon._endingFlag = true;
2165             this.Close();
2166         }
2167
2168         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2169         {
2170             if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2171             {
2172                 //_endingFlag=false:フォームの×ボタン
2173                 e.Cancel = true;
2174                 this.Visible = false;
2175             }
2176             else
2177             {
2178                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2179                 _ignoreConfigSave = true;
2180                 MyCommon._endingFlag = true;
2181                 TimerTimeline.Enabled = false;
2182                 TimerRefreshIcon.Enabled = false;
2183             }
2184         }
2185
2186         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2187         {
2188             this.Visible = true;
2189             if (this.WindowState == FormWindowState.Minimized)
2190             {
2191                 this.WindowState = FormWindowState.Normal;
2192             }
2193             this.Activate();
2194             this.BringToFront();
2195         }
2196
2197         private static int errorCount = 0;
2198
2199         private static bool CheckAccountValid()
2200         {
2201             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2202             {
2203                 errorCount += 1;
2204                 if (errorCount > 5)
2205                 {
2206                     errorCount = 0;
2207                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2208                     return true;
2209                 }
2210                 return false;
2211             }
2212             errorCount = 0;
2213             return true;
2214         }
2215
2216         private Task GetHomeTimelineAsync()
2217         {
2218             return this.GetHomeTimelineAsync(loadMore: false);
2219         }
2220
2221         private async Task GetHomeTimelineAsync(bool loadMore)
2222         {
2223             await this.workerSemaphore.WaitAsync();
2224
2225             try
2226             {
2227                 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2228                 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2229
2230                 this.RefreshTimeline();
2231             }
2232             catch (WebApiException ex)
2233             {
2234                 this._myStatusError = true;
2235                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2236             }
2237             finally
2238             {
2239                 this.workerSemaphore.Release();
2240             }
2241         }
2242
2243         private Task GetReplyAsync()
2244         {
2245             return this.GetReplyAsync(loadMore: false);
2246         }
2247
2248         private async Task GetReplyAsync(bool loadMore)
2249         {
2250             await this.workerSemaphore.WaitAsync();
2251
2252             try
2253             {
2254                 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2255                 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2256
2257                 this.RefreshTimeline();
2258             }
2259             catch (WebApiException ex)
2260             {
2261                 this._myStatusError = true;
2262                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2263             }
2264             finally
2265             {
2266                 this.workerSemaphore.Release();
2267             }
2268         }
2269
2270         private Task GetDirectMessagesAsync()
2271         {
2272             return this.GetDirectMessagesAsync(loadMore: false);
2273         }
2274
2275         private async Task GetDirectMessagesAsync(bool loadMore)
2276         {
2277             await this.workerSemaphore.WaitAsync();
2278
2279             try
2280             {
2281                 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2282                 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2283
2284                 this.RefreshTimeline();
2285             }
2286             catch (WebApiException ex)
2287             {
2288                 this._myStatusError = true;
2289                 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2290             }
2291             finally
2292             {
2293                 this.workerSemaphore.Release();
2294             }
2295         }
2296
2297         private Task GetFavoritesAsync()
2298         {
2299             return this.GetFavoritesAsync(loadMore: false);
2300         }
2301
2302         private async Task GetFavoritesAsync(bool loadMore)
2303         {
2304             await this.workerSemaphore.WaitAsync();
2305
2306             try
2307             {
2308                 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2309                 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2310
2311                 this.RefreshTimeline();
2312             }
2313             catch (WebApiException ex)
2314             {
2315                 this._myStatusError = true;
2316                 this.StatusLabel.Text = ex.Message;
2317             }
2318             finally
2319             {
2320                 this.workerSemaphore.Release();
2321             }
2322         }
2323
2324         private Task GetPublicSearchAllAsync()
2325         {
2326             var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2327
2328             return this.GetPublicSearchAsync(tabs, loadMore: false);
2329         }
2330
2331         private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2332         {
2333             return this.GetPublicSearchAsync(tab, loadMore: false);
2334         }
2335
2336         private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2337         {
2338             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2339         }
2340
2341         private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2342         {
2343             await this.workerSemaphore.WaitAsync();
2344
2345             try
2346             {
2347                 foreach (var tab in tabs)
2348                 {
2349                     try
2350                     {
2351                         await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2352                     }
2353                     catch (WebApiException ex)
2354                     {
2355                         this._myStatusError = true;
2356                         this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2357                     }
2358                 }
2359
2360                 this.RefreshTimeline();
2361             }
2362             finally
2363             {
2364                 this.workerSemaphore.Release();
2365             }
2366         }
2367
2368         private Task GetUserTimelineAllAsync()
2369         {
2370             var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2371
2372             return this.GetUserTimelineAsync(tabs, loadMore: false);
2373         }
2374
2375         private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2376         {
2377             return this.GetUserTimelineAsync(tab, loadMore: false);
2378         }
2379
2380         private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2381         {
2382             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2383         }
2384
2385         private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2386         {
2387             await this.workerSemaphore.WaitAsync();
2388
2389             try
2390             {
2391                 foreach (var tab in tabs)
2392                 {
2393                     try
2394                     {
2395                         await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2396                     }
2397                     catch (WebApiException ex)
2398                     {
2399                         this._myStatusError = true;
2400                         this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2401                     }
2402                 }
2403
2404                 this.RefreshTimeline();
2405             }
2406             finally
2407             {
2408                 this.workerSemaphore.Release();
2409             }
2410         }
2411
2412         private Task GetListTimelineAllAsync()
2413         {
2414             var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2415
2416             return this.GetListTimelineAsync(tabs, loadMore: false);
2417         }
2418
2419         private Task GetListTimelineAsync(ListTimelineTabModel tab)
2420         {
2421             return this.GetListTimelineAsync(tab, loadMore: false);
2422         }
2423
2424         private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2425         {
2426             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2427         }
2428
2429         private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2430         {
2431             await this.workerSemaphore.WaitAsync();
2432
2433             try
2434             {
2435                 foreach (var tab in tabs)
2436                 {
2437                     try
2438                     {
2439                         await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2440                     }
2441                     catch (WebApiException ex)
2442                     {
2443                         this._myStatusError = true;
2444                         this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2445                     }
2446                 }
2447
2448                 this.RefreshTimeline();
2449             }
2450             finally
2451             {
2452                 this.workerSemaphore.Release();
2453             }
2454         }
2455
2456         private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2457         {
2458             await this.workerSemaphore.WaitAsync();
2459
2460             try
2461             {
2462                 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2463
2464                 this.RefreshTimeline();
2465             }
2466             catch (WebApiException ex)
2467             {
2468                 this._myStatusError = true;
2469                 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2470             }
2471             finally
2472             {
2473                 this.workerSemaphore.Release();
2474             }
2475         }
2476
2477         private async Task FavAddAsync(long statusId, TabModel tab)
2478         {
2479             await this.workerSemaphore.WaitAsync();
2480
2481             try
2482             {
2483                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2484
2485                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2486             }
2487             catch (WebApiException ex)
2488             {
2489                 this._myStatusError = true;
2490                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2491             }
2492             finally
2493             {
2494                 this.workerSemaphore.Release();
2495             }
2496         }
2497
2498         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2499         {
2500             if (ct.IsCancellationRequested)
2501                 return;
2502
2503             if (!CheckAccountValid())
2504                 throw new WebApiException("Auth error. Check your account");
2505
2506             PostClass post;
2507             if (!tab.Posts.TryGetValue(statusId, out post))
2508                 return;
2509
2510             if (post.IsFav)
2511                 return;
2512
2513             await Task.Run(async () =>
2514             {
2515                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2516
2517                 try
2518                 {
2519                     await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2520                         .IgnoreResponse()
2521                         .ConfigureAwait(false);
2522
2523                     if (SettingManager.Common.RestrictFavCheck)
2524                     {
2525                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2526                             .ConfigureAwait(false);
2527
2528                         if (status.Favorited != true)
2529                             throw new WebApiException("NG(Restricted?)");
2530                     }
2531
2532                     this._favTimestamps.Add(DateTime.Now);
2533
2534                     // TLでも取得済みならfav反映
2535                     if (this._statuses.ContainsKey(statusId))
2536                     {
2537                         var postTl = this._statuses[statusId];
2538                         postTl.IsFav = true;
2539
2540                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2541                         favTab.AddPostQueue(postTl);
2542                     }
2543
2544                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2545                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2546                     {
2547                         if (tb.Contains(statusId))
2548                             tb.Posts[statusId].IsFav = true;
2549                     }
2550
2551                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2552                 }
2553                 catch (WebApiException)
2554                 {
2555                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2556                     throw;
2557                 }
2558
2559                 // 時速表示用
2560                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2561                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2562                 {
2563                     if (this._favTimestamps[i] < oneHour)
2564                         this._favTimestamps.RemoveAt(i);
2565                 }
2566
2567                 this._statuses.DistributePosts();
2568             });
2569
2570             if (ct.IsCancellationRequested)
2571                 return;
2572
2573             this.RefreshTimeline();
2574
2575             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2576             {
2577                 using (ControlTransaction.Update(this._curList))
2578                 {
2579                     var idx = tab.IndexOf(statusId);
2580                     if (idx != -1)
2581                         this.ChangeCacheStyleRead(post.IsRead, idx);
2582                 }
2583
2584                 if (statusId == this._curPost.StatusId)
2585                     await this.DispSelectedPost(true); // 選択アイテム再表示
2586             }
2587         }
2588
2589         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2590         {
2591             await this.workerSemaphore.WaitAsync();
2592
2593             try
2594             {
2595                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2596
2597                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2598             }
2599             catch (WebApiException ex)
2600             {
2601                 this._myStatusError = true;
2602                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2603             }
2604             finally
2605             {
2606                 this.workerSemaphore.Release();
2607             }
2608         }
2609
2610         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2611         {
2612             if (ct.IsCancellationRequested)
2613                 return;
2614
2615             if (!CheckAccountValid())
2616                 throw new WebApiException("Auth error. Check your account");
2617
2618             var successIds = new List<long>();
2619
2620             await Task.Run(async () =>
2621             {
2622                 //スレッド処理はしない
2623                 var allCount = 0;
2624                 var failedCount = 0;
2625                 foreach (var statusId in statusIds)
2626                 {
2627                     allCount++;
2628
2629                     var post = tab.Posts[statusId];
2630
2631                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2632
2633                     if (!post.IsFav)
2634                         continue;
2635
2636                     try
2637                     {
2638                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2639                             .IgnoreResponse()
2640                             .ConfigureAwait(false);
2641                     }
2642                     catch (WebApiException)
2643                     {
2644                         failedCount++;
2645                         continue;
2646                     }
2647
2648                     successIds.Add(statusId);
2649                     post.IsFav = false; // リスト再描画必要
2650
2651                     if (this._statuses.ContainsKey(statusId))
2652                     {
2653                         this._statuses[statusId].IsFav = false;
2654                     }
2655
2656                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2657                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2658                     {
2659                         if (tb.Contains(statusId))
2660                             tb.Posts[statusId].IsFav = false;
2661                     }
2662                 }
2663             });
2664
2665             if (ct.IsCancellationRequested)
2666                 return;
2667
2668             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2669             foreach (var statusId in successIds)
2670             {
2671                 // ツイートが削除された訳ではないので IsDeleted はセットしない
2672                 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2673             }
2674
2675             this.RefreshTimeline();
2676
2677             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2678             {
2679                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2680                 {
2681                     // 色変えは不要
2682                 }
2683                 else
2684                 {
2685                     using (ControlTransaction.Update(this._curList))
2686                     {
2687                         foreach (var statusId in successIds)
2688                         {
2689                             var idx = tab.IndexOf(statusId);
2690                             if (idx == -1)
2691                                 continue;
2692
2693                             var post = tab.Posts[statusId];
2694                             this.ChangeCacheStyleRead(post.IsRead, idx);
2695                         }
2696                     }
2697
2698                     if (successIds.Contains(this._curPost.StatusId))
2699                         await this.DispSelectedPost(true); // 選択アイテム再表示
2700                 }
2701             }
2702         }
2703
2704         private async Task PostMessageAsync(PostingStatus status)
2705         {
2706             await this.workerSemaphore.WaitAsync();
2707
2708             try
2709             {
2710                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2711
2712                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2713             }
2714             catch (WebApiException ex)
2715             {
2716                 this._myStatusError = true;
2717                 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2718             }
2719             finally
2720             {
2721                 this.workerSemaphore.Release();
2722             }
2723         }
2724
2725         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2726         {
2727             if (ct.IsCancellationRequested)
2728                 return;
2729
2730             if (!CheckAccountValid())
2731                 throw new WebApiException("Auth error. Check your account");
2732
2733             p.Report("Posting...");
2734
2735             var errMsg = "";
2736
2737             try
2738             {
2739                 await Task.Run(async () =>
2740                 {
2741                     if (status.mediaItems == null || status.mediaItems.Length == 0)
2742                     {
2743                         await this.tw.PostStatus(status.status, status.inReplyToId)
2744                             .ConfigureAwait(false);
2745                     }
2746                     else
2747                     {
2748                         var service = ImageSelector.GetService(status.imageService);
2749                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2750                             .ConfigureAwait(false);
2751                     }
2752                 });
2753
2754                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2755             }
2756             catch (WebApiException ex)
2757             {
2758                 // 処理は中断せずエラーの表示のみ行う
2759                 errMsg = $"Err:{ex.Message}(PostMessage)";
2760                 p.Report(errMsg);
2761                 this._myStatusError = true;
2762             }
2763             catch (UnauthorizedAccessException ex)
2764             {
2765                 // アップロード対象のファイルが開けなかった場合など
2766                 errMsg = $"Err:{ex.Message}(PostMessage)";
2767                 p.Report(errMsg);
2768                 this._myStatusError = true;
2769             }
2770             finally
2771             {
2772                 // 使い終わった MediaItem は破棄する
2773                 if (status.mediaItems != null)
2774                 {
2775                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2776                     {
2777                         disposableItem.Dispose();
2778                     }
2779                 }
2780             }
2781
2782             if (ct.IsCancellationRequested)
2783                 return;
2784
2785             if (!string.IsNullOrEmpty(errMsg) &&
2786                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2787                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2788             {
2789                 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2790
2791                 var ret = MessageBox.Show(
2792                     message,
2793                     "Failed to update status",
2794                     MessageBoxButtons.RetryCancel,
2795                     MessageBoxIcon.Question);
2796
2797                 if (ret == DialogResult.Retry)
2798                 {
2799                     await this.PostMessageAsync(status);
2800                 }
2801                 else
2802                 {
2803                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2804                     if (this.ToolStripFocusLockMenuItem.Checked)
2805                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2806                 }
2807                 return;
2808             }
2809
2810             this._postTimestamps.Add(DateTime.Now);
2811
2812             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2813             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2814             {
2815                 if (this._postTimestamps[i] < oneHour)
2816                     this._postTimestamps.RemoveAt(i);
2817             }
2818
2819             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2820             {
2821                 this.HashMgr.ClearHashtag();
2822                 this.HashStripSplitButton.Text = "#[-]";
2823                 this.HashToggleMenuItem.Checked = false;
2824                 this.HashToggleToolStripMenuItem.Checked = false;
2825             }
2826
2827             this.SetMainWindowTitle();
2828
2829             if (SettingManager.Common.PostAndGet)
2830             {
2831                 if (this.tw.UserStreamActive)
2832                     this.RefreshTimeline();
2833                 else
2834                     await this.GetHomeTimelineAsync();
2835             }
2836         }
2837
2838         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2839         {
2840             await this.workerSemaphore.WaitAsync();
2841
2842             try
2843             {
2844                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2845
2846                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2847
2848                 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2849                     await this.GetHomeTimelineAsync();
2850             }
2851             catch (WebApiException ex)
2852             {
2853                 this._myStatusError = true;
2854                 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2855             }
2856             finally
2857             {
2858                 this.workerSemaphore.Release();
2859             }
2860         }
2861
2862         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2863         {
2864             if (ct.IsCancellationRequested)
2865                 return;
2866
2867             if (!CheckAccountValid())
2868                 throw new WebApiException("Auth error. Check your account");
2869
2870             bool read;
2871             if (!SettingManager.Common.UnreadManage)
2872                 read = true;
2873             else
2874                 read = this._initial && SettingManager.Common.Read;
2875
2876             p.Report("Posting...");
2877
2878             foreach (var statusId in statusIds)
2879             {
2880                 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2881             }
2882
2883             if (ct.IsCancellationRequested)
2884                 return;
2885
2886             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2887
2888             this._postTimestamps.Add(DateTime.Now);
2889
2890             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2891             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2892             {
2893                 if (this._postTimestamps[i] < oneHour)
2894                     this._postTimestamps.RemoveAt(i);
2895             }
2896         }
2897
2898         private async Task RefreshFollowerIdsAsync()
2899         {
2900             await this.workerSemaphore.WaitAsync();
2901             try
2902             {
2903                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2904
2905                 await this.tw.RefreshFollowerIds();
2906
2907                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2908
2909                 this.RefreshTimeline();
2910                 this.PurgeListViewItemCache();
2911                 this._curList?.Refresh();
2912             }
2913             catch (WebApiException ex)
2914             {
2915                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2916             }
2917             finally
2918             {
2919                 this.workerSemaphore.Release();
2920             }
2921         }
2922
2923         private async Task RefreshNoRetweetIdsAsync()
2924         {
2925             await this.workerSemaphore.WaitAsync();
2926             try
2927             {
2928                 await this.tw.RefreshNoRetweetIds();
2929
2930                 this.StatusLabel.Text = "NoRetweetIds refreshed";
2931             }
2932             catch (WebApiException ex)
2933             {
2934                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2935             }
2936             finally
2937             {
2938                 this.workerSemaphore.Release();
2939             }
2940         }
2941
2942         private async Task RefreshBlockIdsAsync()
2943         {
2944             await this.workerSemaphore.WaitAsync();
2945             try
2946             {
2947                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2948
2949                 await this.tw.RefreshBlockIds();
2950
2951                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2952             }
2953             catch (WebApiException ex)
2954             {
2955                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2956             }
2957             finally
2958             {
2959                 this.workerSemaphore.Release();
2960             }
2961         }
2962
2963         private async Task RefreshTwitterConfigurationAsync()
2964         {
2965             await this.workerSemaphore.WaitAsync();
2966             try
2967             {
2968                 await this.tw.RefreshConfiguration();
2969
2970                 if (this.tw.Configuration.PhotoSizeLimit != 0)
2971                 {
2972                     foreach (var service in this.ImageSelector.GetServices())
2973                     {
2974                         service.UpdateTwitterConfiguration(this.tw.Configuration);
2975                     }
2976                 }
2977
2978                 this.PurgeListViewItemCache();
2979
2980                 this._curList?.Refresh();
2981             }
2982             catch (WebApiException ex)
2983             {
2984                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2985             }
2986             finally
2987             {
2988                 this.workerSemaphore.Release();
2989             }
2990         }
2991
2992         private async Task RefreshMuteUserIdsAsync()
2993         {
2994             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2995
2996             try
2997             {
2998                 await tw.RefreshMuteUserIdsAsync();
2999             }
3000             catch (WebApiException ex)
3001             {
3002                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3003                 return;
3004             }
3005
3006             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3007         }
3008
3009         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3010         {
3011             if (e.Button == MouseButtons.Left)
3012             {
3013                 this.Visible = true;
3014                 if (this.WindowState == FormWindowState.Minimized)
3015                 {
3016                     this.WindowState = _formWindowState;
3017                 }
3018                 this.Activate();
3019                 this.BringToFront();
3020             }
3021         }
3022
3023         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3024         {
3025             switch (SettingManager.Common.ListDoubleClickAction)
3026             {
3027                 case 0:
3028                     MakeReplyOrDirectStatus();
3029                     break;
3030                 case 1:
3031                     await this.FavoriteChange(true);
3032                     break;
3033                 case 2:
3034                     if (_curPost != null)
3035                         await this.ShowUserStatus(_curPost.ScreenName, false);
3036                     break;
3037                 case 3:
3038                     ShowUserTimeline();
3039                     break;
3040                 case 4:
3041                     ShowRelatedStatusesMenuItem_Click(null, null);
3042                     break;
3043                 case 5:
3044                     MoveToHomeToolStripMenuItem_Click(null, null);
3045                     break;
3046                 case 6:
3047                     StatusOpenMenuItem_Click(null, null);
3048                     break;
3049                 case 7:
3050                     //動作なし
3051                     break;
3052             }
3053         }
3054
3055         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3056         {
3057             await this.FavoriteChange(true);
3058         }
3059
3060         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3061         {
3062             await this.FavoriteChange(false);
3063         }
3064
3065
3066         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3067         {
3068             await this.FavoritesRetweetOfficial();
3069         }
3070
3071         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3072         {
3073             await this.FavoritesRetweetUnofficial();
3074         }
3075
3076         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3077         {
3078             TabModel tab;
3079             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3080                 return;
3081
3082             //trueでFavAdd,falseでFavRemove
3083             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3084                 || !this.ExistCurrentPost) return;
3085
3086             if (this._curList.SelectedIndices.Count > 1)
3087             {
3088                 if (FavAdd)
3089                 {
3090                     // 複数ツイートの一括ふぁぼは禁止
3091                     // https://support.twitter.com/articles/76915#favoriting
3092                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3093                     _DoFavRetweetFlags = false;
3094                     return;
3095                 }
3096                 else
3097                 {
3098                     if (multiFavoriteChangeDialogEnable)
3099                     {
3100                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3101                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3102                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3103
3104                         if (confirm == DialogResult.Cancel)
3105                             return;
3106                     }
3107                 }
3108             }
3109
3110             if (FavAdd)
3111             {
3112                 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3113                 if (selectedPost.IsFav)
3114                 {
3115                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3116                     return;
3117                 }
3118
3119                 await this.FavAddAsync(selectedPost.StatusId, tab);
3120             }
3121             else
3122             {
3123                 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3124                     .Select(x => this.GetCurTabPost(x))
3125                     .Where(x => x.IsFav);
3126
3127                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3128                 if (statusIds.Length == 0)
3129                 {
3130                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3131                     return;
3132                 }
3133
3134                 await this.FavRemoveAsync(statusIds, tab);
3135             }
3136         }
3137
3138         private PostClass GetCurTabPost(int Index)
3139         {
3140             var listCache = this._listItemCache;
3141             if (listCache != null)
3142             {
3143                 ListViewItem item;
3144                 PostClass post;
3145                 if (listCache.TryGetValue(Index, out item, out post))
3146                     return post;
3147             }
3148
3149             return _statuses.Tabs[_curTab.Text][Index];
3150         }
3151
3152         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3153         {
3154             if (_curList.SelectedIndices.Count > 0)
3155                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3156             else if (_curList.SelectedIndices.Count == 0)
3157                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3158         }
3159
3160         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3161         {
3162             if (_curList.SelectedIndices.Count > 0)
3163                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3164         }
3165
3166         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3167         {
3168             if ((!_initialLayout) && this.Visible)
3169             {
3170                 if (this.WindowState == FormWindowState.Normal)
3171                 {
3172                     _mySize = this.ClientSize;
3173                     _mySpDis = this.SplitContainer1.SplitterDistance;
3174                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3175                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3176                     ModifySettingLocal = true;
3177                 }
3178             }
3179         }
3180
3181         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3182         {
3183             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3184             if (comparerMode == null)
3185                 return;
3186
3187             this.SetSortColumn(comparerMode.Value);
3188         }
3189
3190         /// <summary>
3191         /// 列インデックスからソートを行う ComparerMode を求める
3192         /// </summary>
3193         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3194         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3195         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3196         {
3197             if (this._iconCol)
3198                 return ComparerMode.Id;
3199
3200             switch (columnIndex)
3201             {
3202                 case 1: // ニックネーム
3203                     return ComparerMode.Nickname;
3204                 case 2: // 本文
3205                     return ComparerMode.Data;
3206                 case 3: // 時刻=発言Id
3207                     return ComparerMode.Id;
3208                 case 4: // 名前
3209                     return ComparerMode.Name;
3210                 case 7: // Source
3211                     return ComparerMode.Source;
3212                 default:
3213                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3214                     return null;
3215             }
3216         }
3217
3218         /// <summary>
3219         /// 発言一覧の指定した位置の列でソートする
3220         /// </summary>
3221         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3222         private void SetSortColumnByDisplayIndex(int columnIndex)
3223         {
3224             // 表示上の列の位置から ColumnHeader を求める
3225             var col = this._curList.Columns.Cast<ColumnHeader>()
3226                 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3227
3228             if (col == null)
3229                 return;
3230
3231             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3232             if (comparerMode == null)
3233                 return;
3234
3235             this.SetSortColumn(comparerMode.Value);
3236         }
3237
3238         /// <summary>
3239         /// 発言一覧の最後列の項目でソートする
3240         /// </summary>
3241         private void SetSortLastColumn()
3242         {
3243             // 表示上の最後列にある ColumnHeader を求める
3244             var col = this._curList.Columns.Cast<ColumnHeader>()
3245                 .OrderByDescending(x => x.DisplayIndex)
3246                 .First();
3247
3248             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3249             if (comparerMode == null)
3250                 return;
3251
3252             this.SetSortColumn(comparerMode.Value);
3253         }
3254
3255         /// <summary>
3256         /// 発言一覧を指定された ComparerMode に基づいてソートする
3257         /// </summary>
3258         private void SetSortColumn(ComparerMode sortColumn)
3259         {
3260             if (SettingManager.Common.SortOrderLock)
3261                 return;
3262
3263             this._statuses.ToggleSortOrder(sortColumn);
3264             this.InitColumnText();
3265
3266             var list = this._curList;
3267             if (_iconCol)
3268             {
3269                 list.Columns[0].Text = this.ColumnText[0];
3270                 list.Columns[1].Text = this.ColumnText[2];
3271             }
3272             else
3273             {
3274                 for (var i = 0; i <= 7; i++)
3275                 {
3276                     list.Columns[i].Text = this.ColumnText[i];
3277                 }
3278             }
3279
3280             this.PurgeListViewItemCache();
3281
3282             var tab = this._statuses.Tabs[this._curTab.Text];
3283             if (tab.AllCount > 0 && this._curPost != null)
3284             {
3285                 var idx = tab.IndexOf(this._curPost.StatusId);
3286                 if (idx > -1)
3287                 {
3288                     this.SelectListItem(list, idx);
3289                     list.EnsureVisible(idx);
3290                 }
3291             }
3292             list.Refresh();
3293
3294             this.ModifySettingCommon = true;
3295         }
3296
3297         private void TweenMain_LocationChanged(object sender, EventArgs e)
3298         {
3299             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3300             {
3301                 _myLoc = this.DesktopLocation;
3302                 ModifySettingLocal = true;
3303             }
3304         }
3305
3306         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3307         {
3308             if (ListTab.SelectedTab == null) return;
3309             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3310             if (!this.ExistCurrentPost)
3311             {
3312                 ReplyStripMenuItem.Enabled = false;
3313                 ReplyAllStripMenuItem.Enabled = false;
3314                 DMStripMenuItem.Enabled = false;
3315                 ShowProfileMenuItem.Enabled = false;
3316                 ShowUserTimelineContextMenuItem.Enabled = false;
3317                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3318                 MoveToFavToolStripMenuItem.Enabled = false;
3319                 TabMenuItem.Enabled = false;
3320                 IDRuleMenuItem.Enabled = false;
3321                 SourceRuleMenuItem.Enabled = false;
3322                 ReadedStripMenuItem.Enabled = false;
3323                 UnreadStripMenuItem.Enabled = false;
3324             }
3325             else
3326             {
3327                 ShowProfileMenuItem.Enabled = true;
3328                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3329                 ReplyStripMenuItem.Enabled = true;
3330                 ReplyAllStripMenuItem.Enabled = true;
3331                 DMStripMenuItem.Enabled = true;
3332                 ShowUserTimelineContextMenuItem.Enabled = true;
3333                 MoveToFavToolStripMenuItem.Enabled = true;
3334                 TabMenuItem.Enabled = true;
3335                 IDRuleMenuItem.Enabled = true;
3336                 SourceRuleMenuItem.Enabled = true;
3337                 ReadedStripMenuItem.Enabled = true;
3338                 UnreadStripMenuItem.Enabled = true;
3339             }
3340             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3341             {
3342                 FavAddToolStripMenuItem.Enabled = false;
3343                 FavRemoveToolStripMenuItem.Enabled = false;
3344                 StatusOpenMenuItem.Enabled = false;
3345                 FavorareMenuItem.Enabled = false;
3346                 ShowRelatedStatusesMenuItem.Enabled = false;
3347
3348                 ReTweetStripMenuItem.Enabled = false;
3349                 ReTweetUnofficialStripMenuItem.Enabled = false;
3350                 QuoteStripMenuItem.Enabled = false;
3351                 FavoriteRetweetContextMenu.Enabled = false;
3352                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3353             }
3354             else
3355             {
3356                 FavAddToolStripMenuItem.Enabled = true;
3357                 FavRemoveToolStripMenuItem.Enabled = true;
3358                 StatusOpenMenuItem.Enabled = true;
3359                 FavorareMenuItem.Enabled = true;
3360                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3361
3362                 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3363                 {
3364                     ReTweetStripMenuItem.Enabled = false;
3365                     ReTweetUnofficialStripMenuItem.Enabled = false;
3366                     QuoteStripMenuItem.Enabled = false;
3367                     FavoriteRetweetContextMenu.Enabled = false;
3368                     FavoriteRetweetUnofficialContextMenu.Enabled = false;
3369                 }
3370                 else
3371                 {
3372                     ReTweetStripMenuItem.Enabled = true;
3373                     ReTweetUnofficialStripMenuItem.Enabled = true;
3374                     QuoteStripMenuItem.Enabled = true;
3375                     FavoriteRetweetContextMenu.Enabled = true;
3376                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3377                 }
3378             }
3379             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3380             //{
3381             //    RefreshMoreStripMenuItem.Enabled = true;
3382             //}
3383             //else
3384             //{
3385             //    RefreshMoreStripMenuItem.Enabled = false;
3386             //}
3387             if (!this.ExistCurrentPost
3388                 || _curPost.InReplyToStatusId == null)
3389             {
3390                 RepliedStatusOpenMenuItem.Enabled = false;
3391             }
3392             else
3393             {
3394                 RepliedStatusOpenMenuItem.Enabled = true;
3395             }
3396             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3397             {
3398                 MoveToRTHomeMenuItem.Enabled = false;
3399             }
3400             else
3401             {
3402                 MoveToRTHomeMenuItem.Enabled = true;
3403             }
3404
3405             if (this.ExistCurrentPost)
3406             {
3407                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3408                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3409                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3410                 else
3411                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3412             }
3413         }
3414
3415         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3416         {
3417             MakeReplyOrDirectStatus(false, true);
3418         }
3419
3420         private void DMStripMenuItem_Click(object sender, EventArgs e)
3421         {
3422             MakeReplyOrDirectStatus(false, false);
3423         }
3424
3425         private async Task doStatusDelete()
3426         {
3427             if (this._curTab == null || this._curList == null)
3428                 return;
3429
3430             if (this._curList.SelectedIndices.Count == 0)
3431                 return;
3432
3433             var posts = this._curList.SelectedIndices.Cast<int>()
3434                 .Select(x => this.GetCurTabPost(x))
3435                 .ToArray();
3436
3437             // 選択されたツイートの中に削除可能なものが一つでもあるか
3438             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3439                 return;
3440
3441             var ret = MessageBox.Show(this,
3442                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3443                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3444                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3445
3446             if (ret != DialogResult.OK)
3447                 return;
3448
3449             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3450
3451             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3452             {
3453                 Exception lastException = null;
3454                 foreach (var post in posts)
3455                 {
3456                     if (!post.CanDeleteBy(this.tw.UserId))
3457                         continue;
3458
3459                     try
3460                     {
3461                         if (post.IsDm)
3462                         {
3463                             await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3464                                 .IgnoreResponse();
3465                         }
3466                         else
3467                         {
3468                             if (post.RetweetedByUserId == this.tw.UserId)
3469                             {
3470                                 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3471                                 //   => RT を取り消し
3472                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3473                                     .IgnoreResponse();
3474                             }
3475                             else
3476                             {
3477                                 if (post.UserId == this.tw.UserId)
3478                                 {
3479                                     if (post.RetweetedId != null)
3480                                         // 他人に RT された自分のツイート
3481                                         //   => RT 元の自分のツイートを削除
3482                                         await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3483                                             .IgnoreResponse();
3484                                     else
3485                                         // 自分のツイート
3486                                         //   => ツイートを削除
3487                                         await this.twitterApi.StatusesDestroy(post.StatusId)
3488                                             .IgnoreResponse();
3489                                 }
3490                             }
3491                         }
3492                     }
3493                     catch (WebApiException ex)
3494                     {
3495                         lastException = ex;
3496                         continue;
3497                     }
3498
3499                     this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3500                 }
3501
3502                 if (lastException == null)
3503                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3504                 else
3505                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3506
3507                 this.PurgeListViewItemCache();
3508                 this._curPost = null;
3509                 this._curItemIndex = -1;
3510
3511                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3512                 {
3513                     var listView = (DetailsListView)tabPage.Tag;
3514                     var tab = this._statuses.Tabs[tabPage.Text];
3515
3516                     using (ControlTransaction.Update(listView))
3517                     {
3518                         listView.VirtualListSize = tab.AllCount;
3519
3520                         if (tabPage == this._curTab)
3521                         {
3522                             listView.SelectedIndices.Clear();
3523
3524                             if (tab.AllCount != 0)
3525                             {
3526                                 int selectedIndex;
3527                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3528                                     selectedIndex = focusedIndex;
3529                                 else
3530                                     selectedIndex = tab.AllCount - 1;
3531
3532                                 listView.SelectedIndices.Add(selectedIndex);
3533                                 listView.EnsureVisible(selectedIndex);
3534                                 listView.FocusedItem = listView.Items[selectedIndex];
3535                             }
3536                         }
3537                     }
3538
3539                     if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3540                     {
3541                         if (tabPage.ImageIndex == 0)
3542                             tabPage.ImageIndex = -1; // タブアイコン
3543                     }
3544                 }
3545
3546                 if (!SettingManager.Common.TabIconDisp)
3547                     this.ListTab.Refresh();
3548             }
3549         }
3550
3551         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3552         {
3553             await this.doStatusDelete();
3554         }
3555
3556         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3557         {
3558             using (ControlTransaction.Update(this._curList))
3559             {
3560                 foreach (int idx in _curList.SelectedIndices)
3561                 {
3562                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3563                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3564                     ChangeCacheStyleRead(true, idx);
3565                 }
3566                 ColorizeList();
3567             }
3568             foreach (TabPage tb in ListTab.TabPages)
3569             {
3570                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3571                 {
3572                     if (SettingManager.Common.TabIconDisp)
3573                     {
3574                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3575                     }
3576                 }
3577             }
3578             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3579         }
3580
3581         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3582         {
3583             using (ControlTransaction.Update(this._curList))
3584             {
3585                 foreach (int idx in _curList.SelectedIndices)
3586                 {
3587                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3588                     this._statuses.SetReadAllTab(post.StatusId, read: false);
3589                     ChangeCacheStyleRead(false, idx);
3590                 }
3591                 ColorizeList();
3592             }
3593             foreach (TabPage tb in ListTab.TabPages)
3594             {
3595                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3596                 {
3597                     if (SettingManager.Common.TabIconDisp)
3598                     {
3599                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3600                     }
3601                 }
3602             }
3603             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3604         }
3605
3606         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3607         {
3608             await this.DoRefresh();
3609         }
3610
3611         private async Task DoRefresh()
3612         {
3613             if (_curTab != null)
3614             {
3615                 TabModel tab;
3616                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3617                     return;
3618
3619                 switch (_statuses.Tabs[_curTab.Text].TabType)
3620                 {
3621                     case MyCommon.TabUsageType.Mentions:
3622                         await this.GetReplyAsync();
3623                         break;
3624                     case MyCommon.TabUsageType.DirectMessage:
3625                         await this.GetDirectMessagesAsync();
3626                         break;
3627                     case MyCommon.TabUsageType.Favorites:
3628                         await this.GetFavoritesAsync();
3629                         break;
3630                     //case MyCommon.TabUsageType.Profile:
3631                         //// TODO
3632                     case MyCommon.TabUsageType.PublicSearch:
3633                         var searchTab = (PublicSearchTabModel)tab;
3634                         if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3635                         await this.GetPublicSearchAsync(searchTab);
3636                         break;
3637                     case MyCommon.TabUsageType.UserTimeline:
3638                         await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3639                         break;
3640                     case MyCommon.TabUsageType.Lists:
3641                         var listTab = (ListTimelineTabModel)tab;
3642                         if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3643                         await this.GetListTimelineAsync(listTab);
3644                         break;
3645                     default:
3646                         await this.GetHomeTimelineAsync();
3647                         break;
3648                 }
3649             }
3650             else
3651             {
3652                 await this.GetHomeTimelineAsync();
3653             }
3654         }
3655
3656         private async Task DoRefreshMore()
3657         {
3658             //ページ指定をマイナス1に
3659             if (_curTab != null)
3660             {
3661                 TabModel tab;
3662                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3663                     return;
3664
3665                 switch (_statuses.Tabs[_curTab.Text].TabType)
3666                 {
3667                     case MyCommon.TabUsageType.Mentions:
3668                         await this.GetReplyAsync(loadMore: true);
3669                         break;
3670                     case MyCommon.TabUsageType.DirectMessage:
3671                         await this.GetDirectMessagesAsync(loadMore: true);
3672                         break;
3673                     case MyCommon.TabUsageType.Favorites:
3674                         await this.GetFavoritesAsync(loadMore: true);
3675                         break;
3676                     case MyCommon.TabUsageType.Profile:
3677                         //// TODO
3678                         break;
3679                     case MyCommon.TabUsageType.PublicSearch:
3680                         var searchTab = (PublicSearchTabModel)tab;
3681                         if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3682                         await this.GetPublicSearchAsync(searchTab, loadMore: true);
3683                         break;
3684                     case MyCommon.TabUsageType.UserTimeline:
3685                         await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3686                         break;
3687                     case MyCommon.TabUsageType.Lists:
3688                         var listTab = (ListTimelineTabModel)tab;
3689                         if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3690                         await this.GetListTimelineAsync(listTab, loadMore: true);
3691                         break;
3692                     default:
3693                         await this.GetHomeTimelineAsync(loadMore: true);
3694                         break;
3695                 }
3696             }
3697             else
3698             {
3699                 await this.GetHomeTimelineAsync(loadMore: true);
3700             }
3701         }
3702
3703         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3704         {
3705             DialogResult result = DialogResult.Abort;
3706
3707             using (var settingDialog = new AppendSettingDialog())
3708             {
3709                 settingDialog.Icon = this.MainIcon;
3710                 settingDialog.Owner = this;
3711                 settingDialog.ShowInTaskbar = showTaskbarIcon;
3712                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3713
3714                 settingDialog.tw = this.tw;
3715                 settingDialog.twitterApi = this.twitterApi;
3716
3717                 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3718
3719                 try
3720                 {
3721                     result = settingDialog.ShowDialog(this);
3722                 }
3723                 catch (Exception)
3724                 {
3725                     return DialogResult.Abort;
3726                 }
3727
3728                 if (result == DialogResult.OK)
3729                 {
3730                     lock (_syncObject)
3731                     {
3732                         settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3733                     }
3734                 }
3735             }
3736
3737             return result;
3738         }
3739
3740         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3741         {
3742             // 設定画面表示前のユーザー情報
3743             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3744
3745             var oldIconSz = SettingManager.Common.IconSize;
3746
3747             if (ShowSettingDialog() == DialogResult.OK)
3748             {
3749                 lock (_syncObject)
3750                 {
3751                     tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3752                     tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3753                     ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3754                     ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3755                     ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3756                     TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3757
3758                     Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3759                     Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3760                     Networking.SetWebProxy(SettingManager.Local.ProxyType,
3761                         SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3762                         SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3763                     Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3764
3765                     ImageSelector.Reset(tw, this.tw.Configuration);
3766
3767                     try
3768                     {
3769                         if (SettingManager.Common.TabIconDisp)
3770                         {
3771                             ListTab.DrawItem -= ListTab_DrawItem;
3772                             ListTab.DrawMode = TabDrawMode.Normal;
3773                             ListTab.ImageList = this.TabImage;
3774                         }
3775                         else
3776                         {
3777                             ListTab.DrawItem -= ListTab_DrawItem;
3778                             ListTab.DrawItem += ListTab_DrawItem;
3779                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3780                             ListTab.ImageList = null;
3781                         }
3782                     }
3783                     catch (Exception ex)
3784                     {
3785                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
3786                         ex.Data["IsTerminatePermission"] = false;
3787                         throw;
3788                     }
3789
3790                     try
3791                     {
3792                         if (!SettingManager.Common.UnreadManage)
3793                         {
3794                             ReadedStripMenuItem.Enabled = false;
3795                             UnreadStripMenuItem.Enabled = false;
3796                             if (SettingManager.Common.TabIconDisp)
3797                             {
3798                                 foreach (TabPage myTab in ListTab.TabPages)
3799                                 {
3800                                     myTab.ImageIndex = -1;
3801                                 }
3802                             }
3803                         }
3804                         else
3805                         {
3806                             ReadedStripMenuItem.Enabled = true;
3807                             UnreadStripMenuItem.Enabled = true;
3808                         }
3809                     }
3810                     catch (Exception ex)
3811                     {
3812                         ex.Data["Instance"] = "ListTab(UnreadManage)";
3813                         ex.Data["IsTerminatePermission"] = false;
3814                         throw;
3815                     }
3816
3817                     // タブの表示位置の決定
3818                     SetTabAlignment();
3819
3820                     SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3821
3822                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3823                     imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3824                     imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3825
3826                     this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3827                     this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3828                     _fntUnread = SettingManager.Local.FontUnread;
3829                     _clUnread = SettingManager.Local.ColorUnread;
3830                     _fntReaded = SettingManager.Local.FontRead;
3831                     _clReaded = SettingManager.Local.ColorRead;
3832                     _clFav = SettingManager.Local.ColorFav;
3833                     _clOWL = SettingManager.Local.ColorOWL;
3834                     _clRetweet = SettingManager.Local.ColorRetweet;
3835                     _fntDetail = SettingManager.Local.FontDetail;
3836                     _clDetail = SettingManager.Local.ColorDetail;
3837                     _clDetailLink = SettingManager.Local.ColorDetailLink;
3838                     _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3839                     _clSelf = SettingManager.Local.ColorSelf;
3840                     _clAtSelf = SettingManager.Local.ColorAtSelf;
3841                     _clTarget = SettingManager.Local.ColorTarget;
3842                     _clAtTarget = SettingManager.Local.ColorAtTarget;
3843                     _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3844                     _clAtTo = SettingManager.Local.ColorAtTo;
3845                     _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3846                     _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3847                     _clInputFont = SettingManager.Local.ColorInputFont;
3848                     _fntInputFont = SettingManager.Local.FontInputFont;
3849                     _brsBackColorMine.Dispose();
3850                     _brsBackColorAt.Dispose();
3851                     _brsBackColorYou.Dispose();
3852                     _brsBackColorAtYou.Dispose();
3853                     _brsBackColorAtFromTarget.Dispose();
3854                     _brsBackColorAtTo.Dispose();
3855                     _brsBackColorNone.Dispose();
3856                     _brsBackColorMine = new SolidBrush(_clSelf);
3857                     _brsBackColorAt = new SolidBrush(_clAtSelf);
3858                     _brsBackColorYou = new SolidBrush(_clTarget);
3859                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3860                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3861                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
3862                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
3863
3864                     try
3865                     {
3866                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3867                         StatusText.Font = _fntInputFont;
3868                         StatusText.ForeColor = _clInputFont;
3869                     }
3870                     catch (Exception ex)
3871                     {
3872                         MessageBox.Show(ex.Message);
3873                     }
3874
3875                     try
3876                     {
3877                         InitDetailHtmlFormat();
3878                     }
3879                     catch (Exception ex)
3880                     {
3881                         ex.Data["Instance"] = "Font";
3882                         ex.Data["IsTerminatePermission"] = false;
3883                         throw;
3884                     }
3885
3886                     try
3887                     {
3888                         foreach (TabPage tb in ListTab.TabPages)
3889                         {
3890                             if (SettingManager.Common.TabIconDisp)
3891                             {
3892                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3893                                     tb.ImageIndex = -1;
3894                                 else
3895                                     tb.ImageIndex = 0;
3896                             }
3897                         }
3898                     }
3899                     catch (Exception ex)
3900                     {
3901                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3902                         ex.Data["IsTerminatePermission"] = false;
3903                         throw;
3904                     }
3905
3906                     try
3907                     {
3908                         var oldIconCol = _iconCol;
3909
3910                         if (SettingManager.Common.IconSize != oldIconSz)
3911                             ApplyListViewIconSize(SettingManager.Common.IconSize);
3912
3913                         foreach (TabPage tp in ListTab.TabPages)
3914                         {
3915                             DetailsListView lst = (DetailsListView)tp.Tag;
3916
3917                             using (ControlTransaction.Update(lst))
3918                             {
3919                                 lst.GridLines = SettingManager.Common.ShowGrid;
3920                                 lst.Font = _fntReaded;
3921                                 lst.BackColor = _clListBackcolor;
3922
3923                                 if (_iconCol != oldIconCol)
3924                                     ResetColumns(lst);
3925                             }
3926                         }
3927                     }
3928                     catch (Exception ex)
3929                     {
3930                         ex.Data["Instance"] = "ListView(IconSize)";
3931                         ex.Data["IsTerminatePermission"] = false;
3932                         throw;
3933                     }
3934
3935                     SetMainWindowTitle();
3936                     SetNotifyIconText();
3937
3938                     this.PurgeListViewItemCache();
3939                     _curList?.Refresh();
3940                     ListTab.Refresh();
3941
3942                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3943                     if (SettingManager.Common.HotkeyEnabled)
3944                     {
3945                         ///グローバルホットキーの登録。設定で変更可能にするかも
3946                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3947                         if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3948                             modKey |= HookGlobalHotkey.ModKeys.Alt;
3949                         if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3950                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3951                         if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3952                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
3953                         if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3954                             modKey |= HookGlobalHotkey.ModKeys.Win;
3955
3956                         _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3957                     }
3958
3959                     if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3960                     try
3961                     {
3962                         StatusText_TextChanged(null, null);
3963                     }
3964                     catch (Exception)
3965                     {
3966                     }
3967                 }
3968             }
3969             else
3970             {
3971                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3972                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3973             }
3974
3975             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3976
3977             this.TopMost = SettingManager.Common.AlwaysTop;
3978             SaveConfigsAll(false);
3979
3980             if (tw.Username != oldUser.Username)
3981                 await this.doGetFollowersMenu();
3982         }
3983
3984         /// <summary>
3985         /// タブの表示位置を設定する
3986         /// </summary>
3987         private void SetTabAlignment()
3988         {
3989             var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3990             if (ListTab.Alignment == newAlignment) return;
3991
3992             // 各タブのリスト上の選択位置などを退避
3993             var listSelections = this.SaveListViewSelection();
3994
3995             ListTab.Alignment = newAlignment;
3996
3997             foreach (TabPage tab in ListTab.TabPages)
3998             {
3999                 DetailsListView lst = (DetailsListView)tab.Tag;
4000                 TabModel tabInfo = _statuses.Tabs[tab.Text];
4001                 using (ControlTransaction.Update(lst))
4002                 {
4003                     // 選択位置などを復元
4004                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4005                 }
4006             }
4007         }
4008
4009         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4010         {
4011             // アイコンサイズの再設定
4012             _iconCol = false;
4013             switch (iconSz)
4014             {
4015                 case MyCommon.IconSizes.IconNone:
4016                     _iconSz = 0;
4017                     break;
4018                 case MyCommon.IconSizes.Icon16:
4019                     _iconSz = 16;
4020                     break;
4021                 case MyCommon.IconSizes.Icon24:
4022                     _iconSz = 26;
4023                     break;
4024                 case MyCommon.IconSizes.Icon48:
4025                     _iconSz = 48;
4026                     break;
4027                 case MyCommon.IconSizes.Icon48_2:
4028                     _iconSz = 48;
4029                     _iconCol = true;
4030                     break;
4031             }
4032
4033             if (_iconSz > 0)
4034             {
4035                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4036                 _listViewImageList.ImageSize = new Size(
4037                     1,
4038                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4039             }
4040             else
4041             {
4042                 _listViewImageList.ImageSize = new Size(1, 1);
4043             }
4044         }
4045
4046         private void ResetColumns(DetailsListView list)
4047         {
4048             using (ControlTransaction.Update(list))
4049             using (ControlTransaction.Layout(list, false))
4050             {
4051                 // カラムヘッダの再設定
4052                 list.ColumnClick -= MyList_ColumnClick;
4053                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4054                 list.ColumnReordered -= MyList_ColumnReordered;
4055                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4056
4057                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4058                 list.Columns.Clear();
4059                 cols.ForEach(col => col.Dispose());
4060                 cols.Clear();
4061
4062                 InitColumns(list, true);
4063
4064                 list.ColumnClick += MyList_ColumnClick;
4065                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4066                 list.ColumnReordered += MyList_ColumnReordered;
4067                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4068             }
4069         }
4070
4071         public void AddNewTabForSearch(string searchWord)
4072         {
4073             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4074             foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4075             {
4076                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4077                 {
4078                     foreach (TabPage tp in ListTab.TabPages)
4079                     {
4080                         if (tb.TabName == tp.Text)
4081                         {
4082                             ListTab.SelectedTab = tp;
4083                             return;
4084                         }
4085                     }
4086                 }
4087             }
4088             //ユニークなタブ名生成
4089             string tabName = searchWord;
4090             for (int i = 0; i <= 100; i++)
4091             {
4092                 if (_statuses.ContainsTab(tabName))
4093                     tabName += "_";
4094                 else
4095                     break;
4096             }
4097             //タブ追加
4098             var tab = new PublicSearchTabModel(tabName);
4099             _statuses.AddTab(tab);
4100             AddNewTab(tab, startup: false);
4101             //追加したタブをアクティブに
4102             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4103             //検索条件の設定
4104             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4105             cmb.Items.Add(searchWord);
4106             cmb.Text = searchWord;
4107             SaveConfigsTabs();
4108             //検索実行
4109             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4110         }
4111
4112         private void ShowUserTimeline()
4113         {
4114             if (!this.ExistCurrentPost) return;
4115             AddNewTabForUserTimeline(_curPost.ScreenName);
4116         }
4117
4118         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4119         {
4120             if (e.KeyCode == Keys.Escape)
4121             {
4122                 TabPage relTp = ListTab.SelectedTab;
4123                 RemoveSpecifiedTab(relTp.Text, false);
4124                 SaveConfigsTabs();
4125                 e.SuppressKeyPress = true;
4126             }
4127         }
4128
4129         public void AddNewTabForUserTimeline(string user)
4130         {
4131             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4132             foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4133             {
4134                 if (tb.ScreenName == user)
4135                 {
4136                     foreach (TabPage tp in ListTab.TabPages)
4137                     {
4138                         if (tb.TabName == tp.Text)
4139                         {
4140                             ListTab.SelectedTab = tp;
4141                             return;
4142                         }
4143                     }
4144                 }
4145             }
4146             //ユニークなタブ名生成
4147             string tabName = "user:" + user;
4148             while (_statuses.ContainsTab(tabName))
4149             {
4150                 tabName += "_";
4151             }
4152             //タブ追加
4153             var tab = new UserTimelineTabModel(tabName, user);
4154             this._statuses.AddTab(tab);
4155             this.AddNewTab(tab, startup: false);
4156             //追加したタブをアクティブに
4157             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4158             SaveConfigsTabs();
4159             //検索実行
4160             this.GetUserTimelineAsync(tab);
4161         }
4162
4163         public bool AddNewTab(TabModel tab, bool startup)
4164         {
4165             //重複チェック
4166             foreach (TabPage tb in ListTab.TabPages)
4167             {
4168                 if (tb.Text == tab.TabName) return false;
4169             }
4170
4171             //新規タブ名チェック
4172             if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4173
4174             var _tabPage = new TabPage();
4175             var _listCustom = new DetailsListView();
4176
4177             int cnt = ListTab.TabPages.Count;
4178
4179             ///ToDo:Create and set controls follow tabtypes
4180
4181             using (ControlTransaction.Update(_listCustom))
4182             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4183             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4184             using (ControlTransaction.Layout(this.SplitContainer1, false))
4185             using (ControlTransaction.Layout(this.ListTab, false))
4186             using (ControlTransaction.Layout(this))
4187             using (ControlTransaction.Layout(_tabPage, false))
4188             {
4189                 _tabPage.Controls.Add(_listCustom);
4190
4191                 /// UserTimeline関連
4192                 var userTab = tab as UserTimelineTabModel;
4193                 var listTab = tab as ListTimelineTabModel;
4194                 var searchTab = tab as PublicSearchTabModel;
4195
4196                 if (userTab != null || listTab != null)
4197                 {
4198                     var label = new Label();
4199                     label.Dock = DockStyle.Top;
4200                     label.Name = "labelUser";
4201                     label.TabIndex = 0;
4202
4203                     if (listTab != null)
4204                     {
4205                         label.Text = listTab.ListInfo.ToString();
4206                     }
4207                     else if (userTab != null)
4208                     {
4209                         label.Text = userTab.ScreenName + "'s Timeline";
4210                     }
4211                     label.TextAlign = ContentAlignment.MiddleLeft;
4212                     using (ComboBox tmpComboBox = new ComboBox())
4213                     {
4214                         label.Height = tmpComboBox.Height;
4215                     }
4216                     _tabPage.Controls.Add(label);
4217                 }
4218                 /// 検索関連の準備
4219                 else if (searchTab != null)
4220                 {
4221                     var pnl = new Panel();
4222
4223                     var lbl = new Label();
4224                     var cmb = new ComboBox();
4225                     var btn = new Button();
4226                     var cmbLang = new ComboBox();
4227
4228                     using (ControlTransaction.Layout(pnl, false))
4229                     {
4230                         pnl.Controls.Add(cmb);
4231                         pnl.Controls.Add(cmbLang);
4232                         pnl.Controls.Add(btn);
4233                         pnl.Controls.Add(lbl);
4234                         pnl.Name = "panelSearch";
4235                         pnl.TabIndex = 0;
4236                         pnl.Dock = DockStyle.Top;
4237                         pnl.Height = cmb.Height;
4238                         pnl.Enter += SearchControls_Enter;
4239                         pnl.Leave += SearchControls_Leave;
4240
4241                         cmb.Text = "";
4242                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4243                         cmb.Dock = DockStyle.Fill;
4244                         cmb.Name = "comboSearch";
4245                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4246                         cmb.ImeMode = ImeMode.NoControl;
4247                         cmb.TabStop = false;
4248                         cmb.TabIndex = 1;
4249                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4250                         cmb.KeyDown += SearchComboBox_KeyDown;
4251
4252                         cmbLang.Text = "";
4253                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4254                         cmbLang.Dock = DockStyle.Right;
4255                         cmbLang.Width = 50;
4256                         cmbLang.Name = "comboLang";
4257                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4258                         cmbLang.TabStop = false;
4259                         cmbLang.TabIndex = 2;
4260                         cmbLang.Items.Add("");
4261                         cmbLang.Items.Add("ja");
4262                         cmbLang.Items.Add("en");
4263                         cmbLang.Items.Add("ar");
4264                         cmbLang.Items.Add("da");
4265                         cmbLang.Items.Add("nl");
4266                         cmbLang.Items.Add("fa");
4267                         cmbLang.Items.Add("fi");
4268                         cmbLang.Items.Add("fr");
4269                         cmbLang.Items.Add("de");
4270                         cmbLang.Items.Add("hu");
4271                         cmbLang.Items.Add("is");
4272                         cmbLang.Items.Add("it");
4273                         cmbLang.Items.Add("no");
4274                         cmbLang.Items.Add("pl");
4275                         cmbLang.Items.Add("pt");
4276                         cmbLang.Items.Add("ru");
4277                         cmbLang.Items.Add("es");
4278                         cmbLang.Items.Add("sv");
4279                         cmbLang.Items.Add("th");
4280
4281                         lbl.Text = "Search(C-S-f)";
4282                         lbl.Name = "label1";
4283                         lbl.Dock = DockStyle.Left;
4284                         lbl.Width = 90;
4285                         lbl.Height = cmb.Height;
4286                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4287                         lbl.TabIndex = 0;
4288
4289                         btn.Text = "Search";
4290                         btn.Name = "buttonSearch";
4291                         btn.UseVisualStyleBackColor = true;
4292                         btn.Dock = DockStyle.Right;
4293                         btn.TabStop = false;
4294                         btn.TabIndex = 3;
4295                         btn.Click += SearchButton_Click;
4296
4297                         if (!string.IsNullOrEmpty(searchTab.SearchWords))
4298                         {
4299                             cmb.Items.Add(searchTab.SearchWords);
4300                             cmb.Text = searchTab.SearchWords;
4301                         }
4302
4303                         cmbLang.Text = searchTab.SearchLang;
4304
4305                         _tabPage.Controls.Add(pnl);
4306                     }
4307                 }
4308
4309                 _tabPage.Tag = _listCustom;
4310                 this.ListTab.Controls.Add(_tabPage);
4311
4312                 _tabPage.Location = new Point(4, 4);
4313                 _tabPage.Name = "CTab" + cnt;
4314                 _tabPage.Size = new Size(380, 260);
4315                 _tabPage.TabIndex = 2 + cnt;
4316                 _tabPage.Text = tab.TabName;
4317                 _tabPage.UseVisualStyleBackColor = true;
4318                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4319
4320                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4321                 _listCustom.TabIndex = 1;
4322                 _listCustom.AllowColumnReorder = true;
4323                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4324                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4325                 _listCustom.Dock = DockStyle.Fill;
4326                 _listCustom.FullRowSelect = true;
4327                 _listCustom.HideSelection = false;
4328                 _listCustom.Location = new Point(0, 0);
4329                 _listCustom.Margin = new Padding(0);
4330                 _listCustom.Name = "CList" + Environment.TickCount;
4331                 _listCustom.ShowItemToolTips = true;
4332                 _listCustom.Size = new Size(380, 260);
4333                 _listCustom.UseCompatibleStateImageBehavior = false;
4334                 _listCustom.View = View.Details;
4335                 _listCustom.OwnerDraw = true;
4336                 _listCustom.VirtualMode = true;
4337                 _listCustom.Font = _fntReaded;
4338                 _listCustom.BackColor = _clListBackcolor;
4339
4340                 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4341                 _listCustom.AllowDrop = true;
4342
4343                 _listCustom.SmallImageList = _listViewImageList;
4344
4345                 InitColumns(_listCustom, startup);
4346
4347                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4348                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4349                 _listCustom.ColumnClick += MyList_ColumnClick;
4350                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4351                 _listCustom.DragDrop += TweenMain_DragDrop;
4352                 _listCustom.DragEnter += TweenMain_DragEnter;
4353                 _listCustom.DragOver += TweenMain_DragOver;
4354                 _listCustom.DrawItem += MyList_DrawItem;
4355                 _listCustom.MouseClick += MyList_MouseClick;
4356                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4357                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4358                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4359                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4360                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4361                 _listCustom.HScrolled += MyList_HScrolled;
4362             }
4363
4364             return true;
4365         }
4366
4367         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4368         {
4369             var tabInfo = _statuses.GetTabByName(TabName);
4370             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4371
4372             if (confirm)
4373             {
4374                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4375                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4376                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4377                 {
4378                     return false;
4379                 }
4380             }
4381
4382             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4383             if (_tabPage == null) return false;
4384
4385             SetListProperty();   //他のタブに列幅等を反映
4386
4387             //オブジェクトインスタンスの削除
4388             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4389             _tabPage.Tag = null;
4390
4391             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4392             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4393             using (ControlTransaction.Layout(this.SplitContainer1, false))
4394             using (ControlTransaction.Layout(this.ListTab, false))
4395             using (ControlTransaction.Layout(this))
4396             using (ControlTransaction.Layout(_tabPage, false))
4397             {
4398                 if (this.ListTab.SelectedTab == _tabPage)
4399                 {
4400                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4401                     this._beforeSelectedTab = null;
4402                 }
4403                 this.ListTab.Controls.Remove(_tabPage);
4404
4405                 // 後付けのコントロールを破棄
4406                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4407                 {
4408                     using (Control label = _tabPage.Controls["labelUser"])
4409                     {
4410                         _tabPage.Controls.Remove(label);
4411                     }
4412                 }
4413                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4414                 {
4415                     using (Control pnl = _tabPage.Controls["panelSearch"])
4416                     {
4417                         pnl.Enter -= SearchControls_Enter;
4418                         pnl.Leave -= SearchControls_Leave;
4419                         _tabPage.Controls.Remove(pnl);
4420
4421                         foreach (Control ctrl in pnl.Controls)
4422                         {
4423                             if (ctrl.Name == "buttonSearch")
4424                             {
4425                                 ctrl.Click -= SearchButton_Click;
4426                             }
4427                             else if (ctrl.Name == "comboSearch")
4428                             {
4429                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4430                             }
4431                             pnl.Controls.Remove(ctrl);
4432                             ctrl.Dispose();
4433                         }
4434                     }
4435                 }
4436
4437                 _tabPage.Controls.Remove(_listCustom);
4438
4439                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4440                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4441                 _listCustom.ColumnClick -= MyList_ColumnClick;
4442                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4443                 _listCustom.DragDrop -= TweenMain_DragDrop;
4444                 _listCustom.DragEnter -= TweenMain_DragEnter;
4445                 _listCustom.DragOver -= TweenMain_DragOver;
4446                 _listCustom.DrawItem -= MyList_DrawItem;
4447                 _listCustom.MouseClick -= MyList_MouseClick;
4448                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4449                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4450                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4451                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4452                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4453                 _listCustom.HScrolled -= MyList_HScrolled;
4454
4455                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4456                 _listCustom.Columns.Clear();
4457                 cols.ForEach(col => col.Dispose());
4458                 cols.Clear();
4459
4460                 _listCustom.ContextMenuStrip = null;
4461                 _listCustom.ColumnHeaderContextMenuStrip = null;
4462                 _listCustom.Font = null;
4463
4464                 _listCustom.SmallImageList = null;
4465                 _listCustom.ListViewItemSorter = null;
4466
4467                 //キャッシュのクリア
4468                 if (_curTab.Equals(_tabPage))
4469                 {
4470                     _curTab = null;
4471                     _curItemIndex = -1;
4472                     _curList = null;
4473                     _curPost = null;
4474                 }
4475                 this.PurgeListViewItemCache();
4476             }
4477
4478             _tabPage.Dispose();
4479             _listCustom.Dispose();
4480             _statuses.RemoveTab(TabName);
4481
4482             foreach (TabPage tp in ListTab.TabPages)
4483             {
4484                 DetailsListView lst = (DetailsListView)tp.Tag;
4485                 var count = _statuses.Tabs[tp.Text].AllCount;
4486                 lst.VirtualListSize = count;
4487             }
4488
4489             return true;
4490         }
4491
4492         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4493         {
4494             this.PurgeListViewItemCache();
4495             _beforeSelectedTab = e.TabPage;
4496         }
4497
4498         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4499         {
4500             //タブのD&D
4501
4502             if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4503             {
4504                 string tn = "";
4505                 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4506                 if (!dragEnableRectangle.Contains(e.Location))
4507                 {
4508                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4509                     tn = ListTab.SelectedTab.Text;
4510                 }
4511
4512                 if (string.IsNullOrEmpty(tn)) return;
4513
4514                 foreach (TabPage tb in ListTab.TabPages)
4515                 {
4516                     if (tb.Text == tn)
4517                     {
4518                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4519                         break;
4520                     }
4521                 }
4522             }
4523             else
4524             {
4525                 _tabDrag = false;
4526             }
4527
4528             Point cpos = new Point(e.X, e.Y);
4529             for (int i = 0; i < ListTab.TabPages.Count; i++)
4530             {
4531                 Rectangle rect = ListTab.GetTabRect(i);
4532                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4533                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4534                 {
4535                     _rclickTabName = ListTab.TabPages[i].Text;
4536                     break;
4537                 }
4538             }
4539         }
4540
4541         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4542         {
4543             //_curList.Refresh();
4544             SetMainWindowTitle();
4545             SetStatusLabelUrl();
4546             SetApiStatusLabel();
4547             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4548             TabMenuControl(ListTab.SelectedTab.Text);
4549             this.PushSelectPostChain();
4550             await DispSelectedPost();
4551         }
4552
4553         private void SetListProperty()
4554         {
4555             //削除などで見つからない場合は処理せず
4556             if (_curList == null) return;
4557             if (!_isColumnChanged) return;
4558
4559             int[] dispOrder = new int[_curList.Columns.Count];
4560             for (int i = 0; i < _curList.Columns.Count; i++)
4561             {
4562                 for (int j = 0; j < _curList.Columns.Count; j++)
4563                 {
4564                     if (_curList.Columns[j].DisplayIndex == i)
4565                     {
4566                         dispOrder[i] = j;
4567                         break;
4568                     }
4569                 }
4570             }
4571
4572             //列幅、列並びを他のタブに設定
4573             foreach (TabPage tb in ListTab.TabPages)
4574             {
4575                 if (!tb.Equals(_curTab))
4576                 {
4577                     if (tb.Tag != null && tb.Controls.Count > 0)
4578                     {
4579                         DetailsListView lst = (DetailsListView)tb.Tag;
4580                         for (int i = 0; i < lst.Columns.Count; i++)
4581                         {
4582                             lst.Columns[dispOrder[i]].DisplayIndex = i;
4583                             lst.Columns[i].Width = _curList.Columns[i].Width;
4584                         }
4585                     }
4586                 }
4587             }
4588
4589             _isColumnChanged = false;
4590         }
4591
4592         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4593         {
4594             if (e.KeyChar == '@')
4595             {
4596                 if (!SettingManager.Common.UseAtIdSupplement) return;
4597                 //@マーク
4598                 int cnt = AtIdSupl.ItemCount;
4599                 ShowSuplDialog(StatusText, AtIdSupl);
4600                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4601                 e.Handled = true;
4602             }
4603             else if (e.KeyChar == '#')
4604             {
4605                 if (!SettingManager.Common.UseHashSupplement) return;
4606                 ShowSuplDialog(StatusText, HashSupl);
4607                 e.Handled = true;
4608             }
4609         }
4610
4611         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4612         {
4613             ShowSuplDialog(owner, dialog, 0, "");
4614         }
4615
4616         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4617         {
4618             ShowSuplDialog(owner, dialog, offset, "");
4619         }
4620
4621         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4622         {
4623             dialog.StartsWith = startswith;
4624             if (dialog.Visible)
4625             {
4626                 dialog.Focus();
4627             }
4628             else
4629             {
4630                 dialog.ShowDialog();
4631             }
4632             this.TopMost = SettingManager.Common.AlwaysTop;
4633             int selStart = owner.SelectionStart;
4634             string fHalf = "";
4635             string eHalf = "";
4636             if (dialog.DialogResult == DialogResult.OK)
4637             {
4638                 if (!string.IsNullOrEmpty(dialog.inputText))
4639                 {
4640                     if (selStart > 0)
4641                     {
4642                         fHalf = owner.Text.Substring(0, selStart - offset);
4643                     }
4644                     if (selStart < owner.Text.Length)
4645                     {
4646                         eHalf = owner.Text.Substring(selStart);
4647                     }
4648                     owner.Text = fHalf + dialog.inputText + eHalf;
4649                     owner.SelectionStart = selStart + dialog.inputText.Length;
4650                 }
4651             }
4652             else
4653             {
4654                 if (selStart > 0)
4655                 {
4656                     fHalf = owner.Text.Substring(0, selStart);
4657                 }
4658                 if (selStart < owner.Text.Length)
4659                 {
4660                     eHalf = owner.Text.Substring(selStart);
4661                 }
4662                 owner.Text = fHalf + eHalf;
4663                 if (selStart > 0)
4664                 {
4665                     owner.SelectionStart = selStart;
4666                 }
4667             }
4668             owner.Focus();
4669         }
4670
4671         private void StatusText_KeyUp(object sender, KeyEventArgs e)
4672         {
4673             //スペースキーで未読ジャンプ
4674             if (!e.Alt && !e.Control && !e.Shift)
4675             {
4676                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4677                 {
4678                     bool isSpace = false;
4679                     foreach (char c in StatusText.Text)
4680                     {
4681                         if (c == ' ' || c == ' ')
4682                         {
4683                             isSpace = true;
4684                         }
4685                         else
4686                         {
4687                             isSpace = false;
4688                             break;
4689                         }
4690                     }
4691                     if (isSpace)
4692                     {
4693                         e.Handled = true;
4694                         StatusText.Text = "";
4695                         JumpUnreadMenuItem_Click(null, null);
4696                     }
4697                 }
4698             }
4699             this.StatusText_TextChanged(null, null);
4700         }
4701
4702         private void StatusText_TextChanged(object sender, EventArgs e)
4703         {
4704             //文字数カウント
4705             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4706             lblLen.Text = pLen.ToString();
4707             if (pLen < 0)
4708             {
4709                 StatusText.ForeColor = Color.Red;
4710             }
4711             else
4712             {
4713                 StatusText.ForeColor = _clInputFont;
4714             }
4715
4716             this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4717
4718             if (string.IsNullOrEmpty(StatusText.Text))
4719             {
4720                 this.inReplyTo = null;
4721             }
4722         }
4723
4724         /// <summary>
4725         /// ツイート投稿前のフッター付与などの前処理を行います
4726         /// </summary>
4727         private string FormatStatusText(string statusText)
4728         {
4729             statusText = statusText.Replace("\r\n", "\n");
4730
4731             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4732             {
4733                 // URLと全角文字の切り離し
4734                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4735             }
4736
4737             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4738             {
4739                 // 文中の全角スペースを半角スペース1個にする
4740                 statusText = statusText.Replace(" ", " ");
4741             }
4742
4743             // DM の場合はこれ以降の処理を行わない
4744             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4745                 return statusText;
4746
4747             bool disableFooter;
4748             if (SettingManager.Common.PostShiftEnter)
4749             {
4750                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4751             }
4752             else
4753             {
4754                 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4755                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
4756                 else
4757                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4758             }
4759
4760             if (statusText.Contains("RT @"))
4761                 disableFooter = true;
4762
4763             var header = "";
4764             var footer = "";
4765
4766             var hashtag = this.HashMgr.UseHash;
4767             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4768             {
4769                 if (HashMgr.IsHead)
4770                     header = HashMgr.UseHash + " ";
4771                 else
4772                     footer = " " + HashMgr.UseHash;
4773             }
4774
4775             if (!disableFooter)
4776             {
4777                 if (SettingManager.Local.UseRecommendStatus)
4778                 {
4779                     // 推奨ステータスを使用する
4780                     footer += this.recommendedStatusFooter;
4781                 }
4782                 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4783                 {
4784                     // テキストボックスに入力されている文字列を使用する
4785                     footer += " " + SettingManager.Local.StatusText.Trim();
4786                 }
4787             }
4788
4789             statusText = header + statusText + footer;
4790
4791             if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4792             {
4793                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4794                 // 参照: https://support.twitter.com/articles/14020
4795
4796                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4797                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
4798                 {
4799                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4800                     statusText = '\u200b' + statusText;
4801                 }
4802             }
4803
4804             return statusText;
4805         }
4806
4807         /// <summary>
4808         /// 投稿欄に表示する入力可能な文字数を計算します
4809         /// </summary>
4810         private int GetRestStatusCount(string statusText)
4811         {
4812             //文字数カウント
4813             var remainCount = this.tw.GetTextLengthRemain(statusText);
4814
4815             var uploadService = this.ImageSelector.SelectedService;
4816             if (this.ImageSelector.Visible && uploadService != null)
4817             {
4818                 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4819                 remainCount -= uploadService.GetReservedTextLength(1);
4820             }
4821
4822             return remainCount;
4823         }
4824
4825         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4826         {
4827             if (sender != this._curList)
4828                 return;
4829
4830             var listCache = this._listItemCache;
4831             if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4832             {
4833                 // If the newly requested cache is a subset of the old cache,
4834                 // no need to rebuild everything, so do nothing.
4835                 return;
4836             }
4837
4838             // Now we need to rebuild the cache.
4839             this.CreateCache(e.StartIndex, e.EndIndex);
4840         }
4841
4842         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4843         {
4844             var listCache = this._listItemCache;
4845             if (listCache?.TargetList == sender)
4846             {
4847                 ListViewItem item;
4848                 PostClass cacheItemPost;
4849                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4850                 {
4851                     e.Item = item;
4852                     return;
4853                 }
4854             }
4855
4856             // A cache miss, so create a new ListViewItem and pass it back.
4857             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4858             try
4859             {
4860                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4861             }
4862             catch (Exception)
4863             {
4864                 // 不正な要求に対する間に合わせの応答
4865                 string[] sitem = {"", "", "", "", "", "", "", ""};
4866                 e.Item = new ImageListViewItem(sitem);
4867             }
4868         }
4869
4870         private void CreateCache(int startIndex, int endIndex)
4871         {
4872             var tabInfo = this._statuses.Tabs[this._curTab.Text];
4873
4874             if (tabInfo.AllCount == 0)
4875                 return;
4876
4877             // キャッシュ要求(要求範囲±30を作成)
4878             startIndex = Math.Max(startIndex - 30, 0);
4879             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4880
4881             var cacheLength = endIndex - startIndex + 1;
4882
4883             var posts = tabInfo[startIndex, endIndex]; //配列で取得
4884             var listItems = Enumerable.Range(0, cacheLength)
4885                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4886                 .ToArray();
4887
4888             var listCache = new ListViewItemCache
4889             {
4890                 TargetList = this._curList,
4891                 StartIndex = startIndex,
4892                 EndIndex = endIndex,
4893                 Post = posts,
4894                 ListItem = listItems,
4895             };
4896
4897             Interlocked.Exchange(ref this._listItemCache, listCache);
4898         }
4899
4900         /// <summary>
4901         /// DetailsListView のための ListViewItem のキャッシュを消去する
4902         /// </summary>
4903         private void PurgeListViewItemCache()
4904         {
4905             Interlocked.Exchange(ref this._listItemCache, null);
4906         }
4907
4908         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4909         {
4910             StringBuilder mk = new StringBuilder();
4911             //if (Post.IsDeleted) mk.Append("×");
4912             //if (Post.IsMark) mk.Append("♪");
4913             //if (Post.IsProtect) mk.Append("Ю");
4914             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4915             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4916             ImageListViewItem itm;
4917             if (Post.RetweetedId == null)
4918             {
4919                 string[] sitem= {"",
4920                                  Post.Nickname,
4921                                  Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4922                                  Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4923                                  Post.ScreenName,
4924                                  "",
4925                                  mk.ToString(),
4926                                  Post.Source};
4927                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4928             }
4929             else
4930             {
4931                 string[] sitem = {"",
4932                                   Post.Nickname,
4933                                   Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4934                                   Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4935                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4936                                   "",
4937                                   mk.ToString(),
4938                                   Post.Source};
4939                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4940             }
4941             itm.StateIndex = Post.StateIndex;
4942             itm.Tag = Post;
4943
4944             bool read = Post.IsRead;
4945             //未読管理していなかったら既読として扱う
4946             if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4947             ChangeItemStyleRead(read, itm, Post, null);
4948             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4949             return itm;
4950         }
4951
4952         /// <summary>
4953         /// 全てのタブの振り分けルールを反映し直します
4954         /// </summary>
4955         private void ApplyPostFilters()
4956         {
4957             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4958             {
4959                 this.PurgeListViewItemCache();
4960                 this._curPost = null;
4961                 this._curItemIndex = -1;
4962                 this._statuses.FilterAll();
4963
4964                 foreach (TabPage tabPage in this.ListTab.TabPages)
4965                 {
4966                     var tab = this._statuses.Tabs[tabPage.Text];
4967
4968                     var listview = (DetailsListView)tabPage.Tag;
4969                     using (ControlTransaction.Update(listview))
4970                     {
4971                         listview.VirtualListSize = tab.AllCount;
4972                     }
4973
4974                     if (SettingManager.Common.TabIconDisp)
4975                     {
4976                         if (tab.UnreadCount > 0)
4977                             tabPage.ImageIndex = 0;
4978                         else
4979                             tabPage.ImageIndex = -1;
4980                     }
4981                 }
4982
4983                 if (!SettingManager.Common.TabIconDisp)
4984                     this.ListTab.Refresh();
4985
4986                 SetMainWindowTitle();
4987                 SetStatusLabelUrl();
4988             }
4989         }
4990
4991         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4992         {
4993             e.DrawDefault = true;
4994         }
4995
4996         private void MyList_HScrolled(object sender, EventArgs e)
4997         {
4998             DetailsListView listView = (DetailsListView)sender;
4999             listView.Refresh();
5000         }
5001
5002         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5003         {
5004             if (e.State == 0) return;
5005             e.DrawDefault = false;
5006
5007             SolidBrush brs2 = null;
5008             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5009             {
5010                 if (e.Item.BackColor == _clSelf)
5011                     brs2 = _brsBackColorMine;
5012                 else if (e.Item.BackColor == _clAtSelf)
5013                     brs2 = _brsBackColorAt;
5014                 else if (e.Item.BackColor == _clTarget)
5015                     brs2 = _brsBackColorYou;
5016                 else if (e.Item.BackColor == _clAtTarget)
5017                     brs2 = _brsBackColorAtYou;
5018                 else if (e.Item.BackColor == _clAtFromTarget)
5019                     brs2 = _brsBackColorAtFromTarget;
5020                 else if (e.Item.BackColor == _clAtTo)
5021                     brs2 = _brsBackColorAtTo;
5022                 else
5023                     brs2 = _brsBackColorNone;
5024             }
5025             else
5026             {
5027                 //選択中の行
5028                 if (((Control)sender).Focused)
5029                     brs2 = _brsHighLight;
5030                 else
5031                     brs2 = _brsDeactiveSelection;
5032             }
5033             e.Graphics.FillRectangle(brs2, e.Bounds);
5034             e.DrawFocusRectangle();
5035             this.DrawListViewItemIcon(e);
5036         }
5037
5038         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5039         {
5040             if (e.ItemState == 0) return;
5041
5042             if (e.ColumnIndex > 0)
5043             {
5044                 //アイコン以外の列
5045                 var post = (PostClass)e.Item.Tag;
5046
5047                 RectangleF rct = e.Bounds;
5048                 rct.Width = e.Header.Width;
5049                 int fontHeight = e.Item.Font.Height;
5050                 if (_iconCol)
5051                 {
5052                     rct.Y += fontHeight;
5053                     rct.Height -= fontHeight;
5054                 }
5055
5056                 int heightDiff;
5057                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5058
5059                 //if (heightDiff > fontHeight * 0.7)
5060                 //{
5061                 //    rct.Height += fontHeight;
5062                 //    drawLineCount += 1;
5063                 //}
5064
5065                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5066                 if (!_iconCol && drawLineCount <= 1)
5067                 {
5068                     //rct.Inflate(0, heightDiff / -2);
5069                     //rct.Height += fontHeight / 2;
5070                 }
5071                 else if (heightDiff < fontHeight * 0.7)
5072                 {
5073                     //最終行が70%以上欠けていたら、最終行は表示しない
5074                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5075                     rct.Height = (fontHeight * drawLineCount) - 1;
5076                 }
5077                 else
5078                 {
5079                     drawLineCount += 1;
5080                 }
5081
5082                 //if (!_iconCol && drawLineCount > 1)
5083                 //{
5084                 //    rct.Y += fontHeight * 0.2;
5085                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5086                 //}
5087
5088                 if (rct.Width > 0)
5089                 {
5090                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5091                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5092                         _clUnread;
5093
5094                     if (_iconCol)
5095                     {
5096                         Rectangle rctB = e.Bounds;
5097                         rctB.Width = e.Header.Width;
5098                         rctB.Height = fontHeight;
5099
5100                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5101                         {
5102                             TextRenderer.DrawText(e.Graphics,
5103                                                     post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5104                                                     e.Item.Font,
5105                                                     Rectangle.Round(rct),
5106                                                     color,
5107                                                     TextFormatFlags.WordBreak |
5108                                                     TextFormatFlags.EndEllipsis |
5109                                                     TextFormatFlags.GlyphOverhangPadding |
5110                                                     TextFormatFlags.NoPrefix);
5111                             TextRenderer.DrawText(e.Graphics,
5112                                                     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 + "]",
5113                                                     fnt,
5114                                                     rctB,
5115                                                     color,
5116                                                     TextFormatFlags.SingleLine |
5117                                                     TextFormatFlags.EndEllipsis |
5118                                                     TextFormatFlags.GlyphOverhangPadding |
5119                                                     TextFormatFlags.NoPrefix);
5120                         }
5121                     }
5122                     else
5123                     {
5124                         string text;
5125                         if (e.ColumnIndex != 2)
5126                             text = e.SubItem.Text;
5127                         else
5128                             text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5129
5130                         if (drawLineCount == 1)
5131                         {
5132                             TextRenderer.DrawText(e.Graphics,
5133                                                     text,
5134                                                     e.Item.Font,
5135                                                     Rectangle.Round(rct),
5136                                                     color,
5137                                                     TextFormatFlags.SingleLine |
5138                                                     TextFormatFlags.EndEllipsis |
5139                                                     TextFormatFlags.GlyphOverhangPadding |
5140                                                     TextFormatFlags.NoPrefix |
5141                                                     TextFormatFlags.VerticalCenter);
5142                         }
5143                         else
5144                         {
5145                             TextRenderer.DrawText(e.Graphics,
5146                                                     text,
5147                                                     e.Item.Font,
5148                                                     Rectangle.Round(rct),
5149                                                     color,
5150                                                     TextFormatFlags.WordBreak |
5151                                                     TextFormatFlags.EndEllipsis |
5152                                                     TextFormatFlags.GlyphOverhangPadding |
5153                                                     TextFormatFlags.NoPrefix);
5154                         }
5155                     }
5156                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5157                 }
5158             }
5159         }
5160
5161         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5162         {
5163             if (_iconSz == 0) return;
5164
5165             ImageListViewItem item = (ImageListViewItem)e.Item;
5166
5167             //e.Bounds.Leftが常に0を指すから自前で計算
5168             Rectangle itemRect = item.Bounds;
5169             var col0 = e.Item.ListView.Columns[0];
5170             itemRect.Width = col0.Width;
5171
5172             if (col0.DisplayIndex > 0)
5173             {
5174                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5175                 {
5176                     if (clm.DisplayIndex < col0.DisplayIndex)
5177                         itemRect.X += clm.Width;
5178                 }
5179             }
5180
5181             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5182             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5183             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5184
5185             Rectangle iconRect;
5186             var img = item.Image;
5187             if (img != null)
5188             {
5189                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5190                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5191
5192                 if (iconRect.Width > 0)
5193                 {
5194                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5195                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5196                     try
5197                     {
5198                         e.Graphics.DrawImage(img.Image, iconRect);
5199                     }
5200                     catch (ArgumentException)
5201                     {
5202                         item.RefreshImageAsync();
5203                     }
5204                 }
5205             }
5206             else
5207             {
5208                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5209                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5210
5211                 item.GetImageAsync();
5212             }
5213
5214             if (item.StateIndex > -1)
5215             {
5216                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5217                 if (stateRect.Width > 0)
5218                 {
5219                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5220                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5221                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5222                 }
5223             }
5224         }
5225
5226         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5227         {
5228             base.ScaleControl(factor, specified);
5229
5230             ScaleChildControl(this.TabImage, factor);
5231
5232             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5233             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5234
5235             foreach (var listview in listviews)
5236             {
5237                 ScaleChildControl(listview, factor);
5238             }
5239         }
5240
5241         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5242         //{
5243         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5244         //    if (item.StateImageIndex > -1)
5245         //    {
5246         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5247         //        //Rectangle itemRect = item.Bounds;
5248         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5249
5250         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5251         //        //{
5252         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5253         //        //    {
5254         //        //        itemRect.X += clm.Width;
5255         //        //    }
5256         //        //}
5257
5258         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5259         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5260
5261         //        if (rct.Width > 0)
5262         //        {
5263         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5264         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5265         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5266         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5267         //        }
5268         //    }
5269         //}
5270
5271         internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5272         {
5273             var tab = this._statuses.Tabs[this._curTab.Text];
5274
5275             if (tab.AllCount == 0)
5276             {
5277                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5278                 return;
5279             }
5280
5281             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5282
5283             int startIndex;
5284             switch (searchType)
5285             {
5286                 case SEARCHTYPE.NextSearch: // 次を検索
5287                     if (selectedIndex != -1)
5288                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5289                     else
5290                         startIndex = 0;
5291                     break;
5292                 case SEARCHTYPE.PrevSearch: // 前を検索
5293                     if (selectedIndex != -1)
5294                         startIndex = Math.Max(selectedIndex - 1, 0);
5295                     else
5296                         startIndex = tab.AllCount - 1;
5297                     break;
5298                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5299                 default:
5300                     if (selectedIndex != -1)
5301                         startIndex = selectedIndex;
5302                     else
5303                         startIndex = 0;
5304                     break;
5305             }
5306
5307             Func<string, bool> stringComparer;
5308             try
5309             {
5310                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5311             }
5312             catch (ArgumentException)
5313             {
5314                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5315                 return;
5316             }
5317
5318             var reverse = searchType == SEARCHTYPE.PrevSearch;
5319             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5320                 .DefaultIfEmpty(-1).First();
5321
5322             if (foundIndex == -1)
5323             {
5324                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5325                 return;
5326             }
5327
5328             this.SelectListItem(this._curList, foundIndex);
5329             this._curList.EnsureVisible(foundIndex);
5330         }
5331
5332         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5333         {
5334             // 検索メニュー
5335             this.ShowSearchDialog();
5336         }
5337
5338         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5339         {
5340             var previousSearch = this.SearchDialog.ResultOptions;
5341             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5342             {
5343                 this.SearchDialog.Reset();
5344                 this.ShowSearchDialog();
5345                 return;
5346             }
5347
5348             // 次を検索
5349             this.DoTabSearch(
5350                 previousSearch.Query,
5351                 previousSearch.CaseSensitive,
5352                 previousSearch.UseRegex,
5353                 SEARCHTYPE.NextSearch);
5354         }
5355
5356         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5357         {
5358             var previousSearch = this.SearchDialog.ResultOptions;
5359             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5360             {
5361                 this.SearchDialog.Reset();
5362                 this.ShowSearchDialog();
5363                 return;
5364             }
5365
5366             // 前を検索
5367             this.DoTabSearch(
5368                 previousSearch.Query,
5369                 previousSearch.CaseSensitive,
5370                 previousSearch.UseRegex,
5371                 SEARCHTYPE.PrevSearch);
5372         }
5373
5374         /// <summary>
5375         /// 検索ダイアログを表示し、検索を実行します
5376         /// </summary>
5377         private void ShowSearchDialog()
5378         {
5379             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5380             {
5381                 this.TopMost = SettingManager.Common.AlwaysTop;
5382                 return;
5383             }
5384             this.TopMost = SettingManager.Common.AlwaysTop;
5385
5386             var searchOptions = this.SearchDialog.ResultOptions;
5387             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5388             {
5389                 if (searchOptions.NewTab)
5390                 {
5391                     var tabName = Properties.Resources.SearchResults_TabName;
5392
5393                     try
5394                     {
5395                         tabName = this._statuses.MakeTabName(tabName);
5396                     }
5397                     catch (TabException ex)
5398                     {
5399                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5400                     }
5401
5402                     var resultTab = new LocalSearchTabModel(tabName);
5403                     this.AddNewTab(resultTab, startup: false);
5404                     this._statuses.AddTab(resultTab);
5405
5406                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5407
5408                     Func<string, bool> stringComparer;
5409                     try
5410                     {
5411                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5412                     }
5413                     catch (ArgumentException)
5414                     {
5415                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5416                         return;
5417                     }
5418
5419                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5420                     if (foundIndices.Length == 0)
5421                     {
5422                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5423                         return;
5424                     }
5425
5426                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5427                     foreach (var post in foundPosts)
5428                     {
5429                         resultTab.AddPostQueue(post);
5430                     }
5431
5432                     this._statuses.DistributePosts();
5433                     this.RefreshTimeline();
5434
5435                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5436                         .First(x => x.Text == tabName);
5437
5438                     this.ListTab.SelectedTab = tabPage;
5439                 }
5440                 else
5441                 {
5442                     this.DoTabSearch(
5443                         searchOptions.Query,
5444                         searchOptions.CaseSensitive,
5445                         searchOptions.UseRegex,
5446                         SEARCHTYPE.DialogSearch);
5447                 }
5448             }
5449             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5450             {
5451                 this.AddNewTabForSearch(searchOptions.Query);
5452             }
5453         }
5454
5455         /// <summary>発言検索に使用するメソッドを生成します</summary>
5456         /// <exception cref="ArgumentException">
5457         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5458         /// </exception>
5459         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5460         {
5461             if (useRegex)
5462             {
5463                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5464                 var regex = new Regex(query, regexOption);
5465
5466                 return x => regex.IsMatch(x);
5467             }
5468             else
5469             {
5470                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5471
5472                 return x => x.IndexOf(query, comparisonType) != -1;
5473             }
5474         }
5475
5476         private void AboutMenuItem_Click(object sender, EventArgs e)
5477         {
5478             using (TweenAboutBox about = new TweenAboutBox())
5479             {
5480                 about.ShowDialog(this);
5481             }
5482             this.TopMost = SettingManager.Common.AlwaysTop;
5483         }
5484
5485         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5486         {
5487             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5488
5489             if (ImageSelector.Enabled)
5490                 return;
5491
5492             TabModel foundTab = null;
5493             int foundIndex = 0;
5494
5495             DetailsListView lst = null;
5496
5497             //現在タブから最終タブまで探索
5498             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5499             {
5500                 var tabPage = this.ListTab.TabPages[i];
5501                 var tab = this._statuses.Tabs[tabPage.Text];
5502                 var unreadIndex = tab.NextUnreadIndex;
5503
5504                 if (unreadIndex != -1)
5505                 {
5506                     ListTab.SelectedIndex = i;
5507                     foundTab = tab;
5508                     foundIndex = unreadIndex;
5509                     lst = (DetailsListView)tabPage.Tag;
5510                     break;
5511                 }
5512             }
5513
5514             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5515             if (foundTab == null && bgnIdx > 0)
5516             {
5517                 for (int i = 0; i < bgnIdx; i++)
5518                 {
5519                     var tabPage = this.ListTab.TabPages[i];
5520                     var tab = this._statuses.Tabs[tabPage.Text];
5521                     var unreadIndex = tab.NextUnreadIndex;
5522
5523                     if (unreadIndex != -1)
5524                     {
5525                         ListTab.SelectedIndex = i;
5526                         foundTab = tab;
5527                         foundIndex = unreadIndex;
5528                         lst = (DetailsListView)tabPage.Tag;
5529                         break;
5530                     }
5531                 }
5532             }
5533
5534             if (foundTab == null)
5535             {
5536                 //全部調べたが未読見つからず→先頭タブの最新発言へ
5537                 ListTab.SelectedIndex = 0;
5538                 var tabPage = this.ListTab.TabPages[0];
5539                 var tab = this._statuses.Tabs[tabPage.Text];
5540
5541                 if (tab.AllCount == 0)
5542                     return;
5543
5544                 if (_statuses.SortOrder == SortOrder.Ascending)
5545                     foundIndex = tab.AllCount - 1;
5546                 else
5547                     foundIndex = 0;
5548
5549                 lst = (DetailsListView)tabPage.Tag;
5550             }
5551
5552             SelectListItem(lst, foundIndex);
5553
5554             if (_statuses.SortMode == ComparerMode.Id)
5555             {
5556                 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5557                     _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5558                 {
5559                     MoveTop();
5560                 }
5561                 else
5562                 {
5563                     lst.EnsureVisible(foundIndex);
5564                 }
5565             }
5566             else
5567             {
5568                 lst.EnsureVisible(foundIndex);
5569             }
5570
5571             lst.Focus();
5572         }
5573
5574         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5575         {
5576             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5577             {
5578                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5579                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5580             }
5581         }
5582
5583         private async void FavorareMenuItem_Click(object sender, EventArgs e)
5584         {
5585             if (_curList.SelectedIndices.Count > 0)
5586             {
5587                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5588                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5589             }
5590         }
5591
5592         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5593         {
5594             await this.CheckNewVersion(false);
5595         }
5596
5597         private void RunTweenUp()
5598         {
5599             ProcessStartInfo pinfo = new ProcessStartInfo();
5600             pinfo.UseShellExecute = true;
5601             pinfo.WorkingDirectory = MyCommon.settingPath;
5602             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5603             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5604             try
5605             {
5606                 Process.Start(pinfo);
5607             }
5608             catch (Exception)
5609             {
5610                 MessageBox.Show("Failed to execute TweenUp3.exe.");
5611             }
5612         }
5613
5614         public class VersionInfo
5615         {
5616             public Version Version { get; set; }
5617             public Uri DownloadUri { get; set; }
5618             public string ReleaseNote { get; set; }
5619         }
5620
5621         /// <summary>
5622         /// OpenTween の最新バージョンの情報を取得します
5623         /// </summary>
5624         public async Task<VersionInfo> GetVersionInfoAsync()
5625         {
5626             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5627                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5628
5629             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5630                 .ConfigureAwait(false);
5631
5632             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5633             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5634
5635             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5636             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5637
5638             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5639
5640             return new VersionInfo
5641             {
5642                 Version = Version.Parse(msgHeader[0]),
5643                 DownloadUri = new Uri(msgHeader[1]),
5644                 ReleaseNote = msgBody,
5645             };
5646         }
5647
5648         private async Task CheckNewVersion(bool startup = false)
5649         {
5650             if (ApplicationSettings.VersionInfoUrl == null)
5651                 return; // 更新チェック無効化
5652
5653             try
5654             {
5655                 var versionInfo = await this.GetVersionInfoAsync();
5656
5657                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5658                 {
5659                     // 更新不要
5660                     if (!startup)
5661                     {
5662                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5663                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5664                         msgtext = MyCommon.ReplaceAppName(msgtext);
5665
5666                         MessageBox.Show(msgtext,
5667                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5668                             MessageBoxButtons.OK, MessageBoxIcon.Information);
5669                     }
5670                     return;
5671                 }
5672
5673                 using (var dialog = new UpdateDialog())
5674                 {
5675                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5676                         MyCommon.GetReadableVersion(versionInfo.Version));
5677                     dialog.DetailsText = versionInfo.ReleaseNote;
5678
5679                     if (dialog.ShowDialog(this) == DialogResult.Yes)
5680                     {
5681                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5682                     }
5683                 }
5684             }
5685             catch (Exception)
5686             {
5687                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5688                 if (!startup)
5689                 {
5690                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5691                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5692                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5693                 }
5694             }
5695         }
5696
5697         private async Task Colorize()
5698         {
5699             _colorize = false;
5700             await this.DispSelectedPost();
5701             //件数関連の場合、タイトル即時書き換え
5702             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5703                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5704                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5705                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5706             {
5707                 SetMainWindowTitle();
5708             }
5709             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5710                 SetStatusLabelUrl();
5711             foreach (TabPage tb in ListTab.TabPages)
5712             {
5713                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5714                 {
5715                     if (SettingManager.Common.TabIconDisp)
5716                     {
5717                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5718                     }
5719                 }
5720             }
5721             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5722         }
5723
5724         public string createDetailHtml(string orgdata)
5725         {
5726             if (SettingManager.Local.UseTwemoji)
5727                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5728
5729             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5730         }
5731
5732         private Task DispSelectedPost()
5733         {
5734             return this.DispSelectedPost(false);
5735         }
5736
5737         private PostClass displayPost = new PostClass();
5738
5739         /// <summary>
5740         /// サムネイル表示に使用する CancellationToken の生成元
5741         /// </summary>
5742         private CancellationTokenSource thumbnailTokenSource = null;
5743
5744         private async Task DispSelectedPost(bool forceupdate)
5745         {
5746             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5747                 return;
5748
5749             var oldDisplayPost = this.displayPost;
5750             this.displayPost = this._curPost;
5751
5752             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5753                 return;
5754
5755             var loadTasks = new List<Task>
5756             {
5757                 this.tweetDetailsView.ShowPostDetails(this._curPost),
5758             };
5759
5760             this.SplitContainer3.Panel2Collapsed = true;
5761
5762             if (SettingManager.Common.PreviewEnable)
5763             {
5764                 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5765                 oldTokenSource?.Cancel();
5766
5767                 var token = this.thumbnailTokenSource.Token;
5768                 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5769             }
5770
5771             try
5772             {
5773                 await Task.WhenAll(loadTasks);
5774             }
5775             catch (OperationCanceledException) { }
5776         }
5777
5778         private async void MatomeMenuItem_Click(object sender, EventArgs e)
5779         {
5780             await this.OpenApplicationWebsite();
5781         }
5782
5783         private async Task OpenApplicationWebsite()
5784         {
5785             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5786         }
5787
5788         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5789         {
5790             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5791         }
5792
5793         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5794         {
5795             if (ListTab.SelectedTab != null)
5796             {
5797                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5798                 {
5799                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5800                     if (pnl.Controls["comboSearch"].Focused ||
5801                         pnl.Controls["comboLang"].Focused ||
5802                         pnl.Controls["buttonSearch"].Focused) return;
5803                 }
5804
5805                 if (e.Control || e.Shift || e.Alt)
5806                     this._anchorFlag = false;
5807
5808                 Task asyncTask;
5809                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5810                 {
5811                     e.Handled = true;
5812                     e.SuppressKeyPress = true;
5813                 }
5814
5815                 if (asyncTask != null)
5816                     await asyncTask;
5817             }
5818         }
5819
5820         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5821
5822         private void InitializeShortcuts()
5823         {
5824             this.shortcutCommands = new[]
5825             {
5826                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5827                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5828                     .FocusedOn(FocusedControl.ListTab)
5829                     .Do(() => SendKeys.Send("{DOWN}")),
5830
5831                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5832                     .FocusedOn(FocusedControl.ListTab)
5833                     .Do(() => SendKeys.Send("{UP}")),
5834
5835                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5836                     .FocusedOn(FocusedControl.ListTab)
5837                     .Do(() => SendKeys.Send("{PGDN}")),
5838
5839                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5840                     .FocusedOn(FocusedControl.ListTab)
5841                     .Do(() => SendKeys.Send("{PGUP}")),
5842
5843                 ShortcutCommand.Create(Keys.F1)
5844                     .Do(() => this.OpenApplicationWebsite()),
5845
5846                 ShortcutCommand.Create(Keys.F3)
5847                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
5848
5849                 ShortcutCommand.Create(Keys.F5)
5850                     .Do(() => this.DoRefresh()),
5851
5852                 ShortcutCommand.Create(Keys.F6)
5853                     .Do(() => this.GetReplyAsync()),
5854
5855                 ShortcutCommand.Create(Keys.F7)
5856                     .Do(() => this.GetDirectMessagesAsync()),
5857
5858                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5859                     .NotFocusedOn(FocusedControl.StatusText)
5860                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5861
5862                 ShortcutCommand.Create(Keys.G)
5863                     .NotFocusedOn(FocusedControl.StatusText)
5864                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5865
5866                 ShortcutCommand.Create(Keys.Right, Keys.N)
5867                     .FocusedOn(FocusedControl.ListTab)
5868                     .Do(() => this.GoRelPost(forward: true)),
5869
5870                 ShortcutCommand.Create(Keys.Left, Keys.P)
5871                     .FocusedOn(FocusedControl.ListTab)
5872                     .Do(() => this.GoRelPost(forward: false)),
5873
5874                 ShortcutCommand.Create(Keys.OemPeriod)
5875                     .FocusedOn(FocusedControl.ListTab)
5876                     .Do(() => this.GoAnchor()),
5877
5878                 ShortcutCommand.Create(Keys.I)
5879                     .FocusedOn(FocusedControl.ListTab)
5880                     .OnlyWhen(() => this.StatusText.Enabled)
5881                     .Do(() => this.StatusText.Focus()),
5882
5883                 ShortcutCommand.Create(Keys.Enter)
5884                     .FocusedOn(FocusedControl.ListTab)
5885                     .Do(() => this.MakeReplyOrDirectStatus()),
5886
5887                 ShortcutCommand.Create(Keys.R)
5888                     .FocusedOn(FocusedControl.ListTab)
5889                     .Do(() => this.DoRefresh()),
5890
5891                 ShortcutCommand.Create(Keys.L)
5892                     .FocusedOn(FocusedControl.ListTab)
5893                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5894
5895                 ShortcutCommand.Create(Keys.H)
5896                     .FocusedOn(FocusedControl.ListTab)
5897                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5898
5899                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5900                     .FocusedOn(FocusedControl.ListTab)
5901                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5902
5903                 ShortcutCommand.Create(Keys.S)
5904                     .FocusedOn(FocusedControl.ListTab)
5905                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5906
5907                 ShortcutCommand.Create(Keys.A)
5908                     .FocusedOn(FocusedControl.ListTab)
5909                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5910
5911                 // ] in_reply_to参照元へ戻る
5912                 ShortcutCommand.Create(Keys.Oem4)
5913                     .FocusedOn(FocusedControl.ListTab)
5914                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5915
5916                 // [ in_reply_toへジャンプ
5917                 ShortcutCommand.Create(Keys.Oem6)
5918                     .FocusedOn(FocusedControl.ListTab)
5919                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5920
5921                 ShortcutCommand.Create(Keys.Escape)
5922                     .FocusedOn(FocusedControl.ListTab)
5923                     .Do(() => {
5924                         this._anchorFlag = false;
5925                         if (ListTab.SelectedTab != null)
5926                         {
5927                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5928                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5929                             {
5930                                 var relTp = ListTab.SelectedTab;
5931                                 RemoveSpecifiedTab(relTp.Text, false);
5932                                 SaveConfigsTabs();
5933                             }
5934                         }
5935                     }),
5936
5937                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5938                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5939                     .FocusedOn(FocusedControl.ListTab)
5940                     .Do(() => this._anchorFlag = false, preventDefault: false),
5941
5942                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5943                 ShortcutCommand.Create(Keys.Up, Keys.Down)
5944                     .FocusedOn(FocusedControl.PostBrowser)
5945                     .Do(() => { }),
5946
5947                 ShortcutCommand.Create(Keys.Control | Keys.R)
5948                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5949
5950                 ShortcutCommand.Create(Keys.Control | Keys.D)
5951                     .Do(() => this.doStatusDelete()),
5952
5953                 ShortcutCommand.Create(Keys.Control | Keys.M)
5954                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5955
5956                 ShortcutCommand.Create(Keys.Control | Keys.S)
5957                     .Do(() => this.FavoriteChange(FavAdd: true)),
5958
5959                 ShortcutCommand.Create(Keys.Control | Keys.I)
5960                     .Do(() => this.doRepliedStatusOpen()),
5961
5962                 ShortcutCommand.Create(Keys.Control | Keys.Q)
5963                     .Do(() => this.doQuoteOfficial()),
5964
5965                 ShortcutCommand.Create(Keys.Control | Keys.B)
5966                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5967
5968                 ShortcutCommand.Create(Keys.Control | Keys.T)
5969                     .Do(() => this.HashManageMenuItem_Click(null, null)),
5970
5971                 ShortcutCommand.Create(Keys.Control | Keys.L)
5972                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5973
5974                 ShortcutCommand.Create(Keys.Control | Keys.Y)
5975                     .NotFocusedOn(FocusedControl.PostBrowser)
5976                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
5977
5978                 ShortcutCommand.Create(Keys.Control | Keys.F)
5979                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
5980
5981                 ShortcutCommand.Create(Keys.Control | Keys.U)
5982                     .Do(() => this.ShowUserTimeline()),
5983
5984                 ShortcutCommand.Create(Keys.Control | Keys.H)
5985                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5986
5987                 ShortcutCommand.Create(Keys.Control | Keys.G)
5988                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5989
5990                 ShortcutCommand.Create(Keys.Control | Keys.O)
5991                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5992
5993                 ShortcutCommand.Create(Keys.Control | Keys.E)
5994                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
5995
5996                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5997                     .FocusedOn(FocusedControl.ListTab)
5998                     .Do(() => this._colorize = true, preventDefault: false),
5999
6000                 ShortcutCommand.Create(Keys.Control | Keys.N)
6001                     .FocusedOn(FocusedControl.ListTab)
6002                     .Do(() => this.GoNextTab(forward: true)),
6003
6004                 ShortcutCommand.Create(Keys.Control | Keys.P)
6005                     .FocusedOn(FocusedControl.ListTab)
6006                     .Do(() => this.GoNextTab(forward: false)),
6007
6008                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6009                     .FocusedOn(FocusedControl.ListTab)
6010                     .Do(() => this.CopyStot()),
6011
6012                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6013                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6014                     .FocusedOn(FocusedControl.ListTab)
6015                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6016                     .Do(() => this.ListTab.SelectedIndex = 0),
6017
6018                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6019                     .FocusedOn(FocusedControl.ListTab)
6020                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6021                     .Do(() => this.ListTab.SelectedIndex = 1),
6022
6023                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6024                     .FocusedOn(FocusedControl.ListTab)
6025                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6026                     .Do(() => this.ListTab.SelectedIndex = 2),
6027
6028                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6029                     .FocusedOn(FocusedControl.ListTab)
6030                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6031                     .Do(() => this.ListTab.SelectedIndex = 3),
6032
6033                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6034                     .FocusedOn(FocusedControl.ListTab)
6035                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6036                     .Do(() => this.ListTab.SelectedIndex = 4),
6037
6038                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6039                     .FocusedOn(FocusedControl.ListTab)
6040                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6041                     .Do(() => this.ListTab.SelectedIndex = 5),
6042
6043                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6044                     .FocusedOn(FocusedControl.ListTab)
6045                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6046                     .Do(() => this.ListTab.SelectedIndex = 6),
6047
6048                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6049                     .FocusedOn(FocusedControl.ListTab)
6050                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6051                     .Do(() => this.ListTab.SelectedIndex = 7),
6052
6053                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6054                     .FocusedOn(FocusedControl.ListTab)
6055                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6056
6057                 ShortcutCommand.Create(Keys.Control | Keys.A)
6058                     .FocusedOn(FocusedControl.StatusText)
6059                     .Do(() => this.StatusText.SelectAll()),
6060
6061                 ShortcutCommand.Create(Keys.Control | Keys.V)
6062                     .FocusedOn(FocusedControl.StatusText)
6063                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6064
6065                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6066                     .FocusedOn(FocusedControl.StatusText)
6067                     .Do(() => {
6068                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6069                         {
6070                             var inReplyToStatusId = this.inReplyTo?.Item1;
6071                             var inReplyToScreenName = this.inReplyTo?.Item2;
6072                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6073                         }
6074                         _hisIdx -= 1;
6075                         if (_hisIdx < 0) _hisIdx = 0;
6076
6077                         var historyItem = this._history[this._hisIdx];
6078                         StatusText.Text = historyItem.status;
6079                         StatusText.SelectionStart = StatusText.Text.Length;
6080                         if (historyItem.inReplyToId != null)
6081                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6082                         else
6083                             this.inReplyTo = null;
6084                     }),
6085
6086                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6087                     .FocusedOn(FocusedControl.StatusText)
6088                     .Do(() => {
6089                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6090                         {
6091                             var inReplyToStatusId = this.inReplyTo?.Item1;
6092                             var inReplyToScreenName = this.inReplyTo?.Item2;
6093                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6094                         }
6095                         _hisIdx += 1;
6096                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6097
6098                         var historyItem = this._history[this._hisIdx];
6099                         StatusText.Text = historyItem.status;
6100                         StatusText.SelectionStart = StatusText.Text.Length;
6101                         if (historyItem.inReplyToId != null)
6102                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6103                         else
6104                             this.inReplyTo = null;
6105                     }),
6106
6107                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6108                     .FocusedOn(FocusedControl.StatusText)
6109                     .Do(() => {
6110                         if (ListTab.SelectedIndex == 0)
6111                         {
6112                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6113                         }
6114                         else
6115                         {
6116                             ListTab.SelectedIndex -= 1;
6117                         }
6118                         StatusText.Focus();
6119                     }),
6120
6121                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6122                     .FocusedOn(FocusedControl.StatusText)
6123                     .Do(() => {
6124                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6125                         {
6126                             ListTab.SelectedIndex = 0;
6127                         }
6128                         else
6129                         {
6130                             ListTab.SelectedIndex += 1;
6131                         }
6132                         StatusText.Focus();
6133                     }),
6134
6135                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6136                     .FocusedOn(FocusedControl.PostBrowser)
6137                     .Do(() => {
6138                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6139                         MultiLineMenuItem_Click(null, null);
6140                     }),
6141
6142                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6143                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6144
6145                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6146                     .Do(() => this.DoRefreshMore()),
6147
6148                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6149                     .Do(() => this.GetReplyAsync(loadMore: true)),
6150
6151                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6152                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6153
6154                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6155                     .NotFocusedOn(FocusedControl.StatusText)
6156                     .Do(() => this.DoRefreshMore()),
6157
6158                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6159                     .FocusedOn(FocusedControl.ListTab)
6160                     .Do(() => this.GoTopEnd(GoTop: true)),
6161
6162                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6163                     .FocusedOn(FocusedControl.ListTab)
6164                     .Do(() => this.GoTopEnd(GoTop: false)),
6165
6166                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6167                     .FocusedOn(FocusedControl.ListTab)
6168                     .Do(() => this.GoMiddle()),
6169
6170                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6171                     .FocusedOn(FocusedControl.ListTab)
6172                     .Do(() => this.GoLast()),
6173
6174                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6175                     .FocusedOn(FocusedControl.ListTab)
6176                     .Do(() => this.MoveMiddle()),
6177
6178                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6179                     .FocusedOn(FocusedControl.ListTab)
6180                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6181
6182                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6183                     .FocusedOn(FocusedControl.ListTab)
6184                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6185
6186                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6187                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6188                     .FocusedOn(FocusedControl.ListTab)
6189                     .Do(() => this.GoFav(forward: true)),
6190
6191                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6192                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6193                     .FocusedOn(FocusedControl.ListTab)
6194                     .Do(() => this.GoFav(forward: false)),
6195
6196                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6197                     .FocusedOn(FocusedControl.ListTab)
6198                     .Do(() => this.GoBackSelectPostChain()),
6199
6200                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6201                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6202
6203                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6204                     .OnlyWhen(() => this._curPost != null)
6205                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6206
6207                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6208                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6209
6210                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6211                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6212
6213                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6214                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6215
6216                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6217                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6218
6219                 // 別タブの同じ書き込みへ(ALT+←/→)
6220                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6221                     .FocusedOn(FocusedControl.ListTab)
6222                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6223
6224                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6225                     .FocusedOn(FocusedControl.ListTab)
6226                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6227
6228                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6229                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6230
6231                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6232                     .Do(() => this.CopyIdUri()),
6233
6234                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6235                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6236                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6237                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6238
6239                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6240                     .Do(() => this.FavoriteChange(FavAdd: false)),
6241
6242                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6243                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6244
6245                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6246                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6247
6248                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6249                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6250
6251                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6252                     .Do(() => this.doMoveToRTHome()),
6253
6254                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6255                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6256
6257                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6258                     .FocusedOn(FocusedControl.StatusText)
6259                     .Do(() => {
6260                         if (_curList != null && _curList.VirtualListSize != 0 &&
6261                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6262                         {
6263                             var idx = _curList.SelectedIndices[0] - 1;
6264                             SelectListItem(_curList, idx);
6265                             _curList.EnsureVisible(idx);
6266                         }
6267                     }),
6268
6269                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6270                     .FocusedOn(FocusedControl.StatusText)
6271                     .Do(() => {
6272                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6273                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6274                         {
6275                             var idx = _curList.SelectedIndices[0] + 1;
6276                             SelectListItem(_curList, idx);
6277                             _curList.EnsureVisible(idx);
6278                         }
6279                     }),
6280
6281                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6282                     .FocusedOn(FocusedControl.StatusText)
6283                     .Do(() => {
6284                         if (StatusText.SelectionStart > 0)
6285                         {
6286                             int endidx = StatusText.SelectionStart - 1;
6287                             string startstr = "";
6288                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6289                             {
6290                                 char c = StatusText.Text[i];
6291                                 if (Char.IsLetterOrDigit(c) || c == '_')
6292                                 {
6293                                     continue;
6294                                 }
6295                                 if (c == '@')
6296                                 {
6297                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6298                                     int cnt = AtIdSupl.ItemCount;
6299                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6300                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6301                                 }
6302                                 else if (c == '#')
6303                                 {
6304                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6305                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6306                                 }
6307                                 else
6308                                 {
6309                                     break;
6310                                 }
6311                             }
6312                         }
6313                     }),
6314
6315                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6316                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6317                     .FocusedOn(FocusedControl.ListTab)
6318                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6319
6320                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6321                     .FocusedOn(FocusedControl.ListTab)
6322                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
6323
6324                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6325                     .FocusedOn(FocusedControl.ListTab)
6326                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
6327
6328                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6329                     .FocusedOn(FocusedControl.ListTab)
6330                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
6331
6332                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6333                     .FocusedOn(FocusedControl.ListTab)
6334                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
6335
6336                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6337                     .FocusedOn(FocusedControl.ListTab)
6338                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
6339
6340                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6341                     .FocusedOn(FocusedControl.ListTab)
6342                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
6343
6344                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6345                     .FocusedOn(FocusedControl.ListTab)
6346                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
6347
6348                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6349                     .FocusedOn(FocusedControl.ListTab)
6350                     .Do(() => this.SetSortLastColumn()),
6351
6352                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6353                     .Do(() => this.FavoritesRetweetOfficial()),
6354
6355                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6356                     .Do(() => this.FavoritesRetweetUnofficial()),
6357
6358                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6359                     .Do(() => this.OpenUserAppointUrl()),
6360
6361                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6362                     .FocusedOn(FocusedControl.PostBrowser)
6363                     .Do(() => this.doReTweetUnofficial()),
6364
6365                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6366                     .OnlyWhen(() => this.ExistCurrentPost)
6367                     .Do(() => this.tweetDetailsView.DoTranslation()),
6368
6369                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6370                     .Do(() => this.doReTweetUnofficial()),
6371
6372                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6373                     .Do(() => this.CopyUserId()),
6374
6375                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6376                     .Do(() => this.tweetThumbnail1.ScrollUp()),
6377
6378                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6379                     .Do(() => this.tweetThumbnail1.ScrollDown()),
6380
6381                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6382                     .FocusedOn(FocusedControl.ListTab)
6383                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6384                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6385             };
6386         }
6387
6388         internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6389         {
6390             // Task を返す非同期処理があれば asyncTask に代入する
6391             asyncTask = null;
6392
6393             // ShortcutCommand に対応しているコマンドはここで処理される
6394             foreach (var command in this.shortcutCommands)
6395             {
6396                 if (command.IsMatch(keyData, focusedOn))
6397                 {
6398                     asyncTask = command.RunCommand();
6399                     return command.PreventDefault;
6400                 }
6401             }
6402
6403             return false;
6404         }
6405
6406         private void GoNextTab(bool forward)
6407         {
6408             int idx = ListTab.SelectedIndex;
6409             if (forward)
6410             {
6411                 idx += 1;
6412                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6413             }
6414             else
6415             {
6416                 idx -= 1;
6417                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6418             }
6419             ListTab.SelectedIndex = idx;
6420         }
6421
6422         private void CopyStot()
6423         {
6424             string clstr = "";
6425             StringBuilder sb = new StringBuilder();
6426             bool IsProtected = false;
6427             bool isDm = false;
6428             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6429             foreach (int idx in _curList.SelectedIndices)
6430             {
6431                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6432                 if (post.IsDeleted) continue;
6433                 if (!isDm)
6434                 {
6435                     if (post.RetweetedId != null)
6436                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6437                     else
6438                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6439                 }
6440                 else
6441                 {
6442                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6443                 }
6444             }
6445             if (IsProtected)
6446             {
6447                 MessageBox.Show(Properties.Resources.CopyStotText1);
6448             }
6449             if (sb.Length > 0)
6450             {
6451                 clstr = sb.ToString();
6452                 try
6453                 {
6454                     Clipboard.SetDataObject(clstr, false, 5, 100);
6455                 }
6456                 catch (Exception ex)
6457                 {
6458                     MessageBox.Show(ex.Message);
6459                 }
6460             }
6461         }
6462
6463         private void CopyIdUri()
6464         {
6465             if (this._curTab == null)
6466                 return;
6467
6468             var tab = this._statuses.GetTabByName(this._curTab.Text);
6469             if (tab == null || tab is DirectMessagesTabModel)
6470                 return;
6471
6472             var copyUrls = new List<string>();
6473             foreach (int idx in _curList.SelectedIndices)
6474             {
6475                 var post = tab[idx];
6476                 copyUrls.Add(MyCommon.GetStatusUrl(post));
6477             }
6478
6479             if (copyUrls.Count == 0)
6480                 return;
6481
6482             try
6483             {
6484                 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6485             }
6486             catch (ExternalException ex)
6487             {
6488                 MessageBox.Show(ex.Message);
6489             }
6490         }
6491
6492         private void GoFav(bool forward)
6493         {
6494             if (_curList.VirtualListSize == 0) return;
6495             int fIdx = 0;
6496             int toIdx = 0;
6497             int stp = 1;
6498
6499             if (forward)
6500             {
6501                 if (_curList.SelectedIndices.Count == 0)
6502                 {
6503                     fIdx = 0;
6504                 }
6505                 else
6506                 {
6507                     fIdx = _curList.SelectedIndices[0] + 1;
6508                     if (fIdx > _curList.VirtualListSize - 1) return;
6509                 }
6510                 toIdx = _curList.VirtualListSize;
6511                 stp = 1;
6512             }
6513             else
6514             {
6515                 if (_curList.SelectedIndices.Count == 0)
6516                 {
6517                     fIdx = _curList.VirtualListSize - 1;
6518                 }
6519                 else
6520                 {
6521                     fIdx = _curList.SelectedIndices[0] - 1;
6522                     if (fIdx < 0) return;
6523                 }
6524                 toIdx = -1;
6525                 stp = -1;
6526             }
6527
6528             for (int idx = fIdx; idx != toIdx; idx += stp)
6529             {
6530                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6531                 {
6532                     SelectListItem(_curList, idx);
6533                     _curList.EnsureVisible(idx);
6534                     break;
6535                 }
6536             }
6537         }
6538
6539         private void GoSamePostToAnotherTab(bool left)
6540         {
6541             if (this._curList.SelectedIndices.Count == 0)
6542                 return;
6543
6544             var tab = this._statuses.Tabs[this._curTab.Text];
6545
6546             // Directタブは対象外(見つかるはずがない)
6547             if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6548                 return;
6549
6550             var selectedIndex = this._curList.SelectedIndices[0];
6551             var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6552
6553             int fIdx, toIdx, stp;
6554
6555             if (left)
6556             {
6557                 // 左のタブへ
6558                 if (ListTab.SelectedIndex == 0)
6559                 {
6560                     return;
6561                 }
6562                 else
6563                 {
6564                     fIdx = ListTab.SelectedIndex - 1;
6565                 }
6566                 toIdx = -1;
6567                 stp = -1;
6568             }
6569             else
6570             {
6571                 // 右のタブへ
6572                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6573                 {
6574                     return;
6575                 }
6576                 else
6577                 {
6578                     fIdx = ListTab.SelectedIndex + 1;
6579                 }
6580                 toIdx = ListTab.TabCount;
6581                 stp = 1;
6582             }
6583
6584             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6585             {
6586                 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6587
6588                 // Directタブは対象外
6589                 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6590                     continue;
6591
6592                 var foundIndex = targetTab.IndexOf(selectedStatusId);
6593                 if (foundIndex != -1)
6594                 {
6595                     ListTab.SelectedIndex = tabidx;
6596                     SelectListItem(_curList, foundIndex);
6597                     _curList.EnsureVisible(foundIndex);
6598                     return;
6599                 }
6600             }
6601         }
6602
6603         private void GoPost(bool forward)
6604         {
6605             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6606                 return;
6607
6608             var tab = this._statuses.Tabs[this._curTab.Text];
6609             var selectedIndex = this._curList.SelectedIndices[0];
6610
6611             int fIdx, toIdx, stp;
6612
6613             if (forward)
6614             {
6615                 fIdx = selectedIndex + 1;
6616                 if (fIdx > tab.AllCount - 1) return;
6617                 toIdx = tab.AllCount;
6618                 stp = 1;
6619             }
6620             else
6621             {
6622                 fIdx = selectedIndex - 1;
6623                 if (fIdx < 0) return;
6624                 toIdx = -1;
6625                 stp = -1;
6626             }
6627
6628             string name = "";
6629             if (_curPost.RetweetedId == null)
6630             {
6631                 name = _curPost.ScreenName;
6632             }
6633             else
6634             {
6635                 name = _curPost.RetweetedBy;
6636             }
6637             for (int idx = fIdx; idx != toIdx; idx += stp)
6638             {
6639                 var post = tab[idx];
6640                 if (post.RetweetedId == null)
6641                 {
6642                     if (post.ScreenName == name)
6643                     {
6644                         SelectListItem(_curList, idx);
6645                         _curList.EnsureVisible(idx);
6646                         break;
6647                     }
6648                 }
6649                 else
6650                 {
6651                     if (post.RetweetedBy == name)
6652                     {
6653                         SelectListItem(_curList, idx);
6654                         _curList.EnsureVisible(idx);
6655                         break;
6656                     }
6657                 }
6658             }
6659         }
6660
6661         private void GoRelPost(bool forward)
6662         {
6663             if (this._curList.SelectedIndices.Count == 0)
6664                 return;
6665
6666             var tab = this._statuses.Tabs[this._curTab.Text];
6667             var selectedIndex = this._curList.SelectedIndices[0];
6668
6669             int fIdx, toIdx, stp;
6670
6671             if (forward)
6672             {
6673                 fIdx = selectedIndex + 1;
6674                 if (fIdx > tab.AllCount - 1) return;
6675                 toIdx = tab.AllCount;
6676                 stp = 1;
6677             }
6678             else
6679             {
6680                 fIdx = selectedIndex - 1;
6681                 if (fIdx < 0) return;
6682                 toIdx = -1;
6683                 stp = -1;
6684             }
6685
6686             if (!_anchorFlag)
6687             {
6688                 if (_curPost == null) return;
6689                 _anchorPost = _curPost;
6690                 _anchorFlag = true;
6691             }
6692             else
6693             {
6694                 if (_anchorPost == null) return;
6695             }
6696
6697             for (int idx = fIdx; idx != toIdx; idx += stp)
6698             {
6699                 var post = tab[idx];
6700                 if (post.ScreenName == _anchorPost.ScreenName ||
6701                     post.RetweetedBy == _anchorPost.ScreenName ||
6702                     post.ScreenName == _anchorPost.RetweetedBy ||
6703                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6704                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6705                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6706                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6707                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6708                 {
6709                     SelectListItem(_curList, idx);
6710                     _curList.EnsureVisible(idx);
6711                     break;
6712                 }
6713             }
6714         }
6715
6716         private void GoAnchor()
6717         {
6718             if (_anchorPost == null) return;
6719             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6720             if (idx == -1) return;
6721
6722             SelectListItem(_curList, idx);
6723             _curList.EnsureVisible(idx);
6724         }
6725
6726         private void GoTopEnd(bool GoTop)
6727         {
6728             if (_curList.VirtualListSize == 0)
6729                 return;
6730
6731             ListViewItem _item;
6732             int idx;
6733
6734             if (GoTop)
6735             {
6736                 _item = _curList.GetItemAt(0, 25);
6737                 if (_item == null)
6738                     idx = 0;
6739                 else
6740                     idx = _item.Index;
6741             }
6742             else
6743             {
6744                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6745                 if (_item == null)
6746                     idx = _curList.VirtualListSize - 1;
6747                 else
6748                     idx = _item.Index;
6749             }
6750             SelectListItem(_curList, idx);
6751         }
6752
6753         private void GoMiddle()
6754         {
6755             if (_curList.VirtualListSize == 0)
6756                 return;
6757
6758             ListViewItem _item;
6759             int idx1;
6760             int idx2;
6761             int idx3;
6762
6763             _item = _curList.GetItemAt(0, 0);
6764             if (_item == null)
6765             {
6766                 idx1 = 0;
6767             }
6768             else
6769             {
6770                 idx1 = _item.Index;
6771             }
6772
6773             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6774             if (_item == null)
6775             {
6776                 idx2 = _curList.VirtualListSize - 1;
6777             }
6778             else
6779             {
6780                 idx2 = _item.Index;
6781             }
6782             idx3 = (idx1 + idx2) / 2;
6783
6784             SelectListItem(_curList, idx3);
6785         }
6786
6787         private void GoLast()
6788         {
6789             if (_curList.VirtualListSize == 0) return;
6790
6791             if (_statuses.SortOrder == SortOrder.Ascending)
6792             {
6793                 SelectListItem(_curList, _curList.VirtualListSize - 1);
6794                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6795             }
6796             else
6797             {
6798                 SelectListItem(_curList, 0);
6799                 _curList.EnsureVisible(0);
6800             }
6801         }
6802
6803         private void MoveTop()
6804         {
6805             if (_curList.SelectedIndices.Count == 0) return;
6806             int idx = _curList.SelectedIndices[0];
6807             if (_statuses.SortOrder == SortOrder.Ascending)
6808             {
6809                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6810             }
6811             else
6812             {
6813                 _curList.EnsureVisible(0);
6814             }
6815             _curList.EnsureVisible(idx);
6816         }
6817
6818         private async Task GoInReplyToPostTree()
6819         {
6820             if (_curPost == null) return;
6821
6822             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6823
6824             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6825             {
6826                 try
6827                 {
6828                     var post = await tw.GetStatusApi(false, _curPost.StatusId);
6829
6830                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
6831                     _curPost.InReplyToUser = post.InReplyToUser;
6832                     _curPost.IsReply = post.IsReply;
6833                     this.PurgeListViewItemCache();
6834                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6835                 }
6836                 catch (WebApiException ex)
6837                 {
6838                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6839                 }
6840             }
6841
6842             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6843
6844             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6845             {
6846                 replyChains = new Stack<ReplyChain>();
6847             }
6848             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6849
6850             int inReplyToIndex;
6851             string inReplyToTabName;
6852             long inReplyToId = _curPost.InReplyToStatusId.Value;
6853             string inReplyToUser = _curPost.InReplyToUser;
6854             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6855
6856             var inReplyToPosts = from tab in _statuses.Tabs.Values
6857                                  orderby tab != curTabClass
6858                                  from post in tab.Posts.Values
6859                                  where post.StatusId == inReplyToId
6860                                  let index = tab.IndexOf(post.StatusId)
6861                                  where index != -1
6862                                  select new {Tab = tab, Index = index};
6863
6864             var inReplyPost = inReplyToPosts.FirstOrDefault();
6865             if (inReplyPost == null)
6866             {
6867                 try
6868                 {
6869                     await Task.Run(async () =>
6870                     {
6871                         var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6872                             .ConfigureAwait(false);
6873                         post.IsRead = true;
6874
6875                         _statuses.AddPost(post);
6876                         _statuses.DistributePosts();
6877                     });
6878                 }
6879                 catch (WebApiException ex)
6880                 {
6881                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6882                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6883                     return;
6884                 }
6885
6886                 this.RefreshTimeline();
6887
6888                 inReplyPost = inReplyToPosts.FirstOrDefault();
6889                 if (inReplyPost == null)
6890                 {
6891                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6892                     return;
6893                 }
6894             }
6895             inReplyToTabName = inReplyPost.Tab.TabName;
6896             inReplyToIndex = inReplyPost.Index;
6897
6898             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6899             DetailsListView listView = (DetailsListView)tabPage.Tag;
6900
6901             if (_curTab != tabPage)
6902             {
6903                 this.ListTab.SelectTab(tabPage);
6904             }
6905
6906             this.SelectListItem(listView, inReplyToIndex);
6907             listView.EnsureVisible(inReplyToIndex);
6908         }
6909
6910         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6911         {
6912             if (_curPost == null) return;
6913
6914             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6915             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6916
6917             if (parallel)
6918             {
6919                 if (_curPost.InReplyToStatusId != null)
6920                 {
6921                     var posts = from t in _statuses.Tabs
6922                                 from p in t.Value.Posts
6923                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6924                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6925                                 where indexOf > -1
6926                                 orderby isForward ? indexOf : indexOf * -1
6927                                 orderby t.Value != curTabClass
6928                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6929                     try
6930                     {
6931                         var postList = posts.ToList();
6932                         for (int i = postList.Count - 1; i >= 0; i--)
6933                         {
6934                             int index = i;
6935                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6936                             {
6937                                 postList.RemoveAt(index);
6938                             }
6939                         }
6940                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6941                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6942                         if (post == null) post = postList.First();
6943                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6944                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6945                         SelectListItem(listView, post.Index);
6946                         listView.EnsureVisible(post.Index);
6947                     }
6948                     catch (InvalidOperationException)
6949                     {
6950                         return;
6951                     }
6952                 }
6953             }
6954             else
6955             {
6956                 if (replyChains == null || replyChains.Count < 1)
6957                 {
6958                     var posts = from t in _statuses.Tabs
6959                                 from p in t.Value.Posts
6960                                 where p.Value.InReplyToStatusId == _curPost.StatusId
6961                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6962                                 where indexOf > -1
6963                                 orderby indexOf
6964                                 orderby t.Value != curTabClass
6965                                 select new {Tab = t.Value, Index = indexOf};
6966                     try
6967                     {
6968                         var post = posts.First();
6969                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6970                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6971                         SelectListItem(listView, post.Index);
6972                         listView.EnsureVisible(post.Index);
6973                     }
6974                     catch (InvalidOperationException)
6975                     {
6976                         return;
6977                     }
6978                 }
6979                 else
6980                 {
6981                     ReplyChain chainHead = replyChains.Pop();
6982                     if (chainHead.InReplyToId == _curPost.StatusId)
6983                     {
6984                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6985                         if (idx == -1)
6986                         {
6987                             replyChains = null;
6988                         }
6989                         else
6990                         {
6991                             try
6992                             {
6993                                 ListTab.SelectTab(chainHead.OriginalTab);
6994                             }
6995                             catch (Exception)
6996                             {
6997                                 replyChains = null;
6998                             }
6999                             SelectListItem(_curList, idx);
7000                             _curList.EnsureVisible(idx);
7001                         }
7002                     }
7003                     else
7004                     {
7005                         replyChains = null;
7006                         this.GoBackInReplyToPostTree(parallel);
7007                     }
7008                 }
7009             }
7010         }
7011
7012         private void GoBackSelectPostChain()
7013         {
7014             if (this.selectPostChains.Count > 1)
7015             {
7016                 var idx = -1;
7017                 TabPage tp = null;
7018
7019                 do
7020                 {
7021                     try
7022                     {
7023                         this.selectPostChains.Pop();
7024                         var tabPostPair = this.selectPostChains.Peek();
7025
7026                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7027
7028                         if (tabPostPair.Item2 != null)
7029                         {
7030                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7031                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7032                         }
7033
7034                         tp = tabPostPair.Item1;
7035
7036                         this.selectPostChains.Pop();
7037                     }
7038                     catch (InvalidOperationException)
7039                     {
7040                     }
7041
7042                     break;
7043                 }
7044                 while (this.selectPostChains.Count > 1);
7045
7046                 if (tp == null)
7047                 {
7048                     //状態がおかしいので処理を中断
7049                     //履歴が残り1つであればクリアしておく
7050                     if (this.selectPostChains.Count == 1)
7051                         this.selectPostChains.Clear();
7052                     return;
7053                 }
7054
7055                 DetailsListView lst = (DetailsListView)tp.Tag;
7056                 this.ListTab.SelectedTab = tp;
7057                 if (idx > -1)
7058                 {
7059                     SelectListItem(lst, idx);
7060                     lst.EnsureVisible(idx);
7061                 }
7062                 lst.Focus();
7063             }
7064         }
7065
7066         private void PushSelectPostChain()
7067         {
7068             int count = this.selectPostChains.Count;
7069             if (count > 0)
7070             {
7071                 var p = this.selectPostChains.Peek();
7072                 if (p.Item1 == this._curTab)
7073                 {
7074                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7075                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7076                 }
7077             }
7078             if (count >= 2500) TrimPostChain();
7079             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7080         }
7081
7082         private void TrimPostChain()
7083         {
7084             if (this.selectPostChains.Count <= 2000) return;
7085             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7086             for (int i = 0; i < 2000; i++)
7087             {
7088                 p.Push(this.selectPostChains.Pop());
7089             }
7090             this.selectPostChains.Clear();
7091             for (int i = 0; i < 2000; i++)
7092             {
7093                 this.selectPostChains.Push(p.Pop());
7094             }
7095         }
7096
7097         private bool GoStatus(long statusId)
7098         {
7099             if (statusId == 0) return false;
7100             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7101             {
7102                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7103                 {
7104                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7105                     ListTab.SelectedIndex = tabidx;
7106                     SelectListItem(_curList, idx);
7107                     _curList.EnsureVisible(idx);
7108                     return true;
7109                 }
7110             }
7111             return false;
7112         }
7113
7114         private bool GoDirectMessage(long statusId)
7115         {
7116             if (statusId == 0) return false;
7117             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7118             {
7119                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7120                 {
7121                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7122                     ListTab.SelectedIndex = tabidx;
7123                     SelectListItem(_curList, idx);
7124                     _curList.EnsureVisible(idx);
7125                     return true;
7126                 }
7127             }
7128             return false;
7129         }
7130
7131         private void MyList_MouseClick(object sender, MouseEventArgs e)
7132         {
7133             _anchorFlag = false;
7134         }
7135
7136         private void StatusText_Enter(object sender, EventArgs e)
7137         {
7138             // フォーカスの戻り先を StatusText に設定
7139             this.Tag = StatusText;
7140             StatusText.BackColor = _clInputBackcolor;
7141         }
7142
7143         public Color InputBackColor
7144         {
7145             get { return _clInputBackcolor; }
7146             set { _clInputBackcolor = value; }
7147         }
7148
7149         private void StatusText_Leave(object sender, EventArgs e)
7150         {
7151             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7152             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7153             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7154         }
7155
7156         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7157         {
7158             Task asyncTask;
7159             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7160             {
7161                 e.Handled = true;
7162                 e.SuppressKeyPress = true;
7163             }
7164
7165             this.StatusText_TextChanged(null, null);
7166
7167             if (asyncTask != null)
7168                 await asyncTask;
7169         }
7170
7171         private void SaveConfigsAll(bool ifModified)
7172         {
7173             if (!ifModified)
7174             {
7175                 SaveConfigsCommon();
7176                 SaveConfigsLocal();
7177                 SaveConfigsTabs();
7178                 SaveConfigsAtId();
7179             }
7180             else
7181             {
7182                 if (ModifySettingCommon) SaveConfigsCommon();
7183                 if (ModifySettingLocal) SaveConfigsLocal();
7184                 if (ModifySettingAtId) SaveConfigsAtId();
7185             }
7186         }
7187
7188         private void SaveConfigsAtId()
7189         {
7190             if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7191
7192             ModifySettingAtId = false;
7193             SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7194             SettingManager.SaveAtIdList();
7195         }
7196
7197         private void SaveConfigsCommon()
7198         {
7199             if (_ignoreConfigSave) return;
7200
7201             ModifySettingCommon = false;
7202             lock (_syncObject)
7203             {
7204                 SettingManager.Common.UserName = tw.Username;
7205                 SettingManager.Common.UserId = tw.UserId;
7206                 SettingManager.Common.Token = tw.AccessToken;
7207                 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7208
7209                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7210                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7211                 {
7212                     SettingManager.Common.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7213                 }
7214
7215                 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7216                 switch (_statuses.SortMode)
7217                 {
7218                     case ComparerMode.Nickname:  //ニックネーム
7219                         SettingManager.Common.SortColumn = 1;
7220                         break;
7221                     case ComparerMode.Data:  //本文
7222                         SettingManager.Common.SortColumn = 2;
7223                         break;
7224                     case ComparerMode.Id:  //時刻=発言Id
7225                         SettingManager.Common.SortColumn = 3;
7226                         break;
7227                     case ComparerMode.Name:  //名前
7228                         SettingManager.Common.SortColumn = 4;
7229                         break;
7230                     case ComparerMode.Source:  //Source
7231                         SettingManager.Common.SortColumn = 7;
7232                         break;
7233                 }
7234
7235                 SettingManager.Common.HashTags = HashMgr.HashHistories;
7236                 if (HashMgr.IsPermanent)
7237                 {
7238                     SettingManager.Common.HashSelected = HashMgr.UseHash;
7239                 }
7240                 else
7241                 {
7242                     SettingManager.Common.HashSelected = "";
7243                 }
7244                 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7245                 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7246                 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7247                 if (ToolStripFocusLockMenuItem != null &&
7248                         ToolStripFocusLockMenuItem.IsDisposed == false)
7249                 {
7250                     SettingManager.Common.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7251                 }
7252                 SettingManager.Common.TrackWord = tw.TrackWord;
7253                 SettingManager.Common.AllAtReply = tw.AllAtReply;
7254                 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7255                 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7256
7257                 SettingManager.SaveCommon();
7258             }
7259         }
7260
7261         private void SaveConfigsLocal()
7262         {
7263             if (_ignoreConfigSave) return;
7264             lock (_syncObject)
7265             {
7266                 ModifySettingLocal = false;
7267                 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7268                 SettingManager.Local.FormSize = _mySize;
7269                 SettingManager.Local.FormLocation = _myLoc;
7270                 SettingManager.Local.SplitterDistance = _mySpDis;
7271                 SettingManager.Local.PreviewDistance = _mySpDis3;
7272                 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7273                 SettingManager.Local.StatusTextHeight = _mySpDis2;
7274
7275                 SettingManager.Local.FontUnread = _fntUnread;
7276                 SettingManager.Local.ColorUnread = _clUnread;
7277                 SettingManager.Local.FontRead = _fntReaded;
7278                 SettingManager.Local.ColorRead = _clReaded;
7279                 SettingManager.Local.FontDetail = _fntDetail;
7280                 SettingManager.Local.ColorDetail = _clDetail;
7281                 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7282                 SettingManager.Local.ColorDetailLink = _clDetailLink;
7283                 SettingManager.Local.ColorFav = _clFav;
7284                 SettingManager.Local.ColorOWL = _clOWL;
7285                 SettingManager.Local.ColorRetweet = _clRetweet;
7286                 SettingManager.Local.ColorSelf = _clSelf;
7287                 SettingManager.Local.ColorAtSelf = _clAtSelf;
7288                 SettingManager.Local.ColorTarget = _clTarget;
7289                 SettingManager.Local.ColorAtTarget = _clAtTarget;
7290                 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7291                 SettingManager.Local.ColorAtTo = _clAtTo;
7292                 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7293                 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7294                 SettingManager.Local.ColorInputFont = _clInputFont;
7295                 SettingManager.Local.FontInputFont = _fntInputFont;
7296
7297                 if (_ignoreConfigSave) return;
7298                 SettingManager.SaveLocal();
7299             }
7300         }
7301
7302         private void SaveConfigsTabs()
7303         {
7304             var tabSettingList = new List<SettingTabs.SettingTabItem>();
7305
7306             var tabs = this.ListTab.TabPages.Cast<TabPage>()
7307                 .Select(x => this._statuses.Tabs[x.Text])
7308                 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7309
7310             foreach (var tab in tabs)
7311             {
7312                 if (!tab.IsPermanentTabType)
7313                     continue;
7314
7315                 var tabSetting = new SettingTabs.SettingTabItem
7316                 {
7317                     TabName = tab.TabName,
7318                     TabType = tab.TabType,
7319                     UnreadManage = tab.UnreadManage,
7320                     Protected = tab.Protected,
7321                     Notify = tab.Notify,
7322                     SoundFile = tab.SoundFile,
7323                 };
7324
7325                 var filterTab = tab as FilterTabModel;
7326                 if (filterTab != null)
7327                     tabSetting.FilterArray = filterTab.FilterArray;
7328
7329                 var userTab = tab as UserTimelineTabModel;
7330                 if (userTab != null)
7331                     tabSetting.User = userTab.ScreenName;
7332
7333                 var searchTab = tab as PublicSearchTabModel;
7334                 if (searchTab != null)
7335                 {
7336                     tabSetting.SearchWords = searchTab.SearchWords;
7337                     tabSetting.SearchLang = searchTab.SearchLang;
7338                 }
7339
7340                 var listTab = tab as ListTimelineTabModel;
7341                 if (listTab != null)
7342                     tabSetting.ListInfo = listTab.ListInfo;
7343
7344                 tabSettingList.Add(tabSetting);
7345             }
7346
7347             SettingManager.Tabs.Tabs = tabSettingList;
7348             SettingManager.SaveTabs();
7349         }
7350
7351         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7352         {
7353             string inputText;
7354             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7355             if (ret != DialogResult.OK)
7356                 return;
7357
7358             var match = Twitter.StatusUrlRegex.Match(inputText);
7359             if (!match.Success)
7360             {
7361                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7362                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7363                 return;
7364             }
7365
7366             try
7367             {
7368                 var statusId = long.Parse(match.Groups["StatusId"].Value);
7369                 await this.OpenRelatedTab(statusId);
7370             }
7371             catch (TabException ex)
7372             {
7373                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7374             }
7375         }
7376
7377         private void SaveLogMenuItem_Click(object sender, EventArgs e)
7378         {
7379             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7380                     Properties.Resources.SaveLogMenuItem_ClickText2,
7381                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7382             if (rslt == DialogResult.Cancel) return;
7383
7384             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7385             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7386             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7387             SaveFileDialog1.FilterIndex = 0;
7388             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7389             SaveFileDialog1.RestoreDirectory = true;
7390
7391             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7392             {
7393                 if (!SaveFileDialog1.ValidateNames) return;
7394                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7395                 {
7396                     if (rslt == DialogResult.Yes)
7397                     {
7398                         //All
7399                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7400                         {
7401                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402                             string protect = "";
7403                             if (post.IsProtect) protect = "Protect";
7404                             sw.WriteLine(post.Nickname + "\t" +
7405                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7406                                      post.CreatedAt + "\t" +
7407                                      post.ScreenName + "\t" +
7408                                      post.StatusId + "\t" +
7409                                      post.ImageUrl + "\t" +
7410                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7411                                      protect);
7412                         }
7413                     }
7414                     else
7415                     {
7416                         foreach (int idx in _curList.SelectedIndices)
7417                         {
7418                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
7419                             string protect = "";
7420                             if (post.IsProtect) protect = "Protect";
7421                             sw.WriteLine(post.Nickname + "\t" +
7422                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7423                                      post.CreatedAt + "\t" +
7424                                      post.ScreenName + "\t" +
7425                                      post.StatusId + "\t" +
7426                                      post.ImageUrl + "\t" +
7427                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7428                                      protect);
7429                         }
7430                     }
7431                 }
7432             }
7433             this.TopMost = SettingManager.Common.AlwaysTop;
7434         }
7435
7436         public bool TabRename(string origTabName, out string newTabName)
7437         {
7438             //タブ名変更
7439             newTabName = null;
7440             using (InputTabName inputName = new InputTabName())
7441             {
7442                 inputName.TabName = origTabName;
7443                 inputName.ShowDialog();
7444                 if (inputName.DialogResult == DialogResult.Cancel) return false;
7445                 newTabName = inputName.TabName;
7446             }
7447             this.TopMost = SettingManager.Common.AlwaysTop;
7448             if (!string.IsNullOrEmpty(newTabName))
7449             {
7450                 //新タブ名存在チェック
7451                 for (int i = 0; i < ListTab.TabCount; i++)
7452                 {
7453                     if (ListTab.TabPages[i].Text == newTabName)
7454                     {
7455                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7456                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7457                         return false;
7458                     }
7459                 }
7460
7461                 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7462                     .FirstOrDefault(x => x.Text == origTabName);
7463
7464                 // タブ名を変更
7465                 if (tabPage != null)
7466                     tabPage.Text = newTabName;
7467
7468                 _statuses.RenameTab(origTabName, newTabName);
7469
7470                 SaveConfigsCommon();
7471                 SaveConfigsTabs();
7472                 _rclickTabName = newTabName;
7473                 return true;
7474             }
7475             else
7476             {
7477                 return false;
7478             }
7479         }
7480
7481         private void ListTab_MouseClick(object sender, MouseEventArgs e)
7482         {
7483             if (e.Button == MouseButtons.Middle)
7484             {
7485                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7486                 {
7487                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
7488                     {
7489                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7490                         this.SaveConfigsTabs();
7491                         break;
7492                     }
7493                 }
7494             }
7495         }
7496
7497         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7498         {
7499             string _;
7500             TabRename(this.ListTab.SelectedTab.Text, out _);
7501         }
7502
7503         private void ListTab_MouseDown(object sender, MouseEventArgs e)
7504         {
7505             if (SettingManager.Common.TabMouseLock) return;
7506             if (e.Button == MouseButtons.Left)
7507             {
7508                 for (int i = 0; i < ListTab.TabPages.Count; i++)
7509                 {
7510                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
7511                     {
7512                         _tabDrag = true;
7513                         _tabMouseDownPoint = e.Location;
7514                         break;
7515                     }
7516                 }
7517             }
7518             else
7519             {
7520                 _tabDrag = false;
7521             }
7522         }
7523
7524         private void ListTab_DragEnter(object sender, DragEventArgs e)
7525         {
7526             if (e.Data.GetDataPresent(typeof(TabPage)))
7527                 e.Effect = DragDropEffects.Move;
7528             else
7529                 e.Effect = DragDropEffects.None;
7530         }
7531
7532         private void ListTab_DragDrop(object sender, DragEventArgs e)
7533         {
7534             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7535
7536             _tabDrag = false;
7537             string tn = "";
7538             bool bef = false;
7539             Point cpos = new Point(e.X, e.Y);
7540             Point spos = ListTab.PointToClient(cpos);
7541             int i;
7542             for (i = 0; i < ListTab.TabPages.Count; i++)
7543             {
7544                 Rectangle rect = ListTab.GetTabRect(i);
7545                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7546                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7547                 {
7548                     tn = ListTab.TabPages[i].Text;
7549                     if (spos.X <= (rect.Left + rect.Right) / 2)
7550                         bef = true;
7551                     else
7552                         bef = false;
7553
7554                     break;
7555                 }
7556             }
7557
7558             //タブのないところにドロップ->最後尾へ移動
7559             if (string.IsNullOrEmpty(tn))
7560             {
7561                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7562                 bef = false;
7563                 i = ListTab.TabPages.Count - 1;
7564             }
7565
7566             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7567             if (tp.Text == tn) return;
7568
7569             ReOrderTab(tp.Text, tn, bef);
7570         }
7571
7572         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7573         {
7574             var baseIndex = this.GetTabPageIndex(baseTabText);
7575             if (baseIndex == -1)
7576                 return;
7577
7578             var targetIndex = this.GetTabPageIndex(targetTabText);
7579             if (targetIndex == -1)
7580                 return;
7581
7582             using (ControlTransaction.Layout(this.ListTab))
7583             {
7584                 var mTp = this.ListTab.TabPages[targetIndex];
7585                 this.ListTab.TabPages.Remove(mTp);
7586
7587                 if (targetIndex < baseIndex)
7588                     baseIndex--;
7589
7590                 if (isBeforeBaseTab)
7591                     ListTab.TabPages.Insert(baseIndex, mTp);
7592                 else
7593                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
7594             }
7595
7596             SaveConfigsTabs();
7597         }
7598
7599         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7600         {
7601             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7602             //isReply:true=@,false=DM
7603             if (!StatusText.Enabled) return;
7604             if (_curList == null) return;
7605             if (_curTab == null) return;
7606             if (!this.ExistCurrentPost) return;
7607
7608             // 複数あてリプライはReplyではなく通常ポスト
7609             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7610             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7611             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7612
7613             if (_curList.SelectedIndices.Count > 0)
7614             {
7615                 // アイテムが1件以上選択されている
7616                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7617                 {
7618                     // 単独ユーザー宛リプライまたはDM
7619                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7620                     {
7621                         // ダイレクトメッセージ
7622                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7623                         StatusText.SelectionStart = StatusText.Text.Length;
7624                         StatusText.Focus();
7625                         this.inReplyTo = null;
7626                         return;
7627                     }
7628                     if (string.IsNullOrEmpty(StatusText.Text))
7629                     {
7630                         //空の場合
7631
7632                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7633                         StatusText.Text = "@" + _curPost.ScreenName + " ";
7634
7635                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7636                         var inReplyToScreenName = this._curPost.ScreenName;
7637                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7638                     }
7639                     else
7640                     {
7641                         //何か入力済の場合
7642
7643                         if (isAuto)
7644                         {
7645                             //1件選んでEnter or DoubleClick
7646                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7647                             {
7648                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7649                                 {
7650                                     //返信先書き換え
7651                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7652                                     var inReplyToScreenName = this._curPost.ScreenName;
7653                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7654                                 }
7655                                 return;
7656                             }
7657                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7658                             {
7659                                 //文頭@以外
7660                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7661                                 {
7662                                     // 複数リプライ
7663                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7664                                     this.inReplyTo = null;
7665                                 }
7666                                 else
7667                                 {
7668                                     // 単独リプライ
7669                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7670                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7671                                     var inReplyToScreenName = this._curPost.ScreenName;
7672                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7673                                 }
7674                             }
7675                             else
7676                             {
7677                                 //文頭@
7678                                 // 複数リプライ
7679                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7680                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7681                                 this.inReplyTo = null;
7682                             }
7683                         }
7684                         else
7685                         {
7686                             //1件選んでCtrl-Rの場合(返信先操作せず)
7687                             int sidx = StatusText.SelectionStart;
7688                             string id = "@" + _curPost.ScreenName + " ";
7689                             if (sidx > 0)
7690                             {
7691                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7692                                 {
7693                                     id = " " + id;
7694                                 }
7695                             }
7696                             StatusText.Text = StatusText.Text.Insert(sidx, id);
7697                             sidx += id.Length;
7698                             //if (StatusText.Text.StartsWith("@"))
7699                             //{
7700                             //    //複数リプライ
7701                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7702                             //    sidx += 5 + _curPost.ScreenName.Length;
7703                             //}
7704                             //else
7705                             //{
7706                             //    // 複数リプライ
7707                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7708                             //    sidx += 3 + _curPost.ScreenName.Length;
7709                             //}
7710                             StatusText.SelectionStart = sidx;
7711                             StatusText.Focus();
7712                             //_reply_to_id = 0;
7713                             //_reply_to_name = null;
7714                             return;
7715                         }
7716                     }
7717                 }
7718                 else
7719                 {
7720                     // 複数リプライ
7721                     if (!isAuto && !isReply) return;
7722
7723                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7724
7725                     if (isAuto)
7726                     {
7727                         //Enter or DoubleClick
7728
7729                         string sTxt = StatusText.Text;
7730                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7731                         {
7732                             sTxt = ". " + sTxt;
7733                             this.inReplyTo = null;
7734                         }
7735                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7736                         {
7737                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7738                             if (!sTxt.Contains("@" + post.ScreenName + " "))
7739                             {
7740                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7741                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
7742                             }
7743                         }
7744                         StatusText.Text = sTxt;
7745                     }
7746                     else
7747                     {
7748                         //C-S-r or C-r
7749                         if (_curList.SelectedIndices.Count > 1)
7750                         {
7751                             //複数ポスト選択
7752
7753                             string ids = "";
7754                             int sidx = StatusText.SelectionStart;
7755                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7756                             {
7757                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7758                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
7759                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7760                                 {
7761                                     ids += "@" + post.ScreenName + " ";
7762                                 }
7763                                 if (isAll)
7764                                 {
7765                                     foreach (string nm in post.ReplyToList)
7766                                     {
7767                                         if (!ids.Contains("@" + nm + " ") &&
7768                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7769                                         {
7770                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7771                                             if (m.Success)
7772                                                 ids += "@" + m.Result("${id}") + " ";
7773                                             else
7774                                                 ids += "@" + nm + " ";
7775                                         }
7776                                     }
7777                                 }
7778                             }
7779                             if (ids.Length == 0) return;
7780                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7781                             {
7782                                 StatusText.Text = ". " + StatusText.Text;
7783                                 sidx += 2;
7784                                 this.inReplyTo = null;
7785                             }
7786                             if (sidx > 0)
7787                             {
7788                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7789                                 {
7790                                     ids = " " + ids;
7791                                 }
7792                             }
7793                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7794                             sidx += ids.Length;
7795                             //if (StatusText.Text.StartsWith("@"))
7796                             //{
7797                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7798                             //    sidx += 2 + ids.Length;
7799                             //}
7800                             //else
7801                             //{
7802                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
7803                             //    sidx += 1 + ids.Length;
7804                             //}
7805                             StatusText.SelectionStart = sidx;
7806                             StatusText.Focus();
7807                             return;
7808                         }
7809                         else
7810                         {
7811                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
7812
7813                             string ids = "";
7814                             int sidx = StatusText.SelectionStart;
7815                             PostClass post = _curPost;
7816                             if (!ids.Contains("@" + post.ScreenName + " ") &&
7817                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7818                             {
7819                                 ids += "@" + post.ScreenName + " ";
7820                             }
7821                             foreach (string nm in post.ReplyToList)
7822                             {
7823                                 if (!ids.Contains("@" + nm + " ") &&
7824                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7825                                 {
7826                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7827                                     if (m.Success)
7828                                         ids += "@" + m.Result("${id}") + " ";
7829                                     else
7830                                         ids += "@" + nm + " ";
7831                                 }
7832                             }
7833                             if (!string.IsNullOrEmpty(post.RetweetedBy))
7834                             {
7835                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7836                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7837                                 {
7838                                     ids += "@" + post.RetweetedBy + " ";
7839                                 }
7840                             }
7841                             if (ids.Length == 0) return;
7842                             if (string.IsNullOrEmpty(StatusText.Text))
7843                             {
7844                                 //未入力の場合のみ返信先付加
7845                                 StatusText.Text = ids;
7846                                 StatusText.SelectionStart = ids.Length;
7847                                 StatusText.Focus();
7848
7849                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7850                                 var inReplyToScreenName = this._curPost.ScreenName;
7851                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7852                                 return;
7853                             }
7854
7855                             if (sidx > 0)
7856                             {
7857                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7858                                 {
7859                                     ids = " " + ids;
7860                                 }
7861                             }
7862                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7863                             sidx += ids.Length;
7864                             StatusText.SelectionStart = sidx;
7865                             StatusText.Focus();
7866                             return;
7867                         }
7868                     }
7869                 }
7870                 StatusText.SelectionStart = StatusText.Text.Length;
7871                 StatusText.Focus();
7872             }
7873         }
7874
7875         private void ListTab_MouseUp(object sender, MouseEventArgs e)
7876         {
7877             _tabDrag = false;
7878         }
7879
7880         private static int iconCnt = 0;
7881         private static int blinkCnt = 0;
7882         private static bool blink = false;
7883         private static bool idle = false;
7884
7885         private async Task RefreshTasktrayIcon()
7886         {
7887             if (_colorize)
7888                 await this.Colorize();
7889
7890             if (!TimerRefreshIcon.Enabled) return;
7891             //Static usCheckCnt As int = 0
7892
7893             //Static iconDlListTopItem As ListViewItem = null
7894
7895             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7896             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7897             //else
7898             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7899             //
7900             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7901
7902             iconCnt += 1;
7903             blinkCnt += 1;
7904             //usCheckCnt += 1;
7905
7906             //if (usCheckCnt > 300)    //1min
7907             //{
7908             //    usCheckCnt = 0;
7909             //    if (!this.IsReceivedUserStream)
7910             //    {
7911             //        TraceOut("ReconnectUserStream");
7912             //        tw.ReconnectUserStream();
7913             //    }
7914             //}
7915
7916             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7917
7918             if (iconCnt >= this.NIconRefresh.Length)
7919             {
7920                 iconCnt = 0;
7921             }
7922             if (blinkCnt > 10)
7923             {
7924                 blinkCnt = 0;
7925                 //未保存の変更を保存
7926                 SaveConfigsAll(true);
7927             }
7928
7929             if (busy)
7930             {
7931                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7932                 idle = false;
7933                 _myStatusError = false;
7934                 return;
7935             }
7936
7937             TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7938             if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7939             {
7940                 if (blinkCnt > 0) return;
7941                 blink = !blink;
7942                 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7943                 {
7944                     NotifyIcon1.Icon = ReplyIcon;
7945                 }
7946                 else
7947                 {
7948                     NotifyIcon1.Icon = ReplyIconBlink;
7949                 }
7950                 idle = false;
7951                 return;
7952             }
7953
7954             if (idle) return;
7955             idle = true;
7956             //優先度:エラー→オフライン→アイドル
7957             //エラーは更新アイコンでクリアされる
7958             if (_myStatusError)
7959             {
7960                 NotifyIcon1.Icon = NIconAtRed;
7961                 return;
7962             }
7963             if (_myStatusOnline)
7964             {
7965                 NotifyIcon1.Icon = NIconAt;
7966             }
7967             else
7968             {
7969                 NotifyIcon1.Icon = NIconAtSmoke;
7970             }
7971         }
7972
7973         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7974         {
7975             //200ms
7976             await this.RefreshTasktrayIcon();
7977         }
7978
7979         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7980         {
7981             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7982             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7983             {
7984                 if (ListTab != null && ListTab.SelectedTab != null)
7985                     _rclickTabName = ListTab.SelectedTab.Text;
7986                 else
7987                     return;
7988             }
7989
7990             if (_statuses == null) return;
7991             if (_statuses.Tabs == null) return;
7992
7993             TabModel tb;
7994             if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
7995                 return;
7996
7997             NotifyDispMenuItem.Checked = tb.Notify;
7998             this.NotifyTbMenuItem.Checked = tb.Notify;
7999
8000             soundfileListup = true;
8001             SoundFileComboBox.Items.Clear();
8002             this.SoundFileTbComboBox.Items.Clear();
8003             SoundFileComboBox.Items.Add("");
8004             this.SoundFileTbComboBox.Items.Add("");
8005             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8006             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8007             {
8008                 oDir = oDir.GetDirectories("Sounds")[0];
8009             }
8010             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8011             {
8012                 SoundFileComboBox.Items.Add(oFile.Name);
8013                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8014             }
8015             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8016             if (idx == -1) idx = 0;
8017             SoundFileComboBox.SelectedIndex = idx;
8018             this.SoundFileTbComboBox.SelectedIndex = idx;
8019             soundfileListup = false;
8020             UreadManageMenuItem.Checked = tb.UnreadManage;
8021             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8022
8023             TabMenuControl(_rclickTabName);
8024         }
8025
8026         private void TabMenuControl(string tabName)
8027         {
8028             var tabInfo = _statuses.GetTabByName(tabName);
8029
8030             this.FilterEditMenuItem.Enabled = true;
8031             this.EditRuleTbMenuItem.Enabled = true;
8032
8033             if (tabInfo.IsDefaultTabType)
8034             {
8035                 this.ProtectTabMenuItem.Enabled = false;
8036                 this.ProtectTbMenuItem.Enabled = false;
8037             }
8038             else
8039             {
8040                 this.ProtectTabMenuItem.Enabled = true;
8041                 this.ProtectTbMenuItem.Enabled = true;
8042             }
8043
8044             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8045             {
8046                 this.ProtectTabMenuItem.Checked = true;
8047                 this.ProtectTbMenuItem.Checked = true;
8048                 this.DeleteTabMenuItem.Enabled = false;
8049                 this.DeleteTbMenuItem.Enabled = false;
8050             }
8051             else
8052             {
8053                 this.ProtectTabMenuItem.Checked = false;
8054                 this.ProtectTbMenuItem.Checked = false;
8055                 this.DeleteTabMenuItem.Enabled = true;
8056                 this.DeleteTbMenuItem.Enabled = true;
8057             }
8058         }
8059
8060         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8061         {
8062             var checkState = ((ToolStripMenuItem)sender).Checked;
8063
8064             // チェック状態を同期
8065             this.ProtectTbMenuItem.Checked = checkState;
8066             this.ProtectTabMenuItem.Checked = checkState;
8067
8068             // ロック中はタブの削除を無効化
8069             this.DeleteTabMenuItem.Enabled = !checkState;
8070             this.DeleteTbMenuItem.Enabled = !checkState;
8071
8072             if (string.IsNullOrEmpty(_rclickTabName)) return;
8073             _statuses.Tabs[_rclickTabName].Protected = checkState;
8074
8075             SaveConfigsTabs();
8076         }
8077
8078         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8079         {
8080             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8081             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8082
8083             if (string.IsNullOrEmpty(_rclickTabName)) return;
8084             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8085
8086             SaveConfigsTabs();
8087         }
8088
8089         public void ChangeTabUnreadManage(string tabName, bool isManage)
8090         {
8091             var idx = this.GetTabPageIndex(tabName);
8092             if (idx == -1)
8093                 return;
8094
8095             _statuses.Tabs[tabName].UnreadManage = isManage;
8096             if (SettingManager.Common.TabIconDisp)
8097             {
8098                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8099                     ListTab.TabPages[idx].ImageIndex = 0;
8100                 else
8101                     ListTab.TabPages[idx].ImageIndex = -1;
8102             }
8103
8104             if (_curTab.Text == tabName)
8105             {
8106                 this.PurgeListViewItemCache();
8107                 _curList.Refresh();
8108             }
8109
8110             SetMainWindowTitle();
8111             SetStatusLabelUrl();
8112             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8113         }
8114
8115         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8116         {
8117             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8118             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8119
8120             if (string.IsNullOrEmpty(_rclickTabName)) return;
8121
8122             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8123
8124             SaveConfigsTabs();
8125         }
8126
8127         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8128         {
8129             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8130
8131             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8132
8133             SaveConfigsTabs();
8134         }
8135
8136         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8137         {
8138             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8139
8140             RemoveSpecifiedTab(_rclickTabName, true);
8141             SaveConfigsTabs();
8142         }
8143
8144         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8145         {
8146             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8147
8148             using (var fltDialog = new FilterDialog())
8149             {
8150                 fltDialog.Owner = this;
8151                 fltDialog.SetCurrent(_rclickTabName);
8152                 fltDialog.ShowDialog(this);
8153             }
8154             this.TopMost = SettingManager.Common.AlwaysTop;
8155
8156             this.ApplyPostFilters();
8157             SaveConfigsTabs();
8158         }
8159
8160         private void AddTabMenuItem_Click(object sender, EventArgs e)
8161         {
8162             string tabName = null;
8163             MyCommon.TabUsageType tabUsage;
8164             using (InputTabName inputName = new InputTabName())
8165             {
8166                 inputName.TabName = _statuses.MakeTabName("MyTab");
8167                 inputName.IsShowUsage = true;
8168                 inputName.ShowDialog();
8169                 if (inputName.DialogResult == DialogResult.Cancel) return;
8170                 tabName = inputName.TabName;
8171                 tabUsage = inputName.Usage;
8172             }
8173             this.TopMost = SettingManager.Common.AlwaysTop;
8174             if (!string.IsNullOrEmpty(tabName))
8175             {
8176                 //List対応
8177                 ListElement list = null;
8178                 if (tabUsage == MyCommon.TabUsageType.Lists)
8179                 {
8180                     using (ListAvailable listAvail = new ListAvailable())
8181                     {
8182                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8183                         if (listAvail.SelectedList == null) return;
8184                         list = listAvail.SelectedList;
8185                     }
8186                 }
8187
8188                 TabModel tab;
8189                 switch (tabUsage)
8190                 {
8191                     case MyCommon.TabUsageType.UserDefined:
8192                         tab = new FilterTabModel(tabName);
8193                         break;
8194                     case MyCommon.TabUsageType.PublicSearch:
8195                         tab = new PublicSearchTabModel(tabName);
8196                         break;
8197                     case MyCommon.TabUsageType.Lists:
8198                         tab = new ListTimelineTabModel(tabName, list);
8199                         break;
8200                     default:
8201                         return;
8202                 }
8203
8204                 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8205                 {
8206                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8207                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8208                 }
8209                 else
8210                 {
8211                     //成功
8212                     SaveConfigsTabs();
8213                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8214                     {
8215                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8216                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8217                     }
8218                     if (tabUsage == MyCommon.TabUsageType.Lists)
8219                     {
8220                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8221                         var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8222                         this.GetListTimelineAsync(listTab);
8223                     }
8224                 }
8225             }
8226         }
8227
8228         private void TabMenuItem_Click(object sender, EventArgs e)
8229         {
8230             using (var fltDialog = new FilterDialog())
8231             {
8232                 fltDialog.Owner = this;
8233
8234                 //選択発言を元にフィルタ追加
8235                 foreach (int idx in _curList.SelectedIndices)
8236                 {
8237                     string tabName;
8238                     //タブ選択(or追加)
8239                     if (!SelectTab(out tabName)) return;
8240
8241                     fltDialog.SetCurrent(tabName);
8242                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8243                     {
8244                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8245                     }
8246                     else
8247                     {
8248                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8249                     }
8250                     fltDialog.ShowDialog(this);
8251                     this.TopMost = SettingManager.Common.AlwaysTop;
8252                 }
8253             }
8254
8255             this.ApplyPostFilters();
8256             SaveConfigsTabs();
8257             if (this.ListTab.SelectedTab != null &&
8258                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8259             {
8260                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8261             }
8262         }
8263
8264         protected override bool ProcessDialogKey(Keys keyData)
8265         {
8266             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8267             if ((keyData & Keys.KeyCode) == Keys.Enter)
8268             {
8269                 if (StatusText.Focused)
8270                 {
8271                     bool _NewLine = false;
8272                     bool _Post = false;
8273
8274                     if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8275                     {
8276                         if (StatusText.Multiline)
8277                         {
8278                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8279
8280                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8281                         }
8282                         else
8283                         {
8284                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8285                         }
8286
8287                     }
8288                     else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8289                     {
8290                         if (StatusText.Multiline)
8291                         {
8292                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8293
8294                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8295                         }
8296                         else
8297                         {
8298                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8299                         }
8300
8301                     }
8302                     else //Enter投稿時
8303                     {
8304                         if (StatusText.Multiline)
8305                         {
8306                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8307
8308                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8309                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8310                         }
8311                         else
8312                         {
8313                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8314                                 (((keyData & Keys.Control) != Keys.Control) &&
8315                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8316                         }
8317                     }
8318
8319                     if (_NewLine)
8320                     {
8321                         int pos1 = StatusText.SelectionStart;
8322                         if (StatusText.SelectionLength > 0)
8323                         {
8324                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8325                         }
8326                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
8327                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
8328                         return true;
8329                     }
8330                     else if (_Post)
8331                     {
8332                         PostButton_Click(null, null);
8333                         return true;
8334                     }
8335                 }
8336                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8337                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8338                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8339                 {
8340                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8341                     return true;
8342                 }
8343             }
8344
8345             return base.ProcessDialogKey(keyData);
8346         }
8347
8348         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8349         {
8350             MakeReplyOrDirectStatus(false, true, true);
8351         }
8352
8353         private void IDRuleMenuItem_Click(object sender, EventArgs e)
8354         {
8355             //未選択なら処理終了
8356             if (_curList.SelectedIndices.Count == 0) return;
8357
8358             var tab = this._statuses.Tabs[this._curTab.Text];
8359             var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8360                 .Select(x => tab[x])
8361                 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8362                 .ToArray();
8363
8364             this.AddFilterRuleByScreenName(screenNameArray);
8365
8366             if (screenNameArray.Length != 0)
8367             {
8368                 List<string> atids = new List<string>();
8369                 foreach (var screenName in screenNameArray)
8370                 {
8371                     atids.Add("@" + screenName);
8372                 }
8373                 int cnt = AtIdSupl.ItemCount;
8374                 AtIdSupl.AddRangeItem(atids.ToArray());
8375                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8376             }
8377         }
8378
8379         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8380         {
8381             if (this._curList.SelectedIndices.Count == 0)
8382                 return;
8383
8384             var tab = this._statuses.Tabs[this._curTab.Text];
8385             var sourceArray = this._curList.SelectedIndices.Cast<int>()
8386                 .Select(x => tab[x].Source).ToArray();
8387
8388             this.AddFilterRuleBySource(sourceArray);
8389         }
8390
8391         public void AddFilterRuleByScreenName(params string[] screenNameArray)
8392         {
8393             //タブ選択(or追加)
8394             string tabName;
8395             if (!SelectTab(out tabName)) return;
8396
8397             var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8398
8399             bool mv;
8400             bool mk;
8401             if (tab.TabType != MyCommon.TabUsageType.Mute)
8402             {
8403                 this.MoveOrCopy(out mv, out mk);
8404             }
8405             else
8406             {
8407                 // ミュートタブでは常に MoveMatches を true にする
8408                 mv = true;
8409                 mk = false;
8410             }
8411
8412             foreach (var screenName in screenNameArray)
8413             {
8414                 tab.AddFilter(new PostFilterRule
8415                 {
8416                     FilterName = screenName,
8417                     UseNameField = true,
8418                     MoveMatches = mv,
8419                     MarkMatches = mk,
8420                     UseRegex = false,
8421                     FilterByUrl = false,
8422                 });
8423             }
8424
8425             this.ApplyPostFilters();
8426             SaveConfigsTabs();
8427         }
8428
8429         public void AddFilterRuleBySource(params string[] sourceArray)
8430         {
8431             // タブ選択ダイアログを表示(or追加)
8432             string tabName;
8433             if (!this.SelectTab(out tabName))
8434                 return;
8435
8436             var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8437
8438             bool mv;
8439             bool mk;
8440             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8441             {
8442                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8443                 this.MoveOrCopy(out mv, out mk);
8444             }
8445             else
8446             {
8447                 // ミュートタブでは常に MoveMatches を true にする
8448                 mv = true;
8449                 mk = false;
8450             }
8451
8452             // 振り分けルールに追加するSource
8453             foreach (var source in sourceArray)
8454             {
8455                 filterTab.AddFilter(new PostFilterRule
8456                 {
8457                     FilterSource = source,
8458                     MoveMatches = mv,
8459                     MarkMatches = mk,
8460                     UseRegex = false,
8461                     FilterByUrl = false,
8462                 });
8463             }
8464
8465             this.ApplyPostFilters();
8466             this.SaveConfigsTabs();
8467         }
8468
8469         private bool SelectTab(out string tabName)
8470         {
8471             do
8472             {
8473                 tabName = null;
8474
8475                 //振り分け先タブ選択
8476                 using (var dialog = new TabsDialog(_statuses))
8477                 {
8478                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8479
8480                     var selectedTab = dialog.SelectedTab;
8481                     tabName = selectedTab == null ? null : selectedTab.TabName;
8482                 }
8483
8484                 ListTab.SelectedTab.Focus();
8485                 //新規タブを選択→タブ作成
8486                 if (tabName == null)
8487                 {
8488                     using (InputTabName inputName = new InputTabName())
8489                     {
8490                         inputName.TabName = _statuses.MakeTabName("MyTab");
8491                         inputName.ShowDialog();
8492                         if (inputName.DialogResult == DialogResult.Cancel) return false;
8493                         tabName = inputName.TabName;
8494                     }
8495                     this.TopMost = SettingManager.Common.AlwaysTop;
8496                     if (!string.IsNullOrEmpty(tabName))
8497                     {
8498                         var tab = new FilterTabModel(tabName);
8499                         if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8500                         {
8501                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8502                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8503                             //もう一度タブ名入力
8504                         }
8505                         else
8506                         {
8507                             return true;
8508                         }
8509                     }
8510                 }
8511                 else
8512                 {
8513                     //既存タブを選択
8514                     return true;
8515                 }
8516             }
8517             while (true);
8518         }
8519
8520         private void MoveOrCopy(out bool move, out bool mark)
8521         {
8522             {
8523                 //移動するか?
8524                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8525                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8526                     move = false;
8527                 else
8528                     move = true;
8529             }
8530             if (!move)
8531             {
8532                 //マークするか?
8533                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8534                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8535                     mark = true;
8536                 else
8537                     mark = false;
8538             }
8539             else
8540             {
8541                 mark = false;
8542             }
8543         }
8544         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8545         {
8546             this.CopyStot();
8547         }
8548
8549         private void CopyURLMenuItem_Click(object sender, EventArgs e)
8550         {
8551             this.CopyIdUri();
8552         }
8553
8554         private void SelectAllMenuItem_Click(object sender, EventArgs e)
8555         {
8556             if (StatusText.Focused)
8557             {
8558                 // 発言欄でのCtrl+A
8559                 StatusText.SelectAll();
8560             }
8561             else
8562             {
8563                 // ListView上でのCtrl+A
8564                 NativeMethods.SelectAllItems(this._curList);
8565             }
8566         }
8567
8568         private void MoveMiddle()
8569         {
8570             ListViewItem _item;
8571             int idx1;
8572             int idx2;
8573
8574             if (_curList.SelectedIndices.Count == 0) return;
8575
8576             int idx = _curList.SelectedIndices[0];
8577
8578             _item = _curList.GetItemAt(0, 25);
8579             if (_item == null)
8580                 idx1 = 0;
8581             else
8582                 idx1 = _item.Index;
8583
8584             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8585             if (_item == null)
8586                 idx2 = _curList.VirtualListSize - 1;
8587             else
8588                 idx2 = _item.Index;
8589
8590             idx -= Math.Abs(idx1 - idx2) / 2;
8591             if (idx < 0) idx = 0;
8592
8593             _curList.EnsureVisible(_curList.VirtualListSize - 1);
8594             _curList.EnsureVisible(idx);
8595         }
8596
8597         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8598         {
8599             var linkElements = this.tweetDetailsView.GetLinkElements();
8600
8601             if (linkElements.Length > 0)
8602             {
8603                 UrlDialog.ClearUrl();
8604
8605                 string openUrlStr = "";
8606
8607                 if (linkElements.Length == 1)
8608                 {
8609                     // ツイートに含まれる URL が 1 つのみの場合
8610                     //   => OpenURL ダイアログを表示せずにリンクを開く
8611
8612                     string urlStr = "";
8613                     try
8614                     {
8615                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8616                     }
8617                     catch (ArgumentException)
8618                     {
8619                         //変なHTML?
8620                         return;
8621                     }
8622                     catch (Exception)
8623                     {
8624                         return;
8625                     }
8626                     if (string.IsNullOrEmpty(urlStr)) return;
8627                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8628
8629                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8630                     await this.OpenUriAsync(new Uri(openUrlStr));
8631                 }
8632                 else
8633                 {
8634                     // ツイートに含まれる URL が複数ある場合
8635                     //   => OpenURL を表示しユーザーが選択したリンクを開く
8636
8637                     foreach (var linkElm in linkElements)
8638                     {
8639                         string urlStr = "";
8640                         string linkText = "";
8641                         string href = "";
8642                         try
8643                         {
8644                             urlStr = linkElm.GetAttribute("title");
8645                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8646                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8647                             linkText = linkElm.InnerText;
8648                         }
8649                         catch (ArgumentException)
8650                         {
8651                             //変なHTML?
8652                             return;
8653                         }
8654                         catch (Exception)
8655                         {
8656                             return;
8657                         }
8658                         if (string.IsNullOrEmpty(urlStr)) continue;
8659                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8660                     }
8661                     try
8662                     {
8663                         if (UrlDialog.ShowDialog() == DialogResult.OK)
8664                         {
8665                             openUrlStr = UrlDialog.SelectedUrl;
8666
8667                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8668                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8669                         }
8670                     }
8671                     catch (Exception)
8672                     {
8673                         return;
8674                     }
8675                     this.TopMost = SettingManager.Common.AlwaysTop;
8676                 }
8677             }
8678         }
8679
8680         private void ClearTabMenuItem_Click(object sender, EventArgs e)
8681         {
8682             if (string.IsNullOrEmpty(_rclickTabName)) return;
8683             ClearTab(_rclickTabName, true);
8684         }
8685
8686         private void ClearTab(string tabName, bool showWarning)
8687         {
8688             if (showWarning)
8689             {
8690                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8691                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8692                 {
8693                     return;
8694                 }
8695             }
8696
8697             _statuses.ClearTabIds(tabName);
8698             if (ListTab.SelectedTab.Text == tabName)
8699             {
8700                 _anchorPost = null;
8701                 _anchorFlag = false;
8702                 this.PurgeListViewItemCache();
8703                 _curItemIndex = -1;
8704                 _curPost = null;
8705             }
8706             foreach (TabPage tb in ListTab.TabPages)
8707             {
8708                 if (tb.Text == tabName)
8709                 {
8710                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
8711                     tb.ImageIndex = -1;
8712                     break;
8713                 }
8714             }
8715             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8716
8717             SetMainWindowTitle();
8718             SetStatusLabelUrl();
8719         }
8720
8721         private static long followers = 0;
8722
8723         private void SetMainWindowTitle()
8724         {
8725             //メインウインドウタイトルの書き換え
8726             StringBuilder ttl = new StringBuilder(256);
8727             int ur = 0;
8728             int al = 0;
8729             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8730                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8731                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8732                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8733             {
8734                 foreach (var tab in _statuses.Tabs.Values)
8735                 {
8736                     ur += tab.UnreadCount;
8737                     al += tab.AllCount;
8738                 }
8739             }
8740
8741             if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8742             ttl.Append(Application.ProductName);
8743             ttl.Append("  ");
8744             switch (SettingManager.Common.DispLatestPost)
8745             {
8746                 case MyCommon.DispTitleEnum.Ver:
8747                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8748                     break;
8749                 case MyCommon.DispTitleEnum.Post:
8750                     if (_history != null && _history.Count > 1)
8751                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8752                     break;
8753                 case MyCommon.DispTitleEnum.UnreadRepCount:
8754                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8755                     break;
8756                 case MyCommon.DispTitleEnum.UnreadAllCount:
8757                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8758                     break;
8759                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8760                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8761                     break;
8762                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8763                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8764                     break;
8765                 case MyCommon.DispTitleEnum.OwnStatus:
8766                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8767                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8768                     break;
8769             }
8770
8771             try
8772             {
8773                 this.Text = ttl.ToString();
8774             }
8775             catch (AccessViolationException)
8776             {
8777                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8778             }
8779         }
8780
8781         private string GetStatusLabelText()
8782         {
8783             //ステータス欄にカウント表示
8784             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8785             if (_statuses == null) return "";
8786             TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8787             TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8788             if (tbRep == null || tbDm == null) return "";
8789             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8790             int ur = 0;
8791             int al = 0;
8792             int tur = 0;
8793             int tal = 0;
8794             StringBuilder slbl = new StringBuilder(256);
8795             try
8796             {
8797                 foreach (var tab in _statuses.Tabs.Values)
8798                 {
8799                     ur += tab.UnreadCount;
8800                     al += tab.AllCount;
8801                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8802                     {
8803                         tur = tab.UnreadCount;
8804                         tal = tab.AllCount;
8805                     }
8806                 }
8807             }
8808             catch (Exception)
8809             {
8810                 return "";
8811             }
8812
8813             UnreadCounter = ur;
8814             UnreadAtCounter = urat;
8815
8816             var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8817
8818             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8819             if (SettingManager.Common.TimelinePeriod == 0)
8820             {
8821                 slbl.Append(Properties.Resources.SetStatusLabelText2);
8822             }
8823             else
8824             {
8825                 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8826             }
8827             return slbl.ToString();
8828         }
8829
8830         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8831         {
8832             try
8833             {
8834                 if (this.InvokeRequired && !this.IsDisposed)
8835                 {
8836                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8837                 }
8838                 else
8839                 {
8840                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8841                     SetApiStatusLabel(endpointName);
8842                 }
8843             }
8844             catch (ObjectDisposedException)
8845             {
8846                 return;
8847             }
8848             catch (InvalidOperationException)
8849             {
8850                 return;
8851             }
8852         }
8853
8854         private void SetApiStatusLabel(string endpointName = null)
8855         {
8856             if (_curTab == null)
8857             {
8858                 this.toolStripApiGauge.ApiEndpoint = null;
8859             }
8860             else
8861             {
8862                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8863
8864                 if (endpointName == null)
8865                 {
8866                     // 表示中のタブに応じて更新
8867                     switch (tabType)
8868                     {
8869                         case MyCommon.TabUsageType.Home:
8870                         case MyCommon.TabUsageType.UserDefined:
8871                             endpointName = "/statuses/home_timeline";
8872                             break;
8873
8874                         case MyCommon.TabUsageType.Mentions:
8875                             endpointName = "/statuses/mentions_timeline";
8876                             break;
8877
8878                         case MyCommon.TabUsageType.Favorites:
8879                             endpointName = "/favorites/list";
8880                             break;
8881
8882                         case MyCommon.TabUsageType.DirectMessage:
8883                             endpointName = "/direct_messages";
8884                             break;
8885
8886                         case MyCommon.TabUsageType.UserTimeline:
8887                             endpointName = "/statuses/user_timeline";
8888                             break;
8889
8890                         case MyCommon.TabUsageType.Lists:
8891                             endpointName = "/lists/statuses";
8892                             break;
8893
8894                         case MyCommon.TabUsageType.PublicSearch:
8895                             endpointName = "/search/tweets";
8896                             break;
8897
8898                         case MyCommon.TabUsageType.Related:
8899                             endpointName = "/statuses/show/:id";
8900                             break;
8901
8902                         default:
8903                             break;
8904                     }
8905
8906                     this.toolStripApiGauge.ApiEndpoint = endpointName;
8907                 }
8908                 else
8909                 {
8910                     // 表示中のタブに関連する endpoint であれば更新
8911                     var update = false;
8912
8913                     switch (endpointName)
8914                     {
8915                         case "/statuses/home_timeline":
8916                             update = tabType == MyCommon.TabUsageType.Home ||
8917                                      tabType == MyCommon.TabUsageType.UserDefined;
8918                             break;
8919
8920                         case "/statuses/mentions_timeline":
8921                             update = tabType == MyCommon.TabUsageType.Mentions;
8922                             break;
8923
8924                         case "/favorites/list":
8925                             update = tabType == MyCommon.TabUsageType.Favorites;
8926                             break;
8927
8928                         case "/direct_messages:":
8929                             update = tabType == MyCommon.TabUsageType.DirectMessage;
8930                             break;
8931
8932                         case "/statuses/user_timeline":
8933                             update = tabType == MyCommon.TabUsageType.UserTimeline;
8934                             break;
8935
8936                         case "/lists/statuses":
8937                             update = tabType == MyCommon.TabUsageType.Lists;
8938                             break;
8939
8940                         case "/search/tweets":
8941                             update = tabType == MyCommon.TabUsageType.PublicSearch;
8942                             break;
8943
8944                         case "/statuses/show/:id":
8945                             update = tabType == MyCommon.TabUsageType.Related;
8946                             break;
8947
8948                         default:
8949                             break;
8950                     }
8951
8952                     if (update)
8953                     {
8954                         this.toolStripApiGauge.ApiEndpoint = endpointName;
8955                     }
8956                 }
8957             }
8958         }
8959
8960         private void SetStatusLabelUrl()
8961         {
8962             StatusLabelUrl.Text = GetStatusLabelText();
8963         }
8964
8965         public void SetStatusLabel(string text)
8966         {
8967             StatusLabel.Text = text;
8968         }
8969
8970         private void SetNotifyIconText()
8971         {
8972             var ur = new StringBuilder(64);
8973
8974             // タスクトレイアイコンのツールチップテキスト書き換え
8975             // Tween [未読/@]
8976             ur.Remove(0, ur.Length);
8977             if (SettingManager.Common.DispUsername)
8978             {
8979                 ur.Append(tw.Username);
8980                 ur.Append(" - ");
8981             }
8982             ur.Append(Application.ProductName);
8983 #if DEBUG
8984             ur.Append("(Debug Build)");
8985 #endif
8986             if (UnreadCounter != -1 && UnreadAtCounter != -1)
8987             {
8988                 ur.Append(" [");
8989                 ur.Append(UnreadCounter);
8990                 ur.Append("/@");
8991                 ur.Append(UnreadAtCounter);
8992                 ur.Append("]");
8993             }
8994             NotifyIcon1.Text = ur.ToString();
8995         }
8996
8997         internal void CheckReplyTo(string StatusText)
8998         {
8999             MatchCollection m;
9000             //ハッシュタグの保存
9001             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9002             string hstr = "";
9003             foreach (Match hm in m)
9004             {
9005                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9006                 {
9007                     hstr += "#" + hm.Result("$3") + " ";
9008                     HashSupl.AddItem("#" + hm.Result("$3"));
9009                 }
9010             }
9011             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9012             {
9013                 hstr += HashMgr.UseHash;
9014             }
9015             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9016
9017             // 本当にリプライ先指定すべきかどうかの判定
9018             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9019
9020             if (SettingManager.Common.UseAtIdSupplement)
9021             {
9022                 int bCnt = AtIdSupl.ItemCount;
9023                 foreach (Match mid in m)
9024                 {
9025                     AtIdSupl.AddItem(mid.Result("${id}"));
9026                 }
9027                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9028             }
9029
9030             // リプライ先ステータスIDの指定がない場合は指定しない
9031             if (this.inReplyTo == null)
9032                 return;
9033
9034             // 通常Reply
9035             // 次の条件を満たす場合に in_reply_to_status_id 指定
9036             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9037             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9038             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9039
9040             if (m != null)
9041             {
9042                 var inReplyToScreenName = this.inReplyTo.Item2;
9043                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9044                 {
9045                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9046                 }
9047                 else
9048                 {
9049                     foreach (Match mid in m)
9050                     {
9051                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9052                     }
9053                 }
9054             }
9055
9056             this.inReplyTo = null;
9057         }
9058
9059         private void TweenMain_Resize(object sender, EventArgs e)
9060         {
9061             if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9062             {
9063                 this.Visible = false;
9064             }
9065             if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9066             {
9067                 // 現在の DPI と設定保存時の DPI との比を取得する
9068                 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9069
9070                 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9071                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9072                 this.DesktopLocation = SettingManager.Local.FormLocation;
9073                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9074
9075                 // Splitterの位置設定
9076                 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9077                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9078                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9079                 {
9080                     this.SplitContainer1.SplitterDistance = splitterDistance;
9081                 }
9082
9083                 //発言欄複数行
9084                 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9085                 if (StatusText.Multiline)
9086                 {
9087                     var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9088                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9089                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9090                     {
9091                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9092                     }
9093                     StatusText.Height = statusTextHeight;
9094                 }
9095                 else
9096                 {
9097                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9098                     {
9099                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9100                     }
9101                 }
9102
9103                 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9104                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9105                 {
9106                     this.SplitContainer3.SplitterDistance = previewDistance;
9107                 }
9108
9109                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9110                 this.SplitContainer3.Panel2Collapsed = true;
9111
9112                 _initialLayout = false;
9113             }
9114             if (this.WindowState != FormWindowState.Minimized)
9115             {
9116                 _formWindowState = this.WindowState;
9117             }
9118         }
9119
9120         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9121         {
9122             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9123             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9124             if (PlaySoundMenuItem.Checked)
9125             {
9126                 SettingManager.Common.PlaySound = true;
9127             }
9128             else
9129             {
9130                 SettingManager.Common.PlaySound = false;
9131             }
9132             ModifySettingCommon = true;
9133         }
9134
9135         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9136         {
9137             if (this._initialLayout)
9138                 return;
9139
9140             int splitterDistance;
9141             switch (this.WindowState)
9142             {
9143                 case FormWindowState.Normal:
9144                     splitterDistance = this.SplitContainer1.SplitterDistance;
9145                     break;
9146                 case FormWindowState.Maximized:
9147                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9148                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9149                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9150                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9151                     break;
9152                 default:
9153                     return;
9154             }
9155
9156             this._mySpDis = splitterDistance;
9157             this.ModifySettingLocal = true;
9158         }
9159
9160         private async Task doRepliedStatusOpen()
9161         {
9162             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9163             {
9164                 if (MyCommon.IsKeyDown(Keys.Shift))
9165                 {
9166                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9167                     return;
9168                 }
9169                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9170                 {
9171                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9172                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9173                 }
9174                 else
9175                 {
9176                     foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9177                     {
9178                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9179                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9180                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9181                         return;
9182                     }
9183                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9184                 }
9185             }
9186         }
9187
9188         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9189         {
9190             await this.doRepliedStatusOpen();
9191         }
9192
9193         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9194         {
9195             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9196             if (multiline != this.StatusText.Multiline)
9197             {
9198                 this.StatusText.Multiline = multiline;
9199                 MultiLineMenuItem.Checked = multiline;
9200                 ModifySettingLocal = true;
9201             }
9202         }
9203
9204         private void StatusText_MultilineChanged(object sender, EventArgs e)
9205         {
9206             if (this.StatusText.Multiline)
9207                 this.StatusText.ScrollBars = ScrollBars.Vertical;
9208             else
9209                 this.StatusText.ScrollBars = ScrollBars.None;
9210
9211             ModifySettingLocal = true;
9212         }
9213
9214         private void MultiLineMenuItem_Click(object sender, EventArgs e)
9215         {
9216             //発言欄複数行
9217             StatusText.Multiline = MultiLineMenuItem.Checked;
9218             SettingManager.Local.StatusMultiline = MultiLineMenuItem.Checked;
9219             if (MultiLineMenuItem.Checked)
9220             {
9221                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9222                     SplitContainer2.SplitterDistance = 0;
9223                 else
9224                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9225             }
9226             else
9227             {
9228                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9229             }
9230             ModifySettingLocal = true;
9231         }
9232
9233         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9234         {
9235             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9236             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9237
9238             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9239             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9240             //Appendix A.  Collected ABNF for URI
9241             //http://www.ietf.org/rfc/rfc3986.txt
9242
9243             string result = "";
9244
9245             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9246
9247             if (StatusText.SelectionLength > 0)
9248             {
9249                 string tmp = StatusText.SelectedText;
9250                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9251                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9252                 {
9253                     // 文字列が選択されている場合はその文字列について処理
9254
9255                     //nico.ms使用、nicovideoにマッチしたら変換
9256                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9257                     {
9258                         result = nicoms.Shorten(tmp);
9259                     }
9260                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9261                     {
9262                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9263                         try
9264                         {
9265                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9266                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9267                             result = resultUri.AbsoluteUri;
9268                         }
9269                         catch (WebApiException e)
9270                         {
9271                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9272                             return false;
9273                         }
9274                         catch (UriFormatException e)
9275                         {
9276                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9277                             return false;
9278                         }
9279                     }
9280                     else
9281                     {
9282                         return true;
9283                     }
9284
9285                     if (!string.IsNullOrEmpty(result))
9286                     {
9287                         urlUndo undotmp = new urlUndo();
9288
9289                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9290                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9291                         if (origUrlIndex == -1)
9292                             return false;
9293
9294                         StatusText.Select(origUrlIndex, tmp.Length);
9295                         StatusText.SelectedText = result;
9296
9297                         //undoバッファにセット
9298                         undotmp.Before = tmp;
9299                         undotmp.After = result;
9300
9301                         if (urlUndoBuffer == null)
9302                         {
9303                             urlUndoBuffer = new List<urlUndo>();
9304                             UrlUndoToolStripMenuItem.Enabled = true;
9305                         }
9306
9307                         urlUndoBuffer.Add(undotmp);
9308                     }
9309                 }
9310             }
9311             else
9312             {
9313                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9314                                    @"(?<url>(?<protocol>https?://)" +
9315                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9316                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9317                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9318                 // 正規表現にマッチしたURL文字列をtinyurl化
9319                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9320                 {
9321                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9322                     string tmp = mt.Result("${url}");
9323                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9324                     urlUndo undotmp = new urlUndo();
9325
9326                     //選んだURLを選択(?)
9327                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9328
9329                     //nico.ms使用、nicovideoにマッチしたら変換
9330                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9331                     {
9332                         result = nicoms.Shorten(tmp);
9333                     }
9334                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9335                     {
9336                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9337                         try
9338                         {
9339                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9340                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9341                             result = resultUri.AbsoluteUri;
9342                         }
9343                         catch (HttpRequestException e)
9344                         {
9345                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9346                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
9347                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9348
9349                             this.StatusLabel.Text = Converter_Type + ":" + message;
9350                             continue;
9351                         }
9352                         catch (WebApiException e)
9353                         {
9354                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9355                             continue;
9356                         }
9357                         catch (UriFormatException e)
9358                         {
9359                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9360                             continue;
9361                         }
9362                     }
9363                     else
9364                     {
9365                         continue;
9366                     }
9367
9368                     if (!string.IsNullOrEmpty(result))
9369                     {
9370                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9371                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9372                         if (origUrlIndex == -1)
9373                             return false;
9374
9375                         StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9376                         StatusText.SelectedText = result;
9377                         //undoバッファにセット
9378                         undotmp.Before = mt.Result("${url}");
9379                         undotmp.After = result;
9380
9381                         if (urlUndoBuffer == null)
9382                         {
9383                             urlUndoBuffer = new List<urlUndo>();
9384                             UrlUndoToolStripMenuItem.Enabled = true;
9385                         }
9386
9387                         urlUndoBuffer.Add(undotmp);
9388                     }
9389                 }
9390             }
9391
9392             return true;
9393         }
9394
9395         private void doUrlUndo()
9396         {
9397             if (urlUndoBuffer != null)
9398             {
9399                 string tmp = StatusText.Text;
9400                 foreach (urlUndo data in urlUndoBuffer)
9401                 {
9402                     tmp = tmp.Replace(data.After, data.Before);
9403                 }
9404                 StatusText.Text = tmp;
9405                 urlUndoBuffer = null;
9406                 UrlUndoToolStripMenuItem.Enabled = false;
9407                 StatusText.SelectionStart = 0;
9408                 StatusText.SelectionLength = 0;
9409             }
9410         }
9411
9412         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9413         {
9414             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9415         }
9416
9417         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9418         {
9419             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9420         }
9421
9422         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9423         {
9424             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9425         }
9426
9427         private async void UxnuMenuItem_Click(object sender, EventArgs e)
9428         {
9429             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9430         }
9431
9432         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9433         {
9434             if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9435             {
9436                 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9437                 Random rnd = new Random();
9438                 // 前回使用した短縮URLサービス以外を選択する
9439                 do
9440                 {
9441                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9442                 }
9443                 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9444                 await UrlConvertAsync(svc);
9445             }
9446         }
9447
9448         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9449         {
9450             doUrlUndo();
9451         }
9452
9453         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9454         {
9455             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9456             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9457             SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9458             ModifySettingCommon = true;
9459         }
9460
9461         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9462         {
9463             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9464             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9465             SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9466             ModifySettingCommon = true;
9467         }
9468
9469         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9470         {
9471             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9472             MenuStrip1.Tag = new Object();
9473             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9474         }
9475
9476         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9477         {
9478             if (this.Tag != null) // 設定された戻り先へ遷移
9479             {
9480                 if (this.Tag == this.ListTab.SelectedTab)
9481                     ((Control)this.ListTab.SelectedTab.Tag).Select();
9482                 else
9483                     ((Control)this.Tag).Select();
9484             }
9485             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9486             {
9487                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9488                 {
9489                     this.Tag = ListTab.SelectedTab.Tag;
9490                     ((Control)this.Tag).Select();
9491                 }
9492             }
9493             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9494             MenuStrip1.Tag = null;
9495         }
9496
9497         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9498         {
9499             DetailsListView lst = (DetailsListView)sender;
9500             if (SettingManager.Local == null) return;
9501
9502             if (_iconCol)
9503             {
9504                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9505                 SettingManager.Local.Width3 = lst.Columns[1].Width;
9506             }
9507             else
9508             {
9509                 int[] darr = new int[lst.Columns.Count];
9510                 for (int i = 0; i < lst.Columns.Count; i++)
9511                 {
9512                     darr[lst.Columns[i].DisplayIndex] = i;
9513                 }
9514                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9515
9516                 for (int i = 0; i < lst.Columns.Count; i++)
9517                 {
9518                     switch (darr[i])
9519                     {
9520                         case 0:
9521                             SettingManager.Local.DisplayIndex1 = i;
9522                             break;
9523                         case 1:
9524                             SettingManager.Local.DisplayIndex2 = i;
9525                             break;
9526                         case 2:
9527                             SettingManager.Local.DisplayIndex3 = i;
9528                             break;
9529                         case 3:
9530                             SettingManager.Local.DisplayIndex4 = i;
9531                             break;
9532                         case 4:
9533                             SettingManager.Local.DisplayIndex5 = i;
9534                             break;
9535                         case 5:
9536                             SettingManager.Local.DisplayIndex6 = i;
9537                             break;
9538                         case 6:
9539                             SettingManager.Local.DisplayIndex7 = i;
9540                             break;
9541                         case 7:
9542                             SettingManager.Local.DisplayIndex8 = i;
9543                             break;
9544                     }
9545                 }
9546                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9547                 SettingManager.Local.Width2 = lst.Columns[1].Width;
9548                 SettingManager.Local.Width3 = lst.Columns[2].Width;
9549                 SettingManager.Local.Width4 = lst.Columns[3].Width;
9550                 SettingManager.Local.Width5 = lst.Columns[4].Width;
9551                 SettingManager.Local.Width6 = lst.Columns[5].Width;
9552                 SettingManager.Local.Width7 = lst.Columns[6].Width;
9553                 SettingManager.Local.Width8 = lst.Columns[7].Width;
9554             }
9555             ModifySettingLocal = true;
9556             _isColumnChanged = true;
9557         }
9558
9559         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9560         {
9561             DetailsListView lst = (DetailsListView)sender;
9562             if (SettingManager.Local == null) return;
9563             if (_iconCol)
9564             {
9565                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9566                 {
9567                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9568                     ModifySettingLocal = true;
9569                     _isColumnChanged = true;
9570                 }
9571                 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9572                 {
9573                     SettingManager.Local.Width3 = lst.Columns[1].Width;
9574                     ModifySettingLocal = true;
9575                     _isColumnChanged = true;
9576                 }
9577             }
9578             else
9579             {
9580                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9581                 {
9582                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9583                     ModifySettingLocal = true;
9584                     _isColumnChanged = true;
9585                 }
9586                 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9587                 {
9588                     SettingManager.Local.Width2 = lst.Columns[1].Width;
9589                     ModifySettingLocal = true;
9590                     _isColumnChanged = true;
9591                 }
9592                 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9593                 {
9594                     SettingManager.Local.Width3 = lst.Columns[2].Width;
9595                     ModifySettingLocal = true;
9596                     _isColumnChanged = true;
9597                 }
9598                 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9599                 {
9600                     SettingManager.Local.Width4 = lst.Columns[3].Width;
9601                     ModifySettingLocal = true;
9602                     _isColumnChanged = true;
9603                 }
9604                 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9605                 {
9606                     SettingManager.Local.Width5 = lst.Columns[4].Width;
9607                     ModifySettingLocal = true;
9608                     _isColumnChanged = true;
9609                 }
9610                 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9611                 {
9612                     SettingManager.Local.Width6 = lst.Columns[5].Width;
9613                     ModifySettingLocal = true;
9614                     _isColumnChanged = true;
9615                 }
9616                 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9617                 {
9618                     SettingManager.Local.Width7 = lst.Columns[6].Width;
9619                     ModifySettingLocal = true;
9620                     _isColumnChanged = true;
9621                 }
9622                 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9623                 {
9624                     SettingManager.Local.Width8 = lst.Columns[7].Width;
9625                     ModifySettingLocal = true;
9626                     _isColumnChanged = true;
9627                 }
9628             }
9629             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9630             //if (changed)
9631             //{
9632             //    SaveConfigsLocal();
9633             //}
9634         }
9635
9636         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9637         {
9638             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9639             ModifySettingLocal = true;
9640         }
9641
9642         private void TweenMain_DragDrop(object sender, DragEventArgs e)
9643         {
9644             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9645             {
9646                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9647                 {
9648                     SelectMedia_DragDrop(e);
9649                 }
9650             }
9651             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9652             {
9653                 var url = GetUrlFromDataObject(e.Data);
9654
9655                 string appendText;
9656                 if (url.Item2 == null)
9657                     appendText = url.Item1;
9658                 else
9659                     appendText = url.Item2 + " " + url.Item1;
9660
9661                 if (this.StatusText.TextLength == 0)
9662                     this.StatusText.Text = appendText;
9663                 else
9664                     this.StatusText.Text += " " + appendText;
9665             }
9666             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9667             {
9668                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9669                 if (text != null)
9670                     this.StatusText.Text += text;
9671             }
9672             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9673             {
9674                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9675                 if (data != null) StatusText.Text += data;
9676             }
9677         }
9678
9679         /// <summary>
9680         /// IDataObject から URL とタイトルの対を取得します
9681         /// </summary>
9682         /// <remarks>
9683         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9684         /// </remarks>
9685         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9686         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9687         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9688         {
9689             if (data.GetDataPresent("text/x-moz-url"))
9690             {
9691                 // Firefox, Google Chrome で利用可能
9692                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9693
9694                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9695                 {
9696                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9697                     if (lines.Length < 2)
9698                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9699
9700                     return new Tuple<string, string>(lines[0], lines[1]);
9701                 }
9702             }
9703             else if (data.GetDataPresent("IESiteModeToUrl"))
9704             {
9705                 // Internet Exproler 用
9706                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9707
9708                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9709                 {
9710                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9711                     if (lines.Length < 2)
9712                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9713
9714                     return new Tuple<string, string>(lines[0], lines[1]);
9715                 }
9716             }
9717             else if (data.GetDataPresent("UniformResourceLocatorW"))
9718             {
9719                 // それ以外のブラウザ向け
9720
9721                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9722                 {
9723                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9724                     return new Tuple<string, string>(url, null);
9725                 }
9726             }
9727
9728             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9729         }
9730
9731         private void TweenMain_DragEnter(object sender, DragEventArgs e)
9732         {
9733             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9734             {
9735                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9736                 {
9737                     SelectMedia_DragEnter(e);
9738                     return;
9739                 }
9740             }
9741             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9742             {
9743                 e.Effect = DragDropEffects.Copy;
9744                 return;
9745             }
9746             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9747             {
9748                 e.Effect = DragDropEffects.Copy;
9749                 return;
9750             }
9751             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9752             {
9753                 e.Effect = DragDropEffects.Copy;
9754                 return;
9755             }
9756
9757             e.Effect = DragDropEffects.None;
9758         }
9759
9760         private void TweenMain_DragOver(object sender, DragEventArgs e)
9761         {
9762         }
9763
9764         public bool IsNetworkAvailable()
9765         {
9766             bool nw = true;
9767             nw = MyCommon.IsNetworkAvailable();
9768             _myStatusOnline = nw;
9769             return nw;
9770         }
9771
9772         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9773         {
9774             var uriStr = uri.AbsoluteUri;
9775
9776             // OpenTween 内部で使用する URL
9777             if (uri.Authority == "opentween")
9778             {
9779                 await this.OpenInternalUriAsync(uri);
9780                 return;
9781             }
9782
9783             // ハッシュタグを含む Twitter 検索
9784             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9785             {
9786                 // ハッシュタグの場合は、タブで開く
9787                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9788                 var pos = unescapedQuery.IndexOf('#');
9789                 if (pos == -1) return;
9790
9791                 var hash = unescapedQuery.Substring(pos);
9792                 this.HashSupl.AddItem(hash);
9793                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9794                 this.AddNewTabForSearch(hash);
9795                 return;
9796             }
9797
9798             // ユーザープロフィールURL
9799             // フラグが立っている場合は設定と逆の動作をする
9800             if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9801                 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9802             {
9803                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9804                 if (userUriMatch.Success)
9805                 {
9806                     var screenName = userUriMatch.Groups["ScreenName"].Value;
9807                     if (this.IsTwitterId(screenName))
9808                     {
9809                         this.AddNewTabForUserTimeline(screenName);
9810                         return;
9811                     }
9812                 }
9813             }
9814
9815             // どのパターンにも該当しないURL
9816             await this.OpenUriInBrowserAsync(uriStr);
9817         }
9818
9819         /// <summary>
9820         /// OpenTween 内部の機能を呼び出すための URL を開きます
9821         /// </summary>
9822         private async Task OpenInternalUriAsync(Uri uri)
9823         {
9824             // ツイートを開く (//opentween/status/:status_id)
9825             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9826             if (match.Success)
9827             {
9828                 var statusId = long.Parse(match.Groups[1].Value);
9829                 await this.OpenRelatedTab(statusId);
9830                 return;
9831             }
9832         }
9833
9834         public Task OpenUriInBrowserAsync(string UriString)
9835         {
9836             return Task.Run(() =>
9837             {
9838                 string myPath = UriString;
9839
9840                 try
9841                 {
9842                     var configBrowserPath = SettingManager.Local.BrowserPath;
9843                     if (!string.IsNullOrEmpty(configBrowserPath))
9844                     {
9845                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9846                         {
9847                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9848                             string browserPath = configBrowserPath.Substring(1, sep - 1);
9849                             string arg = "";
9850                             if (sep < configBrowserPath.Length - 1)
9851                             {
9852                                 arg = configBrowserPath.Substring(sep + 1);
9853                             }
9854                             myPath = arg + " " + myPath;
9855                             System.Diagnostics.Process.Start(browserPath, myPath);
9856                         }
9857                         else
9858                         {
9859                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
9860                         }
9861                     }
9862                     else
9863                     {
9864                         System.Diagnostics.Process.Start(myPath);
9865                     }
9866                 }
9867                 catch (Exception)
9868                 {
9869                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9870                 }
9871             });
9872         }
9873
9874         private void ListTabSelect(TabPage _tab)
9875         {
9876             SetListProperty();
9877
9878             this.PurgeListViewItemCache();
9879
9880             _curTab = _tab;
9881             _curList = (DetailsListView)_tab.Tag;
9882
9883             if (_curList.SelectedIndices.Count > 0)
9884             {
9885                 _curItemIndex = _curList.SelectedIndices[0];
9886                 _curPost = GetCurTabPost(_curItemIndex);
9887             }
9888             else
9889             {
9890                 _curItemIndex = -1;
9891                 _curPost = null;
9892             }
9893
9894             _anchorPost = null;
9895             _anchorFlag = false;
9896
9897             if (_iconCol)
9898             {
9899                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9900             }
9901             else
9902             {
9903                 for (int i = 0; i < _curList.Columns.Count; i++)
9904                 {
9905                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9906                 }
9907             }
9908         }
9909
9910         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9911         {
9912             ListTabSelect(e.TabPage);
9913         }
9914
9915         private void SelectListItem(DetailsListView LView, int Index)
9916         {
9917             //単一
9918             Rectangle bnd = new Rectangle();
9919             bool flg = false;
9920             var item = LView.FocusedItem;
9921             if (item != null)
9922             {
9923                 bnd = item.Bounds;
9924                 flg = true;
9925             }
9926
9927             do
9928             {
9929                 LView.SelectedIndices.Clear();
9930             }
9931             while (LView.SelectedIndices.Count > 0);
9932             item = LView.Items[Index];
9933             item.Selected = true;
9934             item.Focused = true;
9935
9936             if (flg) LView.Invalidate(bnd);
9937         }
9938
9939         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9940         {
9941             //複数
9942             Rectangle bnd = new Rectangle();
9943             bool flg = false;
9944             var item = LView.FocusedItem;
9945             if (item != null)
9946             {
9947                 bnd = item.Bounds;
9948                 flg = true;
9949             }
9950
9951             if (Index != null)
9952             {
9953                 do
9954                 {
9955                     LView.SelectedIndices.Clear();
9956                 }
9957                 while (LView.SelectedIndices.Count > 0);
9958                 LView.SelectItems(Index);
9959             }
9960             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9961             {
9962                 LView.SelectionMark = selectionMarkIndex;
9963             }
9964             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9965             {
9966                 LView.Items[focusedIndex].Focused = true;
9967             }
9968             else if (Index != null && Index.Length != 0)
9969             {
9970                 LView.Items[Index.Last()].Focused = true;
9971             }
9972
9973             if (flg) LView.Invalidate(bnd);
9974         }
9975
9976         private void StartUserStream()
9977         {
9978             tw.NewPostFromStream += tw_NewPostFromStream;
9979             tw.UserStreamStarted += tw_UserStreamStarted;
9980             tw.UserStreamStopped += tw_UserStreamStopped;
9981             tw.PostDeleted += tw_PostDeleted;
9982             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9983
9984             this.RefreshUserStreamsMenu();
9985
9986             if (SettingManager.Common.UserstreamStartup)
9987                 tw.StartUserStream();
9988         }
9989
9990         private async void TweenMain_Shown(object sender, EventArgs e)
9991         {
9992             NotifyIcon1.Visible = true;
9993
9994             if (this.IsNetworkAvailable())
9995             {
9996                 StartUserStream();
9997
9998                 var loadTasks = new List<Task>
9999                 {
10000                     this.RefreshMuteUserIdsAsync(),
10001                     this.RefreshBlockIdsAsync(),
10002                     this.RefreshNoRetweetIdsAsync(),
10003                     this.RefreshTwitterConfigurationAsync(),
10004                     this.GetHomeTimelineAsync(),
10005                     this.GetReplyAsync(),
10006                     this.GetDirectMessagesAsync(),
10007                     this.GetPublicSearchAllAsync(),
10008                     this.GetUserTimelineAllAsync(),
10009                     this.GetListTimelineAllAsync(),
10010                 };
10011
10012                 if (SettingManager.Common.StartupFollowers)
10013                     loadTasks.Add(this.RefreshFollowerIdsAsync());
10014
10015                 if (SettingManager.Common.GetFav)
10016                     loadTasks.Add(this.GetFavoritesAsync());
10017
10018                 var allTasks = Task.WhenAll(loadTasks);
10019
10020                 var i = 0;
10021                 while (true)
10022                 {
10023                     var timeout = Task.Delay(5000);
10024                     if (await Task.WhenAny(allTasks, timeout) != timeout)
10025                         break;
10026
10027                     i += 1;
10028                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10029
10030                     if (MyCommon._endingFlag)
10031                         return;
10032                 }
10033
10034                 if (MyCommon._endingFlag) return;
10035
10036                 if (ApplicationSettings.VersionInfoUrl != null)
10037                 {
10038                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10039                     if (SettingManager.Common.StartupVersion)
10040                         await this.CheckNewVersion(true);
10041                 }
10042                 else
10043                 {
10044                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10045                     this.VerUpMenuItem.Enabled = false;
10046                     this.VerUpMenuItem.Available = false;
10047                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10048                 }
10049
10050                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10051                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10052                 {
10053                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
10054                     SettingStripMenuItem_Click(null, null);
10055                 }
10056
10057                 // 取得失敗の場合は再試行する
10058                 var reloadTasks = new List<Task>();
10059
10060                 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10061                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
10062
10063                 if (!tw.GetNoRetweetSuccess)
10064                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10065
10066                 if (this.tw.Configuration.PhotoSizeLimit == 0)
10067                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10068
10069                 await Task.WhenAll(reloadTasks);
10070             }
10071
10072             _initial = false;
10073
10074             TimerTimeline.Enabled = true;
10075         }
10076
10077         private async Task doGetFollowersMenu()
10078         {
10079             await this.RefreshFollowerIdsAsync();
10080             await this.DispSelectedPost(true);
10081         }
10082
10083         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10084         {
10085             await this.doGetFollowersMenu();
10086         }
10087
10088         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10089         {
10090             doReTweetUnofficial();
10091         }
10092
10093         private async Task doReTweetOfficial(bool isConfirm)
10094         {
10095             //公式RT
10096             if (this.ExistCurrentPost)
10097             {
10098                 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10099                 {
10100                     if (this._curPost.IsProtect)
10101                         MessageBox.Show("Protected.");
10102
10103                     _DoFavRetweetFlags = false;
10104                     return;
10105                 }
10106                 if (_curList.SelectedIndices.Count > 15)
10107                 {
10108                     MessageBox.Show(Properties.Resources.RetweetLimitText);
10109                     _DoFavRetweetFlags = false;
10110                     return;
10111                 }
10112                 else if (_curList.SelectedIndices.Count > 1)
10113                 {
10114                     string QuestionText = Properties.Resources.RetweetQuestion2;
10115                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10116                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10117                     {
10118                         case DialogResult.Cancel:
10119                         case DialogResult.No:
10120                             _DoFavRetweetFlags = false;
10121                             return;
10122                     }
10123                 }
10124                 else
10125                 {
10126                     if (!SettingManager.Common.RetweetNoConfirm)
10127                     {
10128                         string Questiontext = Properties.Resources.RetweetQuestion1;
10129                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10130                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10131                         {
10132                             _DoFavRetweetFlags = false;
10133                             return;
10134                         }
10135                     }
10136                 }
10137
10138                 var statusIds = new List<long>();
10139                 foreach (int idx in _curList.SelectedIndices)
10140                 {
10141                     PostClass post = GetCurTabPost(idx);
10142                     if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10143                         statusIds.Add(post.StatusId);
10144                 }
10145
10146                 await this.RetweetAsync(statusIds);
10147             }
10148         }
10149
10150         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10151         {
10152             await this.doReTweetOfficial(true);
10153         }
10154
10155         private async Task FavoritesRetweetOfficial()
10156         {
10157             if (!this.ExistCurrentPost) return;
10158             _DoFavRetweetFlags = true;
10159             var retweetTask = this.doReTweetOfficial(true);
10160             if (_DoFavRetweetFlags)
10161             {
10162                 _DoFavRetweetFlags = false;
10163                 var favoriteTask = this.FavoriteChange(true, false);
10164
10165                 await Task.WhenAll(retweetTask, favoriteTask);
10166             }
10167             else
10168             {
10169                 await retweetTask;
10170             }
10171         }
10172
10173         private async Task FavoritesRetweetUnofficial()
10174         {
10175             if (this.ExistCurrentPost && !_curPost.IsDm)
10176             {
10177                 _DoFavRetweetFlags = true;
10178                 var favoriteTask = this.FavoriteChange(true);
10179                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10180                 {
10181                     _DoFavRetweetFlags = false;
10182                     doReTweetUnofficial();
10183                 }
10184
10185                 await favoriteTask;
10186             }
10187         }
10188
10189         /// <summary>
10190         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10191         /// </summary>
10192         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10193         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10194         /// <returns>復元されたツイート本文</returns>
10195         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10196         {
10197             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10198
10199             // 通常の URL
10200             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10201             // メンション
10202             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10203             // ハッシュタグ
10204             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10205
10206             // <br> 除去
10207             if (multiline)
10208                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10209             else
10210                 statusHtml = statusHtml.Replace("<br>", " ");
10211
10212             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10213             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
10214             statusHtml = statusHtml.Replace("&nbsp;", " ");
10215
10216             return WebUtility.HtmlDecode(statusHtml);
10217         }
10218
10219         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10220         {
10221             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10222
10223             if (_curPost != null)
10224                 await this.DispSelectedPost(true);
10225         }
10226
10227         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10228         {
10229             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10230                 DebugModeToolStripMenuItem.Visible = true;
10231             else
10232                 DebugModeToolStripMenuItem.Visible = false;
10233         }
10234
10235         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10236         {
10237             SettingManager.Common.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10238         }
10239
10240         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10241         {
10242             ToolStripMenuItemUrlAutoShorten.Checked = SettingManager.Common.UrlConvertAuto;
10243         }
10244
10245         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10246         {
10247             if (TraceOutToolStripMenuItem.Checked)
10248                 MyCommon.TraceFlag = true;
10249             else
10250                 MyCommon.TraceFlag = false;
10251         }
10252
10253         private void TweenMain_Deactivate(object sender, EventArgs e)
10254         {
10255             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10256             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10257         }
10258
10259         private void TabRenameMenuItem_Click(object sender, EventArgs e)
10260         {
10261             if (string.IsNullOrEmpty(_rclickTabName)) return;
10262
10263             string _;
10264             TabRename(_rclickTabName, out _);
10265         }
10266
10267         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10268         {
10269             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10270         }
10271
10272         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10273         {
10274             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10275         }
10276
10277         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10278         {
10279             TwitterApiStatus apiStatus;
10280
10281             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10282             {
10283                 var cancellationToken = dialog.EnableCancellation();
10284
10285                 try
10286                 {
10287                     var task = this.tw.GetInfoApi();
10288                     apiStatus = await dialog.WaitForAsync(this, task);
10289                 }
10290                 catch (WebApiException)
10291                 {
10292                     apiStatus = null;
10293                 }
10294
10295                 if (cancellationToken.IsCancellationRequested)
10296                     return;
10297
10298                 if (apiStatus == null)
10299                 {
10300                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10301                     return;
10302                 }
10303             }
10304
10305             using (var apiDlg = new ApiInfoDialog())
10306             {
10307                 apiDlg.ShowDialog(this);
10308             }
10309         }
10310
10311         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10312         {
10313             var id = _curPost?.ScreenName ?? "";
10314
10315             await this.FollowCommand(id);
10316         }
10317
10318         internal async Task FollowCommand(string id)
10319         {
10320             using (var inputName = new InputTabName())
10321             {
10322                 inputName.FormTitle = "Follow";
10323                 inputName.FormDescription = Properties.Resources.FRMessage1;
10324                 inputName.TabName = id;
10325
10326                 if (inputName.ShowDialog(this) != DialogResult.OK)
10327                     return;
10328                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10329                     return;
10330
10331                 id = inputName.TabName.Trim();
10332             }
10333
10334             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10335             {
10336                 try
10337                 {
10338                     var task = this.twitterApi.FriendshipsCreate(id);
10339                     await dialog.WaitForAsync(this, task);
10340                 }
10341                 catch (WebApiException ex)
10342                 {
10343                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10344                     return;
10345                 }
10346             }
10347
10348             MessageBox.Show(Properties.Resources.FRMessage3);
10349         }
10350
10351         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10352         {
10353             var id = _curPost?.ScreenName ?? "";
10354
10355             await this.RemoveCommand(id, false);
10356         }
10357
10358         internal async Task RemoveCommand(string id, bool skipInput)
10359         {
10360             if (!skipInput)
10361             {
10362                 using (var inputName = new InputTabName())
10363                 {
10364                     inputName.FormTitle = "Unfollow";
10365                     inputName.FormDescription = Properties.Resources.FRMessage1;
10366                     inputName.TabName = id;
10367
10368                     if (inputName.ShowDialog(this) != DialogResult.OK)
10369                         return;
10370                     if (string.IsNullOrWhiteSpace(inputName.TabName))
10371                         return;
10372
10373                     id = inputName.TabName.Trim();
10374                 }
10375             }
10376
10377             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10378             {
10379                 try
10380                 {
10381                     var task = this.twitterApi.FriendshipsDestroy(id);
10382                     await dialog.WaitForAsync(this, task);
10383                 }
10384                 catch (WebApiException ex)
10385                 {
10386                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10387                     return;
10388                 }
10389             }
10390
10391             MessageBox.Show(Properties.Resources.FRMessage3);
10392         }
10393
10394         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10395         {
10396             var id = _curPost?.ScreenName ?? "";
10397
10398             await this.ShowFriendship(id);
10399         }
10400
10401         internal async Task ShowFriendship(string id)
10402         {
10403             using (var inputName = new InputTabName())
10404             {
10405                 inputName.FormTitle = "Show Friendships";
10406                 inputName.FormDescription = Properties.Resources.FRMessage1;
10407                 inputName.TabName = id;
10408
10409                 if (inputName.ShowDialog(this) != DialogResult.OK)
10410                     return;
10411                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10412                     return;
10413
10414                 id = inputName.TabName.Trim();
10415             }
10416
10417             bool isFollowing, isFollowed;
10418
10419             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10420             {
10421                 var cancellationToken = dialog.EnableCancellation();
10422
10423                 try
10424                 {
10425                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10426                     var friendship = await dialog.WaitForAsync(this, task);
10427
10428                     isFollowing = friendship.Relationship.Source.Following;
10429                     isFollowed = friendship.Relationship.Source.FollowedBy;
10430                 }
10431                 catch (WebApiException ex)
10432                 {
10433                     if (!cancellationToken.IsCancellationRequested)
10434                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10435                     return;
10436                 }
10437
10438                 if (cancellationToken.IsCancellationRequested)
10439                     return;
10440             }
10441
10442             string result = "";
10443             if (isFollowing)
10444             {
10445                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10446             }
10447             else
10448             {
10449                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10450             }
10451             if (isFollowed)
10452             {
10453                 result += Properties.Resources.GetFriendshipInfo3;
10454             }
10455             else
10456             {
10457                 result += Properties.Resources.GetFriendshipInfo4;
10458             }
10459             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10460             MessageBox.Show(result);
10461         }
10462
10463         internal async Task ShowFriendship(string[] ids)
10464         {
10465             foreach (string id in ids)
10466             {
10467                 bool isFollowing, isFollowed;
10468
10469                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10470                 {
10471                     var cancellationToken = dialog.EnableCancellation();
10472
10473                     try
10474                     {
10475                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10476                         var friendship = await dialog.WaitForAsync(this, task);
10477
10478                         isFollowing = friendship.Relationship.Source.Following;
10479                         isFollowed = friendship.Relationship.Source.FollowedBy;
10480                     }
10481                     catch (WebApiException ex)
10482                     {
10483                         if (!cancellationToken.IsCancellationRequested)
10484                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10485                         return;
10486                     }
10487
10488                     if (cancellationToken.IsCancellationRequested)
10489                         return;
10490                 }
10491
10492                 string result = "";
10493                 string ff = "";
10494
10495                 ff = "  ";
10496                 if (isFollowing)
10497                 {
10498                     ff += Properties.Resources.GetFriendshipInfo1;
10499                 }
10500                 else
10501                 {
10502                     ff += Properties.Resources.GetFriendshipInfo2;
10503                 }
10504
10505                 ff += System.Environment.NewLine + "  ";
10506                 if (isFollowed)
10507                 {
10508                     ff += Properties.Resources.GetFriendshipInfo3;
10509                 }
10510                 else
10511                 {
10512                     ff += Properties.Resources.GetFriendshipInfo4;
10513                 }
10514                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10515                 if (isFollowing)
10516                 {
10517                     if (MessageBox.Show(
10518                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10519                         MessageBoxButtons.YesNo,
10520                         MessageBoxIcon.Question,
10521                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10522                     {
10523                         await this.RemoveCommand(id, true);
10524                     }
10525                 }
10526                 else
10527                 {
10528                     MessageBox.Show(result);
10529                 }
10530             }
10531         }
10532
10533         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10534         {
10535             await this.doShowUserStatus(tw.Username, false);
10536             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10537             //{
10538             //    doShowUserStatus(tw.Username, false);
10539             //}
10540             //else
10541             //{
10542             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10543             //    return;
10544             //}
10545         }
10546
10547         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10548         // URLから切り出した文字列を渡す
10549
10550         public bool IsTwitterId(string name)
10551         {
10552             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10553                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10554             else
10555                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10556         }
10557
10558         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10559         {
10560             ModifySettingCommon = true;
10561         }
10562
10563         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10564         {
10565             ModifySettingCommon = true;
10566         }
10567
10568         private void doQuoteOfficial()
10569         {
10570             if (this.ExistCurrentPost)
10571             {
10572                 if (_curPost.IsDm ||
10573                     !StatusText.Enabled) return;
10574
10575                 if (_curPost.IsProtect)
10576                 {
10577                     MessageBox.Show("Protected.");
10578                     return;
10579                 }
10580
10581                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10582
10583                 this.inReplyTo = null;
10584
10585                 StatusText.SelectionStart = 0;
10586                 StatusText.Focus();
10587             }
10588         }
10589
10590         private void doReTweetUnofficial()
10591         {
10592             //RT @id:内容
10593             if (this.ExistCurrentPost)
10594             {
10595                 if (_curPost.IsDm || !StatusText.Enabled)
10596                     return;
10597
10598                 if (_curPost.IsProtect)
10599                 {
10600                     MessageBox.Show("Protected.");
10601                     return;
10602                 }
10603                 string rtdata = _curPost.Text;
10604                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10605
10606                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10607
10608                 // 投稿時に in_reply_to_status_id を付加する
10609                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10610                 var inReplyToScreenName = this._curPost.ScreenName;
10611                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10612
10613                 StatusText.SelectionStart = 0;
10614                 StatusText.Focus();
10615             }
10616         }
10617
10618         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10619         {
10620             doQuoteOfficial();
10621         }
10622
10623         private void SearchButton_Click(object sender, EventArgs e)
10624         {
10625             //公式検索
10626             Control pnl = ((Control)sender).Parent;
10627             if (pnl == null) return;
10628             string tbName = pnl.Parent.Text;
10629             var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10630             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10631             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10632             cmb.Text = cmb.Text.Trim();
10633             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10634             bool Quote = false;
10635             StringBuilder buf = new StringBuilder();
10636             char[] c = cmb.Text.ToCharArray();
10637             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10638             {
10639                 if (cnt > cmb.Text.Length - 4)
10640                 {
10641                     buf.Append(cmb.Text.Substring(cnt));
10642                     break;
10643                 }
10644                 if (c[cnt] == '"')
10645                 {
10646                     Quote = !Quote;
10647                 }
10648                 else
10649                 {
10650                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10651                     {
10652                         buf.Append(" OR ");
10653                         cnt += 3;
10654                         continue;
10655                     }
10656                 }
10657                 buf.Append(c[cnt]);
10658             }
10659             cmb.Text = buf.ToString();
10660
10661             var listView = (DetailsListView)pnl.Parent.Tag;
10662
10663             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10664
10665             tb.SearchWords = cmb.Text;
10666             tb.SearchLang = cmbLang.Text;
10667             if (string.IsNullOrEmpty(cmb.Text))
10668             {
10669                 listView.Focus();
10670                 SaveConfigsTabs();
10671                 return;
10672             }
10673             if (queryChanged)
10674             {
10675                 int idx = cmb.Items.IndexOf(tb.SearchWords);
10676                 if (idx > -1) cmb.Items.RemoveAt(idx);
10677                 cmb.Items.Insert(0, tb.SearchWords);
10678                 cmb.Text = tb.SearchWords;
10679                 cmb.SelectAll();
10680                 this.PurgeListViewItemCache();
10681                 listView.VirtualListSize = 0;
10682                 _statuses.ClearTabIds(tbName);
10683                 SaveConfigsTabs();   //検索条件の保存
10684             }
10685
10686             this.GetPublicSearchAsync(tb);
10687             listView.Focus();
10688         }
10689
10690         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10691         {
10692             //もっと前を取得
10693             await this.DoRefreshMore();
10694         }
10695
10696         /// <summary>
10697         /// 指定されたタブのListTabにおける位置を返します
10698         /// </summary>
10699         /// <remarks>
10700         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10701         /// </remarks>
10702         public int GetTabPageIndex(string tabName)
10703         {
10704             var index = 0;
10705             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10706             {
10707                 if (tabPage.Text == tabName)
10708                     return index;
10709
10710                 index++;
10711             }
10712
10713             return -1;
10714         }
10715
10716         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10717         {
10718             if (_statuses.RemovedTab.Count == 0)
10719             {
10720                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10721                 return;
10722             }
10723             else
10724             {
10725                 DetailsListView listView = null;
10726
10727                 TabModel tb = _statuses.RemovedTab.Pop();
10728                 if (tb.TabType == MyCommon.TabUsageType.Related)
10729                 {
10730                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10731                     if (relatedTab != null)
10732                     {
10733                         // 関連発言なら既存のタブを置き換える
10734                         tb.TabName = relatedTab.TabName;
10735                         this.ClearTab(tb.TabName, false);
10736                         _statuses.Tabs[tb.TabName] = tb;
10737
10738                         for (int i = 0; i < ListTab.TabPages.Count; i++)
10739                         {
10740                             var tabPage = ListTab.TabPages[i];
10741                             if (tb.TabName == tabPage.Text)
10742                             {
10743                                 listView = (DetailsListView)tabPage.Tag;
10744                                 ListTab.SelectedIndex = i;
10745                                 break;
10746                             }
10747                         }
10748                     }
10749                     else
10750                     {
10751                         const string TabName = "Related Tweets";
10752                         string renamed = TabName;
10753                         for (int i = 2; i <= 100; i++)
10754                         {
10755                             if (!_statuses.ContainsTab(renamed)) break;
10756                             renamed = TabName + i;
10757                         }
10758                         tb.TabName = renamed;
10759
10760                         _statuses.AddTab(tb);
10761                         AddNewTab(tb, startup: false);
10762
10763                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10764                         listView = (DetailsListView)tabPage.Tag;
10765                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10766                     }
10767                 }
10768                 else
10769                 {
10770                     string renamed = tb.TabName;
10771                     for (int i = 1; i < int.MaxValue; i++)
10772                     {
10773                         if (!_statuses.ContainsTab(renamed)) break;
10774                         renamed = tb.TabName + "(" + i + ")";
10775                     }
10776                     tb.TabName = renamed;
10777
10778                     _statuses.AddTab(tb);
10779                     AddNewTab(tb, startup: false);
10780
10781                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10782                     listView = (DetailsListView)tabPage.Tag;
10783                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10784                 }
10785                 SaveConfigsTabs();
10786
10787                 if (listView != null)
10788                 {
10789                     using (ControlTransaction.Update(listView))
10790                     {
10791                         listView.VirtualListSize = tb.AllCount;
10792                     }
10793                 }
10794             }
10795         }
10796
10797         private async Task doMoveToRTHome()
10798         {
10799             if (_curList.SelectedIndices.Count > 0)
10800             {
10801                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10802                 if (post.RetweetedId != null)
10803                 {
10804                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10805                 }
10806             }
10807         }
10808
10809         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10810         {
10811             await this.doMoveToRTHome();
10812         }
10813
10814         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10815         {
10816             var screenName = this._curPost?.ScreenName;
10817             if (screenName != null)
10818                 this.ListManageUserContext(screenName);
10819         }
10820
10821         public void ListManageUserContext(string screenName)
10822         {
10823             using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10824             {
10825                 listSelectForm.ShowDialog(this);
10826             }
10827         }
10828
10829         private void SearchControls_Enter(object sender, EventArgs e)
10830         {
10831             Control pnl = (Control)sender;
10832             foreach (Control ctl in pnl.Controls)
10833             {
10834                 ctl.TabStop = true;
10835             }
10836         }
10837
10838         private void SearchControls_Leave(object sender, EventArgs e)
10839         {
10840             Control pnl = (Control)sender;
10841             foreach (Control ctl in pnl.Controls)
10842             {
10843                 ctl.TabStop = false;
10844             }
10845         }
10846
10847         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10848         {
10849             if (ListTab.SelectedTab != null)
10850             {
10851                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10852                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10853             }
10854         }
10855
10856         private void StatusLabel_DoubleClick(object sender, EventArgs e)
10857         {
10858             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10859         }
10860
10861         private void HashManageMenuItem_Click(object sender, EventArgs e)
10862         {
10863             DialogResult rslt = DialogResult.Cancel;
10864             try
10865             {
10866                 rslt = HashMgr.ShowDialog();
10867             }
10868             catch (Exception)
10869             {
10870                 return;
10871             }
10872             this.TopMost = SettingManager.Common.AlwaysTop;
10873             if (rslt == DialogResult.Cancel) return;
10874             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10875             {
10876                 HashStripSplitButton.Text = HashMgr.UseHash;
10877                 HashToggleMenuItem.Checked = true;
10878                 HashToggleToolStripMenuItem.Checked = true;
10879             }
10880             else
10881             {
10882                 HashStripSplitButton.Text = "#[-]";
10883                 HashToggleMenuItem.Checked = false;
10884                 HashToggleToolStripMenuItem.Checked = false;
10885             }
10886             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10887             //{
10888             //    int sidx = StatusText.SelectionStart;
10889             //    string hash = HashMgr.UseHash + " ";
10890             //    if (sidx > 0)
10891             //    {
10892             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10893             //            hash = " " + hash;
10894             //    }
10895             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
10896             //    sidx += hash.Length;
10897             //    StatusText.SelectionStart = sidx;
10898             //    StatusText.Focus();
10899             //}
10900             ModifySettingCommon = true;
10901             this.StatusText_TextChanged(null, null);
10902         }
10903
10904         private void HashToggleMenuItem_Click(object sender, EventArgs e)
10905         {
10906             HashMgr.ToggleHash();
10907             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10908             {
10909                 HashStripSplitButton.Text = HashMgr.UseHash;
10910                 HashToggleMenuItem.Checked = true;
10911                 HashToggleToolStripMenuItem.Checked = true;
10912             }
10913             else
10914             {
10915                 HashStripSplitButton.Text = "#[-]";
10916                 HashToggleMenuItem.Checked = false;
10917                 HashToggleToolStripMenuItem.Checked = false;
10918             }
10919             ModifySettingCommon = true;
10920             this.StatusText_TextChanged(null, null);
10921         }
10922
10923         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10924         {
10925             HashToggleMenuItem_Click(null, null);
10926         }
10927
10928         public void SetPermanentHashtag(string hashtag)
10929         {
10930             HashMgr.SetPermanentHash("#" + hashtag);
10931             HashStripSplitButton.Text = HashMgr.UseHash;
10932             HashToggleMenuItem.Checked = true;
10933             HashToggleToolStripMenuItem.Checked = true;
10934             //使用ハッシュタグとして設定
10935             ModifySettingCommon = true;
10936         }
10937
10938         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10939         {
10940             if (ListTab.SelectedTab == null) return;
10941             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10942             if (!this.ExistCurrentPost)
10943             {
10944                 this.ReplyOpMenuItem.Enabled = false;
10945                 this.ReplyAllOpMenuItem.Enabled = false;
10946                 this.DmOpMenuItem.Enabled = false;
10947                 this.ShowProfMenuItem.Enabled = false;
10948                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10949                 this.ListManageMenuItem.Enabled = false;
10950                 this.OpenFavOpMenuItem.Enabled = false;
10951                 this.CreateTabRuleOpMenuItem.Enabled = false;
10952                 this.CreateIdRuleOpMenuItem.Enabled = false;
10953                 this.CreateSourceRuleOpMenuItem.Enabled = false;
10954                 this.ReadOpMenuItem.Enabled = false;
10955                 this.UnreadOpMenuItem.Enabled = false;
10956             }
10957             else
10958             {
10959                 this.ReplyOpMenuItem.Enabled = true;
10960                 this.ReplyAllOpMenuItem.Enabled = true;
10961                 this.DmOpMenuItem.Enabled = true;
10962                 this.ShowProfMenuItem.Enabled = true;
10963                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10964                 this.ListManageMenuItem.Enabled = true;
10965                 this.OpenFavOpMenuItem.Enabled = true;
10966                 this.CreateTabRuleOpMenuItem.Enabled = true;
10967                 this.CreateIdRuleOpMenuItem.Enabled = true;
10968                 this.CreateSourceRuleOpMenuItem.Enabled = true;
10969                 this.ReadOpMenuItem.Enabled = true;
10970                 this.UnreadOpMenuItem.Enabled = true;
10971             }
10972
10973             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10974             {
10975                 this.FavOpMenuItem.Enabled = false;
10976                 this.UnFavOpMenuItem.Enabled = false;
10977                 this.OpenStatusOpMenuItem.Enabled = false;
10978                 this.OpenFavotterOpMenuItem.Enabled = false;
10979                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10980                 this.RtOpMenuItem.Enabled = false;
10981                 this.RtUnOpMenuItem.Enabled = false;
10982                 this.QtOpMenuItem.Enabled = false;
10983                 this.FavoriteRetweetMenuItem.Enabled = false;
10984                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10985             }
10986             else
10987             {
10988                 this.FavOpMenuItem.Enabled = true;
10989                 this.UnFavOpMenuItem.Enabled = true;
10990                 this.OpenStatusOpMenuItem.Enabled = true;
10991                 this.OpenFavotterOpMenuItem.Enabled = true;
10992                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
10993
10994                 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10995                 {
10996                     this.RtOpMenuItem.Enabled = false;
10997                     this.RtUnOpMenuItem.Enabled = false;
10998                     this.QtOpMenuItem.Enabled = false;
10999                     this.FavoriteRetweetMenuItem.Enabled = false;
11000                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11001                 }
11002                 else
11003                 {
11004                     this.RtOpMenuItem.Enabled = true;
11005                     this.RtUnOpMenuItem.Enabled = true;
11006                     this.QtOpMenuItem.Enabled = true;
11007                     this.FavoriteRetweetMenuItem.Enabled = true;
11008                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11009                 }
11010             }
11011
11012             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11013             {
11014                 this.RefreshPrevOpMenuItem.Enabled = true;
11015             }
11016             else
11017             {
11018                 this.RefreshPrevOpMenuItem.Enabled = false;
11019             }
11020             if (!this.ExistCurrentPost
11021                 || _curPost.InReplyToStatusId == null)
11022             {
11023                 OpenRepSourceOpMenuItem.Enabled = false;
11024             }
11025             else
11026             {
11027                 OpenRepSourceOpMenuItem.Enabled = true;
11028             }
11029             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11030             {
11031                 OpenRterHomeMenuItem.Enabled = false;
11032             }
11033             else
11034             {
11035                 OpenRterHomeMenuItem.Enabled = true;
11036             }
11037
11038             if (this.ExistCurrentPost)
11039             {
11040                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11041             }
11042         }
11043
11044         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11045         {
11046             ContextMenuTabProperty_Opening(sender, null);
11047         }
11048
11049         public Twitter TwitterInstance
11050         {
11051             get { return tw; }
11052         }
11053
11054         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11055         {
11056             if (this._initialLayout)
11057                 return;
11058
11059             int splitterDistance;
11060             switch (this.WindowState)
11061             {
11062                 case FormWindowState.Normal:
11063                     splitterDistance = this.SplitContainer3.SplitterDistance;
11064                     break;
11065                 case FormWindowState.Maximized:
11066                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11067                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11068                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11069                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11070                     break;
11071                 default:
11072                     return;
11073             }
11074
11075             this._mySpDis3 = splitterDistance;
11076             this.ModifySettingLocal = true;
11077         }
11078
11079         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11080         {
11081             if (_statuses.RemovedTab.Count == 0)
11082             {
11083                 UndoRemoveTabMenuItem.Enabled = false;
11084             }
11085             else
11086             {
11087                 UndoRemoveTabMenuItem.Enabled = true;
11088             }
11089             if (ListTab.SelectedTab != null)
11090             {
11091                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11092                     PublicSearchQueryMenuItem.Enabled = true;
11093                 else
11094                     PublicSearchQueryMenuItem.Enabled = false;
11095             }
11096             else
11097             {
11098                 PublicSearchQueryMenuItem.Enabled = false;
11099             }
11100             if (!this.ExistCurrentPost)
11101             {
11102                 this.CopySTOTMenuItem.Enabled = false;
11103                 this.CopyURLMenuItem.Enabled = false;
11104                 this.CopyUserIdStripMenuItem.Enabled = false;
11105             }
11106             else
11107             {
11108                 this.CopySTOTMenuItem.Enabled = true;
11109                 this.CopyURLMenuItem.Enabled = true;
11110                 this.CopyUserIdStripMenuItem.Enabled = true;
11111                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11112                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11113             }
11114         }
11115
11116         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11117         {
11118             SetNotifyIconText();
11119         }
11120
11121         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11122         {
11123             var id = _curPost?.ScreenName ?? "";
11124
11125             await this.ShowUserStatus(id);
11126         }
11127
11128         private async Task doShowUserStatus(string id, bool ShowInputDialog)
11129         {
11130             TwitterUser user = null;
11131
11132             if (ShowInputDialog)
11133             {
11134                 using (var inputName = new InputTabName())
11135                 {
11136                     inputName.FormTitle = "Show UserStatus";
11137                     inputName.FormDescription = Properties.Resources.FRMessage1;
11138                     inputName.TabName = id;
11139
11140                     if (inputName.ShowDialog(this) != DialogResult.OK)
11141                         return;
11142                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11143                         return;
11144
11145                     id = inputName.TabName.Trim();
11146                 }
11147             }
11148
11149             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11150             {
11151                 var cancellationToken = dialog.EnableCancellation();
11152
11153                 try
11154                 {
11155                     var task = this.twitterApi.UsersShow(id);
11156                     user = await dialog.WaitForAsync(this, task);
11157                 }
11158                 catch (WebApiException ex)
11159                 {
11160                     if (!cancellationToken.IsCancellationRequested)
11161                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11162                     return;
11163                 }
11164
11165                 if (cancellationToken.IsCancellationRequested)
11166                     return;
11167             }
11168
11169             await this.doShowUserStatus(user);
11170         }
11171
11172         private async Task doShowUserStatus(TwitterUser user)
11173         {
11174             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11175             {
11176                 var showUserTask = userDialog.ShowUserAsync(user);
11177                 userDialog.ShowDialog(this);
11178
11179                 this.Activate();
11180                 this.BringToFront();
11181
11182                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11183                 await showUserTask;
11184             }
11185         }
11186
11187         internal Task ShowUserStatus(string id, bool ShowInputDialog)
11188         {
11189             return this.doShowUserStatus(id, ShowInputDialog);
11190         }
11191
11192         internal Task ShowUserStatus(string id)
11193         {
11194             return this.doShowUserStatus(id, true);
11195         }
11196
11197         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11198         {
11199             if (_curPost != null)
11200             {
11201                 await this.ShowUserStatus(_curPost.ScreenName, false);
11202             }
11203         }
11204
11205         private async void RtCountMenuItem_Click(object sender, EventArgs e)
11206         {
11207             if (!this.ExistCurrentPost)
11208                 return;
11209
11210             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11211             TwitterStatus status;
11212
11213             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11214             {
11215                 var cancellationToken = dialog.EnableCancellation();
11216
11217                 try
11218                 {
11219                     var task = this.twitterApi.StatusesShow(statusId);
11220                     status = await dialog.WaitForAsync(this, task);
11221                 }
11222                 catch (WebApiException ex)
11223                 {
11224                     if (!cancellationToken.IsCancellationRequested)
11225                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11226                     return;
11227                 }
11228
11229                 if (cancellationToken.IsCancellationRequested)
11230                     return;
11231             }
11232
11233             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11234         }
11235
11236         private HookGlobalHotkey _hookGlobalHotkey;
11237         public TweenMain()
11238         {
11239             _hookGlobalHotkey = new HookGlobalHotkey(this);
11240
11241             // この呼び出しは、Windows フォーム デザイナで必要です。
11242             InitializeComponent();
11243
11244             // InitializeComponent() 呼び出しの後で初期化を追加します。
11245
11246             if (!this.DesignMode)
11247             {
11248                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11249                 this.StatusText.Dock = DockStyle.Fill;
11250             }
11251
11252             this.tweetDetailsView.Owner = this;
11253
11254             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11255             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11256             this.gh.NotifyClicked += GrowlHelper_Callback;
11257
11258             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11259             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11260
11261             this.ImageSelector.Visible = false;
11262             this.ImageSelector.Enabled = false;
11263             this.ImageSelector.FilePickDialog = OpenFileDialog1;
11264
11265             this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11266
11267             this.ReplaceAppName();
11268             this.InitializeShortcuts();
11269         }
11270
11271         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11272         {
11273             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11274             {
11275                 //アイコン化
11276                 this.Visible = false;
11277             }
11278             else if (Form.ActiveForm == null)
11279             {
11280                 this.Visible = true;
11281                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11282                 this.Activate();
11283                 this.BringToFront();
11284                 this.StatusText.Focus();
11285             }
11286         }
11287
11288         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11289         {
11290             this.MultiLineMenuItem.PerformClick();
11291         }
11292
11293         public PostClass CurPost
11294         {
11295             get { return _curPost; }
11296         }
11297
11298 #region "画像投稿"
11299         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11300         {
11301             if (ImageSelector.Visible)
11302                 ImageSelector.EndSelection();
11303             else
11304                 ImageSelector.BeginSelection();
11305         }
11306
11307         private void SelectMedia_DragEnter(DragEventArgs e)
11308         {
11309             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11310             {
11311                 e.Effect = DragDropEffects.Copy;
11312                 return;
11313             }
11314             e.Effect = DragDropEffects.None;
11315         }
11316
11317         private void SelectMedia_DragDrop(DragEventArgs e)
11318         {
11319             this.Activate();
11320             this.BringToFront();
11321             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11322             StatusText.Focus();
11323         }
11324
11325         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11326         {
11327             TimelinePanel.Visible = false;
11328             TimelinePanel.Enabled = false;
11329         }
11330
11331         private void ImageSelector_EndSelecting(object sender, EventArgs e)
11332         {
11333             TimelinePanel.Visible = true;
11334             TimelinePanel.Enabled = true;
11335             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11336         }
11337
11338         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11339         {
11340             this.AllowDrop = false;
11341         }
11342
11343         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11344         {
11345             this.AllowDrop = true;
11346         }
11347
11348         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11349         {
11350             if (ImageSelector.Visible)
11351             {
11352                 ModifySettingCommon = true;
11353                 SaveConfigsAll(true);
11354
11355                 this.StatusText_TextChanged(null, null);
11356             }
11357         }
11358
11359         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11360         {
11361             this.StatusText_TextChanged(null, null);
11362         }
11363
11364         /// <summary>
11365         /// StatusTextでCtrl+Vが押下された時の処理
11366         /// </summary>
11367         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11368         {
11369             try
11370             {
11371                 if (Clipboard.ContainsText())
11372                 {
11373                     // clipboardにテキストがある場合は貼り付け処理
11374                     this.StatusText.Paste(Clipboard.GetText());
11375                 }
11376                 else if (Clipboard.ContainsImage())
11377                 {
11378                     // 画像があるので投稿処理を行う
11379                     if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11380                                        Properties.Resources.PostPictureWarn4,
11381                                        MessageBoxButtons.OKCancel,
11382                                        MessageBoxIcon.Question,
11383                                        MessageBoxDefaultButton.Button2)
11384                                    == DialogResult.OK)
11385                     {
11386                         // clipboardから画像を取得
11387                         using (var image = Clipboard.GetImage())
11388                         {
11389                             this.ImageSelector.BeginSelection(image);
11390                         }
11391                     }
11392                 }
11393             }
11394             catch (ExternalException ex)
11395             {
11396                 MessageBox.Show(ex.Message);
11397             }
11398         }
11399 #endregion
11400
11401         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11402         {
11403             using (ListManage form = new ListManage(tw))
11404             {
11405                 form.ShowDialog(this);
11406             }
11407         }
11408
11409         public bool ModifySettingCommon { get; set; }
11410         public bool ModifySettingLocal { get; set; }
11411         public bool ModifySettingAtId { get; set; }
11412
11413         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11414         {
11415             if (this.ExistCurrentPost && !_curPost.IsDm)
11416                 RtCountMenuItem.Enabled = true;
11417             else
11418                 RtCountMenuItem.Enabled = false;
11419
11420             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11421             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
11422             //else
11423             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
11424         }
11425
11426         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11427         {
11428             CopyUserId();
11429         }
11430
11431         private void CopyUserId()
11432         {
11433             if (_curPost == null) return;
11434             string clstr = _curPost.ScreenName;
11435             try
11436             {
11437                 Clipboard.SetDataObject(clstr, false, 5, 100);
11438             }
11439             catch (Exception ex)
11440             {
11441                 MessageBox.Show(ex.Message);
11442             }
11443         }
11444
11445         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11446         {
11447             if (this.ExistCurrentPost && !_curPost.IsDm)
11448             {
11449                 try
11450                 {
11451                     await this.OpenRelatedTab(this._curPost);
11452                 }
11453                 catch (TabException ex)
11454                 {
11455                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11456                 }
11457             }
11458         }
11459
11460         /// <summary>
11461         /// 指定されたツイートに対する関連発言タブを開きます
11462         /// </summary>
11463         /// <param name="statusId">表示するツイートのID</param>
11464         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11465         private async Task OpenRelatedTab(long statusId)
11466         {
11467             var post = this._statuses[statusId];
11468             if (post == null)
11469             {
11470                 try
11471                 {
11472                     post = await this.tw.GetStatusApi(false, statusId);
11473                 }
11474                 catch (WebApiException ex)
11475                 {
11476                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11477                     return;
11478                 }
11479             }
11480
11481             await this.OpenRelatedTab(post);
11482         }
11483
11484         /// <summary>
11485         /// 指定されたツイートに対する関連発言タブを開きます
11486         /// </summary>
11487         /// <param name="post">表示する対象となるツイート</param>
11488         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11489         private async Task OpenRelatedTab(PostClass post)
11490         {
11491             var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11492             if (tabRelated != null)
11493             {
11494                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11495             }
11496
11497             var tabName = this._statuses.MakeTabName("Related Tweets");
11498
11499             tabRelated = new RelatedPostsTabModel(tabName, post);
11500             tabRelated.UnreadManage = false;
11501             tabRelated.Notify = false;
11502
11503             this._statuses.AddTab(tabRelated);
11504             this.AddNewTab(tabRelated, startup: false);
11505
11506             TabPage tabPage;
11507             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11508             {
11509                 tabPage = this.ListTab.TabPages[i];
11510                 if (tabName == tabPage.Text)
11511                 {
11512                     this.ListTab.SelectedIndex = i;
11513                     break;
11514                 }
11515             }
11516
11517             await this.GetRelatedTweetsAsync(tabRelated);
11518
11519             tabPage = this.ListTab.TabPages.Cast<TabPage>()
11520                 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11521
11522             if (tabPage != null)
11523             {
11524                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11525
11526                 var listView = (DetailsListView)tabPage.Tag;
11527                 var targetPost = tabRelated.TargetPost;
11528                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11529
11530                 if (index != -1 && index < listView.Items.Count)
11531                 {
11532                     listView.SelectedIndices.Add(index);
11533                     listView.Items[index].Focused = true;
11534                 }
11535             }
11536         }
11537
11538         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11539         {
11540             StringBuilder buf = new StringBuilder();
11541             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11542             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11543             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
11544             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11545             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11546         }
11547
11548         private void tw_UserIdChanged()
11549         {
11550             this.ModifySettingCommon = true;
11551         }
11552
11553 #region "Userstream"
11554         private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11555         {
11556             try
11557             {
11558                 if (InvokeRequired && !IsDisposed)
11559                 {
11560                     await this.InvokeAsync(async () =>
11561                     {
11562                         this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11563                         if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11564                         {
11565                             this.PurgeListViewItemCache();
11566                             ((DetailsListView)_curTab.Tag).Update();
11567                             if (_curPost != null && _curPost.StatusId == e.StatusId)
11568                                 await this.DispSelectedPost(true);
11569                         }
11570                     });
11571                     return;
11572                 }
11573             }
11574             catch (ObjectDisposedException)
11575             {
11576                 return;
11577             }
11578             catch (InvalidOperationException)
11579             {
11580                 return;
11581             }
11582         }
11583
11584         private int userStreamsRefreshing = 0;
11585
11586         private async void tw_NewPostFromStream(object sender, EventArgs e)
11587         {
11588             if (SettingManager.Common.ReadOldPosts)
11589             {
11590                 _statuses.SetReadHomeTab(); //新着時未読クリア
11591             }
11592
11593             this._statuses.DistributePosts();
11594
11595             if (SettingManager.Common.UserstreamPeriod > 0) return;
11596
11597             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11598             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11599             {
11600                 try
11601                 {
11602                     await this.InvokeAsync(() => this.RefreshTimeline())
11603                         .ConfigureAwait(false);
11604                 }
11605                 finally
11606                 {
11607                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11608                 }
11609             }
11610         }
11611
11612         private async void tw_UserStreamStarted(object sender, EventArgs e)
11613         {
11614             try
11615             {
11616                 if (InvokeRequired && !IsDisposed)
11617                 {
11618                     await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11619                     return;
11620                 }
11621             }
11622             catch (ObjectDisposedException)
11623             {
11624                 return;
11625             }
11626             catch (InvalidOperationException)
11627             {
11628                 return;
11629             }
11630
11631             this.RefreshUserStreamsMenu();
11632             this.MenuItemUserStream.Enabled = true;
11633
11634             StatusLabel.Text = "UserStream Started.";
11635         }
11636
11637         private async void tw_UserStreamStopped(object sender, EventArgs e)
11638         {
11639             try
11640             {
11641                 if (InvokeRequired && !IsDisposed)
11642                 {
11643                     await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11644                     return;
11645                 }
11646             }
11647             catch (ObjectDisposedException)
11648             {
11649                 return;
11650             }
11651             catch (InvalidOperationException)
11652             {
11653                 return;
11654             }
11655
11656             this.RefreshUserStreamsMenu();
11657             this.MenuItemUserStream.Enabled = true;
11658
11659             StatusLabel.Text = "UserStream Stopped.";
11660         }
11661
11662         private void RefreshUserStreamsMenu()
11663         {
11664             if (this.tw.UserStreamActive)
11665             {
11666                 this.MenuItemUserStream.Text = "&UserStream ▶";
11667                 this.StopToolStripMenuItem.Text = "&Stop";
11668             }
11669             else
11670             {
11671                 this.MenuItemUserStream.Text = "&UserStream ■";
11672                 this.StopToolStripMenuItem.Text = "&Start";
11673             }
11674         }
11675
11676         private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11677         {
11678             try
11679             {
11680                 if (InvokeRequired && !IsDisposed)
11681                 {
11682                     await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11683                     return;
11684                 }
11685             }
11686             catch (ObjectDisposedException)
11687             {
11688                 return;
11689             }
11690             catch (InvalidOperationException)
11691             {
11692                 return;
11693             }
11694             var ev = e.EventData;
11695             StatusLabel.Text = "Event: " + ev.Event;
11696             //if (ev.Event == "favorite")
11697             //{
11698             //    NotifyFavorite(ev);
11699             //}
11700             NotifyEvent(ev);
11701             if (ev.Event == "favorite" || ev.Event == "unfavorite")
11702             {
11703                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11704                 {
11705                     this.PurgeListViewItemCache();
11706                     ((DetailsListView)_curTab.Tag).Update();
11707                 }
11708                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11709                 {
11710                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11711                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11712                 }
11713             }
11714         }
11715
11716         private void NotifyEvent(Twitter.FormattedEvent ev)
11717         {
11718             //新着通知 
11719             if (BalloonRequired(ev))
11720             {
11721                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11722                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11723                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11724                 StringBuilder title = new StringBuilder();
11725                 if (SettingManager.Common.DispUsername)
11726                 {
11727                     title.Append(tw.Username);
11728                     title.Append(" - ");
11729                 }
11730                 else
11731                 {
11732                     //title.Clear();
11733                 }
11734                 title.Append(Application.ProductName);
11735                 title.Append(" [");
11736                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11737                 title.Append("] by ");
11738                 if (!string.IsNullOrEmpty(ev.Username))
11739                 {
11740                     title.Append(ev.Username);
11741                 }
11742                 else
11743                 {
11744                     //title.Append("");
11745                 }
11746                 string text;
11747                 if (!string.IsNullOrEmpty(ev.Target))
11748                 {
11749                     //NotifyIcon1.BalloonTipText = ev.Target;
11750                     text = ev.Target;
11751                 }
11752                 else
11753                 {
11754                     //NotifyIcon1.BalloonTipText = " ";
11755                     text = " ";
11756                 }
11757                 //NotifyIcon1.ShowBalloonTip(500);
11758                 if (SettingManager.Common.IsUseNotifyGrowl)
11759                 {
11760                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11761                               ev.Id.ToString(), title.ToString(), text);
11762                 }
11763                 else
11764                 {
11765                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11766                     NotifyIcon1.BalloonTipTitle = title.ToString();
11767                     NotifyIcon1.BalloonTipText = text;
11768                     NotifyIcon1.ShowBalloonTip(500);
11769                 }
11770             }
11771
11772             //サウンド再生
11773             string snd = SettingManager.Common.EventSoundFile;
11774             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11775             {
11776                 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11777                 {
11778                     try
11779                     {
11780                         string dir = Application.StartupPath;
11781                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
11782                         {
11783                             dir = Path.Combine(dir, "Sounds");
11784                         }
11785                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11786                         {
11787                             player.Play();
11788                         }
11789                     }
11790                     catch (Exception)
11791                     {
11792                     }
11793                 }
11794             }
11795         }
11796
11797         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11798         {
11799             MenuItemUserStream.Enabled = false;
11800             if (StopRefreshAllMenuItem.Checked)
11801             {
11802                 StopRefreshAllMenuItem.Checked = false;
11803                 return;
11804             }
11805             if (this.tw.UserStreamActive)
11806             {
11807                 tw.StopUserStream();
11808             }
11809             else
11810             {
11811                 tw.StartUserStream();
11812             }
11813         }
11814
11815         private static string inputTrack = "";
11816
11817         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11818         {
11819             if (TrackToolStripMenuItem.Checked)
11820             {
11821                 using (InputTabName inputForm = new InputTabName())
11822                 {
11823                     inputForm.TabName = inputTrack;
11824                     inputForm.FormTitle = "Input track word";
11825                     inputForm.FormDescription = "Track word";
11826                     if (inputForm.ShowDialog() != DialogResult.OK)
11827                     {
11828                         TrackToolStripMenuItem.Checked = false;
11829                         return;
11830                     }
11831                     inputTrack = inputForm.TabName.Trim();
11832                 }
11833                 if (!inputTrack.Equals(tw.TrackWord))
11834                 {
11835                     tw.TrackWord = inputTrack;
11836                     this.ModifySettingCommon = true;
11837                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11838                     tw.ReconnectUserStream();
11839                 }
11840             }
11841             else
11842             {
11843                 tw.TrackWord = "";
11844                 tw.ReconnectUserStream();
11845             }
11846             this.ModifySettingCommon = true;
11847         }
11848
11849         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11850         {
11851             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11852             this.ModifySettingCommon = true;
11853             tw.ReconnectUserStream();
11854         }
11855
11856         private void EventViewerMenuItem_Click(object sender, EventArgs e)
11857         {
11858             if (evtDialog == null || evtDialog.IsDisposed)
11859             {
11860                 evtDialog = null;
11861                 evtDialog = new EventViewerDialog();
11862                 evtDialog.Owner = this;
11863                 //親の中央に表示
11864                 Point pos = evtDialog.Location;
11865                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11866                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11867                 evtDialog.Location = pos;
11868             }
11869             evtDialog.EventSource = tw.StoredEvent;
11870             if (!evtDialog.Visible)
11871             {
11872                 evtDialog.Show(this);
11873             }
11874             else
11875             {
11876                 evtDialog.Activate();
11877             }
11878             this.TopMost = SettingManager.Common.AlwaysTop;
11879         }
11880 #endregion
11881
11882         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11883         {
11884             MyCommon._endingFlag = true;
11885             try
11886             {
11887                 this.Close();
11888                 Application.Restart();
11889             }
11890             catch (Exception)
11891             {
11892                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11893             }
11894         }
11895
11896         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11897         {
11898             if (!string.IsNullOrEmpty(tw.Username))
11899                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11900         }
11901
11902         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11903         {
11904             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11905         }
11906
11907         private bool ExistCurrentPost
11908         {
11909             get
11910             {
11911                 if (_curPost == null) return false;
11912                 if (_curPost.IsDeleted) return false;
11913                 return true;
11914             }
11915         }
11916
11917         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11918         {
11919             ShowUserTimeline();
11920         }
11921
11922         private string GetUserIdFromCurPostOrInput(string caption)
11923         {
11924             var id = _curPost?.ScreenName ?? "";
11925
11926             using (InputTabName inputName = new InputTabName())
11927             {
11928                 inputName.FormTitle = caption;
11929                 inputName.FormDescription = Properties.Resources.FRMessage1;
11930                 inputName.TabName = id;
11931                 if (inputName.ShowDialog() == DialogResult.OK &&
11932                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
11933                 {
11934                     id = inputName.TabName.Trim();
11935                 }
11936                 else
11937                 {
11938                     id = "";
11939                 }
11940             }
11941             return id;
11942         }
11943
11944         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11945         {
11946             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11947             if (!string.IsNullOrEmpty(id))
11948             {
11949                 AddNewTabForUserTimeline(id);
11950             }
11951         }
11952
11953         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11954         {
11955             string id = GetUserIdFromCurPostOrInput("Show Favstar");
11956             if (!string.IsNullOrEmpty(id))
11957             {
11958                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11959             }
11960         }
11961
11962         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11963         {
11964             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11965         }
11966
11967         private void TimelineRefreshEnableChange(bool isEnable)
11968         {
11969             if (isEnable)
11970             {
11971                 tw.StartUserStream();
11972             }
11973             else
11974             {
11975                 tw.StopUserStream();
11976             }
11977             TimerTimeline.Enabled = isEnable;
11978         }
11979
11980         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11981         {
11982             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11983         }
11984
11985         private async Task OpenUserAppointUrl()
11986         {
11987             if (SettingManager.Common.UserAppointUrl != null)
11988             {
11989                 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11990                 {
11991                     if (_curPost != null)
11992                     {
11993                         string xUrl = SettingManager.Common.UserAppointUrl;
11994                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11995
11996                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11997                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11998
11999                         await this.OpenUriInBrowserAsync(xUrl);
12000                     }
12001                 }
12002                 else
12003                 {
12004                     await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12005                 }
12006             }
12007         }
12008
12009         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12010         {
12011             await this.OpenUserAppointUrl();
12012         }
12013
12014         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12015         {
12016             if (Form.ActiveForm == null)
12017             {
12018                 await this.InvokeAsync(() =>
12019                 {
12020                     this.Visible = true;
12021                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12022                     this.Activate();
12023                     this.BringToFront();
12024                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12025                     {
12026                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12027                     }
12028                     else
12029                     {
12030                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12031                     }
12032                 });
12033             }
12034         }
12035
12036         private void ReplaceAppName()
12037         {
12038             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12039             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12040         }
12041
12042         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12043         {
12044             this.SplitContainer3.Panel2Collapsed = false;
12045         }
12046
12047         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12048         {
12049             await this.OpenThumbnailPicture(e.Thumbnail);
12050         }
12051
12052         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12053         {
12054             await this.OpenUriInBrowserAsync(e.ImageUrl);
12055         }
12056
12057         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12058         {
12059             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12060
12061             await this.OpenUriInBrowserAsync(url);
12062         }
12063
12064         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12065         {
12066             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12067         }
12068
12069         private void PostButton_KeyDown(object sender, KeyEventArgs e)
12070         {
12071             if (e.KeyCode == Keys.Space)
12072             {
12073                 this.JumpUnreadMenuItem_Click(null, null);
12074
12075                 e.SuppressKeyPress = true;
12076             }
12077         }
12078
12079         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12080         {
12081             this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12082             this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12083             this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12084             this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12085             this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12086
12087             this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12088         }
12089
12090         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12091         {
12092             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12093         }
12094
12095         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12096         {
12097             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12098         }
12099
12100         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12101         {
12102             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12103         }
12104
12105         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12106         {
12107             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12108         }
12109
12110         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12111         {
12112             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12113         }
12114
12115         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12116         {
12117             if (SettingManager.Common.IconSize == iconSize) return;
12118
12119             var oldIconCol = _iconCol;
12120
12121             SettingManager.Common.IconSize = iconSize;
12122             ApplyListViewIconSize(iconSize);
12123
12124             if (_iconCol != oldIconCol)
12125             {
12126                 foreach (TabPage tp in ListTab.TabPages)
12127                 {
12128                     ResetColumns((DetailsListView)tp.Tag);
12129                 }
12130             }
12131
12132             _curList?.Refresh();
12133
12134             ModifySettingCommon = true;
12135         }
12136
12137         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12138         {
12139             var state = this.LockListSortOrderToolStripMenuItem.Checked;
12140             if (SettingManager.Common.SortOrderLock == state) return;
12141
12142             SettingManager.Common.SortOrderLock = state;
12143
12144             ModifySettingCommon = true;
12145         }
12146
12147         private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12148         {
12149             if (!string.IsNullOrEmpty(e.StatusText))
12150             {
12151                 this.StatusLabelUrl.Text = e.StatusText;
12152             }
12153             else
12154             {
12155                 this.SetStatusLabelUrl();
12156             }
12157         }
12158     }
12159 }