OSDN Git Service

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