OSDN Git Service

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