OSDN Git Service

Twitter公式のミュート機能を使用したユーザーIDによるミュートを実装
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
35 using System.Drawing;
36 using System.IO;
37 using System.Linq;
38 using System.Media;
39 using System.Net;
40 using System.Net.Http;
41 using System.Reflection;
42 using System.Text;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
47 using OpenTween.Api;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
51
52 namespace OpenTween
53 {
54     public partial class TweenMain : OTBaseForm
55     {
56         private readonly HttpClient http;
57
58         //各種設定
59         private Size _mySize;           //画面サイズ
60         private Point _myLoc;           //画面位置
61         private int _mySpDis;           //区切り位置
62         private int _mySpDis2;          //発言欄区切り位置
63         private int _mySpDis3;          //プレビュー区切り位置
64         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
65         private bool _iconCol;          //1列表示の時true(48サイズのとき)
66
67         //雑多なフラグ類
68         private bool _initial;         //true:起動時処理中
69         private bool _initialLayout = true;
70         private bool _ignoreConfigSave;         //true:起動時処理中
71         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
72         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
73         private Point _tabMouseDownPoint;
74         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
75         private readonly object _syncObject = new object();    //ロック用
76         private const string detailHtmlFormatMono1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- pre {font-family: \"";
77         private const string detailHtmlFormat2 = "\", sans-serif; font-size: ";
78         private const string detailHtmlFormat3 = "pt; margin: 0; word-wrap: break-word; white-space: pre-wrap; color:rgb(";
79         private const string detailHtmlFormat4 = ");} a:link, a:visited, a:active, a:hover {color:rgb(";
80         private const string detailHtmlFormat5 = "); } --></style></head><body style=\"margin:0px; background-color:rgb(";
81         private const string detailHtmlFormatMono6 = ");\"><pre>";
82         private const string detailHtmlFormatMono7 = "</pre></body></html>";
83         private const string detailHtmlFormat1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- p {font-family: \"";
84         private const string detailHtmlFormat6 = ");\"><p><span style=\"vertical-align:text-bottom\">";
85         private const string detailHtmlFormat7 = "</span></p></body></html>";
86         private string detailHtmlFormatHeader;
87         private string detailHtmlFormatFooter;
88         private bool _myStatusError = false;
89         private bool _myStatusOnline = false;
90         private bool soundfileListup = false;
91         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
92
93         //設定ファイル関連
94         //private SettingToConfig _cfg; //旧
95         private SettingLocal _cfgLocal;
96         private SettingCommon _cfgCommon;
97         private bool _modifySettingLocal = false;
98         private bool _modifySettingCommon = false;
99         private bool _modifySettingAtId = false;
100
101         //twitter解析部
102         private Twitter tw = new Twitter();
103
104         //Growl呼び出し部
105         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
106
107         //サブ画面インスタンス
108         private AppendSettingDialog SettingDialog = AppendSettingDialog.Instance;       //設定画面インスタンス
109         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
110         private FilterDialog fltDialog = new FilterDialog(); //フィルター編集画面
111         private OpenURL UrlDialog = new OpenURL();
112         public AtIdSupplement AtIdSupl;     //@id補助
113         public AtIdSupplement HashSupl;    //Hashtag補助
114         public HashtagManage HashMgr;
115         private EventViewerDialog evtDialog;
116
117         //表示フォント、色、アイコン
118         private Font _fntUnread;            //未読用フォント
119         private Color _clUnread;            //未読用文字色
120         private Font _fntReaded;            //既読用フォント
121         private Color _clReaded;            //既読用文字色
122         private Color _clFav;               //Fav用文字色
123         private Color _clOWL;               //片思い用文字色
124         private Color _clRetweet;               //Retweet用文字色
125         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
126         private Font _fntDetail;            //発言詳細部用フォント
127         private Color _clDetail;              //発言詳細部用色
128         private Color _clDetailLink;          //発言詳細部用リンク文字色
129         private Color _clDetailBackcolor;     //発言詳細部用背景色
130         private Color _clSelf;              //自分の発言用背景色
131         private Color _clAtSelf;            //自分宛返信用背景色
132         private Color _clTarget;            //選択発言者の他の発言用背景色
133         private Color _clAtTarget;          //選択発言中の返信先用背景色
134         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
135         private Color _clAtTo;              //選択発言の唯一@先
136         private Color _clListBackcolor;       //リスト部通常発言背景色
137         private Color _clInputBackcolor;      //入力欄背景色
138         private Color _clInputFont;           //入力欄文字色
139         private Font _fntInputFont;           //入力欄フォント
140         private ImageCache IconCache;        //アイコン画像リスト
141         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
142         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
143         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
144         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
145         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
146         private Icon MainIcon;              //Main.ico           画面左上のアイコン
147         private Icon ReplyIcon;               //5g
148         private Icon ReplyIconBlink;          //6g
149
150         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
151
152         private PostClass _anchorPost;
153         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
154
155         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
156         private int _hisIdx;                  //発言履歴カレントインデックス
157
158         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
159         private long? _reply_to_id;     // リプライ先のステータスID 0の場合はリプライではない 注:複数あてのものはリプライではない
160         private string _reply_to_name;    // リプライ先ステータスの書き込み者の名前
161
162         //時速表示用
163         private List<DateTime> _postTimestamps = new List<DateTime>();
164         private List<DateTime> _favTimestamps = new List<DateTime>();
165         private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
166         private int _tlCount;
167
168         // 以下DrawItem関連
169         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
170         private SolidBrush _brsBackColorMine;
171         private SolidBrush _brsBackColorAt;
172         private SolidBrush _brsBackColorYou;
173         private SolidBrush _brsBackColorAtYou;
174         private SolidBrush _brsBackColorAtFromTarget;
175         private SolidBrush _brsBackColorAtTo;
176         private SolidBrush _brsBackColorNone;
177         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
178         private StringFormat sfTab = new StringFormat();
179
180         //////////////////////////////////////////////////////////////////////////////////////////////////////////
181         private ToolStripAPIGauge _apiGauge;
182         private TabInformations _statuses;
183
184         // ListViewItem のキャッシュ関連
185         private int _itemCacheIndex;
186         private ListViewItem[] _itemCache;
187         private PostClass[] _postCache;
188         private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
189
190         private TabPage _curTab;
191         private int _curItemIndex;
192         private DetailsListView _curList;
193         private PostClass _curPost;
194         private bool _isColumnChanged = false;
195         private bool _waitTimeline = false;
196         private bool _waitReply = false;
197         private bool _waitDm = false;
198         private bool _waitFav = false;
199         private bool _waitPubSearch = false;
200         private bool _waitUserTimeline = false;
201         private bool _waitLists = false;
202         private BackgroundWorker[] _bw = new BackgroundWorker[20];
203         private BackgroundWorker _bwFollower;
204         private InternetSecurityManager SecurityManager;
205
206         private int UnreadCounter = -1;
207         private int UnreadAtCounter = -1;
208
209         private string[] ColumnOrgText = new string[9];
210         private string[] ColumnText = new string[9];
211
212         private bool _DoFavRetweetFlags = false;
213         private bool osResumed = false;
214         private Dictionary<string, IMultimediaShareService> pictureService;
215
216         //////////////////////////////////////////////////////////////////////////////////////////////////////////
217         private string _postBrowserStatusText = "";
218
219         private bool _colorize = false;
220
221         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
222
223         private ImageListViewItem displayItem;
224
225         /// <summary>
226         /// デザイン時の DPI (96dpi) と実際の表示時の DPI との比を表します
227         /// </summary>
228         protected SizeF currentScaleFactor = new SizeF();
229
230         //URL短縮のUndo用
231         private struct urlUndo
232         {
233             public string Before;
234             public string After;
235         }
236
237         private List<urlUndo> urlUndoBuffer = null;
238
239         private struct ReplyChain
240         {
241             public long OriginalId;
242             public long InReplyToId;
243             public TabPage OriginalTab;
244
245             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
246             {
247                 this.OriginalId = originalId;
248                 this.InReplyToId = inReplyToId;
249                 this.OriginalTab = originalTab;
250             }
251         }
252
253         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
254         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
255
256         //Backgroundworkerの処理結果通知用引数構造体
257         private class GetWorkerResult
258         {
259             public string retMsg = "";                     //処理結果詳細メッセージ。エラー時に値がセットされる
260             public int page;                      //取得対象ページ番号
261             public int endPage = 0;                   //取得終了ページ番号(継続可能ならインクリメントされて返る。pageと比較して継続判定)
262             public MyCommon.WORKERTYPE type;                   //処理種別
263             public Dictionary<string, Image> imgs = null;                    //新規取得したアイコンイメージ
264             public string tName = "";                  //Fav追加・削除時のタブ名
265             public List<long> ids = null;               //Fav追加・削除時のID
266             public List<long> sIds = null;                  //Fav追加・削除成功分のID
267             public bool newDM = false;
268             public int addCount;
269             public PostingStatus status;
270         }
271
272         //Backgroundworkerへ処理内容を通知するための引数用構造体
273         private class GetWorkerArg
274         {
275             public int page;                      //処理対象ページ番号
276             public int endPage;                   //処理終了ページ番号(起動時の読み込みページ数。通常時はpageと同じ値をセット)
277             public MyCommon.WORKERTYPE type;                   //処理種別
278             public string url = "";            //URLをブラウザで開くときのアドレス
279             public PostingStatus status = new PostingStatus();          //発言POST時の発言内容
280             public List<long> ids;               //Fav追加・削除時のItemIndex
281             public List<long> sIds;              //Fav追加・削除成功分のItemIndex
282             public string tName = "";            //Fav追加・削除時のタブ名
283         }
284
285         //検索処理タイプ
286         private enum SEARCHTYPE
287         {
288             DialogSearch,
289             NextSearch,
290             PrevSearch,
291         }
292
293         private class PostingStatus
294         {
295             public string status = "";
296             public long? inReplyToId = null;
297             public string inReplyToName = null;
298             public string imageService = "";      //画像投稿サービス名
299             public string imagePath = "";
300             public PostingStatus()
301             {
302             }
303             public PostingStatus(string status, long? replyToId, string replyToName)
304             {
305                 this.status = status;
306                 this.inReplyToId = replyToId;
307                 this.inReplyToName = replyToName;
308             }
309         }
310
311         private void TweenMain_Activated(object sender, EventArgs e)
312         {
313             //画面がアクティブになったら、発言欄の背景色戻す
314             if (StatusText.Focused)
315             {
316                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
317             }
318         }
319
320         private void TweenMain_Disposed(object sender, EventArgs e)
321         {
322             //後始末
323             SettingDialog.Dispose();
324             SearchDialog.Dispose();
325             fltDialog.Dispose();
326             UrlDialog.Dispose();
327             if (NIconAt != null) NIconAt.Dispose();
328             if (NIconAtRed != null) NIconAtRed.Dispose();
329             if (NIconAtSmoke != null) NIconAtSmoke.Dispose();
330             if (NIconRefresh[0] != null) NIconRefresh[0].Dispose();
331             if (NIconRefresh[1] != null) NIconRefresh[1].Dispose();
332             if (NIconRefresh[2] != null) NIconRefresh[2].Dispose();
333             if (NIconRefresh[3] != null) NIconRefresh[3].Dispose();
334             if (TabIcon != null) TabIcon.Dispose();
335             if (MainIcon != null) MainIcon.Dispose();
336             if (ReplyIcon != null) ReplyIcon.Dispose();
337             if (ReplyIconBlink != null) ReplyIconBlink.Dispose();
338             _listViewImageList.Dispose();
339             _brsHighLight.Dispose();
340             if (_brsBackColorMine != null) _brsBackColorMine.Dispose();
341             if (_brsBackColorAt != null) _brsBackColorAt.Dispose();
342             if (_brsBackColorYou != null) _brsBackColorYou.Dispose();
343             if (_brsBackColorAtYou != null) _brsBackColorAtYou.Dispose();
344             if (_brsBackColorAtFromTarget != null) _brsBackColorAtFromTarget.Dispose();
345             if (_brsBackColorAtTo != null) _brsBackColorAtTo.Dispose();
346             if (_brsBackColorNone != null) _brsBackColorNone.Dispose();
347             if (_brsDeactiveSelection != null) _brsDeactiveSelection.Dispose();
348             //sf.Dispose();
349             sfTab.Dispose();
350             foreach (BackgroundWorker bw in _bw)
351             {
352                 if (bw != null)
353                     bw.Dispose();
354             }
355             if (_bwFollower != null)
356             {
357                 _bwFollower.Dispose();
358             }
359             this._apiGauge.Dispose();
360             if (IconCache != null)
361             {
362                 this.IconCache.CancelAsync();
363                 this.IconCache.Dispose();
364             }
365
366             this.http.Dispose();
367
368             // 終了時にRemoveHandlerしておかないとメモリリークする
369             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
370             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
371         }
372
373         private void LoadIcon(ref Icon IconInstance, string FileName)
374         {
375             string dir = Application.StartupPath;
376             if (File.Exists(Path.Combine(dir, FileName)))
377             {
378                 try
379                 {
380                     IconInstance = new Icon(Path.Combine(dir, FileName));
381                 }
382                 catch (Exception)
383                 {
384                 }
385             }
386         }
387
388         private void LoadIcons()
389         {
390             //着せ替えアイコン対応
391             //タスクトレイ通常時アイコン
392             string dir = Application.StartupPath;
393
394             NIconAt = Properties.Resources.At;
395             NIconAtRed = Properties.Resources.AtRed;
396             NIconAtSmoke = Properties.Resources.AtSmoke;
397             NIconRefresh[0] = Properties.Resources.Refresh;
398             NIconRefresh[1] = Properties.Resources.Refresh2;
399             NIconRefresh[2] = Properties.Resources.Refresh3;
400             NIconRefresh[3] = Properties.Resources.Refresh4;
401             TabIcon = Properties.Resources.TabIcon;
402             MainIcon = Properties.Resources.MIcon;
403             ReplyIcon = Properties.Resources.Reply;
404             ReplyIconBlink = Properties.Resources.ReplyBlink;
405
406             if (!Directory.Exists(Path.Combine(dir, "Icons")))
407                 return;
408
409             LoadIcon(ref NIconAt, "Icons\\At.ico");
410
411             //タスクトレイエラー時アイコン
412             LoadIcon(ref NIconAtRed, "Icons\\AtRed.ico");
413
414             //タスクトレイオフライン時アイコン
415             LoadIcon(ref NIconAtSmoke, "Icons\\AtSmoke.ico");
416
417             //タスクトレイ更新中アイコン
418             //アニメーション対応により4種類読み込み
419             LoadIcon(ref NIconRefresh[0], "Icons\\Refresh.ico");
420             LoadIcon(ref NIconRefresh[1], "Icons\\Refresh2.ico");
421             LoadIcon(ref NIconRefresh[2], "Icons\\Refresh3.ico");
422             LoadIcon(ref NIconRefresh[3], "Icons\\Refresh4.ico");
423
424             //タブ見出し未読表示アイコン
425             LoadIcon(ref TabIcon, "Icons\\Tab.ico");
426
427             //画面のアイコン
428             LoadIcon(ref MainIcon, "Icons\\MIcon.ico");
429
430             //Replyのアイコン
431             LoadIcon(ref ReplyIcon, "Icons\\Reply.ico");
432
433             //Reply点滅のアイコン
434             LoadIcon(ref ReplyIconBlink, "Icons\\ReplyBlink.ico");
435         }
436
437         private void InitColumns(ListView list, bool startup)
438         {
439             ColumnHeader _colHd1 = new ColumnHeader();  //アイコン
440             ColumnHeader _colHd2 = new ColumnHeader();  //ニックネーム
441             ColumnHeader _colHd3 = new ColumnHeader();  //本文
442             ColumnHeader _colHd4 = new ColumnHeader();  //日付
443             ColumnHeader _colHd5 = new ColumnHeader();  //ユーザID
444             ColumnHeader _colHd6 = new ColumnHeader();  //未読
445             ColumnHeader _colHd7 = new ColumnHeader();  //マーク&プロテクト
446             ColumnHeader _colHd8 = new ColumnHeader();  //ソース
447
448             if (!_iconCol)
449             {
450                 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
451             }
452             else
453             {
454                 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
455             }
456
457             InitColumnText();
458             _colHd1.Text = ColumnText[0];
459             _colHd1.Width = 48;
460             _colHd2.Text = ColumnText[1];
461             _colHd2.Width = 80;
462             _colHd3.Text = ColumnText[2];
463             _colHd3.Width = 300;
464             _colHd4.Text = ColumnText[3];
465             _colHd4.Width = 50;
466             _colHd5.Text = ColumnText[4];
467             _colHd5.Width = 50;
468             _colHd6.Text = ColumnText[5];
469             _colHd6.Width = 16;
470             _colHd7.Text = ColumnText[6];
471             _colHd7.Width = 16;
472             _colHd8.Text = ColumnText[7];
473             _colHd8.Width = 50;
474
475             int[] dispOrder = new int[8];
476             if (!startup)
477             {
478                 for (int i = 0; i < _curList.Columns.Count; i++)
479                 {
480                     for (int j = 0; j < _curList.Columns.Count; j++)
481                     {
482                         if (_curList.Columns[j].DisplayIndex == i)
483                         {
484                             dispOrder[i] = j;
485                             break;
486                         }
487                     }
488                 }
489                 for (int i = 0; i < _curList.Columns.Count; i++)
490                 {
491                     list.Columns[i].Width = _curList.Columns[i].Width;
492                     list.Columns[dispOrder[i]].DisplayIndex = i;
493                 }
494             }
495             else
496             {
497                 if (_iconCol)
498                 {
499                     list.Columns[0].Width = _cfgLocal.Width1;
500                     list.Columns[1].Width = _cfgLocal.Width3;
501                     list.Columns[0].DisplayIndex = 0;
502                     list.Columns[1].DisplayIndex = 1;
503                 }
504                 else
505                 {
506                     for (int i = 0; i <= 7; i++)
507                     {
508                         if (_cfgLocal.DisplayIndex1 == i)
509                             dispOrder[i] = 0;
510                         else if (_cfgLocal.DisplayIndex2 == i)
511                             dispOrder[i] = 1;
512                         else if (_cfgLocal.DisplayIndex3 == i)
513                             dispOrder[i] = 2;
514                         else if (_cfgLocal.DisplayIndex4 == i)
515                             dispOrder[i] = 3;
516                         else if (_cfgLocal.DisplayIndex5 == i)
517                             dispOrder[i] = 4;
518                         else if (_cfgLocal.DisplayIndex6 == i)
519                             dispOrder[i] = 5;
520                         else if (_cfgLocal.DisplayIndex7 == i)
521                             dispOrder[i] = 6;
522                         else if (_cfgLocal.DisplayIndex8 == i)
523                             dispOrder[i] = 7;
524                     }
525                     list.Columns[0].Width = _cfgLocal.Width1;
526                     list.Columns[1].Width = _cfgLocal.Width2;
527                     list.Columns[2].Width = _cfgLocal.Width3;
528                     list.Columns[3].Width = _cfgLocal.Width4;
529                     list.Columns[4].Width = _cfgLocal.Width5;
530                     list.Columns[5].Width = _cfgLocal.Width6;
531                     list.Columns[6].Width = _cfgLocal.Width7;
532                     list.Columns[7].Width = _cfgLocal.Width8;
533                     for (int i = 0; i <= 7; i++)
534                     {
535                         list.Columns[dispOrder[i]].DisplayIndex = i;
536                     }
537                 }
538             }
539         }
540
541         private void InitColumnText()
542         {
543             ColumnText[0] = "";
544             ColumnText[1] = Properties.Resources.AddNewTabText2;
545             ColumnText[2] = Properties.Resources.AddNewTabText3;
546             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
547             ColumnText[4] = Properties.Resources.AddNewTabText5;
548             ColumnText[5] = "";
549             ColumnText[6] = "";
550             ColumnText[7] = "Source";
551
552             ColumnOrgText[0] = "";
553             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
554             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
555             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
556             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
557             ColumnOrgText[5] = "";
558             ColumnOrgText[6] = "";
559             ColumnOrgText[7] = "Source";
560
561             int c = 0;
562             switch (_statuses.SortMode)
563             {
564                 case IdComparerClass.ComparerMode.Nickname:  //ニックネーム
565                     c = 1;
566                     break;
567                 case IdComparerClass.ComparerMode.Data:  //本文
568                     c = 2;
569                     break;
570                 case IdComparerClass.ComparerMode.Id:  //時刻=発言Id
571                     c = 3;
572                     break;
573                 case IdComparerClass.ComparerMode.Name:  //名前
574                     c = 4;
575                     break;
576                 case IdComparerClass.ComparerMode.Source:  //Source
577                     c = 7;
578                     break;
579             }
580
581             if (_iconCol)
582             {
583                 if (_statuses.SortOrder == SortOrder.Descending)
584                 {
585                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
586                     ColumnText[2] = ColumnOrgText[2] + "▾";
587                 }
588                 else
589                 {
590                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
591                     ColumnText[2] = ColumnOrgText[2] + "▴";
592                 }
593             }
594             else
595             {
596                 if (_statuses.SortOrder == SortOrder.Descending)
597                 {
598                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
599                     ColumnText[c] = ColumnOrgText[c] + "▾";
600                 }
601                 else
602                 {
603                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
604                     ColumnText[c] = ColumnOrgText[c] + "▴";
605                 }
606             }
607         }
608
609         private void InitializeTraceFrag()
610         {
611 #if DEBUG
612             TraceOutToolStripMenuItem.Checked = true;
613             MyCommon.TraceFlag = true;
614 #endif
615             if (!MyCommon.FileVersion.EndsWith("0"))
616             {
617                 TraceOutToolStripMenuItem.Checked = true;
618                 MyCommon.TraceFlag = true;
619             }
620         }
621
622         private void TweenMain_Load(object sender, EventArgs e)
623         {
624             _ignoreConfigSave = true;
625             this.Visible = false;
626
627             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
628
629             SecurityManager = new InternetSecurityManager(PostBrowser);
630             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
631
632             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
633             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
634
635             if (MyApplication.StartupOptions.ContainsKey("d"))
636                 MyCommon.TraceFlag = true;
637
638             Regex.CacheSize = 100;
639
640             InitializeTraceFrag();
641             LoadIcons(); // アイコン読み込み
642
643             //発言保持クラス
644             _statuses = TabInformations.GetInstance();
645
646             //アイコン設定
647             this.Icon = MainIcon;              //メインフォーム(TweenMain)
648             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
649             TabImage.Images.Add(TabIcon);    //タブ見出し
650
651             SettingDialog.Owner = this;;
652             SearchDialog.Owner = this;
653             fltDialog.Owner = this;
654             UrlDialog.Owner = this;
655
656             _history.Add(new PostingStatus());
657             _hisIdx = 0;
658             _reply_to_id = null;
659             _reply_to_name = null;
660
661             //<<<<<<<<<設定関連>>>>>>>>>
662             //設定コンバージョン
663             //ConvertConfig();
664
665             ////設定読み出し
666             LoadConfig();
667
668             ThumbnailGenerator.InitializeGenerator(this.http);
669
670             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
671             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
672             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
673
674             Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
675                 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
676                     this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
677
678             //新着バルーン通知のチェック状態設定
679             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
680             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
681
682             //フォント&文字色&背景色保持
683             _fntUnread = _cfgLocal.FontUnread;
684             _clUnread = _cfgLocal.ColorUnread;
685             _fntReaded = _cfgLocal.FontRead;
686             _clReaded = _cfgLocal.ColorRead;
687             _clFav = _cfgLocal.ColorFav;
688             _clOWL = _cfgLocal.ColorOWL;
689             _clRetweet = _cfgLocal.ColorRetweet;
690             _fntDetail = _cfgLocal.FontDetail;
691             _clDetail = _cfgLocal.ColorDetail;
692             _clDetailLink = _cfgLocal.ColorDetailLink;
693             _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
694             _clSelf = _cfgLocal.ColorSelf;
695             _clAtSelf = _cfgLocal.ColorAtSelf;
696             _clTarget = _cfgLocal.ColorTarget;
697             _clAtTarget = _cfgLocal.ColorAtTarget;
698             _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
699             _clAtTo = _cfgLocal.ColorAtTo;
700             _clListBackcolor = _cfgLocal.ColorListBackcolor;
701             _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
702             _clInputFont = _cfgLocal.ColorInputFont;
703             _fntInputFont = _cfgLocal.FontInputFont;
704
705             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
706             if (fontUIGlobal != null)
707             {
708                 OTBaseForm.GlobalFont = fontUIGlobal;
709                 this.Font = fontUIGlobal;
710             }
711
712             // StringFormatオブジェクトへの事前設定
713             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
714             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
715             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
716             sfTab.Alignment = StringAlignment.Center;
717             sfTab.LineAlignment = StringAlignment.Center;
718
719             //設定画面への反映
720             HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
721             SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
722
723             //認証関連
724             if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
725             tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
726
727             SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
728
729             SettingDialog.TimelinePeriodInt = _cfgCommon.TimelinePeriod;
730             SettingDialog.ReplyPeriodInt = _cfgCommon.ReplyPeriod;
731             SettingDialog.DMPeriodInt = _cfgCommon.DMPeriod;
732             SettingDialog.PubSearchPeriodInt = _cfgCommon.PubSearchPeriod;
733             SettingDialog.UserTimelinePeriodInt = _cfgCommon.UserTimelinePeriod;
734             SettingDialog.ListsPeriodInt = _cfgCommon.ListsPeriod;
735             //不正値チェック
736             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
737             {
738                 if (SettingDialog.TimelinePeriodInt < 15 && SettingDialog.TimelinePeriodInt > 0) SettingDialog.TimelinePeriodInt = 15;
739                 if (SettingDialog.ReplyPeriodInt < 15 && SettingDialog.ReplyPeriodInt > 0) SettingDialog.ReplyPeriodInt = 15;
740                 if (SettingDialog.DMPeriodInt < 15 && SettingDialog.DMPeriodInt > 0) SettingDialog.DMPeriodInt = 15;
741                 if (SettingDialog.PubSearchPeriodInt < 30 && SettingDialog.PubSearchPeriodInt > 0) SettingDialog.PubSearchPeriodInt = 30;
742                 if (SettingDialog.UserTimelinePeriodInt < 15 && SettingDialog.UserTimelinePeriodInt > 0) SettingDialog.UserTimelinePeriodInt = 15;
743                 if (SettingDialog.ListsPeriodInt < 15 && SettingDialog.ListsPeriodInt > 0) SettingDialog.ListsPeriodInt = 15;
744             }
745
746             //起動時読み込み分を既読にするか。trueなら既読として処理
747             SettingDialog.Readed = _cfgCommon.Read;
748             //新着取得時のリストスクロールをするか。trueならスクロールしない
749             ListLockMenuItem.Checked = _cfgCommon.ListLock;
750             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
751             SettingDialog.IconSz = _cfgCommon.IconSize;
752             //文末ステータス
753             SettingDialog.Status = _cfgLocal.StatusText;
754             //未読管理。trueなら未読管理する
755             SettingDialog.UnreadManage = _cfgCommon.UnreadManage;
756             //サウンド再生(タブ別設定より優先)
757             SettingDialog.PlaySound = _cfgCommon.PlaySound;
758             PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
759             this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
760             //片思い表示。trueなら片思い表示する
761             SettingDialog.OneWayLove = _cfgCommon.OneWayLove;
762             //フォント&文字色&背景色
763             SettingDialog.FontUnread = _fntUnread;
764             SettingDialog.ColorUnread = _clUnread;
765             SettingDialog.FontReaded = _fntReaded;
766             SettingDialog.ColorReaded = _clReaded;
767             SettingDialog.ColorFav = _clFav;
768             SettingDialog.ColorOWL = _clOWL;
769             SettingDialog.ColorRetweet = _clRetweet;
770             SettingDialog.FontDetail = _fntDetail;
771             SettingDialog.ColorDetail = _clDetail;
772             SettingDialog.ColorDetailLink = _clDetailLink;
773             SettingDialog.ColorDetailBackcolor = _clDetailBackcolor;
774             SettingDialog.ColorSelf = _clSelf;
775             SettingDialog.ColorAtSelf = _clAtSelf;
776             SettingDialog.ColorTarget = _clTarget;
777             SettingDialog.ColorAtTarget = _clAtTarget;
778             SettingDialog.ColorAtFromTarget = _clAtFromTarget;
779             SettingDialog.ColorAtTo = _clAtTo;
780             SettingDialog.ColorListBackcolor = _clListBackcolor;
781             SettingDialog.ColorInputBackcolor = _clInputBackcolor;
782             SettingDialog.ColorInputFont = _clInputFont;
783             SettingDialog.FontInputFont = _fntInputFont;
784
785             SettingDialog.NameBalloon = _cfgCommon.NameBalloon;
786             SettingDialog.PostCtrlEnter = _cfgCommon.PostCtrlEnter;
787             SettingDialog.PostShiftEnter = _cfgCommon.PostShiftEnter;
788
789             SettingDialog.CountApi = _cfgCommon.CountApi;
790             SettingDialog.CountApiReply = _cfgCommon.CountApiReply;
791             if (SettingDialog.CountApi < 20 || SettingDialog.CountApi > 200) SettingDialog.CountApi = 60;
792             if (SettingDialog.CountApiReply < 20 || SettingDialog.CountApiReply > 200) SettingDialog.CountApiReply = 40;
793
794             SettingDialog.BrowserPath = _cfgLocal.BrowserPath;
795             SettingDialog.PostAndGet = _cfgCommon.PostAndGet;
796             SettingDialog.UseRecommendStatus = _cfgLocal.UseRecommendStatus;
797             SettingDialog.DispUsername = _cfgCommon.DispUsername;
798             SettingDialog.CloseToExit = _cfgCommon.CloseToExit;
799             SettingDialog.MinimizeToTray = _cfgCommon.MinimizeToTray;
800             SettingDialog.DispLatestPost = _cfgCommon.DispLatestPost;
801             SettingDialog.SortOrderLock = _cfgCommon.SortOrderLock;
802             SettingDialog.ViewTabBottom = _cfgCommon.ViewTabBottom;
803             SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
804
805             SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
806             SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
807             SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
808             SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
809             SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
810
811             SettingDialog.StartupVersion = _cfgCommon.StartupVersion;
812             SettingDialog.StartupFollowers = _cfgCommon.StartupFollowers;
813             SettingDialog.RestrictFavCheck = _cfgCommon.RestrictFavCheck;
814             SettingDialog.AlwaysTop = _cfgCommon.AlwaysTop;
815             SettingDialog.UrlConvertAuto = false;
816             //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
817
818             SettingDialog.UseUnreadStyle = _cfgCommon.UseUnreadStyle;
819             SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
820             SettingDialog.RetweetNoConfirm = _cfgCommon.RetweetNoConfirm;
821             SettingDialog.PlaySound = _cfgCommon.PlaySound;
822             SettingDialog.DateTimeFormat = _cfgCommon.DateTimeFormat;
823             SettingDialog.LimitBalloon = _cfgCommon.LimitBalloon;
824             SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
825             SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
826             SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
827             SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
828             SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
829             SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
830             SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
831
832             //廃止サービスが選択されていた場合bit.lyへ読み替え
833             if (_cfgCommon.AutoShortUrlFirst < 0)
834                 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
835
836             SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
837             SettingDialog.TabIconDisp = _cfgCommon.TabIconDisp;
838             SettingDialog.ReplyIconState = _cfgCommon.ReplyIconState;
839             SettingDialog.ReadOwnPost = _cfgCommon.ReadOwnPost;
840             SettingDialog.GetFav = _cfgCommon.GetFav;
841             SettingDialog.ReadOldPosts = _cfgCommon.ReadOldPosts;
842             SettingDialog.BitlyUser = _cfgCommon.BilyUser;
843             SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
844             SettingDialog.ShowGrid = _cfgCommon.ShowGrid;
845             SettingDialog.Language = _cfgCommon.Language;
846             SettingDialog.UseAtIdSupplement = _cfgCommon.UseAtIdSupplement;
847             SettingDialog.UseHashSupplement = _cfgCommon.UseHashSupplement;
848             SettingDialog.PreviewEnable = _cfgCommon.PreviewEnable;
849             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
850
851             SettingDialog.IsMonospace = _cfgCommon.IsMonospace;
852
853             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
854             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
855
856             //Regex statregex = new Regex("^0*");
857             SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
858
859             //書式指定文字列エラーチェック
860             try
861             {
862                 if (DateTime.Now.ToString(SettingDialog.DateTimeFormat).Length == 0)
863                 {
864                     // このブロックは絶対に実行されないはず
865                     // 変換が成功した場合にLengthが0にならない
866                     SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
867                 }
868             }
869             catch (FormatException)
870             {
871                 // FormatExceptionが発生したら初期値を設定 (=yyyy/MM/dd H:mm:ssとみなされる)
872                 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
873             }
874
875             SettingDialog.Nicoms = _cfgCommon.Nicoms;
876             SettingDialog.HotkeyEnabled = _cfgCommon.HotkeyEnabled;
877             SettingDialog.HotkeyMod = _cfgCommon.HotkeyModifier;
878             SettingDialog.HotkeyKey = _cfgCommon.HotkeyKey;
879             SettingDialog.HotkeyValue = _cfgCommon.HotkeyValue;
880
881             SettingDialog.BlinkNewMentions = _cfgCommon.BlinkNewMentions;
882
883             SettingDialog.UseAdditionalCount = _cfgCommon.UseAdditionalCount;
884             SettingDialog.MoreCountApi = _cfgCommon.MoreCountApi;
885             SettingDialog.FirstCountApi = _cfgCommon.FirstCountApi;
886             SettingDialog.SearchCountApi = _cfgCommon.SearchCountApi;
887             SettingDialog.FavoritesCountApi = _cfgCommon.FavoritesCountApi;
888             SettingDialog.UserTimelineCountApi = _cfgCommon.UserTimelineCountApi;
889             SettingDialog.ListCountApi = _cfgCommon.ListCountApi;
890
891             SettingDialog.UserstreamStartup = _cfgCommon.UserstreamStartup;
892             SettingDialog.UserstreamPeriodInt = _cfgCommon.UserstreamPeriod;
893             SettingDialog.OpenUserTimeline = _cfgCommon.OpenUserTimeline;
894             SettingDialog.ListDoubleClickAction = _cfgCommon.ListDoubleClickAction;
895             SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
896             SettingDialog.HideDuplicatedRetweets = _cfgCommon.HideDuplicatedRetweets;
897
898             SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
899             SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
900             SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
901             SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
902             SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
903             SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
904             SettingDialog.IsListStatusesIncludeRts = _cfgCommon.IsListsIncludeRts;
905             SettingDialog.TabMouseLock = _cfgCommon.TabMouseLock;
906             SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
907             SettingDialog.IsNotifyUseGrowl = _cfgCommon.IsUseNotifyGrowl;
908
909             //ハッシュタグ関連
910             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
911             HashMgr = new HashtagManage(HashSupl,
912                                     _cfgCommon.HashTags.ToArray(),
913                                     _cfgCommon.HashSelected,
914                                     _cfgCommon.HashIsPermanent,
915                                     _cfgCommon.HashIsHead,
916                                     _cfgCommon.HashIsNotAddToAtReply);
917             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
918
919             _initial = true;
920
921             //アイコンリスト作成
922             this.IconCache = new ImageCache(this.http);
923
924             bool saveRequired = false;
925             bool firstRun = false;
926
927             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
928             if (string.IsNullOrEmpty(tw.Username))
929             {
930                 saveRequired = true;
931                 firstRun = true;
932                 SettingDialog.ShowInTaskbar = true;
933
934                 //設定せずにキャンセルされた場合はプログラム終了
935                 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
936                 {
937                     Application.Exit();  //強制終了
938                     return;
939                 }
940                 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
941                 if (string.IsNullOrEmpty(tw.Username))
942                 {
943                     Application.Exit();  //強制終了
944                     return;
945                 }
946                 SettingDialog.ShowInTaskbar = false;
947
948                 //新しい設定を反映
949                 //フォント&文字色&背景色保持
950                 _fntUnread = SettingDialog.FontUnread;
951                 _clUnread = SettingDialog.ColorUnread;
952                 _fntReaded = SettingDialog.FontReaded;
953                 _clReaded = SettingDialog.ColorReaded;
954                 _clFav = SettingDialog.ColorFav;
955                 _clOWL = SettingDialog.ColorOWL;
956                 _clRetweet = SettingDialog.ColorRetweet;
957                 _fntDetail = SettingDialog.FontDetail;
958                 _clDetail = SettingDialog.ColorDetail;
959                 _clDetailLink = SettingDialog.ColorDetailLink;
960                 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
961                 _clSelf = SettingDialog.ColorSelf;
962                 _clAtSelf = SettingDialog.ColorAtSelf;
963                 _clTarget = SettingDialog.ColorTarget;
964                 _clAtTarget = SettingDialog.ColorAtTarget;
965                 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
966                 _clAtTo = SettingDialog.ColorAtTo;
967                 _clListBackcolor = SettingDialog.ColorListBackcolor;
968                 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
969                 _clInputFont = SettingDialog.ColorInputFont;
970                 _fntInputFont = SettingDialog.FontInputFont;
971
972                 //他の設定項目は、随時設定画面で保持している値を読み出して使用
973             }
974
975             _brsBackColorMine = new SolidBrush(_clSelf);
976             _brsBackColorAt = new SolidBrush(_clAtSelf);
977             _brsBackColorYou = new SolidBrush(_clTarget);
978             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
979             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
980             _brsBackColorAtTo = new SolidBrush(_clAtTo);
981             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
982             _brsBackColorNone = new SolidBrush(_clListBackcolor);
983
984             InitDetailHtmlFormat();
985
986             if (SettingDialog.HotkeyEnabled)
987             {
988                 //////グローバルホットキーの登録
989                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
990                 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
991                 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
992                 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
993                 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
994
995                 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
996             }
997
998             //Twitter用通信クラス初期化
999             HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
1000                                                 SettingDialog.SelectedProxyType,
1001                                                 SettingDialog.ProxyAddress,
1002                                                 SettingDialog.ProxyPort,
1003                                                 SettingDialog.ProxyUser,
1004                                                 SettingDialog.ProxyPassword);
1005
1006             tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
1007             tw.ReadOwnPost = SettingDialog.ReadOwnPost;
1008             ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
1009             ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
1010             ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
1011             HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
1012             tw.TrackWord = _cfgCommon.TrackWord;
1013             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
1014             tw.AllAtReply = _cfgCommon.AllAtReply;
1015             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
1016
1017             //画像投稿サービス
1018             this.CreatePictureServices();
1019             SetImageServiceCombo();
1020             ImageSelectionPanel.Enabled = false;
1021
1022             SelectImageServiceComboItem(_cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
1023
1024             //ウィンドウ設定
1025             this.ClientSize = _cfgLocal.FormSize;
1026             _mySize = _cfgLocal.FormSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1027             _myLoc = _cfgLocal.FormLocation;
1028             //タイトルバー領域
1029             if (this.WindowState != FormWindowState.Minimized)
1030             {
1031                 this.DesktopLocation = _cfgLocal.FormLocation;
1032                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1033                 bool outOfScreen = true;
1034                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
1035                 {
1036                     foreach (Screen scr in Screen.AllScreens)
1037                     {
1038                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1039                         {
1040                             outOfScreen = false;
1041                             break;
1042                         }
1043                     }
1044                     if (outOfScreen)
1045                     {
1046                         this.DesktopLocation = new Point(0, 0);
1047                         _myLoc = this.DesktopLocation;
1048                     }
1049                 }
1050             }
1051             this.TopMost = SettingDialog.AlwaysTop;
1052             _mySpDis = _cfgLocal.SplitterDistance;
1053             _mySpDis2 = _cfgLocal.StatusTextHeight;
1054             _mySpDis3 = _cfgLocal.PreviewDistance;
1055             if (_mySpDis3 == -1)
1056             {
1057                 _mySpDis3 = _mySize.Width - 150;
1058                 if (_mySpDis3 < 1) _mySpDis3 = 50;
1059                 _cfgLocal.PreviewDistance = _mySpDis3;
1060             }
1061             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
1062             //this.Tween_ClientSizeChanged(this, null);
1063             PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
1064             this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
1065             //入力欄
1066             StatusText.Font = _fntInputFont;
1067             StatusText.ForeColor = _clInputFont;
1068
1069             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
1070             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
1071
1072             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1073             if (SettingDialog.UnreadManage == false)
1074             {
1075                 ReadedStripMenuItem.Enabled = false;
1076                 UnreadStripMenuItem.Enabled = false;
1077             }
1078
1079             if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
1080
1081             //タイマー設定
1082             TimerTimeline.AutoReset = true;
1083             TimerTimeline.SynchronizingObject = this;
1084             //Recent取得間隔
1085             TimerTimeline.Interval = 1000;
1086             TimerTimeline.Enabled = true;
1087
1088             //更新中アイコンアニメーション間隔
1089             TimerRefreshIcon.Interval = 200;
1090             TimerRefreshIcon.Enabled = true;
1091
1092             //状態表示部の初期化(画面右下)
1093             StatusLabel.Text = "";
1094             StatusLabel.AutoToolTip = false;
1095             StatusLabel.ToolTipText = "";
1096             //文字カウンタ初期化
1097             lblLen.Text = GetRestStatusCount(true, false).ToString();
1098
1099             ////////////////////////////////////////////////////////////////////////////////
1100             _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1101             IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1102             switch (_cfgCommon.SortColumn)
1103             {
1104                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1105                 case 5:
1106                 case 6:
1107                     //ソートしない
1108                     mode = IdComparerClass.ComparerMode.Id;  //Idソートに読み替え
1109                     break;
1110                 case 1:  //ニックネーム
1111                     mode = IdComparerClass.ComparerMode.Nickname;
1112                     break;
1113                 case 2:  //本文
1114                     mode = IdComparerClass.ComparerMode.Data;
1115                     break;
1116                 case 3:  //時刻=発言Id
1117                     mode = IdComparerClass.ComparerMode.Id;
1118                     break;
1119                 case 4:  //名前
1120                     mode = IdComparerClass.ComparerMode.Name;
1121                     break;
1122                 case 7:  //Source
1123                     mode = IdComparerClass.ComparerMode.Source;
1124                     break;
1125             }
1126             _statuses.SortMode = mode;
1127             ////////////////////////////////////////////////////////////////////////////////
1128
1129             ApplyListViewIconSize(SettingDialog.IconSz);
1130
1131             tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
1132
1133             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1134             StatusLabelUrl.Text = "";            //画面左下のリンク先URL表示部を初期化
1135             NameLabel.Text = "";                 //発言詳細部名前ラベル初期化
1136             DateTimeLabel.Text = "";             //発言詳細部日時ラベル初期化
1137             SourceLinkLabel.Text = "";           //Source部分初期化
1138
1139             //<<<<<<<<タブ関連>>>>>>>
1140             //デフォルトタブの存在チェック、ない場合には追加
1141             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1142             {
1143                 TabClass tab;
1144                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1145                 {
1146                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1147                 }
1148                 else
1149                 {
1150                     tab.TabType = MyCommon.TabUsageType.Home;
1151                 }
1152             }
1153             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1154             {
1155                 TabClass tab;
1156                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1157                 {
1158                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1159                 }
1160                 else
1161                 {
1162                     tab.TabType = MyCommon.TabUsageType.Mentions;
1163                 }
1164             }
1165             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1166             {
1167                 TabClass tab;
1168                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1169                 {
1170                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1171                 }
1172                 else
1173                 {
1174                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1175                 }
1176             }
1177             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1178             {
1179                 TabClass tab;
1180                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1181                 {
1182                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1183                 }
1184                 else
1185                 {
1186                     tab.TabType = MyCommon.TabUsageType.Favorites;
1187                 }
1188             }
1189             foreach (var tab in _statuses.Tabs.Values)
1190             {
1191                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1192                 {
1193                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1194                 }
1195                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo)) throw new Exception(Properties.Resources.TweenMain_LoadText1);
1196             }
1197
1198             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1199             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1200             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1201             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1202
1203             if (SettingDialog.MinimizeToTray == false || this.WindowState != FormWindowState.Minimized)
1204             {
1205                 this.Visible = true;
1206             }
1207             _curTab = ListTab.SelectedTab;
1208             _curItemIndex = -1;
1209             _curList = (DetailsListView)_curTab.Tag;
1210             SetMainWindowTitle();
1211             SetNotifyIconText();
1212
1213             if (SettingDialog.TabIconDisp)
1214             {
1215                 ListTab.DrawMode = TabDrawMode.Normal;
1216             }
1217             else
1218             {
1219                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1220                 ListTab.DrawItem += ListTab_DrawItem;
1221                 ListTab.ImageList = null;
1222             }
1223
1224             _ignoreConfigSave = false;
1225             this.TweenMain_Resize(null, null);
1226             if (saveRequired) SaveConfigsAll(false);
1227
1228             if (tw.UserId == 0)
1229             {
1230                 tw.VerifyCredentials();
1231                 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1232                 {
1233                     if (ua.Username.ToLower() == tw.Username.ToLower())
1234                     {
1235                         ua.UserId = tw.UserId;
1236                         break;
1237                     }
1238                 }
1239             }
1240             foreach (UserAccount ua in SettingDialog.UserAccounts)
1241             {
1242                 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1243                 {
1244                     ua.UserId = tw.UserId;
1245                     break;
1246                 }
1247             }
1248
1249             if (firstRun)
1250             {
1251                 // 初回起動時だけ右下のメニューを目立たせる
1252                 HashStripSplitButton.ShowDropDown();
1253             }
1254
1255             // タブの位置を調整する
1256             SetTabAlignment();
1257         }
1258
1259         private void InitDetailHtmlFormat()
1260         {
1261             if (SettingDialog.IsMonospace)
1262             {
1263                 detailHtmlFormatHeader = detailHtmlFormatMono1;
1264                 detailHtmlFormatFooter = detailHtmlFormatMono7;
1265             }
1266             else
1267             {
1268                 detailHtmlFormatHeader = detailHtmlFormat1;
1269                 detailHtmlFormatFooter = detailHtmlFormat7;
1270             }
1271             detailHtmlFormatHeader += _fntDetail.Name + detailHtmlFormat2 + _fntDetail.Size.ToString() + detailHtmlFormat3 + _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString() + detailHtmlFormat4 + _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString() + detailHtmlFormat5 + _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString();
1272             if (SettingDialog.IsMonospace)
1273             {
1274                 detailHtmlFormatHeader += detailHtmlFormatMono6;
1275             }
1276             else
1277             {
1278                 detailHtmlFormatHeader += detailHtmlFormat6;
1279             }
1280         }
1281
1282         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1283         {
1284             string txt;
1285             try
1286             {
1287                 txt = ListTab.TabPages[e.Index].Text;
1288             }
1289             catch (Exception)
1290             {
1291                 return;
1292             }
1293
1294             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1295             if (e.State == DrawItemState.Selected)
1296             {
1297                 e.DrawFocusRectangle();
1298             }
1299             Brush fore;
1300             try
1301             {
1302                 if (_statuses.Tabs[txt].UnreadCount > 0)
1303                     fore = Brushes.Red;
1304                 else
1305                     fore = System.Drawing.SystemBrushes.ControlText;
1306             }
1307             catch (Exception)
1308             {
1309                 fore = System.Drawing.SystemBrushes.ControlText;
1310             }
1311             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1312         }
1313
1314         private void LoadConfig()
1315         {
1316             _cfgCommon = SettingCommon.Load();
1317             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1318             {
1319                 _cfgCommon.UserAccounts = new List<UserAccount>();
1320                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1321                 {
1322                     UserAccount account = new UserAccount();
1323                     account.Username = _cfgCommon.UserName;
1324                     account.UserId = _cfgCommon.UserId;
1325                     account.Token = _cfgCommon.Token;
1326                     account.TokenSecret = _cfgCommon.TokenSecret;
1327
1328                     _cfgCommon.UserAccounts.Add(account);
1329                 }
1330             }
1331             _cfgLocal = SettingLocal.Load();
1332             List<TabClass> tabs = SettingTabs.Load().Tabs;
1333             foreach (TabClass tb in tabs)
1334             {
1335                 try
1336                 {
1337                     _statuses.Tabs.Add(tb.TabName, tb);
1338                 }
1339                 catch (Exception)
1340                 {
1341                     tb.TabName = _statuses.GetUniqueTabName();
1342                     _statuses.Tabs.Add(tb.TabName, tb);
1343                 }
1344             }
1345             if (_statuses.Tabs.Count == 0)
1346             {
1347                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1348                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1349                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1350                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1351             }
1352         }
1353
1354         private void TimerInterval_Changed(object sender, AppendSettingDialog.IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1355         {
1356             if (!TimerTimeline.Enabled) return;
1357             ResetTimers = e;
1358         }
1359
1360         private AppendSettingDialog.IntervalChangedEventArgs ResetTimers = new AppendSettingDialog.IntervalChangedEventArgs();
1361
1362         private static int homeCounter = 0;
1363         private static int mentionCounter = 0;
1364         private static int dmCounter = 0;
1365         private static int pubSearchCounter = 0;
1366         private static int userTimelineCounter = 0;
1367         private static int listsCounter = 0;
1368         private static int usCounter = 0;
1369         private static int ResumeWait = 0;
1370         private static int refreshFollowers = 0;
1371
1372         private void TimerTimeline_Elapsed(object sender, EventArgs e)
1373         {
1374             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1375             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1376             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1377             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1378             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1379             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1380             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1381             Interlocked.Increment(ref refreshFollowers);
1382
1383             ////タイマー初期化
1384             if (ResetTimers.Timeline || homeCounter <= 0 && SettingDialog.TimelinePeriodInt > 0)
1385             {
1386                 Interlocked.Exchange(ref homeCounter, SettingDialog.TimelinePeriodInt);
1387                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1388                 ResetTimers.Timeline = false;
1389             }
1390             if (ResetTimers.Reply || mentionCounter <= 0 && SettingDialog.ReplyPeriodInt > 0)
1391             {
1392                 Interlocked.Exchange(ref mentionCounter, SettingDialog.ReplyPeriodInt);
1393                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1394                 ResetTimers.Reply = false;
1395             }
1396             if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingDialog.DMPeriodInt > 0)
1397             {
1398                 Interlocked.Exchange(ref dmCounter, SettingDialog.DMPeriodInt);
1399                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1400                 ResetTimers.DirectMessage = false;
1401             }
1402             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingDialog.PubSearchPeriodInt > 0)
1403             {
1404                 Interlocked.Exchange(ref pubSearchCounter, SettingDialog.PubSearchPeriodInt);
1405                 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1406                 ResetTimers.PublicSearch = false;
1407             }
1408             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingDialog.UserTimelinePeriodInt > 0)
1409             {
1410                 Interlocked.Exchange(ref userTimelineCounter, SettingDialog.UserTimelinePeriodInt);
1411                 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1412                 ResetTimers.UserTimeline = false;
1413             }
1414             if (ResetTimers.Lists || listsCounter <= 0 && SettingDialog.ListsPeriodInt > 0)
1415             {
1416                 Interlocked.Exchange(ref listsCounter, SettingDialog.ListsPeriodInt);
1417                 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1418                 ResetTimers.Lists = false;
1419             }
1420             if (ResetTimers.UserStream || usCounter <= 0 && SettingDialog.UserstreamPeriodInt > 0)
1421             {
1422                 Interlocked.Exchange(ref usCounter, SettingDialog.UserstreamPeriodInt);
1423                 if (this._isActiveUserstream) RefreshTimeline(true);
1424                 ResetTimers.UserStream = false;
1425             }
1426             if (refreshFollowers > 6 * 3600)
1427             {
1428                 Interlocked.Exchange(ref refreshFollowers, 0);
1429                 doGetFollowersMenu();
1430                 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
1431                 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1432             }
1433             if (osResumed)
1434             {
1435                 Interlocked.Increment(ref ResumeWait);
1436                 if (ResumeWait > 30)
1437                 {
1438                     osResumed = false;
1439                     Interlocked.Exchange(ref ResumeWait, 0);
1440                     GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1441                     GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1442                     GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1443                     GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1444                     GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1445                     GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1446                     doGetFollowersMenu();
1447                     GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1448                 }
1449             }
1450         }
1451
1452         private void RefreshTimeline(bool isUserStream)
1453         {
1454             if (isUserStream) this.RefreshTasktrayIcon(true);
1455             //スクロール制御準備
1456             int smode = -1;    //-1:制御しない,-2:最新へ,その他:topitem使用
1457             long topId = GetScrollPos(ref smode);
1458             int befCnt = _curList.VirtualListSize;
1459
1460             //現在の選択状態を退避
1461             Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1462             Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1463             SaveSelectedStatus(selId, focusedId);
1464
1465             //mentionsの更新前件数を保持
1466             int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1467
1468             //更新確定
1469             PostClass[] notifyPosts = null;
1470             string soundFile = "";
1471             int addCount = 0;
1472             bool isMention = false;
1473             bool isDelete = false;
1474             addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1475
1476             if (MyCommon._endingFlag) return;
1477
1478             //リストに反映&選択状態復元
1479             try
1480             {
1481                 foreach (TabPage tab in ListTab.TabPages)
1482                 {
1483                     DetailsListView lst = (DetailsListView)tab.Tag;
1484                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1485                     using (ControlTransaction.Update(lst))
1486                     {
1487                         if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1488                         {
1489                             if (lst.Equals(_curList))
1490                             {
1491                                 this.PurgeListViewItemCache();
1492                             }
1493                             try
1494                             {
1495                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1496                             }
1497                             catch (Exception)
1498                             {
1499                                 //アイコン描画不具合あり?
1500                             }
1501                             this.SelectListItem(lst,
1502                                                 _statuses.IndexOf(tab.Text, selId[tab.Text]),
1503                                                 _statuses.IndexOf(tab.Text, focusedId[tab.Text]));
1504                         }
1505                     }
1506                     if (tabInfo.UnreadCount > 0)
1507                         if (SettingDialog.TabIconDisp)
1508                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1509                 }
1510                 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
1511             }
1512             catch (Exception)
1513             {
1514                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1515                 //throw;
1516             }
1517
1518             //スクロール制御後処理
1519             if (smode != -1)
1520             {
1521                 try
1522                 {
1523                     if (befCnt != _curList.VirtualListSize)
1524                     {
1525                         switch (smode)
1526                         {
1527                             case -3:
1528                                 //最上行
1529                                 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1530                                 break;
1531                             case -2:
1532                                 //最下行へ
1533                                 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1534                                 break;
1535                             case -1:
1536                                 //制御しない
1537                                 break;
1538                             default:
1539                                 //表示位置キープ
1540                                 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1541                                 {
1542                                     _curList.EnsureVisible(_curList.VirtualListSize - 1);
1543                                     _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1544                                 }
1545                                 break;
1546                         }
1547                     }
1548                 }
1549                 catch (Exception ex)
1550                 {
1551                     ex.Data["Msg"] = "Ref2";
1552                     throw;
1553                 }
1554             }
1555
1556             //新着通知
1557             NotifyNewPosts(notifyPosts,
1558                            soundFile,
1559                            addCount,
1560                            isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1561
1562             SetMainWindowTitle();
1563             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1564
1565             HashSupl.AddRangeItem(tw.GetHashList());
1566
1567         }
1568
1569         private long GetScrollPos(ref int smode)
1570         {
1571             long topId = -1;
1572             if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1573             {
1574                 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1575                 {
1576                     if (_statuses.SortOrder == SortOrder.Ascending)
1577                     {
1578                         //Id昇順
1579                         if (ListLockMenuItem.Checked)
1580                         {
1581                             //制御しない
1582                             smode = -1;
1583                             ////現在表示位置へ強制スクロール
1584                             //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1585                             //smode = 0;
1586                         }
1587                         else
1588                         {
1589                             //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1590                             ListViewItem _item;
1591                             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);   //一番下
1592                             if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1593                             if (_item.Index == _curList.VirtualListSize - 1)
1594                             {
1595                                 smode = -2;
1596                             }
1597                             else
1598                             {
1599                                 smode = -1;
1600                                 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1601                                 //smode = 0;
1602                             }
1603                         }
1604                     }
1605                     else
1606                     {
1607                         //Id降順
1608                         if (ListLockMenuItem.Checked)
1609                         {
1610                             //現在表示位置へ強制スクロール
1611                             if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1612                             smode = 0;
1613                         }
1614                         else
1615                         {
1616                             //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1617                             ListViewItem _item;
1618
1619                             _item = _curList.GetItemAt(0, 10);     //一番上
1620                             if (_item == null) _item = _curList.Items[0];
1621                             if (_item.Index == 0)
1622                             {
1623                                 smode = -3;  //最上行
1624                             }
1625                             else
1626                             {
1627                                 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1628                                 smode = 0;
1629                             }
1630                         }
1631                     }
1632                 }
1633                 else
1634                 {
1635                     //現在表示位置へ強制スクロール
1636                     if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1637                     smode = 0;
1638                 }
1639             }
1640             else
1641             {
1642                 smode = -1;
1643             }
1644             return topId;
1645         }
1646
1647         private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1648         {
1649             if (MyCommon._endingFlag) return;
1650             foreach (TabPage tab in ListTab.TabPages)
1651             {
1652                 DetailsListView lst = (DetailsListView)tab.Tag;
1653                 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1654                 {
1655                     selId.Add(tab.Text, _statuses.GetId(tab.Text, lst.SelectedIndices));
1656                 }
1657                 else
1658                 {
1659                     selId.Add(tab.Text, new long[1] {-2});
1660                 }
1661
1662                 var fIds = new long[2];  // 0 = focus, 1 = selection mark
1663                 var item = lst.FocusedItem;
1664                 fIds[0] = (item != null) ? _statuses.GetId(tab.Text, item.Index) : -2;
1665                 var mIdx = lst.SelectionMark;
1666                 fIds[1] = (mIdx > -1) ? _statuses.GetId(tab.Text, mIdx) : -2;
1667                 focusedId.Add(tab.Text, fIds);
1668             }
1669
1670         }
1671
1672         private bool BalloonRequired()
1673         {
1674             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1675             ev.Eventtype = MyCommon.EVENTTYPE.None;
1676
1677             return BalloonRequired(ev);
1678         }
1679
1680         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1681         {
1682             return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1683         }
1684
1685         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1686         {
1687             return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1688         }
1689
1690         private bool BalloonRequired(Twitter.FormattedEvent ev)
1691         {
1692             if ((
1693                 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1694                 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1695                 !_initial &&
1696                 (
1697                     (
1698                         SettingDialog.LimitBalloon &&
1699                         (
1700                             this.WindowState == FormWindowState.Minimized ||
1701                             !this.Visible ||
1702                             Form.ActiveForm == null
1703                             )
1704                         ) ||
1705                     !SettingDialog.LimitBalloon
1706                     )
1707                 ) &&
1708                 !Win32Api.IsScreenSaverRunning())
1709             {
1710                 return true;
1711             }
1712             else
1713             {
1714                 return false;
1715             }
1716         }
1717
1718         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1719         {
1720             if (notifyPosts != null &&
1721                 notifyPosts.Length > 0 &&
1722                 this.SettingDialog.ReadOwnPost &&
1723                 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1724             {
1725                 return;
1726             }
1727
1728             //新着通知
1729             if (BalloonRequired())
1730             {
1731                 if (notifyPosts != null && notifyPosts.Length > 0)
1732                 {
1733                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1734                     if (SettingDialog.IsNotifyUseGrowl)
1735                     {
1736                         StringBuilder sb = new StringBuilder();
1737                         bool reply = false;
1738                         bool dm = false;
1739
1740                         foreach (PostClass post in notifyPosts)
1741                         {
1742                             if (!(notifyPosts.Length > 3))
1743                             {
1744                                 sb.Clear();
1745                                 reply = false;
1746                                 dm = false;
1747                             }
1748                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1749                             if (post.IsDm) dm = true;
1750                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1751                             switch (SettingDialog.NameBalloon)
1752                             {
1753                                 case MyCommon.NameBalloonEnum.UserID:
1754                                     sb.Append(post.ScreenName).Append(" : ");
1755                                     break;
1756                                 case MyCommon.NameBalloonEnum.NickName:
1757                                     sb.Append(post.Nickname).Append(" : ");
1758                                     break;
1759                             }
1760                             sb.Append(post.TextFromApi);
1761                             if (notifyPosts.Length > 3)
1762                             {
1763                                 if (notifyPosts.Last() != post) continue;
1764                             }
1765
1766                             StringBuilder title = new StringBuilder();
1767                             GrowlHelper.NotifyType nt;
1768                             if (SettingDialog.DispUsername)
1769                             {
1770                                 title.Append(tw.Username);
1771                                 title.Append(" - ");
1772                             }
1773                             else
1774                             {
1775                                 //title.Clear();
1776                             }
1777                             if (dm)
1778                             {
1779                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1780                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1781                                 title.Append(Application.ProductName);
1782                                 title.Append(" [DM] ");
1783                                 title.Append(Properties.Resources.RefreshDirectMessageText1);
1784                                 title.Append(" ");
1785                                 title.Append(addCount);
1786                                 title.Append(Properties.Resources.RefreshDirectMessageText2);
1787                                 nt = GrowlHelper.NotifyType.DirectMessage;
1788                             }
1789                             else if (reply)
1790                             {
1791                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1792                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1793                                 title.Append(Application.ProductName);
1794                                 title.Append(" [Reply!] ");
1795                                 title.Append(Properties.Resources.RefreshTimelineText1);
1796                                 title.Append(" ");
1797                                 title.Append(addCount);
1798                                 title.Append(Properties.Resources.RefreshTimelineText2);
1799                                 nt = GrowlHelper.NotifyType.Reply;
1800                             }
1801                             else
1802                             {
1803                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1804                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1805                                 title.Append(Application.ProductName);
1806                                 title.Append(" ");
1807                                 title.Append(Properties.Resources.RefreshTimelineText1);
1808                                 title.Append(" ");
1809                                 title.Append(addCount);
1810                                 title.Append(Properties.Resources.RefreshTimelineText2);
1811                                 nt = GrowlHelper.NotifyType.Notify;
1812                             }
1813                             string bText = sb.ToString();
1814                             if (string.IsNullOrEmpty(bText)) return;
1815
1816                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1817                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1818                         }
1819                     }
1820                     else
1821                     {
1822                         StringBuilder sb = new StringBuilder();
1823                         bool reply = false;
1824                         bool dm = false;
1825                         foreach (PostClass post in notifyPosts)
1826                         {
1827                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1828                             if (post.IsDm) dm = true;
1829                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1830                             switch (SettingDialog.NameBalloon)
1831                             {
1832                                 case MyCommon.NameBalloonEnum.UserID:
1833                                     sb.Append(post.ScreenName).Append(" : ");
1834                                     break;
1835                                 case MyCommon.NameBalloonEnum.NickName:
1836                                     sb.Append(post.Nickname).Append(" : ");
1837                                     break;
1838                             }
1839                             sb.Append(post.TextFromApi);
1840
1841                         }
1842                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1843                         StringBuilder title = new StringBuilder();
1844                         ToolTipIcon ntIcon;
1845                         if (SettingDialog.DispUsername)
1846                         {
1847                             title.Append(tw.Username);
1848                             title.Append(" - ");
1849                         }
1850                         else
1851                         {
1852                             //title.Clear();
1853                         }
1854                         if (dm)
1855                         {
1856                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1857                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1858                             ntIcon = ToolTipIcon.Warning;
1859                             title.Append(Application.ProductName);
1860                             title.Append(" [DM] ");
1861                             title.Append(Properties.Resources.RefreshDirectMessageText1);
1862                             title.Append(" ");
1863                             title.Append(addCount);
1864                             title.Append(Properties.Resources.RefreshDirectMessageText2);
1865                         }
1866                         else if (reply)
1867                         {
1868                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1869                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1870                             ntIcon = ToolTipIcon.Warning;
1871                             title.Append(Application.ProductName);
1872                             title.Append(" [Reply!] ");
1873                             title.Append(Properties.Resources.RefreshTimelineText1);
1874                             title.Append(" ");
1875                             title.Append(addCount);
1876                             title.Append(Properties.Resources.RefreshTimelineText2);
1877                         }
1878                         else
1879                         {
1880                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1881                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1882                             ntIcon = ToolTipIcon.Info;
1883                             title.Append(Application.ProductName);
1884                             title.Append(" ");
1885                             title.Append(Properties.Resources.RefreshTimelineText1);
1886                             title.Append(" ");
1887                             title.Append(addCount);
1888                             title.Append(Properties.Resources.RefreshTimelineText2);
1889                         }
1890                         string bText = sb.ToString();
1891                         if (string.IsNullOrEmpty(bText)) return;
1892                         //NotifyIcon1.BalloonTipText = sb.ToString();
1893                         //NotifyIcon1.ShowBalloonTip(500);
1894                         NotifyIcon1.BalloonTipTitle = title.ToString();
1895                         NotifyIcon1.BalloonTipText = bText;
1896                         NotifyIcon1.BalloonTipIcon = ntIcon;
1897                         NotifyIcon1.ShowBalloonTip(500);
1898                     }
1899                 }
1900             }
1901
1902             //サウンド再生
1903             if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(soundFile))
1904             {
1905                 try
1906                 {
1907                     string dir = Application.StartupPath;
1908                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1909                     {
1910                         dir = Path.Combine(dir, "Sounds");
1911                     }
1912                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1913                     {
1914                         player.Play();
1915                     }
1916                 }
1917                 catch (Exception)
1918                 {
1919                 }
1920             }
1921
1922             //mentions新着時に画面ブリンク
1923             if (!_initial && SettingDialog.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1924             {
1925                 Win32Api.FlashMyWindow(this.Handle, Win32Api.FlashSpecification.FlashTray, 3);
1926             }
1927         }
1928
1929         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1930         {
1931             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1932
1933             _curItemIndex = _curList.SelectedIndices[0];
1934             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1935
1936             try
1937             {
1938                 _curPost = GetCurTabPost(_curItemIndex);
1939             }
1940             catch (ArgumentException)
1941             {
1942                 return;
1943             }
1944
1945             this.PushSelectPostChain();
1946
1947             if (SettingDialog.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1948             //キャッシュの書き換え
1949             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1950
1951             ColorizeList();
1952             _colorize = true;
1953         }
1954
1955         private void ChangeCacheStyleRead(bool Read, int Index)
1956         {
1957             //Read:true=既読 false=未読
1958             //未読管理していなかったら既読として扱う
1959             if (!_statuses.Tabs[_curTab.Text].UnreadManage ||
1960                !SettingDialog.UnreadManage) Read = true;
1961
1962             //対象の特定
1963             ListViewItem itm = null;
1964             PostClass post = null;
1965
1966             this.TryGetListViewItemCache(Index, out itm, out post);
1967
1968             if (itm == null || post == null)
1969             {
1970                 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1971                 post = _statuses[_curTab.Text, Index];
1972             }
1973
1974             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1975         }
1976
1977         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1978         {
1979             Font fnt;
1980             //フォント
1981             if (Read)
1982             {
1983                 fnt = _fntReaded;
1984                 Item.SubItems[5].Text = "";
1985             }
1986             else
1987             {
1988                 fnt = _fntUnread;
1989                 Item.SubItems[5].Text = "★";
1990             }
1991             //文字色
1992             Color cl;
1993             if (Post.IsFav)
1994                 cl = _clFav;
1995             else if (Post.RetweetedId != null)
1996                 cl = _clRetweet;
1997             else if (Post.IsOwl && (Post.IsDm || SettingDialog.OneWayLove))
1998                 cl = _clOWL;
1999             else if (Read || !SettingDialog.UseUnreadStyle)
2000                 cl = _clReaded;
2001             else
2002                 cl = _clUnread;
2003
2004             if (DList == null || Item.Index == -1)
2005             {
2006                 Item.ForeColor = cl;
2007                 if (SettingDialog.UseUnreadStyle)
2008                     Item.Font = fnt;
2009             }
2010             else
2011             {
2012                 DList.Update();
2013                 if (SettingDialog.UseUnreadStyle)
2014                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2015                 else
2016                     DList.ChangeItemForeColor(Item.Index, cl);
2017                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2018             }
2019         }
2020
2021         private void ColorizeList()
2022         {
2023             //Index:更新対象のListviewItem.Index。Colorを返す。
2024             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2025             PostClass _post;
2026             if (_anchorFlag)
2027                 _post = _anchorPost;
2028             else
2029                 _post = _curPost;
2030
2031             if (_post == null) return;
2032
2033             var itemColors = new Color[] { };
2034             int itemIndex = -1;
2035
2036             this.itemCacheLock.EnterReadLock();
2037             try
2038             {
2039                 if (this._itemCache == null) return;
2040
2041                 var query = 
2042                     from i in Enumerable.Range(0, this._itemCache.Length)
2043                     select this.JudgeColor(_post, this._postCache[i]);
2044                 
2045                 itemColors = query.ToArray();
2046                 itemIndex = _itemCacheIndex;
2047             }
2048             finally { this.itemCacheLock.ExitReadLock(); }
2049
2050             if (itemIndex < 0) return;
2051
2052             foreach (var backColor in itemColors)
2053             {
2054                 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
2055                 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
2056                 _curList.ChangeItemBackColor(itemIndex++, backColor);
2057             }
2058         }
2059
2060         private void ColorizeList(ListViewItem Item, int Index)
2061         {
2062             //Index:更新対象のListviewItem.Index。Colorを返す。
2063             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2064             PostClass _post;
2065             if (_anchorFlag)
2066                 _post = _anchorPost;
2067             else
2068                 _post = _curPost;
2069
2070             PostClass tPost = GetCurTabPost(Index);
2071
2072             if (_post == null) return;
2073
2074             if (Item.Index == -1)
2075                 Item.BackColor = JudgeColor(_post, tPost);
2076             else
2077                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2078         }
2079
2080         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2081         {
2082             Color cl;
2083             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2084                 //@先
2085                 cl = _clAtTo;
2086             else if (TargetPost.IsMe)
2087                 //自分=発言者
2088                 cl = _clSelf;
2089             else if (TargetPost.IsReply)
2090                 //自分宛返信
2091                 cl = _clAtSelf;
2092             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2093                 //返信先
2094                 cl = _clAtFromTarget;
2095             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2096                 //その人への返信
2097                 cl = _clAtTarget;
2098             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2099                 //発言者
2100                 cl = _clTarget;
2101             else
2102                 //その他
2103                 cl = _clListBackcolor;
2104
2105             return cl;
2106         }
2107
2108         private async void PostButton_Click(object sender, EventArgs e)
2109         {
2110             if (StatusText.Text.Trim().Length == 0)
2111             {
2112                 if (!ImageSelectionPanel.Enabled)
2113                 {
2114                     DoRefresh();
2115                     return;
2116                 }
2117             }
2118
2119             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2120             {
2121                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2122                                                                "Retweet",
2123                                                                MessageBoxButtons.YesNoCancel,
2124                                                                MessageBoxIcon.Question);
2125                 switch (rtResult)
2126                 {
2127                     case DialogResult.Yes:
2128                         doReTweetOfficial(false);
2129                         StatusText.Text = "";
2130                         return;
2131                     case DialogResult.Cancel:
2132                         return;
2133                 }
2134             }
2135
2136             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2137
2138             if (SettingDialog.Nicoms)
2139             {
2140                 StatusText.SelectionStart = StatusText.Text.Length;
2141                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2142             }
2143             //if (SettingDialog.UrlConvertAuto)
2144             //{
2145             //    StatusText.SelectionStart = StatusText.Text.Length;
2146             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2147             //}
2148             //else if (SettingDialog.Nicoms)
2149             //{
2150             //    StatusText.SelectionStart = StatusText.Text.Length;
2151             //    UrlConvert(UrlConverter.Nicoms);
2152             //}
2153             StatusText.SelectionStart = StatusText.Text.Length;
2154             GetWorkerArg args = new GetWorkerArg();
2155             args.page = 0;
2156             args.endPage = 0;
2157             args.type = MyCommon.WORKERTYPE.PostMessage;
2158             CheckReplyTo(StatusText.Text);
2159
2160             //整形によって増加する文字数を取得
2161             int adjustCount = 0;
2162             string tmpStatus = StatusText.Text.Trim();
2163             if (ToolStripMenuItemApiCommandEvasion.Checked)
2164             {
2165                 // APIコマンド回避
2166                 if (Regex.IsMatch(tmpStatus,
2167                     @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2168                     RegexOptions.IgnoreCase)
2169                    && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2170             }
2171
2172             if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2173             {
2174                 // URLと全角文字の切り離し
2175                 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2176             }
2177
2178             bool isCutOff = false;
2179             bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2180             if (StatusText.Multiline && !SettingDialog.PostCtrlEnter)
2181             {
2182                 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2183                 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2184             }
2185             if (SettingDialog.PostShiftEnter)
2186             {
2187                 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2188             }
2189             if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2190             {
2191                 isRemoveFooter = true;
2192             }
2193             if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2194             {
2195                 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2196                 {
2197                     isCutOff = true;
2198                     //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2199                     if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2200                     {
2201                         isRemoveFooter = true;
2202                     }
2203                 }
2204                 else
2205                 {
2206                     return;
2207                 }
2208             }
2209
2210             string footer = "";
2211             string header = "";
2212             if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2213             {
2214                 //DM時は何もつけない
2215                 footer = "";
2216             }
2217             else
2218             {
2219                 //ハッシュタグ
2220                 if (HashMgr.IsNotAddToAtReply)
2221                 {
2222                     if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2223                     {
2224                         if (HashMgr.IsHead)
2225                             header = HashMgr.UseHash + " ";
2226                         else
2227                             footer = " " + HashMgr.UseHash;
2228                     }
2229                 }
2230                 else
2231                 {
2232                     if (!string.IsNullOrEmpty(HashMgr.UseHash))
2233                     {
2234                         if (HashMgr.IsHead)
2235                             header = HashMgr.UseHash + " ";
2236                         else
2237                             footer = " " + HashMgr.UseHash;
2238                     }
2239                 }
2240                 if (!isRemoveFooter)
2241                 {
2242                     if (SettingDialog.UseRecommendStatus)
2243                         // 推奨ステータスを使用する
2244                         footer += SettingDialog.RecommendStatusText;
2245                     else
2246                         // テキストボックスに入力されている文字列を使用する
2247                         footer += " " + SettingDialog.Status.Trim();
2248                 }
2249             }
2250             args.status.status = header + StatusText.Text + footer;
2251
2252             if (ToolStripMenuItemApiCommandEvasion.Checked)
2253             {
2254                 // APIコマンド回避
2255                 if (Regex.IsMatch(args.status.status,
2256                     @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2257                     RegexOptions.IgnoreCase)
2258                    && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2259             }
2260
2261             if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2262             {
2263                 // URLと全角文字の切り離し
2264                 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2265                 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2266             }
2267
2268             if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2269             {
2270                 // 文中の全角スペースを半角スペース1個にする
2271                 args.status.status = args.status.status.Replace(" ", " ");
2272             }
2273
2274             if (isCutOff && args.status.status.Length > 140)
2275             {
2276                 args.status.status = args.status.status.Substring(0, 140);
2277                 string AtId = @"(@|@)[a-z0-9_/]+$";
2278                 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2279                 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2280                 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2281                 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2282                 if (mc.Success)
2283                 {
2284                     //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2285                     args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2286                 }
2287                 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2288             }
2289
2290             args.status.inReplyToId = _reply_to_id;
2291             args.status.inReplyToName = _reply_to_name;
2292             if (ImageSelectionPanel.Visible)
2293             {
2294                 //画像投稿
2295                 if (!TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2296                     return;
2297             }
2298
2299             RunAsync(args);
2300
2301             _reply_to_id = null;
2302             _reply_to_name = null;
2303             StatusText.Text = "";
2304             _history.Add(new PostingStatus());
2305             _hisIdx = _history.Count - 1;
2306             if (!ToolStripFocusLockMenuItem.Checked)
2307                 ((Control)ListTab.SelectedTab.Tag).Focus();
2308             urlUndoBuffer = null;
2309             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2310
2311             //Google検索(試験実装)
2312             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2313             {
2314                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2315                 await this.OpenUriAsync(tmp);
2316             }
2317         }
2318
2319         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2320         {
2321             MyCommon._endingFlag = true;
2322             this.Close();
2323         }
2324
2325         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2326         {
2327             if (!SettingDialog.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2328             {
2329                 //_endingFlag=false:フォームの×ボタン
2330                 e.Cancel = true;
2331                 this.Visible = false;
2332             }
2333             else
2334             {
2335                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2336                 _ignoreConfigSave = true;
2337                 MyCommon._endingFlag = true;
2338                 TimerTimeline.Enabled = false;
2339                 TimerRefreshIcon.Enabled = false;
2340             }
2341         }
2342
2343         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2344         {
2345             this.Visible = true;
2346             if (this.WindowState == FormWindowState.Minimized)
2347             {
2348                 this.WindowState = FormWindowState.Normal;
2349             }
2350             this.Activate();
2351             this.BringToFront();
2352         }
2353
2354         private static int errorCount = 0;
2355
2356         private static bool CheckAccountValid()
2357         {
2358             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2359             {
2360                 errorCount += 1;
2361                 if (errorCount > 5)
2362                 {
2363                     errorCount = 0;
2364                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2365                     return true;
2366                 }
2367                 return false;
2368             }
2369             errorCount = 0;
2370             return true;
2371         }
2372
2373         private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2374         {
2375             BackgroundWorker bw = (BackgroundWorker)sender;
2376             if (bw.CancellationPending || MyCommon._endingFlag)
2377             {
2378                 e.Cancel = true;
2379                 return;
2380             }
2381
2382             Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2383
2384             MyApplication.InitCulture();
2385
2386             string ret = "";
2387             GetWorkerResult rslt = new GetWorkerResult();
2388
2389             bool read = !SettingDialog.UnreadManage;
2390             if (_initial && SettingDialog.UnreadManage) read = SettingDialog.Readed;
2391
2392             GetWorkerArg args = (GetWorkerArg)e.Argument;
2393
2394             if (!CheckAccountValid())
2395             {
2396                 rslt.retMsg = "Auth error. Check your account";
2397                 rslt.type = MyCommon.WORKERTYPE.ErrorState;  //エラー表示のみ行ない、後処理キャンセル
2398                 rslt.tName = args.tName;
2399                 e.Result = rslt;
2400                 return;
2401             }
2402
2403             bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2404
2405             switch (args.type)
2406             {
2407                 case MyCommon.WORKERTYPE.Timeline:
2408                 case MyCommon.WORKERTYPE.Reply:
2409                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2410                     ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2411                     //新着時未読クリア
2412                     if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && SettingDialog.ReadOldPosts)
2413                         _statuses.SetRead();
2414                     //振り分け
2415                     rslt.addCount = _statuses.DistributePosts();
2416                     break;
2417                 case MyCommon.WORKERTYPE.DirectMessegeRcv:    //送信分もまとめて取得
2418                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2419                     ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2420                     if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2421                     rslt.addCount = _statuses.DistributePosts();
2422                     break;
2423
2424                 case MyCommon.WORKERTYPE.FavAdd:
2425                 {
2426                     //スレッド処理はしない
2427                     TabClass tab;
2428                     if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2429                     {
2430                         for (int i = 0; i <= args.ids.Count - 1; i++)
2431                         {
2432                             var post = tab.Posts[args.ids[i]];
2433
2434                             args.page = i + 1;
2435                             bw.ReportProgress(50, MakeStatusMessage(args, false));
2436                             if (!post.IsFav)
2437                             {
2438                                 if (post.RetweetedId == null)
2439                                     ret = tw.PostFavAdd(post.StatusId);
2440                                 else
2441                                     ret = tw.PostFavAdd(post.RetweetedId.Value);
2442
2443                                 if (ret.Length == 0)
2444                                 {
2445                                     args.sIds.Add(post.StatusId);
2446                                     post.IsFav = true;    //リスト再描画必要
2447                                     _favTimestamps.Add(DateTime.Now);
2448                                     if (string.IsNullOrEmpty(post.RelTabName))
2449                                     {
2450                                         //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2451                                         _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2452                                     }
2453                                     else
2454                                     {
2455                                         //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2456                                         if (_statuses.ContainsKey(post.StatusId))
2457                                         {
2458                                             PostClass postTl = _statuses[post.StatusId];
2459                                             postTl.IsFav = true;
2460                                             _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2461                                         }
2462                                     }
2463                                     //検索,リスト,UserTimeline,Relatedの各タブに反映
2464                                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2465                                     {
2466                                         if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2467                                     }
2468                                 }
2469                             }
2470                         }
2471                     }
2472                     rslt.sIds = args.sIds;
2473                     break;
2474                 }
2475
2476                 case MyCommon.WORKERTYPE.FavRemove:
2477                 {
2478                     //スレッド処理はしない
2479                     TabClass tab;
2480                     if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2481                     {
2482                         for (int i = 0; i <= args.ids.Count - 1; i++)
2483                         {
2484                             var post = tab.Posts[args.ids[i]];
2485
2486                             args.page = i + 1;
2487                             bw.ReportProgress(50, MakeStatusMessage(args, false));
2488                             if (post.IsFav)
2489                             {
2490                                 if (post.RetweetedId == null)
2491                                     ret = tw.PostFavRemove(post.StatusId);
2492                                 else
2493                                     ret = tw.PostFavRemove(post.RetweetedId.Value);
2494
2495                                 if (ret.Length == 0)
2496                                 {
2497                                     args.sIds.Add(post.StatusId);
2498                                     post.IsFav = false;    //リスト再描画必要
2499                                     if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2500                                     //検索,リスト,UserTimeline,Relatedの各タブに反映
2501                                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2502                                     {
2503                                         if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2504                                     }
2505                                 }
2506                             }
2507                         }
2508                     }
2509                     rslt.sIds = args.sIds;
2510                     break;
2511                 }
2512
2513                 case MyCommon.WORKERTYPE.PostMessage:
2514                     bw.ReportProgress(200);
2515                     if (string.IsNullOrEmpty(args.status.imagePath))
2516                     {
2517                         ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2518                     }
2519                     else
2520                     {
2521                         ret = this.pictureService[args.status.imageService].Upload(ref args.status.imagePath,
2522                                                                                    ref args.status.status,
2523                                                                                    args.status.inReplyToId);
2524                     }
2525                     bw.ReportProgress(300);
2526                     rslt.status = args.status;
2527                     break;
2528                 case MyCommon.WORKERTYPE.Retweet:
2529                     bw.ReportProgress(200);
2530                     for (int i = 0; i <= args.ids.Count - 1; i++)
2531                     {
2532                         ret = tw.PostRetweet(args.ids[i], read);
2533                     }
2534                     bw.ReportProgress(300);
2535                     break;
2536                 case MyCommon.WORKERTYPE.Follower:
2537                     bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2538                     try
2539                     {
2540                         tw.RefreshFollowerIds();
2541                     }
2542                     catch (WebApiException ex) { ret = ex.Message; }
2543                     break;
2544                 case MyCommon.WORKERTYPE.NoRetweetIds:
2545                     try
2546                     {
2547                         tw.RefreshNoRetweetIds();
2548                     }
2549                     catch (WebApiException ex) { ret = ex.Message; }
2550                     break;
2551                 case MyCommon.WORKERTYPE.Configuration:
2552                     try
2553                     {
2554                         this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2555                     }
2556                     catch (WebApiException ex) { ret = ex.Message; }
2557                     break;
2558                 case MyCommon.WORKERTYPE.Favorites:
2559                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2560                     ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2561                     rslt.addCount = _statuses.DistributePosts();
2562                     break;
2563                 case MyCommon.WORKERTYPE.PublicSearch:
2564                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2565                     if (string.IsNullOrEmpty(args.tName))
2566                     {
2567                         foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2568                         {
2569                             //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2570                             if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2571                         }
2572                     }
2573                     else
2574                     {
2575                         TabClass tb = _statuses.GetTabByName(args.tName);
2576                         if (tb != null)
2577                         {
2578                             //ret = tw.GetPhoenixSearch(read, tb, false);
2579                             ret = tw.GetSearch(read, tb, false);
2580                             if (string.IsNullOrEmpty(ret) && args.page == -1)
2581                             {
2582                                 //ret = tw.GetPhoenixSearch(read, tb, true)
2583                                 ret = tw.GetSearch(read, tb, true);
2584                             }
2585                         }
2586                     }
2587                     //振り分け
2588                     rslt.addCount = _statuses.DistributePosts();
2589                     break;
2590                 case MyCommon.WORKERTYPE.UserTimeline:
2591                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2592                     int count = 20;
2593                     if (SettingDialog.UseAdditionalCount) count = SettingDialog.UserTimelineCountApi;
2594                     if (string.IsNullOrEmpty(args.tName))
2595                     {
2596                         foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2597                         {
2598                             if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2599                         }
2600                     }
2601                     else
2602                     {
2603                         TabClass tb = _statuses.GetTabByName(args.tName);
2604                         if (tb != null)
2605                         {
2606                             ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2607                         }
2608                     }
2609                     //振り分け
2610                     rslt.addCount = _statuses.DistributePosts();
2611                     break;
2612                 case MyCommon.WORKERTYPE.List:
2613                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2614                     if (string.IsNullOrEmpty(args.tName))
2615                     {
2616                         //定期更新
2617                         foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2618                         {
2619                             if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2620                         }
2621                     }
2622                     else
2623                     {
2624                         //手動更新(特定タブのみ更新)
2625                         TabClass tb = _statuses.GetTabByName(args.tName);
2626                         if (tb != null)
2627                         {
2628                             ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2629                         }
2630                     }
2631                     //振り分け
2632                     rslt.addCount = _statuses.DistributePosts();
2633                     break;
2634
2635                 case MyCommon.WORKERTYPE.Related:
2636                 {
2637                     bw.ReportProgress(50, MakeStatusMessage(args, false));
2638                     TabClass tab = _statuses.GetTabByName(args.tName);
2639                     ret = tw.GetRelatedResult(read, tab);
2640                     rslt.addCount = _statuses.DistributePosts();
2641                     break;
2642                 }
2643
2644                 case MyCommon.WORKERTYPE.BlockIds:
2645                     bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2646                     try
2647                     {
2648                         tw.RefreshBlockIds();
2649                     }
2650                     catch (WebApiException ex) { ret = ex.Message; }
2651                     break;
2652             }
2653             //キャンセル要求
2654             if (bw.CancellationPending)
2655             {
2656                 e.Cancel = true;
2657                 return;
2658             }
2659
2660             //時速表示用
2661             if (args.type == MyCommon.WORKERTYPE.FavAdd)
2662             {
2663                 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2664                 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2665                 {
2666                     if (_favTimestamps[i].CompareTo(oneHour) < 0)
2667                     {
2668                         _favTimestamps.RemoveAt(i);
2669                     }
2670                 }
2671             }
2672             if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2673             {
2674                 lock (_syncObject)
2675                 {
2676                     DateTime tm = DateTime.Now;
2677                     if (_tlTimestamps.ContainsKey(tm))
2678                         _tlTimestamps[tm] += rslt.addCount;
2679                     else
2680                         _tlTimestamps.Add(tm, rslt.addCount);
2681
2682                     DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2683                     List<DateTime> keys = new List<DateTime>();
2684                     _tlCount = 0;
2685                     foreach (DateTime key in _tlTimestamps.Keys)
2686                     {
2687                         if (key.CompareTo(oneHour) < 0)
2688                         {
2689                             keys.Add(key);
2690                         }
2691                         else
2692                         {
2693                             _tlCount += _tlTimestamps[key];
2694                         }
2695                     }
2696                     foreach (DateTime key in keys)
2697                     {
2698                         _tlTimestamps.Remove(key);
2699                     }
2700                     keys.Clear();
2701                 }
2702             }
2703
2704             //終了ステータス
2705             bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2706
2707             rslt.retMsg = ret;
2708             rslt.type = args.type;
2709             rslt.tName = args.tName;
2710             if (args.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2711                 args.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2712                 args.type == MyCommon.WORKERTYPE.Reply ||
2713                 args.type == MyCommon.WORKERTYPE.Timeline ||
2714                 args.type == MyCommon.WORKERTYPE.Favorites)
2715             {
2716                 rslt.page = args.page - 1;   //値が正しいか後でチェック。10ページ毎の継続確認
2717             }
2718
2719             e.Result = rslt;
2720         }
2721
2722         private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2723         {
2724             string smsg = "";
2725             if (!Finish)
2726             {
2727                 //継続中メッセージ
2728                 switch (AsyncArg.type)
2729                 {
2730                     case MyCommon.WORKERTYPE.Timeline:
2731                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2732                         break;
2733                     case MyCommon.WORKERTYPE.Reply:
2734                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2735                         break;
2736                     case MyCommon.WORKERTYPE.DirectMessegeRcv:
2737                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2738                         break;
2739                     case MyCommon.WORKERTYPE.FavAdd:
2740                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2741                                             Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2742                         break;
2743                     case MyCommon.WORKERTYPE.FavRemove:
2744                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2745                                             Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2746                         break;
2747                     case MyCommon.WORKERTYPE.Favorites:
2748                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2749                         break;
2750                     case MyCommon.WORKERTYPE.PublicSearch:
2751                         smsg = "Search refreshing...";
2752                         break;
2753                     case MyCommon.WORKERTYPE.List:
2754                         smsg = "List refreshing...";
2755                         break;
2756                     case MyCommon.WORKERTYPE.Related:
2757                         smsg = "Related refreshing...";
2758                         break;
2759                     case MyCommon.WORKERTYPE.UserTimeline:
2760                         smsg = "UserTimeline refreshing...";
2761                         break;
2762                 }
2763             }
2764             else
2765             {
2766                 //完了メッセージ
2767                 switch (AsyncArg.type)
2768                 {
2769                     case MyCommon.WORKERTYPE.Timeline:
2770                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2771                         break;
2772                     case MyCommon.WORKERTYPE.Reply:
2773                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2774                         break;
2775                     case MyCommon.WORKERTYPE.DirectMessegeRcv:
2776                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2777                         break;
2778                     case MyCommon.WORKERTYPE.DirectMessegeSnt:
2779                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2780                         break;
2781                     case MyCommon.WORKERTYPE.FavAdd:
2782                         //進捗メッセージ残す
2783                         break;
2784                     case MyCommon.WORKERTYPE.FavRemove:
2785                         //進捗メッセージ残す
2786                         break;
2787                     case MyCommon.WORKERTYPE.Favorites:
2788                         smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2789                         break;
2790                     case MyCommon.WORKERTYPE.Follower:
2791                         smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2792                         break;
2793                     case MyCommon.WORKERTYPE.NoRetweetIds:
2794                         smsg = "NoRetweetIds refreshed";
2795                         break;
2796                     case MyCommon.WORKERTYPE.Configuration:
2797                         //進捗メッセージ残す
2798                         break;
2799                     case MyCommon.WORKERTYPE.PublicSearch:
2800                         smsg = "Search refreshed";
2801                         break;
2802                     case MyCommon.WORKERTYPE.List:
2803                         smsg = "List refreshed";
2804                         break;
2805                     case MyCommon.WORKERTYPE.Related:
2806                         smsg = "Related refreshed";
2807                         break;
2808                     case MyCommon.WORKERTYPE.UserTimeline:
2809                         smsg = "UserTimeline refreshed";
2810                         break;
2811                     case MyCommon.WORKERTYPE.BlockIds:
2812                         smsg = Properties.Resources.UpdateBlockUserText3;
2813                         break;
2814                 }
2815             }
2816             return smsg;
2817         }
2818
2819         private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2820         {
2821             if (MyCommon._endingFlag) return;
2822             if (e.ProgressPercentage > 100)
2823             {
2824                 //発言投稿
2825                 if (e.ProgressPercentage == 200)    //開始
2826                     StatusLabel.Text = "Posting...";
2827                 if (e.ProgressPercentage == 300)  //終了
2828                     StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2829             }
2830             else
2831             {
2832                 string smsg = (string)e.UserState;
2833                 if (smsg.Length > 0) StatusLabel.Text = smsg;
2834             }
2835         }
2836
2837         private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2838         {
2839             if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2840
2841             if (e.Error != null)
2842             {
2843                 _myStatusError = true;
2844                 _waitTimeline = false;
2845                 _waitReply = false;
2846                 _waitDm = false;
2847                 _waitFav = false;
2848                 _waitPubSearch = false;
2849                 _waitUserTimeline = false;
2850                 _waitLists = false;
2851                 throw new Exception("BackgroundWorker Exception", e.Error);
2852             }
2853
2854             GetWorkerResult rslt = (GetWorkerResult)e.Result;
2855
2856             //エラー
2857             if (rslt.retMsg.Length > 0)
2858             {
2859                 _myStatusError = true;
2860                 StatusLabel.Text = rslt.retMsg;
2861             }
2862
2863             if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2864
2865             if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2866             {
2867                 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2868             }
2869
2870             //リストに反映
2871             //bool busy = false;
2872             //foreach (BackgroundWorker bw in _bw)
2873             //{
2874             //    if (bw != null && bw.IsBusy)
2875             //    {
2876             //        busy = true;
2877             //        break;
2878             //    }
2879             //}
2880             //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2881             if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2882                 rslt.type == MyCommon.WORKERTYPE.Reply ||
2883                 rslt.type == MyCommon.WORKERTYPE.List ||
2884                 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2885                 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2886                 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2887                 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2888                 rslt.type == MyCommon.WORKERTYPE.Follower ||
2889                 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2890                 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2891                 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2892                 rslt.type == MyCommon.WORKERTYPE.Related ||
2893                 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2894                 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2895                 rslt.type == MyCommon.WORKERTYPE.Configuration)
2896             {
2897                 RefreshTimeline(false); //リスト反映
2898             }
2899
2900             switch (rslt.type)
2901             {
2902                 case MyCommon.WORKERTYPE.Timeline:
2903                     _waitTimeline = false;
2904                     if (!_initial)
2905                     {
2906                         //    //API使用時の取得調整は別途考える(カウント調整?)
2907                     }
2908                     break;
2909                 case MyCommon.WORKERTYPE.Reply:
2910                     _waitReply = false;
2911                     if (rslt.newDM && !_initial)
2912                     {
2913                         GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
2914                     }
2915                     break;
2916                 case MyCommon.WORKERTYPE.Favorites:
2917                     _waitFav = false;
2918                     break;
2919                 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2920                     _waitDm = false;
2921                     break;
2922                 case MyCommon.WORKERTYPE.FavAdd:
2923                 case MyCommon.WORKERTYPE.FavRemove:
2924                     if (_curList != null && _curTab != null)
2925                     {
2926                         using (ControlTransaction.Update(this._curList))
2927                         {
2928                             if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2929                             {
2930                                 //色変えは不要
2931                             }
2932                             else
2933                             {
2934                                 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2935                                 {
2936                                     if (_curTab.Text.Equals(rslt.tName))
2937                                     {
2938                                         int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2939                                         if (idx > -1)
2940                                         {
2941                                             PostClass post = null;
2942                                             TabClass tb = _statuses.Tabs[rslt.tName];
2943                                             if (tb != null)
2944                                             {
2945                                                 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2946                                                 {
2947                                                     post = tb.Posts[rslt.sIds[i]];
2948                                                 }
2949                                                 else
2950                                                 {
2951                                                     post = _statuses[rslt.sIds[i]];
2952                                                 }
2953                                                 ChangeCacheStyleRead(post.IsRead, idx);
2954                                             }
2955                                             if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2956                                         }
2957                                     }
2958                                 }
2959                             }
2960                         }
2961                     }
2962                     break;
2963                 case MyCommon.WORKERTYPE.PostMessage:
2964                     if (string.IsNullOrEmpty(rslt.retMsg) ||
2965                         rslt.retMsg.StartsWith("OK:") ||
2966                         rslt.retMsg == "Warn:Status is a duplicate.")
2967                     {
2968                         _postTimestamps.Add(DateTime.Now);
2969                         DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2970                         for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2971                         {
2972                             if (_postTimestamps[i].CompareTo(oneHour) < 0)
2973                             {
2974                                 _postTimestamps.RemoveAt(i);
2975                             }
2976                         }
2977
2978                         if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2979                         {
2980                             HashMgr.ClearHashtag();
2981                             this.HashStripSplitButton.Text = "#[-]";
2982                             this.HashToggleMenuItem.Checked = false;
2983                             this.HashToggleToolStripMenuItem.Checked = false;
2984                         }
2985                         SetMainWindowTitle();
2986                         rslt.retMsg = "";
2987                     }
2988                     else
2989                     {
2990                         DialogResult retry;
2991                         try
2992                         {
2993                             retry = MessageBox.Show(string.Format("{0}   --->   [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
2994                                                                 Properties.Resources.StatusUpdateFailed1,
2995                                                                 Properties.Resources.StatusUpdateFailed2),
2996                                                             "Failed to update status",
2997                                                             MessageBoxButtons.RetryCancel,
2998                                                             MessageBoxIcon.Question);
2999                         }
3000                         catch (Exception)
3001                         {
3002                             retry = DialogResult.Abort;
3003                         }
3004                         if (retry == DialogResult.Retry)
3005                         {
3006                             GetWorkerArg args = new GetWorkerArg();
3007                             args.page = 0;
3008                             args.endPage = 0;
3009                             args.type = MyCommon.WORKERTYPE.PostMessage;
3010                             args.status = rslt.status;
3011                             RunAsync(args);
3012                         }
3013                         else
3014                         {
3015                             if (ToolStripFocusLockMenuItem.Checked)
3016                             {
3017                                 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3018                                 StatusText_Enter(StatusText, new EventArgs());
3019                             }
3020                         }
3021                     }
3022                     if (rslt.retMsg.Length == 0 && SettingDialog.PostAndGet)
3023                     {
3024                         if (_isActiveUserstream)
3025                         {
3026                             RefreshTimeline(true);
3027                         }
3028                         else
3029                         {
3030                             GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3031                         }
3032                     }
3033                     break;
3034                 case MyCommon.WORKERTYPE.Retweet:
3035                     if (rslt.retMsg.Length == 0)
3036                     {
3037                         _postTimestamps.Add(DateTime.Now);
3038                         DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
3039                         for (int i = _postTimestamps.Count - 1; i >= 0; i--)
3040                         {
3041                             if (_postTimestamps[i].CompareTo(oneHour) < 0)
3042                             {
3043                                 _postTimestamps.RemoveAt(i);
3044                             }
3045                         }
3046                         if (!_isActiveUserstream && SettingDialog.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3047                     }
3048                     break;
3049                 case MyCommon.WORKERTYPE.Follower:
3050                     //_waitFollower = false;
3051                     this.PurgeListViewItemCache();
3052                     if (_curList != null) _curList.Refresh();
3053                     break;
3054                 case MyCommon.WORKERTYPE.NoRetweetIds:
3055                     break;
3056                 case MyCommon.WORKERTYPE.Configuration:
3057                     //_waitFollower = false
3058                     if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
3059                     {
3060                         pictureService["Twitter"].Configuration("MaxUploadFilesize", SettingDialog.TwitterConfiguration.PhotoSizeLimit);
3061                     }
3062                     this.PurgeListViewItemCache();
3063                     if (_curList != null) _curList.Refresh();
3064                     break;
3065                 case MyCommon.WORKERTYPE.PublicSearch:
3066                     _waitPubSearch = false;
3067                     break;
3068                 case MyCommon.WORKERTYPE.UserTimeline:
3069                     _waitUserTimeline = false;
3070                     break;
3071                 case MyCommon.WORKERTYPE.List:
3072                     _waitLists = false;
3073                     break;
3074                 case MyCommon.WORKERTYPE.Related:
3075                     TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
3076                     if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3077                     {
3078                         foreach (TabPage tp in ListTab.TabPages)
3079                         {
3080                             if (tp.Text == tab.TabName)
3081                             {
3082                                 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3083                                 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3084                                 break;
3085                             }
3086                         }
3087                     }
3088                     break;
3089             }
3090         }
3091
3092         private async Task RefreshMuteUserIdsAsync()
3093         {
3094             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3095
3096             try
3097             {
3098                 await tw.RefreshMuteUserIdsAsync();
3099             }
3100             catch (WebApiException ex)
3101             {
3102                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3103                 return;
3104             }
3105
3106             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3107         }
3108
3109         private void RemovePostFromFavTab(Int64[] ids)
3110         {
3111             string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3112             int fidx = 0;
3113             if (_curTab.Text.Equals(favTabName))
3114             {
3115                 if (_curList.FocusedItem != null)
3116                     fidx = _curList.FocusedItem.Index;
3117                 else if (_curList.TopItem != null)
3118                     fidx = _curList.TopItem.Index;
3119                 else
3120                     fidx = 0;
3121             }
3122
3123             foreach (long i in ids)
3124             {
3125                 try
3126                 {
3127                     _statuses.RemoveFavPost(i);
3128                 }
3129                 catch (Exception)
3130                 {
3131                     continue;
3132                 }
3133             }
3134             if (_curTab != null && _curTab.Text.Equals(favTabName))
3135             {
3136                 this.PurgeListViewItemCache();
3137                 _curPost = null;
3138                 //_curItemIndex = -1;
3139             }
3140             foreach (TabPage tp in ListTab.TabPages)
3141             {
3142                 if (tp.Text == favTabName)
3143                 {
3144                     ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3145                     break;
3146                 }
3147             }
3148             if (_curTab.Text.Equals(favTabName))
3149             {
3150                 do
3151                 {
3152                     _curList.SelectedIndices.Clear();
3153                 }
3154                 while (_curList.SelectedIndices.Count > 0);
3155
3156                 if (_statuses.Tabs[favTabName].AllCount > 0)
3157                 {
3158                     if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3159                     {
3160                         _curList.SelectedIndices.Add(fidx);
3161                     }
3162                     else
3163                     {
3164                         _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3165                     }
3166                     if (_curList.SelectedIndices.Count > 0)
3167                     {
3168                         _curList.EnsureVisible(_curList.SelectedIndices[0]);
3169                         _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3170                     }
3171                 }
3172             }
3173         }
3174
3175         private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3176
3177         private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, int toPage, string tabName)
3178         {
3179             if (!this.IsNetworkAvailable()) return;
3180
3181             //非同期実行引数設定
3182             GetWorkerArg args = new GetWorkerArg();
3183             args.page = fromPage;
3184             args.endPage = toPage;
3185             args.type = WkType;
3186             args.tName = tabName;
3187
3188             if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3189             double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3190             if (period > 1 || period < -1)
3191             {
3192                 lastTime[WkType] = DateTime.Now;
3193                 RunAsync(args);
3194             }
3195
3196             //Timeline取得モードの場合はReplyも同時に取得
3197             //if (!SettingDialog.UseAPI &&
3198             //   !_initial &&
3199             //   WkType == MyCommon.WORKERTYPE.Timeline &&
3200             //   SettingDialog.CheckReply)
3201             //{
3202             //    //TimerReply.Enabled = false;
3203             //    _mentionCounter = SettingDialog.ReplyPeriodInt;
3204             //    GetWorkerArg _args = new GetWorkerArg();
3205             //    _args.page = fromPage;
3206             //    _args.endPage = toPage;
3207             //    _args.type = MyCommon.WORKERTYPE.Reply;
3208             //    RunAsync(_args);
3209             //}
3210         }
3211
3212         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3213         {
3214             if (e.Button == MouseButtons.Left)
3215             {
3216                 this.Visible = true;
3217                 if (this.WindowState == FormWindowState.Minimized)
3218                 {
3219                     this.WindowState = _formWindowState;
3220                 }
3221                 this.Activate();
3222                 this.BringToFront();
3223             }
3224         }
3225
3226         private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3227         {
3228             switch (SettingDialog.ListDoubleClickAction)
3229             {
3230                 case 0:
3231                     MakeReplyOrDirectStatus();
3232                     break;
3233                 case 1:
3234                     FavoriteChange(true);
3235                     break;
3236                 case 2:
3237                     if (_curPost != null)
3238                         ShowUserStatus(_curPost.ScreenName, false);
3239                     break;
3240                 case 3:
3241                     ShowUserTimeline();
3242                     break;
3243                 case 4:
3244                     ShowRelatedStatusesMenuItem_Click(null, null);
3245                     break;
3246                 case 5:
3247                     MoveToHomeToolStripMenuItem_Click(null, null);
3248                     break;
3249                 case 6:
3250                     StatusOpenMenuItem_Click(null, null);
3251                     break;
3252                 case 7:
3253                     //動作なし
3254                     break;
3255             }
3256         }
3257
3258         private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3259         {
3260             FavoriteChange(true);
3261         }
3262
3263         private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3264         {
3265             FavoriteChange(false);
3266         }
3267
3268
3269         private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3270         {
3271             FavoritesRetweetOriginal();
3272         }
3273
3274         private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3275         {
3276             FavoritesRetweetUnofficial();
3277         }
3278
3279         private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3280         {
3281             //trueでFavAdd,falseでFavRemove
3282             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3283                 || !this.ExistCurrentPost) return;
3284
3285             //複数fav確認msg
3286             if (_curList.SelectedIndices.Count > 250 && FavAdd)
3287             {
3288                 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3289                 _DoFavRetweetFlags = false;
3290                 return;
3291             }
3292             else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3293             {
3294                 if (FavAdd)
3295                 {
3296                     string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3297                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3298                     if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3299                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3300                     {
3301                         _DoFavRetweetFlags = false;
3302                         return;
3303                     }
3304                 }
3305                 else
3306                 {
3307                     if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3308                                     MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3309                     {
3310                         return;
3311                     }
3312                 }
3313             }
3314
3315             GetWorkerArg args = new GetWorkerArg();
3316             args.ids = new List<long>();
3317             args.sIds = new List<long>();
3318             args.tName = _curTab.Text;
3319             if (FavAdd)
3320             {
3321                 args.type = MyCommon.WORKERTYPE.FavAdd;
3322             }
3323             else
3324             {
3325                 args.type = MyCommon.WORKERTYPE.FavRemove;
3326             }
3327             foreach (int idx in _curList.SelectedIndices)
3328             {
3329                 PostClass post = GetCurTabPost(idx);
3330                 if (FavAdd)
3331                 {
3332                     if (!post.IsFav) args.ids.Add(post.StatusId);
3333                 }
3334                 else
3335                 {
3336                     if (post.IsFav) args.ids.Add(post.StatusId);
3337                 }
3338             }
3339             if (args.ids.Count == 0)
3340             {
3341                 if (FavAdd)
3342                     StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3343                 else
3344                     StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3345
3346                 return;
3347             }
3348
3349             RunAsync(args);
3350         }
3351
3352         private PostClass GetCurTabPost(int Index)
3353         {
3354             this.itemCacheLock.EnterReadLock();
3355             try
3356             {
3357                 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3358                     return _postCache[Index - _itemCacheIndex];
3359             }
3360             finally { this.itemCacheLock.ExitReadLock(); }
3361
3362             return _statuses[_curTab.Text, Index];
3363         }
3364
3365
3366         private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3367         {
3368             if (_curList.SelectedIndices.Count > 0)
3369                 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3370             else if (_curList.SelectedIndices.Count == 0)
3371                 OpenUriAsync(MyCommon.TwitterUrl);
3372         }
3373
3374         private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3375         {
3376             if (_curList.SelectedIndices.Count > 0)
3377                 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3378         }
3379
3380         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3381         {
3382             if ((!_initialLayout) && this.Visible)
3383             {
3384                 if (this.WindowState == FormWindowState.Normal)
3385                 {
3386                     _mySize = this.ClientSize;
3387                     _mySpDis = this.SplitContainer1.SplitterDistance;
3388                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3389                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3390                     _modifySettingLocal = true;
3391                 }
3392             }
3393         }
3394
3395         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3396         {
3397             if (SettingDialog.SortOrderLock) return;
3398             IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3399             if (_iconCol)
3400             {
3401                 mode = IdComparerClass.ComparerMode.Id;
3402             }
3403             else
3404             {
3405                 switch (e.Column)
3406                 {
3407                     case 0:
3408                     case 5:
3409                     case 6:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3410                         //ソートしない
3411                         return;
3412                     case 1:  //ニックネーム
3413                         mode = IdComparerClass.ComparerMode.Nickname;
3414                         break;
3415                     case 2:  //本文
3416                         mode = IdComparerClass.ComparerMode.Data;
3417                         break;
3418                     case 3:  //時刻=発言Id
3419                         mode = IdComparerClass.ComparerMode.Id;
3420                         break;
3421                     case 4:  //名前
3422                         mode = IdComparerClass.ComparerMode.Name;
3423                         break;
3424                     case 7:  //Source
3425                         mode = IdComparerClass.ComparerMode.Source;
3426                         break;
3427                 }
3428             }
3429             _statuses.ToggleSortOrder(mode);
3430             InitColumnText();
3431
3432             DetailsListView list = (DetailsListView)sender;
3433             if (_iconCol)
3434             {
3435                 list.Columns[0].Text = ColumnOrgText[0];
3436                 list.Columns[1].Text = ColumnText[2];
3437             }
3438             else
3439             {
3440                 for (int i = 0; i <= 7; i++)
3441                 {
3442                     list.Columns[i].Text = ColumnOrgText[i];
3443                 }
3444                 list.Columns[e.Column].Text = ColumnText[e.Column];
3445             }
3446
3447             this.PurgeListViewItemCache();
3448
3449             if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3450             {
3451                 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3452                 if (idx > -1)
3453                 {
3454                     SelectListItem(_curList, idx);
3455                     _curList.EnsureVisible(idx);
3456                 }
3457             }
3458             _curList.Refresh();
3459             _modifySettingCommon = true;
3460         }
3461
3462         private void TweenMain_LocationChanged(object sender, EventArgs e)
3463         {
3464             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3465             {
3466                 _myLoc = this.DesktopLocation;
3467                 _modifySettingLocal = true;
3468             }
3469         }
3470
3471         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3472         {
3473             if (ListTab.SelectedTab == null) return;
3474             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3475             if (!this.ExistCurrentPost)
3476             {
3477                 ReplyStripMenuItem.Enabled = false;
3478                 ReplyAllStripMenuItem.Enabled = false;
3479                 DMStripMenuItem.Enabled = false;
3480                 ShowProfileMenuItem.Enabled = false;
3481                 ShowUserTimelineContextMenuItem.Enabled = false;
3482                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3483                 MoveToFavToolStripMenuItem.Enabled = false;
3484                 TabMenuItem.Enabled = false;
3485                 IDRuleMenuItem.Enabled = false;
3486                 ReadedStripMenuItem.Enabled = false;
3487                 UnreadStripMenuItem.Enabled = false;
3488             }
3489             else
3490             {
3491                 ShowProfileMenuItem.Enabled = true;
3492                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3493                 ReplyStripMenuItem.Enabled = true;
3494                 ReplyAllStripMenuItem.Enabled = true;
3495                 DMStripMenuItem.Enabled = true;
3496                 ShowUserTimelineContextMenuItem.Enabled = true;
3497                 MoveToFavToolStripMenuItem.Enabled = true;
3498                 TabMenuItem.Enabled = true;
3499                 IDRuleMenuItem.Enabled = true;
3500                 ReadedStripMenuItem.Enabled = true;
3501                 UnreadStripMenuItem.Enabled = true;
3502             }
3503             DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3504             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3505             {
3506                 FavAddToolStripMenuItem.Enabled = false;
3507                 FavRemoveToolStripMenuItem.Enabled = false;
3508                 StatusOpenMenuItem.Enabled = false;
3509                 FavorareMenuItem.Enabled = false;
3510                 ShowRelatedStatusesMenuItem.Enabled = false;
3511
3512                 ReTweetStripMenuItem.Enabled = false;
3513                 ReTweetOriginalStripMenuItem.Enabled = false;
3514                 QuoteStripMenuItem.Enabled = false;
3515                 FavoriteRetweetContextMenu.Enabled = false;
3516                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3517                 if (this.ExistCurrentPost && _curPost.IsDm)
3518                     DeleteStripMenuItem.Enabled = true;
3519                 else
3520                     DeleteStripMenuItem.Enabled = false;
3521             }
3522             else
3523             {
3524                 FavAddToolStripMenuItem.Enabled = true;
3525                 FavRemoveToolStripMenuItem.Enabled = true;
3526                 StatusOpenMenuItem.Enabled = true;
3527                 FavorareMenuItem.Enabled = true;
3528                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3529
3530                 if (_curPost.IsMe)
3531                 {
3532                     ReTweetOriginalStripMenuItem.Enabled = false;
3533                     FavoriteRetweetContextMenu.Enabled = false;
3534                     if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3535                     {
3536                         DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3537                     }
3538                     else
3539                     {
3540                         DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3541                     }
3542                     DeleteStripMenuItem.Enabled = true;
3543                 }
3544                 else
3545                 {
3546                     if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3547                     {
3548                         DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3549                     }
3550                     else
3551                     {
3552                         DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3553                     }
3554                     DeleteStripMenuItem.Enabled = false;
3555                     if (_curPost.IsProtect)
3556                     {
3557                         ReTweetOriginalStripMenuItem.Enabled = false;
3558                         ReTweetStripMenuItem.Enabled = false;
3559                         QuoteStripMenuItem.Enabled = false;
3560                         FavoriteRetweetContextMenu.Enabled = false;
3561                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3562                     }
3563                     else
3564                     {
3565                         ReTweetOriginalStripMenuItem.Enabled = true;
3566                         ReTweetStripMenuItem.Enabled = true;
3567                         QuoteStripMenuItem.Enabled = true;
3568                         FavoriteRetweetContextMenu.Enabled = true;
3569                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3570                     }
3571                 }
3572             }
3573             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3574             //{
3575             //    RefreshMoreStripMenuItem.Enabled = true;
3576             //}
3577             //else
3578             //{
3579             //    RefreshMoreStripMenuItem.Enabled = false;
3580             //}
3581             if (!this.ExistCurrentPost
3582                 || _curPost.InReplyToStatusId == null)
3583             {
3584                 RepliedStatusOpenMenuItem.Enabled = false;
3585             }
3586             else
3587             {
3588                 RepliedStatusOpenMenuItem.Enabled = true;
3589             }
3590             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3591             {
3592                 MoveToRTHomeMenuItem.Enabled = false;
3593             }
3594             else
3595             {
3596                 MoveToRTHomeMenuItem.Enabled = true;
3597             }
3598         }
3599
3600         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3601         {
3602             MakeReplyOrDirectStatus(false, true);
3603         }
3604
3605         private void DMStripMenuItem_Click(object sender, EventArgs e)
3606         {
3607             MakeReplyOrDirectStatus(false, false);
3608         }
3609
3610         private void doStatusDelete()
3611         {
3612             if (_curTab == null || _curList == null) return;
3613             if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3614             {
3615                 bool myPost = false;
3616                 foreach (int idx in _curList.SelectedIndices)
3617                 {
3618                     if (GetCurTabPost(idx).IsMe ||
3619                        GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3620                     {
3621                         myPost = true;
3622                         break;
3623                     }
3624                 }
3625                 if (!myPost) return;
3626             }
3627             else
3628             {
3629                 if (_curList.SelectedIndices.Count == 0)
3630                     return;
3631             }
3632
3633             string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3634
3635             if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3636                   MessageBoxButtons.OKCancel,
3637                   MessageBoxIcon.Question) == DialogResult.Cancel) return;
3638
3639             int fidx;
3640             if (_curList.FocusedItem != null)
3641                 fidx = _curList.FocusedItem.Index;
3642             else if (_curList.TopItem != null)
3643                 fidx = _curList.TopItem.Index;
3644             else
3645                 fidx = 0;
3646
3647             try
3648             {
3649                 this.Cursor = Cursors.WaitCursor;
3650
3651                 bool rslt = true;
3652                 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3653                 {
3654                     string rtn = "";
3655                     if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3656                     {
3657                         rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3658                     }
3659                     else
3660                     {
3661                         if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3662                             rtn = tw.RemoveStatus(Id);
3663                         else
3664                             continue;
3665                     }
3666                     if (rtn.Length > 0)
3667                     {
3668                         //エラー
3669                         rslt = false;
3670                     }
3671                     else
3672                     {
3673                         _statuses.RemovePost(Id);
3674                     }
3675                 }
3676
3677                 if (!rslt)
3678                     StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3;  //失敗
3679                 else
3680                     StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4;  //成功
3681
3682                 this.PurgeListViewItemCache();
3683                 _curPost = null;
3684                 _curItemIndex = -1;
3685                 foreach (TabPage tb in ListTab.TabPages)
3686                 {
3687                     ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3688                     if (_curTab.Equals(tb))
3689                     {
3690                         do
3691                         {
3692                             _curList.SelectedIndices.Clear();
3693                         }
3694                         while (_curList.SelectedIndices.Count > 0);
3695
3696                         if (_statuses.Tabs[tb.Text].AllCount > 0)
3697                         {
3698                             if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3699                                 _curList.SelectedIndices.Add(fidx);
3700                             else
3701                                 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3702
3703                             if (_curList.SelectedIndices.Count > 0)
3704                             {
3705                                 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3706                                 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3707                             }
3708                         }
3709                     }
3710                     if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3711                     {
3712                         if (SettingDialog.TabIconDisp)
3713                         {
3714                             if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3715                         }
3716                     }
3717                 }
3718                 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3719             }
3720             finally
3721             {
3722                 this.Cursor = Cursors.Default;
3723             }
3724         }
3725
3726         private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3727         {
3728             doStatusDelete();
3729         }
3730
3731         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3732         {
3733             using (ControlTransaction.Update(this._curList))
3734             {
3735                 if (SettingDialog.UnreadManage)
3736                 {
3737                     foreach (int idx in _curList.SelectedIndices)
3738                     {
3739                         _statuses.SetReadAllTab(true, _curTab.Text, idx);
3740                     }
3741                 }
3742                 foreach (int idx in _curList.SelectedIndices)
3743                 {
3744                     ChangeCacheStyleRead(true, idx);
3745                 }
3746                 ColorizeList();
3747             }
3748             foreach (TabPage tb in ListTab.TabPages)
3749             {
3750                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3751                 {
3752                     if (SettingDialog.TabIconDisp)
3753                     {
3754                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3755                     }
3756                 }
3757             }
3758             if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3759         }
3760
3761         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3762         {
3763             using (ControlTransaction.Update(this._curList))
3764             {
3765                 if (SettingDialog.UnreadManage)
3766                 {
3767                     foreach (int idx in _curList.SelectedIndices)
3768                     {
3769                         _statuses.SetReadAllTab(false, _curTab.Text, idx);
3770                     }
3771                 }
3772                 foreach (int idx in _curList.SelectedIndices)
3773                 {
3774                     ChangeCacheStyleRead(false, idx);
3775                 }
3776                 ColorizeList();
3777             }
3778             foreach (TabPage tb in ListTab.TabPages)
3779             {
3780                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3781                 {
3782                     if (SettingDialog.TabIconDisp)
3783                     {
3784                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3785                     }
3786                 }
3787             }
3788             if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3789         }
3790
3791         private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3792         {
3793             DoRefresh();
3794         }
3795
3796         private void DoRefresh()
3797         {
3798             if (_curTab != null)
3799             {
3800                 switch (_statuses.Tabs[_curTab.Text].TabType)
3801                 {
3802                     case MyCommon.TabUsageType.Mentions:
3803                         GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
3804                         break;
3805                     case MyCommon.TabUsageType.DirectMessage:
3806                         GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
3807                         break;
3808                     case MyCommon.TabUsageType.Favorites:
3809                         GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 0, "");
3810                         break;
3811                     //case MyCommon.TabUsageType.Profile:
3812                         //// TODO
3813                     case MyCommon.TabUsageType.PublicSearch:
3814                         //// TODO
3815                         TabClass tb = _statuses.Tabs[_curTab.Text];
3816                         if (string.IsNullOrEmpty(tb.SearchWords)) return;
3817                         GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, _curTab.Text);
3818                         break;
3819                     case MyCommon.TabUsageType.UserTimeline:
3820                         GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, _curTab.Text);
3821                         break;
3822                     case MyCommon.TabUsageType.Lists:
3823                         //// TODO
3824                         TabClass tab = _statuses.Tabs[_curTab.Text];
3825                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3826                         GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, _curTab.Text);
3827                         break;
3828                     default:
3829                         GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3830                         break;
3831                 }
3832             }
3833             else
3834             {
3835                 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3836             }
3837         }
3838
3839         private void DoRefreshMore()
3840         {
3841             //ページ指定をマイナス1に
3842             if (_curTab != null)
3843             {
3844                 switch (_statuses.Tabs[_curTab.Text].TabType)
3845                 {
3846                     case MyCommon.TabUsageType.Mentions:
3847                         GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
3848                         break;
3849                     case MyCommon.TabUsageType.DirectMessage:
3850                         GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
3851                         break;
3852                     case MyCommon.TabUsageType.Favorites:
3853                         GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, 0, "");
3854                         break;
3855                     case MyCommon.TabUsageType.Profile:
3856                         //// TODO
3857                         break;
3858                     case MyCommon.TabUsageType.PublicSearch:
3859                         // TODO
3860                         TabClass tb = _statuses.Tabs[_curTab.Text];
3861                         if (string.IsNullOrEmpty(tb.SearchWords)) return;
3862                         GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, 0, _curTab.Text);
3863                         break;
3864                     case MyCommon.TabUsageType.UserTimeline:
3865                         GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, 0, _curTab.Text);
3866                         break;
3867                     case MyCommon.TabUsageType.Lists:
3868                         //// TODO
3869                         TabClass tab = _statuses.Tabs[_curTab.Text];
3870                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3871                         GetTimeline(MyCommon.WORKERTYPE.List, -1, 0, _curTab.Text);
3872                         break;
3873                     default:
3874                         GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3875                         break;
3876                 }
3877             }
3878             else
3879             {
3880                 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3881             }
3882         }
3883
3884         private void SettingStripMenuItem_Click(object sender, EventArgs e)
3885         {
3886             DialogResult result;
3887             string uid = tw.Username.ToLower();
3888             var oldIconSz = SettingDialog.IconSz;
3889
3890             try
3891             {
3892                 result = SettingDialog.ShowDialog(this);
3893             }
3894             catch (Exception)
3895             {
3896                 return;
3897             }
3898
3899             if (result == DialogResult.OK)
3900             {
3901                 lock (_syncObject)
3902                 {
3903                     tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
3904                     tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
3905                     tw.ReadOwnPost = SettingDialog.ReadOwnPost;
3906                     ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3907                     ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3908                     ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3909                     HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3910
3911                     HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
3912                                                         SettingDialog.SelectedProxyType,
3913                                                         SettingDialog.ProxyAddress,
3914                                                         SettingDialog.ProxyPort,
3915                                                         SettingDialog.ProxyUser,
3916                                                         SettingDialog.ProxyPassword);
3917                     this.CreatePictureServices();
3918
3919                     try
3920                     {
3921                         if (SettingDialog.TabIconDisp)
3922                         {
3923                             ListTab.DrawItem -= ListTab_DrawItem;
3924                             ListTab.DrawMode = TabDrawMode.Normal;
3925                             ListTab.ImageList = this.TabImage;
3926                         }
3927                         else
3928                         {
3929                             ListTab.DrawItem -= ListTab_DrawItem;
3930                             ListTab.DrawItem += ListTab_DrawItem;
3931                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3932                             ListTab.ImageList = null;
3933                         }
3934                     }
3935                     catch (Exception ex)
3936                     {
3937                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
3938                         ex.Data["IsTerminatePermission"] = false;
3939                         throw;
3940                     }
3941
3942                     try
3943                     {
3944                         if (!SettingDialog.UnreadManage)
3945                         {
3946                             ReadedStripMenuItem.Enabled = false;
3947                             UnreadStripMenuItem.Enabled = false;
3948                             if (SettingDialog.TabIconDisp)
3949                             {
3950                                 foreach (TabPage myTab in ListTab.TabPages)
3951                                 {
3952                                     myTab.ImageIndex = -1;
3953                                 }
3954                             }
3955                         }
3956                         else
3957                         {
3958                             ReadedStripMenuItem.Enabled = true;
3959                             UnreadStripMenuItem.Enabled = true;
3960                         }
3961                     }
3962                     catch (Exception ex)
3963                     {
3964                         ex.Data["Instance"] = "ListTab(UnreadManage)";
3965                         ex.Data["IsTerminatePermission"] = false;
3966                         throw;
3967                     }
3968
3969                     // タブの表示位置の決定
3970                     SetTabAlignment();
3971
3972                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3973                     imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3974                     imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3975
3976                     PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
3977                     this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
3978                     _fntUnread = SettingDialog.FontUnread;
3979                     _clUnread = SettingDialog.ColorUnread;
3980                     _fntReaded = SettingDialog.FontReaded;
3981                     _clReaded = SettingDialog.ColorReaded;
3982                     _clFav = SettingDialog.ColorFav;
3983                     _clOWL = SettingDialog.ColorOWL;
3984                     _clRetweet = SettingDialog.ColorRetweet;
3985                     _fntDetail = SettingDialog.FontDetail;
3986                     _clDetail = SettingDialog.ColorDetail;
3987                     _clDetailLink = SettingDialog.ColorDetailLink;
3988                     _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
3989                     _clSelf = SettingDialog.ColorSelf;
3990                     _clAtSelf = SettingDialog.ColorAtSelf;
3991                     _clTarget = SettingDialog.ColorTarget;
3992                     _clAtTarget = SettingDialog.ColorAtTarget;
3993                     _clAtFromTarget = SettingDialog.ColorAtFromTarget;
3994                     _clAtTo = SettingDialog.ColorAtTo;
3995                     _clListBackcolor = SettingDialog.ColorListBackcolor;
3996                     _clInputBackcolor = SettingDialog.ColorInputBackcolor;
3997                     _clInputFont = SettingDialog.ColorInputFont;
3998                     _fntInputFont = SettingDialog.FontInputFont;
3999                     _brsBackColorMine.Dispose();
4000                     _brsBackColorAt.Dispose();
4001                     _brsBackColorYou.Dispose();
4002                     _brsBackColorAtYou.Dispose();
4003                     _brsBackColorAtFromTarget.Dispose();
4004                     _brsBackColorAtTo.Dispose();
4005                     _brsBackColorNone.Dispose();
4006                     _brsBackColorMine = new SolidBrush(_clSelf);
4007                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4008                     _brsBackColorYou = new SolidBrush(_clTarget);
4009                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4010                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4011                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4012                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4013
4014                     try
4015                     {
4016                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4017                         StatusText.Font = _fntInputFont;
4018                         StatusText.ForeColor = _clInputFont;
4019                     }
4020                     catch (Exception ex)
4021                     {
4022                         MessageBox.Show(ex.Message);
4023                     }
4024
4025                     try
4026                     {
4027                         InitDetailHtmlFormat();
4028                     }
4029                     catch (Exception ex)
4030                     {
4031                         ex.Data["Instance"] = "Font";
4032                         ex.Data["IsTerminatePermission"] = false;
4033                         throw;
4034                     }
4035
4036                     try
4037                     {
4038                         _statuses.SetUnreadManage(SettingDialog.UnreadManage);
4039                     }
4040                     catch (Exception ex)
4041                     {
4042                         ex.Data["Instance"] = "_statuses";
4043                         ex.Data["IsTerminatePermission"] = false;
4044                         throw;
4045                     }
4046
4047                     try
4048                     {
4049                         foreach (TabPage tb in ListTab.TabPages)
4050                         {
4051                             if (SettingDialog.TabIconDisp)
4052                             {
4053                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4054                                     tb.ImageIndex = -1;
4055                                 else
4056                                     tb.ImageIndex = 0;
4057                             }
4058                         }
4059                     }
4060                     catch (Exception ex)
4061                     {
4062                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4063                         ex.Data["IsTerminatePermission"] = false;
4064                         throw;
4065                     }
4066
4067                     try
4068                     {
4069                         var oldIconCol = _iconCol;
4070
4071                         if (SettingDialog.IconSz != oldIconSz)
4072                             ApplyListViewIconSize(SettingDialog.IconSz);
4073
4074                         foreach (TabPage tp in ListTab.TabPages)
4075                         {
4076                             DetailsListView lst = (DetailsListView)tp.Tag;
4077
4078                             using (ControlTransaction.Update(lst))
4079                             {
4080                                 lst.GridLines = SettingDialog.ShowGrid;
4081                                 lst.Font = _fntReaded;
4082                                 lst.BackColor = _clListBackcolor;
4083
4084                                 if (_iconCol != oldIconCol)
4085                                     ResetColumns(lst);
4086                             }
4087                         }
4088                     }
4089                     catch (Exception ex)
4090                     {
4091                         ex.Data["Instance"] = "ListView(IconSize)";
4092                         ex.Data["IsTerminatePermission"] = false;
4093                         throw;
4094                     }
4095
4096                     SetMainWindowTitle();
4097                     SetNotifyIconText();
4098
4099                     this.PurgeListViewItemCache();
4100                     if (_curList != null) _curList.Refresh();
4101                     ListTab.Refresh();
4102
4103                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4104                     if (SettingDialog.HotkeyEnabled)
4105                     {
4106                         ///グローバルホットキーの登録。設定で変更可能にするかも
4107                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4108                         if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
4109                         if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
4110                         if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
4111                         if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
4112
4113                         _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
4114                     }
4115
4116                     if (uid != tw.Username) this.doGetFollowersMenu();
4117
4118                     SetImageServiceCombo();
4119                     if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
4120                     try
4121                     {
4122                         StatusText_TextChanged(null, null);
4123                     }
4124                     catch (Exception)
4125                     {
4126                     }
4127                 }
4128             }
4129
4130             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4131
4132             this.TopMost = SettingDialog.AlwaysTop;
4133             SaveConfigsAll(false);
4134         }
4135
4136         /// <summary>
4137         /// タブの表示位置を設定する
4138         /// </summary>
4139         private void SetTabAlignment()
4140         {
4141             ListTab.Alignment = (SettingDialog.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top);
4142         }
4143
4144         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4145         {
4146             // アイコンサイズの再設定
4147             _iconCol = false;
4148             switch (iconSz)
4149             {
4150                 case MyCommon.IconSizes.IconNone:
4151                     _iconSz = 0;
4152                     break;
4153                 case MyCommon.IconSizes.Icon16:
4154                     _iconSz = 16;
4155                     break;
4156                 case MyCommon.IconSizes.Icon24:
4157                     _iconSz = 26;
4158                     break;
4159                 case MyCommon.IconSizes.Icon48:
4160                     _iconSz = 48;
4161                     break;
4162                 case MyCommon.IconSizes.Icon48_2:
4163                     _iconSz = 48;
4164                     _iconCol = true;
4165                     break;
4166             }
4167
4168             if (_iconSz > 0)
4169             {
4170                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4171                 _listViewImageList.ImageSize = new Size(
4172                     1,
4173                     (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4174             }
4175             else
4176             {
4177                 _listViewImageList.ImageSize = new Size(1, 1);
4178             }
4179         }
4180
4181         private void ResetColumns(DetailsListView list)
4182         {
4183             using (ControlTransaction.Update(list))
4184             using (ControlTransaction.Layout(list, false))
4185             {
4186                 // カラムヘッダの再設定
4187                 list.ColumnClick -= MyList_ColumnClick;
4188                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4189                 list.ColumnReordered -= MyList_ColumnReordered;
4190                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4191
4192                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4193                 list.Columns.Clear();
4194                 cols.ForEach(col => col.Dispose());
4195                 cols.Clear();
4196
4197                 InitColumns(list, true);
4198
4199                 list.ColumnClick += MyList_ColumnClick;
4200                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4201                 list.ColumnReordered += MyList_ColumnReordered;
4202                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4203             }
4204         }
4205
4206         private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4207         {
4208             if (e.Url.AbsoluteUri != "about:blank")
4209             {
4210                 DispSelectedPost();
4211                 OpenUriAsync(e.Url.OriginalString);
4212             }
4213         }
4214
4215         private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4216         {
4217             if (e.Url.Scheme == "data")
4218             {
4219                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4220             }
4221             else if (e.Url.AbsoluteUri != "about:blank")
4222             {
4223                 e.Cancel = true;
4224
4225                 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4226                    e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4227                 {
4228                     //ハッシュタグの場合は、タブで開く
4229                     string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4230                     int i = urlStr.IndexOf('#');
4231                     if (i == -1) return;
4232
4233                     string hash = urlStr.Substring(i);
4234                     HashSupl.AddItem(hash);
4235                     HashMgr.AddHashToHistory(hash.Trim(), false);
4236                     AddNewTabForSearch(hash);
4237                     return;
4238                 }
4239                 else
4240                 {
4241                     Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4242                     if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4243                     {
4244                         // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4245                         if (SettingDialog.OpenUserTimeline)
4246                         {
4247                             if (MyCommon.IsKeyDown(Keys.Control))
4248                                 OpenUriAsync(e.Url.OriginalString);
4249                             else
4250                                 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4251                         }
4252                         else
4253                         {
4254                             if (MyCommon.IsKeyDown(Keys.Control))
4255                                 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4256                             else
4257                                 OpenUriAsync(e.Url.OriginalString);
4258                         }
4259                     }
4260                     else
4261                     {
4262                         OpenUriAsync(e.Url.OriginalString);
4263                     }
4264                 }
4265             }
4266         }
4267
4268         public void AddNewTabForSearch(string searchWord)
4269         {
4270             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4271             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4272             {
4273                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4274                 {
4275                     foreach (TabPage tp in ListTab.TabPages)
4276                     {
4277                         if (tb.TabName == tp.Text)
4278                         {
4279                             ListTab.SelectedTab = tp;
4280                             return;
4281                         }
4282                     }
4283                 }
4284             }
4285             //ユニークなタブ名生成
4286             string tabName = searchWord;
4287             for (int i = 0; i <= 100; i++)
4288             {
4289                 if (_statuses.ContainsTab(tabName))
4290                     tabName += "_";
4291                 else
4292                     break;
4293             }
4294             //タブ追加
4295             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4296             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4297             //追加したタブをアクティブに
4298             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4299             //検索条件の設定
4300             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4301             cmb.Items.Add(searchWord);
4302             cmb.Text = searchWord;
4303             SaveConfigsTabs();
4304             //検索実行
4305             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4306         }
4307
4308         private void ShowUserTimeline()
4309         {
4310             if (!this.ExistCurrentPost) return;
4311             AddNewTabForUserTimeline(_curPost.ScreenName);
4312         }
4313
4314         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4315         {
4316             if (e.KeyCode == Keys.Escape)
4317             {
4318                 TabPage relTp = ListTab.SelectedTab;
4319                 RemoveSpecifiedTab(relTp.Text, false);
4320                 SaveConfigsTabs();
4321                 e.SuppressKeyPress = true;
4322             }
4323         }
4324
4325         public void AddNewTabForUserTimeline(string user)
4326         {
4327             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4328             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4329             {
4330                 if (tb.User == user)
4331                 {
4332                     foreach (TabPage tp in ListTab.TabPages)
4333                     {
4334                         if (tb.TabName == tp.Text)
4335                         {
4336                             ListTab.SelectedTab = tp;
4337                             return;
4338                         }
4339                     }
4340                 }
4341             }
4342             //ユニークなタブ名生成
4343             string tabName = "user:" + user;
4344             while (_statuses.ContainsTab(tabName))
4345             {
4346                 tabName += "_";
4347             }
4348             //タブ追加
4349             _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4350             _statuses.Tabs[tabName].User = user;
4351             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4352             //追加したタブをアクティブに
4353             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4354             SaveConfigsTabs();
4355             //検索実行
4356
4357             GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, tabName);
4358         }
4359
4360         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4361         {
4362             //重複チェック
4363             foreach (TabPage tb in ListTab.TabPages)
4364             {
4365                 if (tb.Text == tabName) return false;
4366             }
4367
4368             //新規タブ名チェック
4369             if (tabName == Properties.Resources.AddNewTabText1) return false;
4370
4371             //タブタイプ重複チェック
4372             if (!startup)
4373             {
4374                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4375                    tabType == MyCommon.TabUsageType.Favorites ||
4376                    tabType == MyCommon.TabUsageType.Home ||
4377                    tabType == MyCommon.TabUsageType.Mentions ||
4378                    tabType == MyCommon.TabUsageType.Related)
4379                 {
4380                     if (_statuses.GetTabByType(tabType) != null) return false;
4381                 }
4382             }
4383
4384             TabPage _tabPage = new TabPage();
4385             DetailsListView _listCustom = new DetailsListView();
4386
4387             int cnt = ListTab.TabPages.Count;
4388
4389             ///ToDo:Create and set controls follow tabtypes
4390
4391             using (ControlTransaction.Update(_listCustom))
4392             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4393             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4394             using (ControlTransaction.Layout(this.SplitContainer1, false))
4395             using (ControlTransaction.Layout(this.ListTab, false))
4396             using (ControlTransaction.Layout(this))
4397             using (ControlTransaction.Layout(_tabPage, false))
4398             {
4399                 /// UserTimeline関連
4400                 Label label = null;
4401                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4402                 {
4403                     label = new Label();
4404                     label.Dock = DockStyle.Top;
4405                     label.Name = "labelUser";
4406                     if (tabType == MyCommon.TabUsageType.Lists)
4407                     {
4408                         label.Text = listInfo.ToString();
4409                     }
4410                     else
4411                     {
4412                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4413                     }
4414                     label.TextAlign = ContentAlignment.MiddleLeft;
4415                     using (ComboBox tmpComboBox = new ComboBox())
4416                     {
4417                         label.Height = tmpComboBox.Height;
4418                     }
4419                     _tabPage.Controls.Add(label);
4420                 }
4421
4422                 /// 検索関連の準備
4423                 Panel pnl = null;
4424                 if (tabType == MyCommon.TabUsageType.PublicSearch)
4425                 {
4426                     pnl = new Panel();
4427
4428                     Label lbl = new Label();
4429                     ComboBox cmb = new ComboBox();
4430                     Button btn = new Button();
4431                     ComboBox cmbLang = new ComboBox();
4432
4433                     pnl.SuspendLayout();
4434
4435                     pnl.Controls.Add(cmb);
4436                     pnl.Controls.Add(cmbLang);
4437                     pnl.Controls.Add(btn);
4438                     pnl.Controls.Add(lbl);
4439                     pnl.Name = "panelSearch";
4440                     pnl.Dock = DockStyle.Top;
4441                     pnl.Height = cmb.Height;
4442                     pnl.Enter += SearchControls_Enter;
4443                     pnl.Leave += SearchControls_Leave;
4444
4445                     cmb.Text = "";
4446                     cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4447                     cmb.Dock = DockStyle.Fill;
4448                     cmb.Name = "comboSearch";
4449                     cmb.DropDownStyle = ComboBoxStyle.DropDown;
4450                     cmb.ImeMode = ImeMode.NoControl;
4451                     cmb.TabStop = false;
4452                     cmb.AutoCompleteMode = AutoCompleteMode.None;
4453                     cmb.KeyDown += SearchComboBox_KeyDown;
4454
4455                     if (_statuses.ContainsTab(tabName))
4456                     {
4457                         cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4458                         cmb.Text = _statuses.Tabs[tabName].SearchWords;
4459                     }
4460
4461                     cmbLang.Text = "";
4462                     cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4463                     cmbLang.Dock = DockStyle.Right;
4464                     cmbLang.Width = 50;
4465                     cmbLang.Name = "comboLang";
4466                     cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4467                     cmbLang.TabStop = false;
4468                     cmbLang.Items.Add("");
4469                     cmbLang.Items.Add("ja");
4470                     cmbLang.Items.Add("en");
4471                     cmbLang.Items.Add("ar");
4472                     cmbLang.Items.Add("da");
4473                     cmbLang.Items.Add("nl");
4474                     cmbLang.Items.Add("fa");
4475                     cmbLang.Items.Add("fi");
4476                     cmbLang.Items.Add("fr");
4477                     cmbLang.Items.Add("de");
4478                     cmbLang.Items.Add("hu");
4479                     cmbLang.Items.Add("is");
4480                     cmbLang.Items.Add("it");
4481                     cmbLang.Items.Add("no");
4482                     cmbLang.Items.Add("pl");
4483                     cmbLang.Items.Add("pt");
4484                     cmbLang.Items.Add("ru");
4485                     cmbLang.Items.Add("es");
4486                     cmbLang.Items.Add("sv");
4487                     cmbLang.Items.Add("th");
4488                     if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4489
4490                     lbl.Text = "Search(C-S-f)";
4491                     lbl.Name = "label1";
4492                     lbl.Dock = DockStyle.Left;
4493                     lbl.Width = 90;
4494                     lbl.Height = cmb.Height;
4495                     lbl.TextAlign = ContentAlignment.MiddleLeft;
4496
4497                     btn.Text = "Search";
4498                     btn.Name = "buttonSearch";
4499                     btn.UseVisualStyleBackColor = true;
4500                     btn.Dock = DockStyle.Right;
4501                     btn.TabStop = false;
4502                     btn.Click += SearchButton_Click;
4503                 }
4504
4505                 this.ListTab.Controls.Add(_tabPage);
4506                 _tabPage.Controls.Add(_listCustom);
4507
4508                 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4509                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4510
4511                 _tabPage.Location = new Point(4, 4);
4512                 _tabPage.Name = "CTab" + cnt.ToString();
4513                 _tabPage.Size = new Size(380, 260);
4514                 _tabPage.TabIndex = 2 + cnt;
4515                 _tabPage.Text = tabName;
4516                 _tabPage.UseVisualStyleBackColor = true;
4517
4518                 _listCustom.AllowColumnReorder = true;
4519                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4520                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4521                 _listCustom.Dock = DockStyle.Fill;
4522                 _listCustom.FullRowSelect = true;
4523                 _listCustom.HideSelection = false;
4524                 _listCustom.Location = new Point(0, 0);
4525                 _listCustom.Margin = new Padding(0);
4526                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4527                 _listCustom.ShowItemToolTips = true;
4528                 _listCustom.Size = new Size(380, 260);
4529                 _listCustom.UseCompatibleStateImageBehavior = false;
4530                 _listCustom.View = View.Details;
4531                 _listCustom.OwnerDraw = true;
4532                 _listCustom.VirtualMode = true;
4533                 _listCustom.Font = _fntReaded;
4534                 _listCustom.BackColor = _clListBackcolor;
4535
4536                 _listCustom.GridLines = SettingDialog.ShowGrid;
4537                 _listCustom.AllowDrop = true;
4538
4539                 _listCustom.SmallImageList = _listViewImageList;
4540
4541                 InitColumns(_listCustom, startup);
4542
4543                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4544                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4545                 _listCustom.ColumnClick += MyList_ColumnClick;
4546                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4547                 _listCustom.DragDrop += TweenMain_DragDrop;
4548                 _listCustom.DragEnter += TweenMain_DragEnter;
4549                 _listCustom.DragOver += TweenMain_DragOver;
4550                 _listCustom.DrawItem += MyList_DrawItem;
4551                 _listCustom.MouseClick += MyList_MouseClick;
4552                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4553                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4554                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4555                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4556                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4557                 _listCustom.HScrolled += MyList_HScrolled;
4558
4559                 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4560             }
4561
4562             _tabPage.Tag = _listCustom;
4563             return true;
4564         }
4565
4566         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4567         {
4568             if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4569
4570             if (confirm)
4571             {
4572                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4573                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4574                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4575                 {
4576                     return false;
4577                 }
4578             }
4579
4580             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4581             if (_tabPage == null) return false;
4582
4583             SetListProperty();   //他のタブに列幅等を反映
4584
4585             MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4586
4587             //オブジェクトインスタンスの削除
4588             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4589             _tabPage.Tag = null;
4590
4591             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4592             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4593             using (ControlTransaction.Layout(this.SplitContainer1, false))
4594             using (ControlTransaction.Layout(this.ListTab, false))
4595             using (ControlTransaction.Layout(this))
4596             using (ControlTransaction.Layout(_tabPage, false))
4597             {
4598                 if (this.ListTab.SelectedTab == _tabPage)
4599                 {
4600                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4601                     this._beforeSelectedTab = null;
4602                 }
4603                 this.ListTab.Controls.Remove(_tabPage);
4604
4605                 // 後付けのコントロールを破棄
4606                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4607                 {
4608                     using (Control label = _tabPage.Controls["labelUser"])
4609                     {
4610                         _tabPage.Controls.Remove(label);
4611                     }
4612                 }
4613                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4614                 {
4615                     using (Control pnl = _tabPage.Controls["panelSearch"])
4616                     {
4617                         pnl.Enter -= SearchControls_Enter;
4618                         pnl.Leave -= SearchControls_Leave;
4619                         _tabPage.Controls.Remove(pnl);
4620
4621                         foreach (Control ctrl in pnl.Controls)
4622                         {
4623                             if (ctrl.Name == "buttonSearch")
4624                             {
4625                                 ctrl.Click -= SearchButton_Click;
4626                             }
4627                             else if (ctrl.Name == "comboSearch")
4628                             {
4629                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4630                             }
4631                             pnl.Controls.Remove(ctrl);
4632                             ctrl.Dispose();
4633                         }
4634                     }
4635                 }
4636
4637                 _tabPage.Controls.Remove(_listCustom);
4638
4639                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4640                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4641                 _listCustom.ColumnClick -= MyList_ColumnClick;
4642                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4643                 _listCustom.DragDrop -= TweenMain_DragDrop;
4644                 _listCustom.DragEnter -= TweenMain_DragEnter;
4645                 _listCustom.DragOver -= TweenMain_DragOver;
4646                 _listCustom.DrawItem -= MyList_DrawItem;
4647                 _listCustom.MouseClick -= MyList_MouseClick;
4648                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4649                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4650                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4651                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4652                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4653                 _listCustom.HScrolled -= MyList_HScrolled;
4654
4655                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4656                 _listCustom.Columns.Clear();
4657                 cols.ForEach(col => col.Dispose());
4658                 cols.Clear();
4659
4660                 _listCustom.ContextMenuStrip = null;
4661                 _listCustom.ColumnHeaderContextMenuStrip = null;
4662                 _listCustom.Font = null;
4663
4664                 _listCustom.SmallImageList = null;
4665                 _listCustom.ListViewItemSorter = null;
4666
4667                 //キャッシュのクリア
4668                 if (_curTab.Equals(_tabPage))
4669                 {
4670                     _curTab = null;
4671                     _curItemIndex = -1;
4672                     _curList = null;
4673                     _curPost = null;
4674                 }
4675                 this.PurgeListViewItemCache();
4676             }
4677
4678             _tabPage.Dispose();
4679             _listCustom.Dispose();
4680             _statuses.RemoveTab(TabName);
4681
4682             foreach (TabPage tp in ListTab.TabPages)
4683             {
4684                 DetailsListView lst = (DetailsListView)tp.Tag;
4685                 var count = _statuses.Tabs[tp.Text].AllCount;
4686                 if (lst.VirtualListSize != count)
4687                 {
4688                     lst.VirtualListSize = count;
4689                 }
4690             }
4691
4692             return true;
4693         }
4694
4695         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4696         {
4697             this.PurgeListViewItemCache();
4698             _beforeSelectedTab = e.TabPage;
4699         }
4700
4701         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4702         {
4703             //タブのD&D
4704
4705             if (!SettingDialog.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4706             {
4707                 string tn = "";
4708                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4709                 if (!dragEnableRectangle.Contains(e.Location))
4710                 {
4711                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4712                     tn = ListTab.SelectedTab.Text;
4713                 }
4714
4715                 if (string.IsNullOrEmpty(tn)) return;
4716
4717                 foreach (TabPage tb in ListTab.TabPages)
4718                 {
4719                     if (tb.Text == tn)
4720                     {
4721                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4722                         break;
4723                     }
4724                 }
4725             }
4726             else
4727             {
4728                 _tabDrag = false;
4729             }
4730
4731             Point cpos = new Point(e.X, e.Y);
4732             for (int i = 0; i < ListTab.TabPages.Count; i++)
4733             {
4734                 Rectangle rect = ListTab.GetTabRect(i);
4735                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4736                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4737                 {
4738                     _rclickTabName = ListTab.TabPages[i].Text;
4739                     break;
4740                 }
4741             }
4742         }
4743
4744         private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4745         {
4746             //_curList.Refresh();
4747             DispSelectedPost();
4748             SetMainWindowTitle();
4749             SetStatusLabelUrl();
4750             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4751             TabMenuControl(ListTab.SelectedTab.Text);
4752             this.PushSelectPostChain();
4753         }
4754
4755         private void SetListProperty()
4756         {
4757             //削除などで見つからない場合は処理せず
4758             if (_curList == null) return;
4759             if (!_isColumnChanged) return;
4760
4761             int[] dispOrder = new int[_curList.Columns.Count];
4762             for (int i = 0; i < _curList.Columns.Count; i++)
4763             {
4764                 for (int j = 0; j < _curList.Columns.Count; j++)
4765                 {
4766                     if (_curList.Columns[j].DisplayIndex == i)
4767                     {
4768                         dispOrder[i] = j;
4769                         break;
4770                     }
4771                 }
4772             }
4773
4774             //列幅、列並びを他のタブに設定
4775             foreach (TabPage tb in ListTab.TabPages)
4776             {
4777                 if (!tb.Equals(_curTab))
4778                 {
4779                     if (tb.Tag != null && tb.Controls.Count > 0)
4780                     {
4781                         DetailsListView lst = (DetailsListView)tb.Tag;
4782                         for (int i = 0; i < lst.Columns.Count; i++)
4783                         {
4784                             lst.Columns[dispOrder[i]].DisplayIndex = i;
4785                             lst.Columns[i].Width = _curList.Columns[i].Width;
4786                         }
4787                     }
4788                 }
4789             }
4790
4791             _isColumnChanged = false;
4792         }
4793
4794         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4795         {
4796             try
4797             {
4798                 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4799                         || PostBrowser.StatusText.StartsWith("data"))
4800                 {
4801                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4802                 }
4803                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4804                 {
4805                     SetStatusLabelUrl();
4806                 }
4807             }
4808             catch (Exception)
4809             {
4810             }
4811         }
4812
4813         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4814         {
4815             if (e.KeyChar == '@')
4816             {
4817                 if (!SettingDialog.UseAtIdSupplement) return;
4818                 //@マーク
4819                 int cnt = AtIdSupl.ItemCount;
4820                 ShowSuplDialog(StatusText, AtIdSupl);
4821                 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4822                 e.Handled = true;
4823             }
4824             else if (e.KeyChar == '#')
4825             {
4826                 if (!SettingDialog.UseHashSupplement) return;
4827                 ShowSuplDialog(StatusText, HashSupl);
4828                 e.Handled = true;
4829             }
4830         }
4831
4832         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4833         {
4834             ShowSuplDialog(owner, dialog, 0, "");
4835         }
4836
4837         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4838         {
4839             ShowSuplDialog(owner, dialog, offset, "");
4840         }
4841
4842         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4843         {
4844             dialog.StartsWith = startswith;
4845             if (dialog.Visible)
4846             {
4847                 dialog.Focus();
4848             }
4849             else
4850             {
4851                 dialog.ShowDialog();
4852             }
4853             this.TopMost = SettingDialog.AlwaysTop;
4854             int selStart = owner.SelectionStart;
4855             string fHalf = "";
4856             string eHalf = "";
4857             if (dialog.DialogResult == DialogResult.OK)
4858             {
4859                 if (!string.IsNullOrEmpty(dialog.inputText))
4860                 {
4861                     if (selStart > 0)
4862                     {
4863                         fHalf = owner.Text.Substring(0, selStart - offset);
4864                     }
4865                     if (selStart < owner.Text.Length)
4866                     {
4867                         eHalf = owner.Text.Substring(selStart);
4868                     }
4869                     owner.Text = fHalf + dialog.inputText + eHalf;
4870                     owner.SelectionStart = selStart + dialog.inputText.Length;
4871                 }
4872             }
4873             else
4874             {
4875                 if (selStart > 0)
4876                 {
4877                     fHalf = owner.Text.Substring(0, selStart);
4878                 }
4879                 if (selStart < owner.Text.Length)
4880                 {
4881                     eHalf = owner.Text.Substring(selStart);
4882                 }
4883                 owner.Text = fHalf + eHalf;
4884                 if (selStart > 0)
4885                 {
4886                     owner.SelectionStart = selStart;
4887                 }
4888             }
4889             owner.Focus();
4890         }
4891
4892         private void StatusText_KeyUp(object sender, KeyEventArgs e)
4893         {
4894             //スペースキーで未読ジャンプ
4895             if (!e.Alt && !e.Control && !e.Shift)
4896             {
4897                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4898                 {
4899                     bool isSpace = false;
4900                     foreach (char c in StatusText.Text.ToCharArray())
4901                     {
4902                         if (c == ' ' || c == ' ')
4903                         {
4904                             isSpace = true;
4905                         }
4906                         else
4907                         {
4908                             isSpace = false;
4909                             break;
4910                         }
4911                     }
4912                     if (isSpace)
4913                     {
4914                         e.Handled = true;
4915                         StatusText.Text = "";
4916                         JumpUnreadMenuItem_Click(null, null);
4917                     }
4918                 }
4919             }
4920             this.StatusText_TextChanged(null, null);
4921         }
4922
4923         private void StatusText_TextChanged(object sender, EventArgs e)
4924         {
4925             //文字数カウント
4926             int pLen = GetRestStatusCount(true, false);
4927             lblLen.Text = pLen.ToString();
4928             if (pLen < 0)
4929             {
4930                 StatusText.ForeColor = Color.Red;
4931             }
4932             else
4933             {
4934                 StatusText.ForeColor = _clInputFont;
4935             }
4936             if (string.IsNullOrEmpty(StatusText.Text))
4937             {
4938                 _reply_to_id = null;
4939                 _reply_to_name = null;
4940             }
4941         }
4942
4943         private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4944         {
4945             //文字数カウント
4946             var statusText = this.StatusText.Text;
4947             statusText = statusText.Replace("\r\n", "\n");
4948
4949             int pLen = 140 - statusText.Length;
4950             if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4951             if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && SettingDialog.PostShiftEnter) ||
4952                 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !SettingDialog.PostShiftEnter) ||
4953                 (!isAuto && isAddFooter))
4954             {
4955                 if (SettingDialog.UseRecommendStatus)
4956                     pLen -= SettingDialog.RecommendStatusText.Length;
4957                 else if (SettingDialog.Status.Length > 0)
4958                     pLen -= SettingDialog.Status.Length + 1;
4959             }
4960             if (!string.IsNullOrEmpty(HashMgr.UseHash))
4961             {
4962                 pLen -= HashMgr.UseHash.Length + 1;
4963             }
4964             //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4965             //{
4966             //    pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4967             //}
4968             foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4969             {
4970                 string before = m.Result("${before}");
4971                 string url = m.Result("${url}");
4972                 string protocol = m.Result("${protocol}");
4973                 string domain = m.Result("${domain}");
4974                 string path = m.Result("${path}");
4975                 if (protocol.Length == 0)
4976                 {
4977                     if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4978                     {
4979                         continue;
4980                     }
4981
4982                     bool last_url_invalid_match = false;
4983                     string lasturl = null;
4984                     foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4985                     {
4986                         lasturl = mm.ToString();
4987                         last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4988                         if (!last_url_invalid_match)
4989                         {
4990                             pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4991                         }
4992                     }
4993
4994                     if (path.Length != 0)
4995                     {
4996                         if (last_url_invalid_match)
4997                         {
4998                             pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4999                         }
5000                         pLen += path.Length;
5001                     }
5002                 }
5003                 else
5004                 {
5005                     int shortUrlLength = protocol == "https://"
5006                         ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
5007                         : SettingDialog.TwitterConfiguration.ShortUrlLength;
5008
5009                     pLen += url.Length - shortUrlLength;
5010                 }
5011                 
5012                 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5013                 //{
5014                 //    pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5015                 //}
5016             }
5017             if (ImageSelectionPanel.Visible && ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
5018             {
5019                 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
5020             }
5021             return pLen;
5022         }
5023
5024         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5025         {
5026             this.itemCacheLock.EnterUpgradeableReadLock();
5027             try
5028             {
5029                 if (_curList.Equals(sender))
5030                 {
5031                     if (_itemCache != null &&
5032                        e.StartIndex >= _itemCacheIndex &&
5033                        e.EndIndex < _itemCacheIndex + _itemCache.Length)
5034                     {
5035                         //If the newly requested cache is a subset of the old cache, 
5036                         //no need to rebuild everything, so do nothing.
5037                         return;
5038                     }
5039
5040                     //Now we need to rebuild the cache.
5041                     CreateCache(e.StartIndex, e.EndIndex);
5042                 }
5043             }
5044             finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5045         }
5046
5047         private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5048         {
5049             ListViewItem item = null;
5050             PostClass cacheItemPost = null;
5051
5052             if (_curList.Equals(sender))
5053                 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5054
5055             if (item == null)
5056             {
5057                 //A cache miss, so create a new ListViewItem and pass it back.
5058                 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5059                 try
5060                 {
5061                     item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5062                 }
5063                 catch (Exception)
5064                 {
5065                     //不正な要求に対する間に合わせの応答
5066                     string[] sitem = {"", "", "", "", "", "", "", ""};
5067                     item = new ImageListViewItem(sitem);
5068                 }
5069             }
5070
5071             // e.Item に値をセットする前に await しないこと
5072             e.Item = item;
5073
5074             await ((ImageListViewItem)item).GetImageAsync();
5075         }
5076
5077         private void CreateCache(int StartIndex, int EndIndex)
5078         {
5079             this.itemCacheLock.EnterWriteLock();
5080             try
5081             {
5082                 //キャッシュ要求(要求範囲±30を作成)
5083                 StartIndex -= 30;
5084                 if (StartIndex < 0) StartIndex = 0;
5085                 EndIndex += 30;
5086                 if (EndIndex >= _statuses.Tabs[_curTab.Text].AllCount) EndIndex = _statuses.Tabs[_curTab.Text].AllCount - 1;
5087                 _postCache = _statuses[_curTab.Text, StartIndex, EndIndex]; //配列で取得
5088                 _itemCacheIndex = StartIndex;
5089
5090                 _itemCache = new ListViewItem[0] {};
5091                 Array.Resize(ref _itemCache, _postCache.Length);
5092
5093                 for (int i = 0; i < _postCache.Length; i++)
5094                 {
5095                     _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5096                 }
5097             }
5098             catch (Exception)
5099             {
5100                 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5101                 _postCache = null;
5102                 _itemCacheIndex = -1;
5103                 _itemCache = null;
5104             }
5105             finally { this.itemCacheLock.ExitWriteLock(); }
5106         }
5107
5108         /// <summary>
5109         /// DetailsListView のための ListViewItem のキャッシュを消去する
5110         /// </summary>
5111         private void PurgeListViewItemCache()
5112         {
5113             this.itemCacheLock.EnterWriteLock();
5114             try
5115             {
5116                 this._itemCache = null;
5117                 this._itemCacheIndex = -1;
5118                 this._postCache = null;
5119             }
5120             finally { this.itemCacheLock.ExitWriteLock(); }
5121         }
5122
5123         private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5124         {
5125             this.itemCacheLock.EnterReadLock();
5126             try
5127             {
5128                 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5129                 {
5130                     item = this._itemCache[index - _itemCacheIndex];
5131                     post = this._postCache[index - _itemCacheIndex];
5132                     return true;
5133                 }
5134             }
5135             finally { this.itemCacheLock.ExitReadLock(); }
5136
5137             item = null;
5138             post = null;
5139             return false;
5140         }
5141
5142         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5143         {
5144             StringBuilder mk = new StringBuilder();
5145             //if (Post.IsDeleted) mk.Append("×");
5146             //if (Post.IsMark) mk.Append("♪");
5147             //if (Post.IsProtect) mk.Append("Ю");
5148             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5149             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5150             ImageListViewItem itm;
5151             if (Post.RetweetedId == null)
5152             {
5153                 string[] sitem= {"",
5154                                  Post.Nickname,
5155                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5156                                  Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5157                                  Post.ScreenName,
5158                                  "",
5159                                  mk.ToString(),
5160                                  Post.Source};
5161                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5162             }
5163             else
5164             {
5165                 string[] sitem = {"",
5166                                   Post.Nickname,
5167                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5168                                   Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5169                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5170                                   "",
5171                                   mk.ToString(),
5172                                   Post.Source};
5173                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5174             }
5175             itm.StateImageIndex = Post.StateIndex;
5176
5177             bool read = Post.IsRead;
5178             //未読管理していなかったら既読として扱う
5179             if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingDialog.UnreadManage) read = true;
5180             ChangeItemStyleRead(read, itm, Post, null);
5181             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5182             return itm;
5183         }
5184
5185         /// <summary>
5186         /// 全てのタブの振り分けルールを反映し直します
5187         /// </summary>
5188         private void ApplyPostFilters()
5189         {
5190             try
5191             {
5192                 this.Cursor = Cursors.WaitCursor;
5193
5194                 this.PurgeListViewItemCache();
5195                 this._curPost = null;
5196                 this._curItemIndex = -1;
5197                 this._statuses.FilterAll();
5198
5199                 foreach (TabPage tabPage in this.ListTab.TabPages)
5200                 {
5201                     var tab = this._statuses.Tabs[tabPage.Text];
5202
5203                     var listview = (DetailsListView)tabPage.Tag;
5204                     listview.VirtualListSize = tab.AllCount;
5205
5206                     if (this.SettingDialog.TabIconDisp)
5207                     {
5208                         if (tab.UnreadCount > 0)
5209                             tabPage.ImageIndex = 0;
5210                         else
5211                             tabPage.ImageIndex = -1;
5212                     }
5213                 }
5214
5215                 if (!this.SettingDialog.TabIconDisp)
5216                     this.ListTab.Refresh();
5217             }
5218             finally
5219             {
5220                 this.Cursor = Cursors.Default;
5221             }
5222         }
5223
5224         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5225         {
5226             e.DrawDefault = true;
5227         }
5228
5229         private void MyList_HScrolled(object sender, EventArgs e)
5230         {
5231             DetailsListView listView = (DetailsListView)sender;
5232             listView.Refresh();
5233         }
5234
5235         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5236         {
5237             if (e.State == 0) return;
5238             e.DrawDefault = false;
5239             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5240             {
5241                 SolidBrush brs2 = null;
5242
5243                 if (e.Item.BackColor == _clSelf)
5244                     brs2 = _brsBackColorMine;
5245                 else if (e.Item.BackColor == _clAtSelf)
5246                     brs2 = _brsBackColorAt;
5247                 else if (e.Item.BackColor == _clTarget)
5248                     brs2 = _brsBackColorYou;
5249                 else if (e.Item.BackColor == _clAtTarget)
5250                     brs2 = _brsBackColorAtYou;
5251                 else if (e.Item.BackColor == _clAtFromTarget)
5252                     brs2 = _brsBackColorAtFromTarget;
5253                 else if (e.Item.BackColor == _clAtTo)
5254                     brs2 = _brsBackColorAtTo;
5255                 else
5256                     brs2 = _brsBackColorNone;
5257
5258                 e.Graphics.FillRectangle(brs2, e.Bounds);
5259             }
5260             else
5261             {
5262                 //選択中の行
5263                 if (((Control)sender).Focused)
5264                     e.Graphics.FillRectangle(_brsHighLight, e.Bounds);
5265                 else
5266                     e.Graphics.FillRectangle(_brsDeactiveSelection, e.Bounds);
5267             }
5268             if ((e.State & ListViewItemStates.Focused) == ListViewItemStates.Focused) e.DrawFocusRectangle();
5269             this.DrawListViewItemIcon(e);
5270         }
5271
5272         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5273         {
5274             if (e.ItemState == 0) return;
5275
5276             if (e.ColumnIndex > 0)
5277             {
5278                 //アイコン以外の列
5279                 RectangleF rct = e.Bounds;
5280                 rct.Width = e.Header.Width;
5281                 if (_iconCol)
5282                 {
5283                     rct.Y += e.Item.Font.Height;
5284                     rct.Height -= e.Item.Font.Height;
5285                 }
5286
5287                 int heightDiff;
5288                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, e.Item.Font.Height, out heightDiff));
5289
5290                 //if (heightDiff > e.Item.Font.Height * 0.7)
5291                 //{
5292                 //    rct.Height += e.Item.Font.Height;
5293                 //    drawLineCount += 1;
5294                 //}
5295
5296                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5297                 if (!_iconCol && drawLineCount <= 1)
5298                 {
5299                     //rct.Inflate(0, heightDiff / -2);
5300                     //rct.Height += e.Item.Font.Height / 2;
5301                 }
5302                 else if (heightDiff < e.Item.Font.Height * 0.7)
5303                 {
5304                     //最終行が70%以上欠けていたら、最終行は表示しない
5305                     //rct.Height = (float)((e.Item.Font.Height * drawLineCount) + (e.Item.Font.Height / 2));
5306                     rct.Height = (e.Item.Font.Height * drawLineCount) - 1;
5307                 }
5308                 else
5309                 {
5310                     drawLineCount += 1;
5311                 }
5312
5313                 //if (!_iconCol && drawLineCount > 1)
5314                 //{
5315                 //    rct.Y += e.Item.Font.Height * 0.2;
5316                 //    if (heightDiff >= e.Item.Font.Height * 0.8) rct.Height -= e.Item.Font.Height * 0.2;
5317                 //}
5318
5319                 if (rct.Width > 0)
5320                 {
5321                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5322                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5323                         _clUnread;
5324
5325                     if (_iconCol)
5326                     {
5327                         RectangleF rctB = e.Bounds;
5328                         rctB.Width = e.Header.Width;
5329                         rctB.Height = e.Item.Font.Height;
5330
5331                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5332                         {
5333                             TextRenderer.DrawText(e.Graphics,
5334                                                     e.Item.SubItems[2].Text,
5335                                                     e.Item.Font,
5336                                                     Rectangle.Round(rct),
5337                                                     color,
5338                                                     TextFormatFlags.WordBreak |
5339                                                     TextFormatFlags.EndEllipsis |
5340                                                     TextFormatFlags.GlyphOverhangPadding |
5341                                                     TextFormatFlags.NoPrefix);
5342                             TextRenderer.DrawText(e.Graphics,
5343                                                     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 + "]",
5344                                                     fnt,
5345                                                     Rectangle.Round(rctB),
5346                                                     color,
5347                                                     TextFormatFlags.SingleLine |
5348                                                     TextFormatFlags.EndEllipsis |
5349                                                     TextFormatFlags.GlyphOverhangPadding |
5350                                                     TextFormatFlags.NoPrefix);
5351                         }
5352                     }
5353                     else if (drawLineCount == 1)
5354                     {
5355                         TextRenderer.DrawText(e.Graphics,
5356                                                 e.SubItem.Text,
5357                                                 e.Item.Font,
5358                                                 Rectangle.Round(rct),
5359                                                 color,
5360                                                 TextFormatFlags.SingleLine |
5361                                                 TextFormatFlags.EndEllipsis |
5362                                                 TextFormatFlags.GlyphOverhangPadding |
5363                                                 TextFormatFlags.NoPrefix |
5364                                                 TextFormatFlags.VerticalCenter);
5365                     }
5366                     else
5367                     {
5368                         TextRenderer.DrawText(e.Graphics,
5369                                                 e.SubItem.Text,
5370                                                 e.Item.Font,
5371                                                 Rectangle.Round(rct),
5372                                                 color,
5373                                                 TextFormatFlags.WordBreak |
5374                                                 TextFormatFlags.EndEllipsis |
5375                                                 TextFormatFlags.GlyphOverhangPadding |
5376                                                 TextFormatFlags.NoPrefix);
5377                     }
5378                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5379                 }
5380             }
5381         }
5382
5383         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5384         {
5385             ImageListViewItem item = (ImageListViewItem)e.Item;
5386
5387             //e.Bounds.Leftが常に0を指すから自前で計算
5388             Rectangle itemRect = item.Bounds;
5389             itemRect.Width = e.Item.ListView.Columns[0].Width;
5390
5391             foreach (ColumnHeader clm in e.Item.ListView.Columns)
5392             {
5393                 if (clm.DisplayIndex < e.Item.ListView.Columns[0].DisplayIndex)
5394                     itemRect.X += clm.Width;
5395             }
5396
5397             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5398             var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5399             var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5400
5401             Rectangle iconRect;
5402             Rectangle stateRect;
5403             if (item.Image != null)
5404             {
5405                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5406                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5407                 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5408             }
5409             else
5410             {
5411                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5412                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5413                 stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5414             }
5415
5416             var img = item.Image;
5417             if (img != null && iconRect.Width > 0)
5418             {
5419                 e.Graphics.FillRectangle(Brushes.White, iconRect);
5420                 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5421                 try
5422                 {
5423                     e.Graphics.DrawImage(img.Image, iconRect);
5424                 }
5425                 catch (ArgumentException)
5426                 {
5427                     item.RefreshImageAsync();
5428                 }
5429             }
5430
5431             if (item.StateImageIndex > -1)
5432             {
5433                 if (stateRect.Width > 0)
5434                 {
5435                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5436                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5437                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateImageIndex], stateRect);
5438                 }
5439             }
5440         }
5441
5442         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5443         {
5444             base.ScaleControl(factor, specified);
5445
5446             const int baseDpi = 96;
5447
5448             // デザイン時の DPI (96dpi) との比を更新する
5449             this.currentScaleFactor = new SizeF(
5450                 this.CurrentAutoScaleDimensions.Width / baseDpi,
5451                 this.CurrentAutoScaleDimensions.Height / baseDpi);
5452         }
5453
5454         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5455         //{
5456         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5457         //    if (item.StateImageIndex > -1)
5458         //    {
5459         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5460         //        //Rectangle itemRect = item.Bounds;
5461         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5462
5463         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5464         //        //{
5465         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5466         //        //    {
5467         //        //        itemRect.X += clm.Width;
5468         //        //    }
5469         //        //}
5470
5471         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5472         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5473
5474         //        if (rct.Width > 0)
5475         //        {
5476         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5477         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5478         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5479         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5480         //        }
5481         //    }
5482         //}
5483
5484         private void DoTabSearch(string _word,
5485                                  bool CaseSensitive,
5486                                  bool UseRegex,
5487                                  SEARCHTYPE SType)
5488         {
5489             int cidx = 0;
5490             bool fnd = false;
5491             int toIdx;
5492             int stp = 1;
5493
5494             if (_curList.VirtualListSize == 0)
5495             {
5496                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5497             }
5498
5499             if (_curList.SelectedIndices.Count > 0)
5500             {
5501                 cidx = _curList.SelectedIndices[0];
5502             }
5503             toIdx = _curList.VirtualListSize;
5504
5505             switch (SType)
5506             {
5507                 case SEARCHTYPE.DialogSearch:    //ダイアログからの検索
5508                     if (_curList.SelectedIndices.Count > 0)
5509                         cidx = _curList.SelectedIndices[0];
5510                     else
5511                         cidx = 0;
5512                     break;
5513                 case SEARCHTYPE.NextSearch:      //次を検索
5514                     if (_curList.SelectedIndices.Count > 0)
5515                     {
5516                         cidx = _curList.SelectedIndices[0] + 1;
5517                         if (cidx > toIdx) cidx = toIdx;
5518                     }
5519                     else
5520                     {
5521                         cidx = 0;
5522                     }
5523                     break;
5524                 case SEARCHTYPE.PrevSearch:      //前を検索
5525                     if (_curList.SelectedIndices.Count > 0)
5526                     {
5527                         cidx = _curList.SelectedIndices[0] - 1;
5528                         if (cidx < 0) cidx = 0;
5529                     }
5530                     else
5531                     {
5532                         cidx = toIdx;
5533                     }
5534                     toIdx = -1;
5535                     stp = -1;
5536                     break;
5537             }
5538
5539             RegexOptions regOpt = RegexOptions.None;
5540             StringComparison fndOpt = StringComparison.Ordinal;
5541             if (!CaseSensitive)
5542             {
5543                 regOpt = RegexOptions.IgnoreCase;
5544                 fndOpt = StringComparison.OrdinalIgnoreCase;
5545             }
5546             try
5547             {
5548     RETRY:
5549                 if (UseRegex)
5550                 {
5551                     // 正規表現検索
5552                     Regex _search;
5553                     try
5554                     {
5555                         _search = new Regex(_word, regOpt);
5556                         for (int idx = cidx; idx != toIdx; idx += stp)
5557                         {
5558                             PostClass post;
5559                             try
5560                             {
5561                                 post = _statuses[_curTab.Text, idx];
5562                             }
5563                             catch (Exception)
5564                             {
5565                                 continue;
5566                             }
5567                             if (_search.IsMatch(post.Nickname)
5568                                 || _search.IsMatch(post.TextFromApi)
5569                                 || _search.IsMatch(post.ScreenName))
5570                             {
5571                                 SelectListItem(_curList, idx);
5572                                 _curList.EnsureVisible(idx);
5573                                 return;
5574                             }
5575                         }
5576                     }
5577                     catch (ArgumentException)
5578                     {
5579                         MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5580                         return;
5581                     }
5582                 }
5583                 else
5584                 {
5585                     // 通常検索
5586                     for (int idx = cidx; idx != toIdx; idx += stp)
5587                     {
5588                         PostClass post;
5589                         try
5590                         {
5591                             post = _statuses[_curTab.Text, idx];
5592                         }
5593                         catch (Exception)
5594                         {
5595                             continue;
5596                         }
5597                         if (post.Nickname.IndexOf(_word, fndOpt) > -1
5598                             || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5599                             || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5600                         {
5601                             SelectListItem(_curList, idx);
5602                             _curList.EnsureVisible(idx);
5603                             return;
5604                         }
5605                     }
5606                 }
5607
5608                 if (!fnd)
5609                 {
5610                     switch (SType)
5611                     {
5612                         case SEARCHTYPE.DialogSearch:
5613                         case SEARCHTYPE.NextSearch:
5614                             toIdx = cidx;
5615                             cidx = 0;
5616                             break;
5617                         case SEARCHTYPE.PrevSearch:
5618                             toIdx = cidx;
5619                             cidx = _curList.VirtualListSize - 1;
5620                             break;
5621                     }
5622                     fnd = true;
5623                     goto RETRY;
5624                 }
5625             }
5626             catch (ArgumentOutOfRangeException)
5627             {
5628             }
5629             MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5630         }
5631
5632         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5633         {
5634             // 検索メニュー
5635             this.ShowSearchDialog();
5636         }
5637
5638         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5639         {
5640             var previousSearch = this.SearchDialog.ResultOptions;
5641             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5642             {
5643                 this.SearchDialog.Reset();
5644                 this.ShowSearchDialog();
5645                 return;
5646             }
5647
5648             // 次を検索
5649             this.DoTabSearch(
5650                 previousSearch.Query,
5651                 previousSearch.CaseSensitive,
5652                 previousSearch.UseRegex,
5653                 SEARCHTYPE.NextSearch);
5654         }
5655
5656         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5657         {
5658             var previousSearch = this.SearchDialog.ResultOptions;
5659             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5660             {
5661                 this.SearchDialog.Reset();
5662                 this.ShowSearchDialog();
5663                 return;
5664             }
5665
5666             // 前を検索
5667             this.DoTabSearch(
5668                 previousSearch.Query,
5669                 previousSearch.CaseSensitive,
5670                 previousSearch.UseRegex,
5671                 SEARCHTYPE.PrevSearch);
5672         }
5673
5674         /// <summary>
5675         /// 検索ダイアログを表示し、検索を実行します
5676         /// </summary>
5677         private void ShowSearchDialog()
5678         {
5679             // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5680             if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5681                 this.SearchDialog.DisableNewTabButton = false;
5682             else
5683                 this.SearchDialog.DisableNewTabButton = true;
5684
5685             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5686             {
5687                 this.TopMost = this.SettingDialog.AlwaysTop;
5688                 return;
5689             }
5690             this.TopMost = this.SettingDialog.AlwaysTop;
5691
5692             var searchOptions = this.SearchDialog.ResultOptions;
5693             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5694             {
5695                 if (searchOptions.NewTab)
5696                 {
5697                     var tabName = searchOptions.Query;
5698
5699                     try
5700                     {
5701                         tabName = this._statuses.MakeTabName(tabName);
5702                     }
5703                     catch (TabException ex)
5704                     {
5705                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5706                     }
5707
5708                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5709                     this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5710
5711                     var filter = new PostFilterRule
5712                     {
5713                         FilterBody = new[] { searchOptions.Query },
5714                         UseRegex = searchOptions.UseRegex,
5715                         CaseSensitive = searchOptions.CaseSensitive,
5716                     };
5717                     this._statuses.Tabs[tabName].AddFilter(filter);
5718
5719                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5720                         .First(x => x.Text == tabName);
5721
5722                     this.ListTab.SelectedTab = tabPage;
5723                     this.ListTabSelect(tabPage);
5724
5725                     this.ApplyPostFilters();
5726                     this.SaveConfigsTabs();
5727                 }
5728                 else
5729                 {
5730                     this.DoTabSearch(
5731                         searchOptions.Query,
5732                         searchOptions.CaseSensitive,
5733                         searchOptions.UseRegex,
5734                         SEARCHTYPE.DialogSearch);
5735                 }
5736             }
5737             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5738             {
5739                 this.AddNewTabForSearch(searchOptions.Query);
5740             }
5741         }
5742
5743         private void AboutMenuItem_Click(object sender, EventArgs e)
5744         {
5745             using (TweenAboutBox about = new TweenAboutBox())
5746             {
5747                 about.ShowDialog(this);
5748             }
5749             this.TopMost = SettingDialog.AlwaysTop;
5750         }
5751
5752         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5753         {
5754             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5755             int idx = -1;
5756             DetailsListView lst = null;
5757
5758             if (ImageSelectionPanel.Enabled)
5759                 return;
5760
5761             //現在タブから最終タブまで探索
5762             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5763             {
5764                 //未読Index取得
5765                 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5766                 if (idx > -1)
5767                 {
5768                     ListTab.SelectedIndex = i;
5769                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5770                     //_curTab = ListTab.TabPages[i];
5771                     break;
5772                 }
5773             }
5774
5775             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5776             if (idx == -1 && bgnIdx > 0)
5777             {
5778                 for (int i = 0; i < bgnIdx; i++)
5779                 {
5780                     idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5781                     if (idx > -1)
5782                     {
5783                         ListTab.SelectedIndex = i;
5784                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5785                         //_curTab = ListTab.TabPages[i];
5786                         break;
5787                     }
5788                 }
5789             }
5790
5791             //全部調べたが未読見つからず→先頭タブの最新発言へ
5792             if (idx == -1)
5793             {
5794                 ListTab.SelectedIndex = 0;
5795                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5796                 //_curTab = ListTab.TabPages[0];
5797                 if (_statuses.SortOrder == SortOrder.Ascending)
5798                     idx = lst.VirtualListSize - 1;
5799                 else
5800                     idx = 0;
5801             }
5802
5803             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5804             {
5805                 SelectListItem(lst, idx);
5806                 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5807                 {
5808                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5809                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5810                     {
5811                         MoveTop();
5812                     }
5813                     else
5814                     {
5815                         lst.EnsureVisible(idx);
5816                     }
5817                 }
5818                 else
5819                 {
5820                     lst.EnsureVisible(idx);
5821                 }
5822             }
5823             lst.Focus();
5824         }
5825
5826         private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5827         {
5828             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5829             {
5830                 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5831                 OpenUriAsync(MyCommon.GetStatusUrl(post));
5832             }
5833         }
5834
5835         private void FavorareMenuItem_Click(object sender, EventArgs e)
5836         {
5837             if (_curList.SelectedIndices.Count > 0)
5838             {
5839                 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5840                 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5841             }
5842         }
5843
5844         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5845         {
5846             await this.CheckNewVersion(false);
5847         }
5848
5849         private void RunTweenUp()
5850         {
5851             ProcessStartInfo pinfo = new ProcessStartInfo();
5852             pinfo.UseShellExecute = true;
5853             pinfo.WorkingDirectory = MyCommon.settingPath;
5854             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5855             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5856             try
5857             {
5858                 Process.Start(pinfo);
5859             }
5860             catch (Exception)
5861             {
5862                 MessageBox.Show("Failed to execute TweenUp3.exe.");
5863             }
5864         }
5865
5866         public class VersionInfo
5867         {
5868             public Version Version { get; set; }
5869             public Uri DownloadUri { get; set; }
5870             public string ReleaseNote { get; set; }
5871         }
5872
5873         /// <summary>
5874         /// OpenTween の最新バージョンの情報を取得します
5875         /// </summary>
5876         public async Task<VersionInfo> GetVersionInfoAsync()
5877         {
5878             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5879                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5880
5881             var responseText = await this.http.GetStringAsync(versionInfoUrl)
5882                 .ConfigureAwait(false);
5883
5884             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5885             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5886
5887             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5888             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5889
5890             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5891
5892             return new VersionInfo
5893             {
5894                 Version = Version.Parse(msgHeader[0]),
5895                 DownloadUri = new Uri(msgHeader[1]),
5896                 ReleaseNote = msgBody,
5897             };
5898         }
5899
5900         private async Task CheckNewVersion(bool startup = false)
5901         {
5902             if (ApplicationSettings.VersionInfoUrl == null)
5903                 return; // 更新チェック無効化
5904
5905             try
5906             {
5907                 var versionInfo = await this.GetVersionInfoAsync();
5908
5909                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5910                 {
5911                     // 更新不要
5912                     if (!startup)
5913                     {
5914                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5915                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5916                         msgtext = MyCommon.ReplaceAppName(msgtext);
5917
5918                         MessageBox.Show(msgtext,
5919                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5920                             MessageBoxButtons.OK, MessageBoxIcon.Information);
5921                     }
5922                     return;
5923                 }
5924
5925                 using (var dialog = new UpdateDialog())
5926                 {
5927                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5928                         MyCommon.GetReadableVersion(versionInfo.Version));
5929                     dialog.DetailsText = versionInfo.ReleaseNote;
5930
5931                     if (dialog.ShowDialog(this) == DialogResult.Yes)
5932                     {
5933                         await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5934                     }
5935                 }
5936             }
5937             catch (Exception)
5938             {
5939                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5940                 if (!startup)
5941                 {
5942                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5943                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5944                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5945                 }
5946             }
5947         }
5948
5949         private void Colorize()
5950         {
5951             _colorize = false;
5952             DispSelectedPost();
5953             //件数関連の場合、タイトル即時書き換え
5954             if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
5955                SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5956                SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5957                SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5958             {
5959                 SetMainWindowTitle();
5960             }
5961             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5962             foreach (TabPage tb in ListTab.TabPages)
5963             {
5964                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5965                 {
5966                     if (SettingDialog.TabIconDisp)
5967                     {
5968                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5969                     }
5970                 }
5971             }
5972             if (!SettingDialog.TabIconDisp) ListTab.Refresh();
5973         }
5974
5975         public string createDetailHtml(string orgdata)
5976         {
5977             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5978         }
5979
5980         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5981         {
5982             if (sender.Equals(displayItem))
5983             {
5984                 this.ClearUserPicture();
5985
5986                 var img = displayItem.Image;
5987                 try
5988                 {
5989                     if (img != null)
5990                         img = await img.CloneAsync();
5991
5992                     UserPicture.Image = img;
5993                 }
5994                 catch (Exception)
5995                 {
5996                     UserPicture.ShowErrorImage();
5997                 }
5998             }
5999         }
6000
6001         private void DispSelectedPost()
6002         {
6003             DispSelectedPost(false);
6004         }
6005
6006         private static PostClass displaypost = new PostClass();
6007
6008         /// <summary>
6009         /// サムネイルの表示処理を表すタスク
6010         /// </summary>
6011         private Task thumbnailTask = null;
6012
6013         /// <summary>
6014         /// サムネイル表示に使用する CancellationToken の生成元
6015         /// </summary>
6016         private CancellationTokenSource thumbnailTokenSource = null;
6017
6018         private void DispSelectedPost(bool forceupdate)
6019         {
6020             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6021                 return;
6022
6023             if (!forceupdate && _curPost.Equals(displaypost))
6024                 return;
6025
6026             displaypost = _curPost;
6027             if (displayItem != null)
6028             {
6029                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6030                 displayItem = null;
6031             }
6032             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6033             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6034
6035             string dTxt = createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6036             if (_curPost.IsDm)
6037             {
6038                 SourceLinkLabel.Tag = null;
6039                 SourceLinkLabel.Text = "";
6040             }
6041             else
6042             {
6043                 Match mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6044                 if (mc.Success)
6045                 {
6046                     string src = mc.Groups["sourceurl"].Value;
6047                     SourceLinkLabel.Tag = mc.Groups["sourceurl"].Value;
6048                     mc = Regex.Match(src, "^https?://");
6049                     if (!mc.Success)
6050                     {
6051                         src = src.Insert(0, "https://twitter.com");
6052                     }
6053                     SourceLinkLabel.Tag = src;
6054                 }
6055                 else
6056                 {
6057                     SourceLinkLabel.Tag = null;
6058                 }
6059                 if (string.IsNullOrEmpty(_curPost.Source))
6060                 {
6061                     SourceLinkLabel.Text = "";
6062                     //SourceLinkLabel.Visible = false;
6063                 }
6064                 else
6065                 {
6066                     SourceLinkLabel.Text = _curPost.Source;
6067                     //SourceLinkLabel.Visible = true;
6068                 }
6069             }
6070             SourceLinkLabel.TabStop = false;
6071
6072             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && !_curPost.IsOwl)
6073             {
6074                 NameLabel.Text = "DM TO -> ";
6075             }
6076             else if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
6077             {
6078                 NameLabel.Text = "DM FROM <- ";
6079             }
6080             else
6081             {
6082                 NameLabel.Text = "";
6083             }
6084             NameLabel.Text += _curPost.ScreenName + "/" + _curPost.Nickname;
6085             NameLabel.Tag = _curPost.ScreenName;
6086             if (!string.IsNullOrEmpty(_curPost.RetweetedBy))
6087             {
6088                 NameLabel.Text += " (RT:" + _curPost.RetweetedBy + ")";
6089             }
6090
6091             this.ClearUserPicture();
6092
6093             if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6094             {
6095                 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6096                 try
6097                 {
6098                     UserPicture.Image = image != null ? image.Clone() : null;
6099                 }
6100                 catch (Exception)
6101                 {
6102                     UserPicture.ShowErrorImage();
6103                 }
6104             }
6105
6106             NameLabel.ForeColor = System.Drawing.SystemColors.ControlText;
6107             DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6108             if (_curPost.IsOwl && (SettingDialog.OneWayLove || _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)) NameLabel.ForeColor = _clOWL;
6109             if (_curPost.RetweetedId != null) NameLabel.ForeColor = _clRetweet;
6110             if (_curPost.IsFav) NameLabel.ForeColor = _clFav;
6111
6112             if (DumpPostClassToolStripMenuItem.Checked)
6113             {
6114                 StringBuilder sb = new StringBuilder(512);
6115
6116                 sb.Append("-----Start PostClass Dump<br>");
6117                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6118                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6119                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6120                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6121                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6122                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6123                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6124                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6125                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6126                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6127                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6128                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6129                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6130                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6131                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6132             
6133                 foreach (string nm in _curPost.ReplyToList)
6134                 {
6135                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6136                 }
6137
6138                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6139                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6140                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6141                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6142                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6143                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6144                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6145                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6146                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6147                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6148                 sb.AppendFormat("SearchTabName  : {0}<br>", _curPost.RelTabName);
6149                 sb.Append("-----End PostClass Dump<br>");
6150
6151                 PostBrowser.Visible = false;
6152                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6153                 PostBrowser.Visible = true;
6154             }
6155             else
6156             {
6157                 try
6158                 {
6159                     if (PostBrowser.DocumentText != dTxt)
6160                     {
6161                         PostBrowser.Visible = false;
6162                         PostBrowser.DocumentText = dTxt;
6163
6164                         this.SplitContainer3.Panel2Collapsed = true;
6165
6166                         if (this.IsPreviewEnable)
6167                         {
6168                             if (this.thumbnailTokenSource != null)
6169                             {
6170                                 var oldTokenSource = this.thumbnailTokenSource;
6171                                 oldTokenSource.Cancel();
6172                                 this.thumbnailTask.ContinueWith(_ => oldTokenSource.Dispose());
6173                             }
6174
6175                             this.thumbnailTokenSource = new CancellationTokenSource();
6176
6177                             var token = this.thumbnailTokenSource.Token;
6178                             this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6179                         }
6180                     }
6181                 }
6182                 catch (System.Runtime.InteropServices.COMException)
6183                 {
6184                     //原因不明
6185                 }
6186                 catch (UriFormatException)
6187                 {
6188                     PostBrowser.DocumentText = dTxt;
6189                 }
6190                 finally
6191                 {
6192                     PostBrowser.Visible = true;
6193                 }
6194             }
6195         }
6196
6197         private void MatomeMenuItem_Click(object sender, EventArgs e)
6198         {
6199             OpenApplicationWebsite();
6200         }
6201
6202         private void OpenApplicationWebsite()
6203         {
6204             OpenUriAsync(ApplicationSettings.WebsiteUrl);
6205         }
6206
6207         private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6208         {
6209             OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6210         }
6211
6212         private void ListTab_KeyDown(object sender, KeyEventArgs e)
6213         {
6214             if (ListTab.SelectedTab != null)
6215             {
6216                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6217                 {
6218                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6219                     if (pnl.Controls["comboSearch"].Focused ||
6220                         pnl.Controls["comboLang"].Focused ||
6221                         pnl.Controls["buttonSearch"].Focused) return;
6222                 }
6223                 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6224                 if (State == ModifierState.NotFlags) return;
6225                 if (State != ModifierState.None) _anchorFlag = false;
6226                 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6227                 {
6228                     e.Handled = true;
6229                     e.SuppressKeyPress = true;
6230                 }
6231             }
6232         }
6233
6234         private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6235         {
6236             ModifierState state = ModifierState.None;
6237             if (sControl) state = state | ModifierState.Ctrl;
6238             if (sShift) state = state | ModifierState.Shift;
6239             if (sAlt) state = state | ModifierState.Alt;
6240             return state;
6241         }
6242
6243         [FlagsAttribute]
6244         private enum ModifierState
6245         {
6246             None = 0,
6247             Alt = 1,
6248             Shift = 2,
6249             Ctrl = 4,
6250             //CShift = 11,
6251             //CAlt = 12,
6252             //AShift = 13,
6253             NotFlags = 8,
6254
6255             //ListTab = 101,
6256             //PostBrowser = 102,
6257             //StatusText = 103,
6258         }
6259
6260         private enum FocusedControl : int
6261         {
6262             None,
6263             ListTab,
6264             StatusText,
6265             PostBrowser,
6266         }
6267
6268         private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6269         {
6270             //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6271             if (Focused == FocusedControl.ListTab)
6272             {
6273                 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6274                     Modifier == ModifierState.Ctrl ||
6275                     Modifier == ModifierState.None ||
6276                     Modifier == ModifierState.Shift)
6277                 {
6278                     if (KeyCode == Keys.J)
6279                     {
6280                         SendKeys.Send("{DOWN}");
6281                         return true;
6282                     }
6283                     else if (KeyCode == Keys.K)
6284                     {
6285                         SendKeys.Send("{UP}");
6286                         return true;
6287                     }
6288                 }
6289                 if (Modifier == ModifierState.Shift ||
6290                     Modifier == ModifierState.None)
6291                 {
6292                     if (KeyCode == Keys.F)
6293                     {
6294                         SendKeys.Send("{PGDN}");
6295                         return true;
6296                     }
6297                     else if (KeyCode == Keys.B)
6298                     {
6299                         SendKeys.Send("{PGUP}");
6300                         return true;
6301                     }
6302                 }
6303             }
6304
6305             //修飾キーなし
6306             switch (Modifier)
6307             {
6308                 case ModifierState.None:
6309                     //フォーカス関係なし
6310                     switch (KeyCode)
6311                     {
6312                         case Keys.F1:
6313                             OpenApplicationWebsite();
6314                             return true;
6315                         case Keys.F3:
6316                             MenuItemSearchNext_Click(null, null);
6317                             return true;
6318                         case Keys.F5:
6319                             DoRefresh();
6320                             return true;
6321                         case Keys.F6:
6322                             GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
6323                             return true;
6324                         case Keys.F7:
6325                             GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
6326                             return true;
6327                     }
6328                     if (Focused != FocusedControl.StatusText)
6329                     {
6330                         //フォーカスStatusText以外
6331                         switch (KeyCode)
6332                         {
6333                             case Keys.Space:
6334                             case Keys.ProcessKey:
6335                                 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6336                                 JumpUnreadMenuItem_Click(null, null);
6337                                 return true;
6338                             case Keys.G:
6339                                 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6340                                 ShowRelatedStatusesMenuItem_Click(null, null);
6341                                 return true;
6342                         }
6343                     }
6344                     if (Focused == FocusedControl.ListTab)
6345                     {
6346                         //フォーカスList
6347                         switch (KeyCode)
6348                         {
6349                             case Keys.N:
6350                             case Keys.Right:
6351                                 GoRelPost(true);
6352                                 return true;
6353                             case Keys.P:
6354                             case Keys.Left:
6355                                 GoRelPost(false);
6356                                 return true;
6357                             case Keys.OemPeriod:
6358                                 GoAnchor();
6359                                 return true;
6360                             case Keys.I:
6361                                 if (this.StatusText.Enabled) this.StatusText.Focus();
6362                                 return true;
6363                             case Keys.Enter:
6364                                 MakeReplyOrDirectStatus();
6365                                 return true;
6366                             case Keys.R:
6367                                 DoRefresh();
6368                                 return true;
6369                         }
6370                         //以下、アンカー初期化
6371                         _anchorFlag = false;
6372                         switch (KeyCode)
6373                         {
6374                             case Keys.L:
6375                                 GoPost(true);
6376                                 return true;
6377                             case Keys.H:
6378                                 GoPost(false);
6379                                 return true;
6380                             case Keys.Z:
6381                             case Keys.Oemcomma:
6382                                 MoveTop();
6383                                 return true;
6384                             case Keys.S:
6385                                 GoNextTab(true);
6386                                 return true;
6387                             case Keys.A:
6388                                 GoNextTab(false);
6389                                 return true;
6390                             case Keys.Oem4:
6391                                 // ] in_reply_to参照元へ戻る
6392                                 GoInReplyToPostTree();
6393                                 return true;
6394                             case Keys.Oem6:
6395                                 // [ in_reply_toへジャンプ
6396                                 GoBackInReplyToPostTree();
6397                                 return true;
6398                             case Keys.Escape:
6399                                 if (ListTab.SelectedTab != null)
6400                                 {
6401                                     MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6402                                     if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6403                                     {
6404                                         TabPage relTp = ListTab.SelectedTab;
6405                                         RemoveSpecifiedTab(relTp.Text, false);
6406                                         SaveConfigsTabs();
6407                                         return true;
6408                                     }
6409                                 }
6410                                 break;
6411                         }
6412                     }
6413                     else if (Focused == FocusedControl.PostBrowser)
6414                     {
6415                         //フォーカスPostBrowser
6416                         switch (KeyCode)
6417                         {
6418                             case Keys.Up:
6419                             case Keys.Down:
6420                                 //スクロールを発生させるため、true を返す
6421                                 return true;
6422                         }
6423                     }
6424                     break;
6425                 case ModifierState.Ctrl:
6426                     //フォーカス関係なし
6427                     switch (KeyCode)
6428                     {
6429                         case Keys.R:
6430                             MakeReplyOrDirectStatus(false, true);
6431                             return true;
6432                         case Keys.D:
6433                             doStatusDelete();
6434                             return true;
6435                         case Keys.M:
6436                             MakeReplyOrDirectStatus(false, false);
6437                             return true;
6438                         case Keys.S:
6439                             FavoriteChange(true);
6440                             return true;
6441                         case Keys.I:
6442                             doRepliedStatusOpen();
6443                             return true;
6444                         case Keys.Q:
6445                             doQuote();
6446                             return true;
6447                         case Keys.B:
6448                             ReadedStripMenuItem_Click(null, null);
6449                             return true;
6450                         case Keys.T:
6451                             HashManageMenuItem_Click(null, null);
6452                             return true;
6453                         case Keys.L:
6454                             UrlConvertAutoToolStripMenuItem_Click(null, null);
6455                             return true;
6456                         case Keys.Y:
6457                             if (Focused != FocusedControl.PostBrowser)
6458                             {
6459                                 MultiLineMenuItem_Click(null, null);
6460                                 return true;
6461                             }
6462                             break;
6463                         case Keys.F:
6464                             MenuItemSubSearch_Click(null, null);
6465                             return true;
6466                         case Keys.U:
6467                             ShowUserTimeline();
6468                             return true;
6469                         case Keys.H:
6470                             // Webページを開く動作
6471                             MoveToHomeToolStripMenuItem_Click(null, null);
6472                             return true;
6473                         case Keys.G:
6474                             // Webページを開く動作
6475                             MoveToFavToolStripMenuItem_Click(null, null);
6476                             return true;
6477                         case Keys.O:
6478                             // Webページを開く動作
6479                             StatusOpenMenuItem_Click(null, null);
6480                             return true;
6481                         case Keys.E:
6482                             // Webページを開く動作
6483                             OpenURLMenuItem_Click(null, null);
6484                             return true;
6485                     }
6486                     //フォーカスList
6487                     if (Focused == FocusedControl.ListTab)
6488                     {
6489                         switch (KeyCode)
6490                         {
6491                             case Keys.Home:
6492                             case Keys.End:
6493                                 _colorize = true;
6494                                 return false;            //スルーする
6495                             case Keys.N:
6496                                 GoNextTab(true);
6497                                 return true;
6498                             case Keys.P:
6499                                 GoNextTab(false);
6500                                 return true;
6501                             case Keys.C:
6502                                 CopyStot();
6503                                 return true;
6504                             case Keys.D1:
6505                             case Keys.D2:
6506                             case Keys.D3:
6507                             case Keys.D4:
6508                             case Keys.D5:
6509                             case Keys.D6:
6510                             case Keys.D7:
6511                             case Keys.D8:
6512                                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6513                                 int tabNo = KeyCode - Keys.D1;
6514                                 if (ListTab.TabPages.Count < tabNo)
6515                                     return false;
6516                                 ListTab.SelectedIndex = tabNo;
6517                                 ListTabSelect(ListTab.TabPages[tabNo]);
6518                                 return true;
6519                             case Keys.D9:
6520                                 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6521                                 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6522                                 return true;
6523                         }
6524                     }
6525                     else if (Focused == FocusedControl.StatusText)
6526                     {
6527                         //フォーカスStatusText
6528                         switch (KeyCode)
6529                         {
6530                             case Keys.A:
6531                                 StatusText.SelectAll();
6532                                 return true;
6533                             case Keys.Up:
6534                             case Keys.Down:
6535                                 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6536                                 {
6537                                     _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6538                                 }
6539                                 if (KeyCode == Keys.Up)
6540                                 {
6541                                     _hisIdx -= 1;
6542                                     if (_hisIdx < 0) _hisIdx = 0;
6543                                 }
6544                                 else
6545                                 {
6546                                     _hisIdx += 1;
6547                                     if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6548                                 }
6549                                 StatusText.Text = _history[_hisIdx].status;
6550                                 _reply_to_id = _history[_hisIdx].inReplyToId;
6551                                 _reply_to_name = _history[_hisIdx].inReplyToName;
6552                                 StatusText.SelectionStart = StatusText.Text.Length;
6553                                 return true;
6554                             case Keys.PageUp:
6555                             case Keys.P:
6556                                 if (ListTab.SelectedIndex == 0)
6557                                 {
6558                                     ListTab.SelectedIndex = ListTab.TabCount - 1;
6559                                 }
6560                                 else
6561                                 {
6562                                     ListTab.SelectedIndex -= 1;
6563                                 }
6564                                 StatusText.Focus();
6565                                 return true;
6566                             case Keys.PageDown:
6567                             case Keys.N:
6568                                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6569                                 {
6570                                     ListTab.SelectedIndex = 0;
6571                                 }
6572                                 else
6573                                 {
6574                                     ListTab.SelectedIndex += 1;
6575                                 }
6576                                 StatusText.Focus();
6577                                 return true;
6578                         }
6579                     }
6580                     else
6581                     {
6582                         //フォーカスPostBrowserもしくは関係なし
6583                         switch (KeyCode)
6584                         {
6585                             case Keys.A:
6586                                 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6587                                 return true;
6588                             case Keys.C:
6589                             case Keys.Insert:
6590                                 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6591                                 if (!string.IsNullOrEmpty(_selText))
6592                                 {
6593                                     try
6594                                     {
6595                                         Clipboard.SetDataObject(_selText, false, 5, 100);
6596                                     }
6597                                     catch (Exception ex)
6598                                     {
6599                                         MessageBox.Show(ex.Message);
6600                                     }
6601                                 }
6602                                 return true;
6603                             case Keys.Y:
6604                                 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6605                                 MultiLineMenuItem_Click(null, null);
6606                                 return true;
6607                         }
6608                     }
6609                     break;
6610                 case ModifierState.Shift:
6611                     //フォーカス関係なし
6612                     switch (KeyCode)
6613                     {
6614                         case Keys.F3:
6615                             MenuItemSearchPrev_Click(null, null);
6616                             return true;
6617                         case Keys.F5:
6618                             DoRefreshMore();
6619                             return true;
6620                         case Keys.F6:
6621                             GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
6622                             return true;
6623                         case Keys.F7:
6624                             GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
6625                             return true;
6626                     }
6627                     //フォーカスStatusText以外
6628                     if (Focused != FocusedControl.StatusText)
6629                     {
6630                         if (KeyCode == Keys.R)
6631                         {
6632                             DoRefreshMore();
6633                             return true;
6634                         }
6635                     }
6636                     //フォーカスリスト
6637                     if (Focused == FocusedControl.ListTab)
6638                     {
6639                         switch (KeyCode)
6640                         {
6641                             case Keys.H:
6642                                 GoTopEnd(true);
6643                                 return true;
6644                             case Keys.L:
6645                                 GoTopEnd(false);
6646                                 return true;
6647                             case Keys.M:
6648                                 GoMiddle();
6649                                 return true;
6650                             case Keys.G:
6651                                 GoLast();
6652                                 return true;
6653                             case Keys.Z:
6654                                 MoveMiddle();
6655                                 return true;
6656                             case Keys.Oem4:
6657                                 GoBackInReplyToPostTree(true, false);
6658                                 return true;
6659                             case Keys.Oem6:
6660                                 GoBackInReplyToPostTree(true, true);
6661                                 return true;
6662                             case Keys.N:
6663                             case Keys.Right:
6664                                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6665                                 GoFav(true);
6666                                 return true;
6667                             case Keys.P:
6668                             case Keys.Left:
6669                                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6670                                 GoFav(false);
6671                                 return true;
6672                             case Keys.Space:
6673                                 this.GoBackSelectPostChain();
6674                                 return true;
6675                         }
6676                     }
6677                     break;
6678                 case ModifierState.Alt:
6679                     switch (KeyCode)
6680                     {
6681                         case Keys.R:
6682                             doReTweetOfficial(true);
6683                             return true;
6684                         case Keys.P:
6685                             if (_curPost != null)
6686                             {
6687                                 doShowUserStatus(_curPost.ScreenName, false);
6688                                 return true;
6689                             }
6690                             break;
6691                         case Keys.Up:
6692                             ScrollDownPostBrowser(false);
6693                             return true;
6694                         case Keys.Down:
6695                             ScrollDownPostBrowser(true);
6696                             return true;
6697                         case Keys.PageUp:
6698                             PageDownPostBrowser(false);
6699                             return true;
6700                         case Keys.PageDown:
6701                             PageDownPostBrowser(true);
6702                             return true;
6703                     }
6704                     if (Focused == FocusedControl.ListTab)
6705                     {
6706                         // 別タブの同じ書き込みへ(ALT+←/→)
6707                         if (KeyCode == Keys.Right)
6708                         {
6709                             GoSamePostToAnotherTab(false);
6710                             return true;
6711                         }
6712                         else if (KeyCode == Keys.Left)
6713                         {
6714                             GoSamePostToAnotherTab(true);
6715                             return true;
6716                         }
6717                     }
6718                     break;
6719                 case ModifierState.Ctrl | ModifierState.Shift:
6720                     switch (KeyCode)
6721                     {
6722                         case Keys.R:
6723                             MakeReplyOrDirectStatus(false, true, true);
6724                             return true;
6725                         case Keys.C:
6726                             CopyIdUri();
6727                             return true;
6728                         case Keys.F:
6729                             if (ListTab.SelectedTab != null)
6730                             {
6731                                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6732                                 {
6733                                     ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6734                                     return true;
6735                                 }
6736                             }
6737                             break;
6738                         case Keys.S:
6739                             FavoriteChange(false);
6740                             return true;
6741                         case Keys.B:
6742                             UnreadStripMenuItem_Click(null, null);
6743                             return true;
6744                         case Keys.T:
6745                             HashToggleMenuItem_Click(null, null);
6746                             return true;
6747                         case Keys.P:
6748                             ImageSelectMenuItem_Click(null, null);
6749                             return true;
6750                         case Keys.H:
6751                             doMoveToRTHome();
6752                             return true;
6753                         case Keys.O:
6754                             FavorareMenuItem_Click(null, null);
6755                             return true;
6756                     }
6757                     if (Focused == FocusedControl.StatusText)
6758                     {
6759                         int idx = 0;
6760                         switch (KeyCode)
6761                         {
6762                             case Keys.Up:
6763                                 if (_curList != null && _curList.VirtualListSize != 0 &&
6764                                             _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6765                                 {
6766                                     idx = _curList.SelectedIndices[0] - 1;
6767                                     SelectListItem(_curList, idx);
6768                                     _curList.EnsureVisible(idx);
6769                                     return true;
6770                                 }
6771                                 break;
6772                             case Keys.Down:
6773                                 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6774                                             && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6775                                 {
6776                                     idx = _curList.SelectedIndices[0] + 1;
6777                                     SelectListItem(_curList, idx);
6778                                     _curList.EnsureVisible(idx);
6779                                     return true;
6780                                 }
6781                                 break;
6782                             case Keys.Space:
6783                                 if (StatusText.SelectionStart > 0)
6784                                 {
6785                                     int endidx = StatusText.SelectionStart - 1;
6786                                     string startstr = "";
6787                                     bool pressed = false;
6788                                     for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6789                                     {
6790                                         char c = StatusText.Text[i];
6791                                         if (Char.IsLetterOrDigit(c) || c == '_')
6792                                         {
6793                                             continue;
6794                                         }
6795                                         if (c == '@')
6796                                         {
6797                                             pressed = true;
6798                                             startstr = StatusText.Text.Substring(i + 1, endidx - i);
6799                                             int cnt = AtIdSupl.ItemCount;
6800                                             ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6801                                             if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6802                                         }
6803                                         else if (c == '#')
6804                                         {
6805                                             pressed = true;
6806                                             startstr = StatusText.Text.Substring(i + 1, endidx - i);
6807                                             ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6808                                         }
6809                                         else
6810                                         {
6811                                             break;
6812                                         }
6813                                     }
6814                                     return pressed;
6815                                 }
6816                                 break;
6817                         }
6818                     }
6819                     else if (Focused == FocusedControl.ListTab)
6820                     {
6821                         DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6822                         ColumnHeader col;
6823                         switch (KeyCode)
6824                         {
6825                             case Keys.D1:
6826                             case Keys.D2:
6827                             case Keys.D3:
6828                             case Keys.D4:
6829                             case Keys.D5:
6830                             case Keys.D6:
6831                             case Keys.D7:
6832                             case Keys.D8:
6833                                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6834                                 int colNo = KeyCode - Keys.D1;
6835                                 if (lst.Columns.Count < colNo) return false;
6836                                 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6837                                 if (col == null) return false;
6838                                 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6839                                 return true;
6840                             case Keys.D9:
6841                                 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6842                                 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6843                                 return true;
6844                         }
6845                     }
6846                     break;
6847                 case ModifierState.Ctrl | ModifierState.Alt:
6848                     if (KeyCode == Keys.S)
6849                     {
6850                         FavoritesRetweetOriginal();
6851                         return true;
6852                     }
6853                     else if (KeyCode == Keys.R)
6854                     {
6855                         FavoritesRetweetUnofficial();
6856                         return true;
6857                     }
6858                     else if (KeyCode == Keys.H)
6859                     {
6860                         OpenUserAppointUrl();
6861                         return true;
6862                     }
6863                     break;
6864                 case ModifierState.Alt | ModifierState.Shift:
6865                     if (Focused == FocusedControl.PostBrowser)
6866                     {
6867                         if (KeyCode == Keys.R)
6868                             doReTweetUnofficial();
6869                         else if (KeyCode == Keys.C)
6870                             CopyUserId();
6871                         return true;
6872                     }
6873                     switch (KeyCode)
6874                     {
6875                         case Keys.T:
6876                             if (!this.ExistCurrentPost) return false;
6877                             doTranslation(_curPost.TextFromApi);
6878                             return true;
6879                         case Keys.R:
6880                             doReTweetUnofficial();
6881                             return true;
6882                         case Keys.C:
6883                             CopyUserId();
6884                             return true;
6885                         case Keys.Up:
6886                             this.tweetThumbnail1.ScrollUp();
6887                             return true;
6888                         case Keys.Down:
6889                             this.tweetThumbnail1.ScrollDown();
6890                             return true;
6891                     }
6892                     if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6893                     {
6894                         if (!this.SplitContainer3.Panel2Collapsed)
6895                         {
6896                             OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6897                         }
6898                         return true;
6899                     }
6900                     break;
6901             }
6902
6903             return false;
6904         }
6905
6906         private void ScrollDownPostBrowser(bool forward)
6907         {
6908             var doc = PostBrowser.Document;
6909             if (doc == null) return;
6910
6911             var tags = doc.GetElementsByTagName("html");
6912             if (tags.Count > 0)
6913             {
6914                 if (forward)
6915                     tags[0].ScrollTop += SettingDialog.FontDetail.Height;
6916                 else
6917                     tags[0].ScrollTop -= SettingDialog.FontDetail.Height;
6918             }
6919         }
6920
6921         private void PageDownPostBrowser(bool forward)
6922         {
6923             var doc = PostBrowser.Document;
6924             if (doc == null) return;
6925
6926             var tags = doc.GetElementsByTagName("html");
6927             if (tags.Count > 0)
6928             {
6929                 if (forward)
6930                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6931                 else
6932                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6933             }
6934         }
6935
6936         private void GoNextTab(bool forward)
6937         {
6938             int idx = ListTab.SelectedIndex;
6939             if (forward)
6940             {
6941                 idx += 1;
6942                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6943             }
6944             else
6945             {
6946                 idx -= 1;
6947                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6948             }
6949             ListTab.SelectedIndex = idx;
6950             ListTabSelect(ListTab.TabPages[idx]);
6951         }
6952
6953         private void CopyStot()
6954         {
6955             string clstr = "";
6956             StringBuilder sb = new StringBuilder();
6957             bool IsProtected = false;
6958             bool isDm = false;
6959             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6960             foreach (int idx in _curList.SelectedIndices)
6961             {
6962                 PostClass post = _statuses[_curTab.Text, idx];
6963                 if (post.IsProtect)
6964                 {
6965                     IsProtected = true;
6966                     continue;
6967                 }
6968                 if (post.IsDeleted) continue;
6969                 if (!isDm)
6970                 {
6971                     if (post.RetweetedId != null)
6972                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6973                     else
6974                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6975                 }
6976                 else
6977                 {
6978                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6979                 }
6980             }
6981             if (IsProtected)
6982             {
6983                 MessageBox.Show(Properties.Resources.CopyStotText1);
6984             }
6985             if (sb.Length > 0)
6986             {
6987                 clstr = sb.ToString();
6988                 try
6989                 {
6990                     Clipboard.SetDataObject(clstr, false, 5, 100);
6991                 }
6992                 catch (Exception ex)
6993                 {
6994                     MessageBox.Show(ex.Message);
6995                 }
6996             }
6997         }
6998
6999         private void CopyIdUri()
7000         {
7001             string clstr = "";
7002             StringBuilder sb = new StringBuilder();
7003             if (this._curTab == null) return;
7004             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7005             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7006             foreach (int idx in _curList.SelectedIndices)
7007             {
7008                 var post = _statuses[_curTab.Text, idx];
7009                 sb.Append(MyCommon.GetStatusUrl(post));
7010                 sb.Append(Environment.NewLine);
7011             }
7012             if (sb.Length > 0)
7013             {
7014                 clstr = sb.ToString();
7015                 try
7016                 {
7017                     Clipboard.SetDataObject(clstr, false, 5, 100);
7018                 }
7019                 catch (Exception ex)
7020                 {
7021                     MessageBox.Show(ex.Message);
7022                 }
7023             }
7024         }
7025
7026         private void GoFav(bool forward)
7027         {
7028             if (_curList.VirtualListSize == 0) return;
7029             int fIdx = 0;
7030             int toIdx = 0;
7031             int stp = 1;
7032
7033             if (forward)
7034             {
7035                 if (_curList.SelectedIndices.Count == 0)
7036                 {
7037                     fIdx = 0;
7038                 }
7039                 else
7040                 {
7041                     fIdx = _curList.SelectedIndices[0] + 1;
7042                     if (fIdx > _curList.VirtualListSize - 1) return;
7043                 }
7044                 toIdx = _curList.VirtualListSize;
7045                 stp = 1;
7046             }
7047             else
7048             {
7049                 if (_curList.SelectedIndices.Count == 0)
7050                 {
7051                     fIdx = _curList.VirtualListSize - 1;
7052                 }
7053                 else
7054                 {
7055                     fIdx = _curList.SelectedIndices[0] - 1;
7056                     if (fIdx < 0) return;
7057                 }
7058                 toIdx = -1;
7059                 stp = -1;
7060             }
7061
7062             for (int idx = fIdx; idx != toIdx; idx += stp)
7063             {
7064                 if (_statuses[_curTab.Text, idx].IsFav)
7065                 {
7066                     SelectListItem(_curList, idx);
7067                     _curList.EnsureVisible(idx);
7068                     break;
7069                 }
7070             }
7071         }
7072
7073         private void GoSamePostToAnotherTab(bool left)
7074         {
7075             if (_curList.VirtualListSize == 0) return;
7076             int fIdx = 0;
7077             int toIdx = 0;
7078             int stp = 1;
7079             long targetId = 0;
7080
7081             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7082             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7083
7084             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7085
7086             if (left)
7087             {
7088                 // 左のタブへ
7089                 if (ListTab.SelectedIndex == 0)
7090                 {
7091                     return;
7092                 }
7093                 else
7094                 {
7095                     fIdx = ListTab.SelectedIndex - 1;
7096                 }
7097                 toIdx = -1;
7098                 stp = -1;
7099             }
7100             else
7101             {
7102                 // 右のタブへ
7103                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7104                 {
7105                     return;
7106                 }
7107                 else
7108                 {
7109                     fIdx = ListTab.SelectedIndex + 1;
7110                 }
7111                 toIdx = ListTab.TabCount;
7112                 stp = 1;
7113             }
7114
7115             bool found = false;
7116             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7117             {
7118                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7119                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7120                 {
7121                     if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7122                     {
7123                         ListTab.SelectedIndex = tabidx;
7124                         ListTabSelect(ListTab.TabPages[tabidx]);
7125                         SelectListItem(_curList, idx);
7126                         _curList.EnsureVisible(idx);
7127                         found = true;
7128                         break;
7129                     }
7130                 }
7131                 if (found) break;
7132             }
7133         }
7134
7135         private void GoPost(bool forward)
7136         {
7137             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7138             int fIdx = 0;
7139             int toIdx = 0;
7140             int stp = 1;
7141
7142             if (forward)
7143             {
7144                 fIdx = _curList.SelectedIndices[0] + 1;
7145                 if (fIdx > _curList.VirtualListSize - 1) return;
7146                 toIdx = _curList.VirtualListSize;
7147                 stp = 1;
7148             }
7149             else
7150             {
7151                 fIdx = _curList.SelectedIndices[0] - 1;
7152                 if (fIdx < 0) return;
7153                 toIdx = -1;
7154                 stp = -1;
7155             }
7156
7157             string name = "";
7158             if (_curPost.RetweetedId == null)
7159             {
7160                 name = _curPost.ScreenName;
7161             }
7162             else
7163             {
7164                 name = _curPost.RetweetedBy;
7165             }
7166             for (int idx = fIdx; idx != toIdx; idx += stp)
7167             {
7168                 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7169                 {
7170                     if (_statuses[_curTab.Text, idx].ScreenName == name)
7171                     {
7172                         SelectListItem(_curList, idx);
7173                         _curList.EnsureVisible(idx);
7174                         break;
7175                     }
7176                 }
7177                 else
7178                 {
7179                     if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7180                     {
7181                         SelectListItem(_curList, idx);
7182                         _curList.EnsureVisible(idx);
7183                         break;
7184                     }
7185                 }
7186             }
7187         }
7188
7189         private void GoRelPost(bool forward)
7190         {
7191             if (_curList.SelectedIndices.Count == 0) return;
7192
7193             int fIdx = 0;
7194             int toIdx = 0;
7195             int stp = 1;
7196             if (forward)
7197             {
7198                 fIdx = _curList.SelectedIndices[0] + 1;
7199                 if (fIdx > _curList.VirtualListSize - 1) return;
7200                 toIdx = _curList.VirtualListSize;
7201                 stp = 1;
7202             }
7203             else
7204             {
7205                 fIdx = _curList.SelectedIndices[0] - 1;
7206                 if (fIdx < 0) return;
7207                 toIdx = -1;
7208                 stp = -1;
7209             }
7210
7211             if (!_anchorFlag)
7212             {
7213                 if (_curPost == null) return;
7214                 _anchorPost = _curPost;
7215                 _anchorFlag = true;
7216             }
7217             else
7218             {
7219                 if (_anchorPost == null) return;
7220             }
7221
7222             for (int idx = fIdx; idx != toIdx; idx += stp)
7223             {
7224                 PostClass post = _statuses[_curTab.Text, idx];
7225                 if (post.ScreenName == _anchorPost.ScreenName ||
7226                     post.RetweetedBy == _anchorPost.ScreenName ||
7227                     post.ScreenName == _anchorPost.RetweetedBy ||
7228                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7229                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7230                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7231                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7232                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7233                 {
7234                     SelectListItem(_curList, idx);
7235                     _curList.EnsureVisible(idx);
7236                     break;
7237                 }
7238             }
7239         }
7240
7241         private void GoAnchor()
7242         {
7243             if (_anchorPost == null) return;
7244             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7245             if (idx == -1) return;
7246
7247             SelectListItem(_curList, idx);
7248             _curList.EnsureVisible(idx);
7249         }
7250
7251         private void GoTopEnd(bool GoTop)
7252         {
7253             ListViewItem _item;
7254             int idx;
7255
7256             if (GoTop)
7257             {
7258                 _item = _curList.GetItemAt(0, 25);
7259                 if (_item == null)
7260                     idx = 0;
7261                 else
7262                     idx = _item.Index;
7263             }
7264             else
7265             {
7266                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7267                 if (_item == null)
7268                     idx = _curList.VirtualListSize - 1;
7269                 else
7270                     idx = _item.Index;
7271             }
7272             SelectListItem(_curList, idx);
7273         }
7274
7275         private void GoMiddle()
7276         {
7277             ListViewItem _item;
7278             int idx1;
7279             int idx2;
7280             int idx3;
7281
7282             _item = _curList.GetItemAt(0, 0);
7283             if (_item == null)
7284             {
7285                 idx1 = 0;
7286             }
7287             else
7288             {
7289                 idx1 = _item.Index;
7290             }
7291
7292             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7293             if (_item == null)
7294             {
7295                 idx2 = _curList.VirtualListSize - 1;
7296             }
7297             else
7298             {
7299                 idx2 = _item.Index;
7300             }
7301             idx3 = (idx1 + idx2) / 2;
7302
7303             SelectListItem(_curList, idx3);
7304         }
7305
7306         private void GoLast()
7307         {
7308             if (_curList.VirtualListSize == 0) return;
7309
7310             if (_statuses.SortOrder == SortOrder.Ascending)
7311             {
7312                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7313                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7314             }
7315             else
7316             {
7317                 SelectListItem(_curList, 0);
7318                 _curList.EnsureVisible(0);
7319             }
7320         }
7321
7322         private void MoveTop()
7323         {
7324             if (_curList.SelectedIndices.Count == 0) return;
7325             int idx = _curList.SelectedIndices[0];
7326             if (_statuses.SortOrder == SortOrder.Ascending)
7327             {
7328                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7329             }
7330             else
7331             {
7332                 _curList.EnsureVisible(0);
7333             }
7334             _curList.EnsureVisible(idx);
7335         }
7336
7337         private void GoInReplyToPostTree()
7338         {
7339             if (_curPost == null) return;
7340
7341             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7342
7343             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7344             {
7345                 PostClass post = null;
7346                 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7347                 if (string.IsNullOrEmpty(r) && post != null)
7348                 {
7349                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7350                     _curPost.InReplyToUser = post.InReplyToUser;
7351                     _curPost.IsReply = post.IsReply;
7352                     this.PurgeListViewItemCache();
7353                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7354                 }
7355                 else
7356                 {
7357                     this.StatusLabel.Text = r;
7358                 }
7359             }
7360
7361             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7362
7363             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7364             {
7365                 replyChains = new Stack<ReplyChain>();
7366             }
7367             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7368
7369             int inReplyToIndex;
7370             string inReplyToTabName;
7371             long inReplyToId = _curPost.InReplyToStatusId.Value;
7372             string inReplyToUser = _curPost.InReplyToUser;
7373             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7374
7375             var inReplyToPosts = from tab in _statuses.Tabs.Values
7376                                  orderby tab != curTabClass
7377                                  from post in tab.Posts.Values
7378                                  where post.StatusId == inReplyToId
7379                                  let index = tab.IndexOf(post.StatusId)
7380                                  where index != -1
7381                                  select new {Tab = tab, Index = index};
7382
7383             try
7384             {
7385                 var inReplyPost = inReplyToPosts.First();
7386                 inReplyToTabName = inReplyPost.Tab.TabName;
7387                 inReplyToIndex = inReplyPost.Index;
7388             }
7389             catch (InvalidOperationException)
7390             {
7391                 PostClass post = null;
7392                 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7393                 if (string.IsNullOrEmpty(r) && post != null)
7394                 {
7395                     post.IsRead = true;
7396                     _statuses.AddPost(post);
7397                     _statuses.DistributePosts();
7398                     //_statuses.SubmitUpdate(null, null, null, false);
7399                     this.RefreshTimeline(false);
7400                     try
7401                     {
7402                         var inReplyPost = inReplyToPosts.First();
7403                         inReplyToTabName = inReplyPost.Tab.TabName;
7404                         inReplyToIndex = inReplyPost.Index;
7405                     }
7406                     catch (InvalidOperationException)
7407                     {
7408                         OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7409                         return;
7410                     }
7411                 }
7412                 else
7413                 {
7414                     this.StatusLabel.Text = r;
7415                     OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7416                     return;
7417                 }
7418             }
7419
7420             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7421             DetailsListView listView = (DetailsListView)tabPage.Tag;
7422
7423             if (_curTab != tabPage)
7424             {
7425                 this.ListTab.SelectTab(tabPage);
7426             }
7427
7428             this.SelectListItem(listView, inReplyToIndex);
7429             listView.EnsureVisible(inReplyToIndex);
7430         }
7431
7432         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7433         {
7434             if (_curPost == null) return;
7435
7436             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7437             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7438
7439             if (parallel)
7440             {
7441                 if (_curPost.InReplyToStatusId != null)
7442                 {
7443                     var posts = from t in _statuses.Tabs
7444                                 from p in t.Value.Posts
7445                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7446                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7447                                 where indexOf > -1
7448                                 orderby isForward ? indexOf : indexOf * -1
7449                                 orderby t.Value != curTabClass
7450                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7451                     try
7452                     {
7453                         var postList = posts.ToList();
7454                         for (int i = postList.Count - 1; i >= 0; i--)
7455                         {
7456                             int index = i;
7457                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7458                             {
7459                                 postList.RemoveAt(index);
7460                             }
7461                         }
7462                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7463                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7464                         if (post == null) post = postList.First();
7465                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7466                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7467                         SelectListItem(listView, post.Index);
7468                         listView.EnsureVisible(post.Index);
7469                     }
7470                     catch (InvalidOperationException)
7471                     {
7472                         return;
7473                     }
7474                 }
7475             }
7476             else
7477             {
7478                 if (replyChains == null || replyChains.Count < 1)
7479                 {
7480                     var posts = from t in _statuses.Tabs
7481                                 from p in t.Value.Posts
7482                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7483                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7484                                 where indexOf > -1
7485                                 orderby indexOf
7486                                 orderby t.Value != curTabClass
7487                                 select new {Tab = t.Value, Index = indexOf};
7488                     try
7489                     {
7490                         var post = posts.First();
7491                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7492                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7493                         SelectListItem(listView, post.Index);
7494                         listView.EnsureVisible(post.Index);
7495                     }
7496                     catch (InvalidOperationException)
7497                     {
7498                         return;
7499                     }
7500                 }
7501                 else
7502                 {
7503                     ReplyChain chainHead = replyChains.Pop();
7504                     if (chainHead.InReplyToId == _curPost.StatusId)
7505                     {
7506                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7507                         if (idx == -1)
7508                         {
7509                             replyChains = null;
7510                         }
7511                         else
7512                         {
7513                             try
7514                             {
7515                                 ListTab.SelectTab(chainHead.OriginalTab);
7516                             }
7517                             catch (Exception)
7518                             {
7519                                 replyChains = null;
7520                             }
7521                             SelectListItem(_curList, idx);
7522                             _curList.EnsureVisible(idx);
7523                         }
7524                     }
7525                     else
7526                     {
7527                         replyChains = null;
7528                         this.GoBackInReplyToPostTree(parallel);
7529                     }
7530                 }
7531             }
7532         }
7533
7534         private void GoBackSelectPostChain()
7535         {
7536             if (this.selectPostChains.Count > 1)
7537             {
7538                 var idx = -1;
7539                 TabPage tp = null;
7540
7541                 do
7542                 {
7543                     try
7544                     {
7545                         this.selectPostChains.Pop();
7546                         var tabPostPair = this.selectPostChains.Peek();
7547
7548                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7549
7550                         if (tabPostPair.Item2 != null)
7551                         {
7552                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7553                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7554                         }
7555
7556                         tp = tabPostPair.Item1;
7557
7558                         this.selectPostChains.Pop();
7559                     }
7560                     catch (InvalidOperationException)
7561                     {
7562                     }
7563
7564                     break;
7565                 }
7566                 while (this.selectPostChains.Count > 1);
7567
7568                 if (tp == null)
7569                 {
7570                     //状態がおかしいので処理を中断
7571                     //履歴が残り1つであればクリアしておく
7572                     if (this.selectPostChains.Count == 1)
7573                         this.selectPostChains.Clear();
7574                     return;
7575                 }
7576
7577                 DetailsListView lst = (DetailsListView)tp.Tag;
7578                 this.ListTab.SelectedTab = tp;
7579                 if (idx > -1)
7580                 {
7581                     SelectListItem(lst, idx);
7582                     lst.EnsureVisible(idx);
7583                 }
7584                 lst.Focus();
7585             }
7586         }
7587
7588         private void PushSelectPostChain()
7589         {
7590             int count = this.selectPostChains.Count;
7591             if (count > 0)
7592             {
7593                 var p = this.selectPostChains.Peek();
7594                 if (p.Item1 == this._curTab)
7595                 {
7596                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7597                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7598                 }
7599             }
7600             if (count >= 2500) TrimPostChain();
7601             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7602         }
7603
7604         private void TrimPostChain()
7605         {
7606             if (this.selectPostChains.Count <= 2000) return;
7607             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7608             for (int i = 0; i < 2000; i++)
7609             {
7610                 p.Push(this.selectPostChains.Pop());
7611             }
7612             this.selectPostChains.Clear();
7613             for (int i = 0; i < 2000; i++)
7614             {
7615                 this.selectPostChains.Push(p.Pop());
7616             }
7617         }
7618
7619         private bool GoStatus(long statusId)
7620         {
7621             if (statusId == 0) return false;
7622             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7623             {
7624                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7625                 {
7626                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7627                     ListTab.SelectedIndex = tabidx;
7628                     ListTabSelect(ListTab.TabPages[tabidx]);
7629                     SelectListItem(_curList, idx);
7630                     _curList.EnsureVisible(idx);
7631                     return true;
7632                 }
7633             }
7634             return false;
7635         }
7636
7637         private bool GoDirectMessage(long statusId)
7638         {
7639             if (statusId == 0) return false;
7640             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7641             {
7642                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7643                 {
7644                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7645                     ListTab.SelectedIndex = tabidx;
7646                     ListTabSelect(ListTab.TabPages[tabidx]);
7647                     SelectListItem(_curList, idx);
7648                     _curList.EnsureVisible(idx);
7649                     return true;
7650                 }
7651             }
7652             return false;
7653         }
7654
7655         private void MyList_MouseClick(object sender, MouseEventArgs e)
7656         {
7657             _anchorFlag = false;
7658         }
7659
7660         private void StatusText_Enter(object sender, EventArgs e)
7661         {
7662             // フォーカスの戻り先を StatusText に設定
7663             this.Tag = StatusText;
7664             StatusText.BackColor = _clInputBackcolor;
7665         }
7666
7667         public Color InputBackColor
7668         {
7669             get { return _clInputBackcolor; }
7670             set { _clInputBackcolor = value; }
7671         }
7672
7673         private void StatusText_Leave(object sender, EventArgs e)
7674         {
7675             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7676             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7677             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7678         }
7679
7680         private void StatusText_KeyDown(object sender, KeyEventArgs e)
7681         {
7682             ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7683             if (State == ModifierState.NotFlags) return;
7684             if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7685             {
7686                 e.Handled = true;
7687                 e.SuppressKeyPress = true;
7688             }
7689
7690             this.StatusText_TextChanged(null, null);
7691         }
7692
7693         private void SaveConfigsAll(bool ifModified)
7694         {
7695             if (!ifModified)
7696             {
7697                 SaveConfigsCommon();
7698                 SaveConfigsLocal();
7699                 SaveConfigsTabs();
7700                 SaveConfigsAtId();
7701             }
7702             else
7703             {
7704                 if (_modifySettingCommon) SaveConfigsCommon();
7705                 if (_modifySettingLocal) SaveConfigsLocal();
7706                 if (_modifySettingAtId) SaveConfigsAtId();
7707             }
7708         }
7709
7710         private void SaveConfigsAtId()
7711         {
7712             if (_ignoreConfigSave || !SettingDialog.UseAtIdSupplement && AtIdSupl == null) return;
7713
7714             _modifySettingAtId = false;
7715             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7716             cfgAtId.Save();
7717         }
7718
7719         private void SaveConfigsCommon()
7720         {
7721             if (_ignoreConfigSave) return;
7722
7723             _modifySettingCommon = false;
7724             lock (_syncObject)
7725             {
7726                 _cfgCommon.UserName = tw.Username;
7727                 _cfgCommon.UserId = tw.UserId;
7728                 _cfgCommon.Password = tw.Password;
7729                 _cfgCommon.Token = tw.AccessToken;
7730                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7731                 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7732                 _cfgCommon.UserstreamStartup = SettingDialog.UserstreamStartup;
7733                 _cfgCommon.UserstreamPeriod = SettingDialog.UserstreamPeriodInt;
7734                 _cfgCommon.TimelinePeriod = SettingDialog.TimelinePeriodInt;
7735                 _cfgCommon.ReplyPeriod = SettingDialog.ReplyPeriodInt;
7736                 _cfgCommon.DMPeriod = SettingDialog.DMPeriodInt;
7737                 _cfgCommon.PubSearchPeriod = SettingDialog.PubSearchPeriodInt;
7738                 _cfgCommon.ListsPeriod = SettingDialog.ListsPeriodInt;
7739                 _cfgCommon.UserTimelinePeriod = SettingDialog.UserTimelinePeriodInt;
7740                 _cfgCommon.Read = SettingDialog.Readed;
7741                 _cfgCommon.IconSize = SettingDialog.IconSz;
7742                 _cfgCommon.UnreadManage = SettingDialog.UnreadManage;
7743                 _cfgCommon.PlaySound = SettingDialog.PlaySound;
7744                 _cfgCommon.OneWayLove = SettingDialog.OneWayLove;
7745
7746                 _cfgCommon.NameBalloon = SettingDialog.NameBalloon;
7747                 _cfgCommon.PostCtrlEnter = SettingDialog.PostCtrlEnter;
7748                 _cfgCommon.PostShiftEnter = SettingDialog.PostShiftEnter;
7749                 _cfgCommon.CountApi = SettingDialog.CountApi;
7750                 _cfgCommon.CountApiReply = SettingDialog.CountApiReply;
7751                 _cfgCommon.PostAndGet = SettingDialog.PostAndGet;
7752                 _cfgCommon.DispUsername = SettingDialog.DispUsername;
7753                 _cfgCommon.MinimizeToTray = SettingDialog.MinimizeToTray;
7754                 _cfgCommon.CloseToExit = SettingDialog.CloseToExit;
7755                 _cfgCommon.DispLatestPost = SettingDialog.DispLatestPost;
7756                 _cfgCommon.SortOrderLock = SettingDialog.SortOrderLock;
7757                 _cfgCommon.ViewTabBottom = SettingDialog.ViewTabBottom;
7758                 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7759                 _cfgCommon.StartupVersion = SettingDialog.StartupVersion;
7760                 _cfgCommon.StartupFollowers = SettingDialog.StartupFollowers;
7761                 _cfgCommon.RestrictFavCheck = SettingDialog.RestrictFavCheck;
7762                 _cfgCommon.AlwaysTop = SettingDialog.AlwaysTop;
7763                 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7764                 _cfgCommon.UseUnreadStyle = SettingDialog.UseUnreadStyle;
7765                 _cfgCommon.DateTimeFormat = SettingDialog.DateTimeFormat;
7766                 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7767                 _cfgCommon.RetweetNoConfirm = SettingDialog.RetweetNoConfirm;
7768                 _cfgCommon.LimitBalloon = SettingDialog.LimitBalloon;
7769                 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7770                 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7771                 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7772                 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7773                 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7774                 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7775                 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7776                 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7777                 _cfgCommon.TabIconDisp = SettingDialog.TabIconDisp;
7778                 _cfgCommon.ReplyIconState = SettingDialog.ReplyIconState;
7779                 _cfgCommon.ReadOwnPost = SettingDialog.ReadOwnPost;
7780                 _cfgCommon.GetFav = SettingDialog.GetFav;
7781                 _cfgCommon.IsMonospace = SettingDialog.IsMonospace;
7782                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7783                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7784                 {
7785                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7786                 }
7787                 _cfgCommon.ReadOldPosts = SettingDialog.ReadOldPosts;
7788                 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7789                 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7790                 _cfgCommon.ShowGrid = SettingDialog.ShowGrid;
7791                 _cfgCommon.UseAtIdSupplement = SettingDialog.UseAtIdSupplement;
7792                 _cfgCommon.UseHashSupplement = SettingDialog.UseHashSupplement;
7793                 _cfgCommon.PreviewEnable = SettingDialog.PreviewEnable;
7794                 _cfgCommon.Language = SettingDialog.Language;
7795
7796                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7797                 switch (_statuses.SortMode)
7798                 {
7799                     case IdComparerClass.ComparerMode.Nickname:  //ニックネーム
7800                         _cfgCommon.SortColumn = 1;
7801                         break;
7802                     case IdComparerClass.ComparerMode.Data:  //本文
7803                         _cfgCommon.SortColumn = 2;
7804                         break;
7805                     case IdComparerClass.ComparerMode.Id:  //時刻=発言Id
7806                         _cfgCommon.SortColumn = 3;
7807                         break;
7808                     case IdComparerClass.ComparerMode.Name:  //名前
7809                         _cfgCommon.SortColumn = 4;
7810                         break;
7811                     case IdComparerClass.ComparerMode.Source:  //Source
7812                         _cfgCommon.SortColumn = 7;
7813                         break;
7814                 }
7815
7816                 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7817                 _cfgCommon.HashTags = HashMgr.HashHistories;
7818                 if (HashMgr.IsPermanent)
7819                 {
7820                     _cfgCommon.HashSelected = HashMgr.UseHash;
7821                 }
7822                 else
7823                 {
7824                     _cfgCommon.HashSelected = "";
7825                 }
7826                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7827                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7828                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7829                 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7830                 _cfgCommon.HotkeyEnabled = SettingDialog.HotkeyEnabled;
7831                 _cfgCommon.HotkeyModifier = SettingDialog.HotkeyMod;
7832                 _cfgCommon.HotkeyKey = SettingDialog.HotkeyKey;
7833                 _cfgCommon.HotkeyValue = SettingDialog.HotkeyValue;
7834                 _cfgCommon.BlinkNewMentions = SettingDialog.BlinkNewMentions;
7835                 if (ToolStripFocusLockMenuItem != null &&
7836                         ToolStripFocusLockMenuItem.IsDisposed == false)
7837                 {
7838                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7839                 }
7840                 _cfgCommon.UseAdditionalCount = SettingDialog.UseAdditionalCount;
7841                 _cfgCommon.MoreCountApi = SettingDialog.MoreCountApi;
7842                 _cfgCommon.FirstCountApi = SettingDialog.FirstCountApi;
7843                 _cfgCommon.SearchCountApi = SettingDialog.SearchCountApi;
7844                 _cfgCommon.FavoritesCountApi = SettingDialog.FavoritesCountApi;
7845                 _cfgCommon.UserTimelineCountApi = SettingDialog.UserTimelineCountApi;
7846                 _cfgCommon.TrackWord = tw.TrackWord;
7847                 _cfgCommon.AllAtReply = tw.AllAtReply;
7848                 _cfgCommon.OpenUserTimeline = SettingDialog.OpenUserTimeline;
7849                 _cfgCommon.ListCountApi = SettingDialog.ListCountApi;
7850                 _cfgCommon.UseImageService = ImageServiceCombo.SelectedIndex;
7851                 _cfgCommon.UseImageServiceName = this.ImageService;
7852                 _cfgCommon.ListDoubleClickAction = SettingDialog.ListDoubleClickAction;
7853                 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7854                 _cfgCommon.HideDuplicatedRetweets = SettingDialog.HideDuplicatedRetweets;
7855                 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7856                 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7857                 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7858                 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7859                 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7860                 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7861                 _cfgCommon.IsListsIncludeRts = SettingDialog.IsListStatusesIncludeRts;
7862                 _cfgCommon.TabMouseLock = SettingDialog.TabMouseLock;
7863                 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7864                 _cfgCommon.IsUseNotifyGrowl = SettingDialog.IsNotifyUseGrowl;
7865
7866                 _cfgCommon.Save();
7867             }
7868         }
7869
7870         private void SaveConfigsLocal()
7871         {
7872             if (_ignoreConfigSave) return;
7873             lock (_syncObject)
7874             {
7875                 _modifySettingLocal = false;
7876                 _cfgLocal.FormSize = _mySize;
7877                 _cfgLocal.FormLocation = _myLoc;
7878                 _cfgLocal.SplitterDistance = _mySpDis;
7879                 _cfgLocal.PreviewDistance = _mySpDis3;
7880                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7881                 _cfgLocal.StatusTextHeight = _mySpDis2;
7882                 _cfgLocal.StatusText = SettingDialog.Status;
7883
7884                 _cfgLocal.FontUnread = _fntUnread;
7885                 _cfgLocal.ColorUnread = _clUnread;
7886                 _cfgLocal.FontRead = _fntReaded;
7887                 _cfgLocal.ColorRead = _clReaded;
7888                 _cfgLocal.FontDetail = _fntDetail;
7889                 _cfgLocal.ColorDetail = _clDetail;
7890                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7891                 _cfgLocal.ColorDetailLink = _clDetailLink;
7892                 _cfgLocal.ColorFav = _clFav;
7893                 _cfgLocal.ColorOWL = _clOWL;
7894                 _cfgLocal.ColorRetweet = _clRetweet;
7895                 _cfgLocal.ColorSelf = _clSelf;
7896                 _cfgLocal.ColorAtSelf = _clAtSelf;
7897                 _cfgLocal.ColorTarget = _clTarget;
7898                 _cfgLocal.ColorAtTarget = _clAtTarget;
7899                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7900                 _cfgLocal.ColorAtTo = _clAtTo;
7901                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7902                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7903                 _cfgLocal.ColorInputFont = _clInputFont;
7904                 _cfgLocal.FontInputFont = _fntInputFont;
7905
7906                 _cfgLocal.BrowserPath = SettingDialog.BrowserPath;
7907                 _cfgLocal.UseRecommendStatus = SettingDialog.UseRecommendStatus;
7908                 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7909                 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7910                 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7911                 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7912                 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7913                 if (_ignoreConfigSave) return;
7914                 _cfgLocal.Save();
7915             }
7916         }
7917
7918         private void SaveConfigsTabs()
7919         {
7920             SettingTabs tabSetting = new SettingTabs();
7921             for (int i = 0; i < ListTab.TabPages.Count; i++)
7922             {
7923                 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7924             }
7925             tabSetting.Save();
7926         }
7927
7928         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7929         {
7930             string inputText;
7931             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7932             if (ret != DialogResult.OK)
7933                 return;
7934
7935             var match = Twitter.StatusUrlRegex.Match(inputText);
7936             if (!match.Success)
7937             {
7938                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7939                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7940                 return;
7941             }
7942
7943             var statusId = long.Parse(match.Groups["StatusId"].Value);
7944
7945             var post = this._statuses[statusId];
7946             if (post == null)
7947             {
7948                 try
7949                 {
7950                     post = await Task.Run(() =>
7951                     {
7952                         PostClass newPost = null;
7953
7954                         var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7955                         if (!string.IsNullOrEmpty(err))
7956                             throw new WebApiException(err);
7957
7958                         return newPost;
7959                     });
7960                 }
7961                 catch (WebApiException ex)
7962                 {
7963                     var message = ex.InnerException.Message;
7964                     MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7965                         Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7966                     return;
7967                 }
7968             }
7969
7970             try
7971             {
7972                 this.OpenRelatedTab(post);
7973             }
7974             catch (TabException ex)
7975             {
7976                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7977             }
7978         }
7979
7980         private void SaveLogMenuItem_Click(object sender, EventArgs e)
7981         {
7982             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7983                     Properties.Resources.SaveLogMenuItem_ClickText2,
7984                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7985             if (rslt == DialogResult.Cancel) return;
7986
7987             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7988             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7989             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7990             SaveFileDialog1.FilterIndex = 0;
7991             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7992             SaveFileDialog1.RestoreDirectory = true;
7993
7994             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7995             {
7996                 if (!SaveFileDialog1.ValidateNames) return;
7997                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7998                 {
7999                     if (rslt == DialogResult.Yes)
8000                     {
8001                         //All
8002                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8003                         {
8004                             PostClass post = _statuses[_curTab.Text, idx];
8005                             string protect = "";
8006                             if (post.IsProtect) protect = "Protect";
8007                             sw.WriteLine(post.Nickname + "\t" +
8008                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8009                                      post.CreatedAt.ToString() + "\t" +
8010                                      post.ScreenName + "\t" +
8011                                      post.StatusId.ToString() + "\t" +
8012                                      post.ImageUrl + "\t" +
8013                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8014                                      protect);
8015                         }
8016                     }
8017                     else
8018                     {
8019                         foreach (int idx in _curList.SelectedIndices)
8020                         {
8021                             PostClass post = _statuses[_curTab.Text, idx];
8022                             string protect = "";
8023                             if (post.IsProtect) protect = "Protect";
8024                             sw.WriteLine(post.Nickname + "\t" +
8025                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8026                                      post.CreatedAt.ToString() + "\t" +
8027                                      post.ScreenName + "\t" +
8028                                      post.StatusId.ToString() + "\t" +
8029                                      post.ImageUrl + "\t" +
8030                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8031                                      protect);
8032                         }
8033                     }
8034                 }
8035             }
8036             this.TopMost = SettingDialog.AlwaysTop;
8037         }
8038
8039         private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8040         {
8041             ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
8042             if (State == ModifierState.NotFlags) return;
8043             bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
8044             if (KeyRes)
8045             {
8046                 e.IsInputKey = true;
8047             }
8048         }
8049         public bool TabRename(ref string tabName)
8050         {
8051             //タブ名変更
8052             string newTabText = null;
8053             using (InputTabName inputName = new InputTabName())
8054             {
8055                 inputName.TabName = tabName;
8056                 inputName.ShowDialog();
8057                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8058                 newTabText = inputName.TabName;
8059             }
8060             this.TopMost = SettingDialog.AlwaysTop;
8061             if (!string.IsNullOrEmpty(newTabText))
8062             {
8063                 //新タブ名存在チェック
8064                 for (int i = 0; i < ListTab.TabCount; i++)
8065                 {
8066                     if (ListTab.TabPages[i].Text == newTabText)
8067                     {
8068                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8069                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8070                         return false;
8071                     }
8072                 }
8073                 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
8074                 for (int i = 0; i < ListTab.TabCount; i++)
8075                 {
8076                     if (ListTab.TabPages[i].Text == tabName)
8077                     {
8078                         ListTab.TabPages[i].Text = newTabText;
8079                     }
8080                 }
8081                 _statuses.RenameTab(tabName, newTabText);
8082
8083                 for (int i = 0; i < ListTab.TabCount; i++)
8084                 {
8085                     if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
8086                     {
8087                         if (ListTab.TabPages[i].Text == tabName)
8088                         {
8089                             ListTab.TabPages[i].Text = newTabText;
8090                         }
8091                     }
8092                 }
8093                 SaveConfigsCommon();
8094                 SaveConfigsTabs();
8095                 _rclickTabName = newTabText;
8096                 tabName = newTabText;
8097                 return true;
8098             }
8099             else
8100             {
8101                 return false;
8102             }
8103         }
8104
8105         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8106         {
8107             if (e.Button == MouseButtons.Middle)
8108             {
8109                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8110                 {
8111                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8112                     {
8113                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8114                         this.SaveConfigsTabs();
8115                         break;
8116                     }
8117                 }
8118             }
8119         }
8120
8121         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8122         {
8123             string tn = ListTab.SelectedTab.Text;
8124             TabRename(ref tn);
8125         }
8126
8127         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8128         {
8129             if (SettingDialog.TabMouseLock) return;
8130             Point cpos = new Point(e.X, e.Y);
8131             if (e.Button == MouseButtons.Left)
8132             {
8133                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8134                 {
8135                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8136                     {
8137                         _tabDrag = true;
8138                         _tabMouseDownPoint = e.Location;
8139                         break;
8140                     }
8141                 }
8142             }
8143             else
8144             {
8145                 _tabDrag = false;
8146             }
8147         }
8148
8149         private void ListTab_DragEnter(object sender, DragEventArgs e)
8150         {
8151             if (e.Data.GetDataPresent(typeof(TabPage)))
8152                 e.Effect = DragDropEffects.Move;
8153             else
8154                 e.Effect = DragDropEffects.None;
8155         }
8156
8157         private void ListTab_DragDrop(object sender, DragEventArgs e)
8158         {
8159             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8160
8161             _tabDrag = false;
8162             string tn = "";
8163             bool bef = false;
8164             Point cpos = new Point(e.X, e.Y);
8165             Point spos = ListTab.PointToClient(cpos);
8166             int i;
8167             for (i = 0; i < ListTab.TabPages.Count; i++)
8168             {
8169                 Rectangle rect = ListTab.GetTabRect(i);
8170                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8171                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8172                 {
8173                     tn = ListTab.TabPages[i].Text;
8174                     if (spos.X <= (rect.Left + rect.Right) / 2)
8175                         bef = true;
8176                     else
8177                         bef = false;
8178
8179                     break;
8180                 }
8181             }
8182
8183             //タブのないところにドロップ->最後尾へ移動
8184             if (string.IsNullOrEmpty(tn))
8185             {
8186                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8187                 bef = false;
8188                 i = ListTab.TabPages.Count - 1;
8189             }
8190
8191             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8192             if (tp.Text == tn) return;
8193
8194             ReOrderTab(tp.Text, tn, bef);
8195         }
8196
8197         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8198         {
8199             int baseIndex = 0;
8200             for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8201             {
8202                 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8203             }
8204
8205             using (ControlTransaction.Layout(this.ListTab))
8206             {
8207                 TabPage mTp = null;
8208                 for (int j = 0; j < ListTab.TabPages.Count; j++)
8209                 {
8210                     if (ListTab.TabPages[j].Text == targetTabText)
8211                     {
8212                         mTp = ListTab.TabPages[j];
8213                         ListTab.TabPages.Remove(mTp);
8214                         if (j < baseIndex) baseIndex -= 1;
8215                         break;
8216                     }
8217                 }
8218                 if (isBeforeBaseTab)
8219                     ListTab.TabPages.Insert(baseIndex, mTp);
8220                 else
8221                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8222             }
8223
8224             SaveConfigsTabs();
8225         }
8226
8227         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8228         {
8229             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8230             //isReply:true=@,false=DM
8231             if (!StatusText.Enabled) return;
8232             if (_curList == null) return;
8233             if (_curTab == null) return;
8234             if (!this.ExistCurrentPost) return;
8235
8236             // 複数あてリプライはReplyではなく通常ポスト
8237             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8238             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8239             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8240
8241             if (_curList.SelectedIndices.Count > 0)
8242             {
8243                 // アイテムが1件以上選択されている
8244                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8245                 {
8246                     // 単独ユーザー宛リプライまたはDM
8247                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8248                     {
8249                         // ダイレクトメッセージ
8250                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8251                         StatusText.SelectionStart = StatusText.Text.Length;
8252                         StatusText.Focus();
8253                         _reply_to_id = null;
8254                         _reply_to_name = null;
8255                         return;
8256                     }
8257                     if (string.IsNullOrEmpty(StatusText.Text))
8258                     {
8259                         //空の場合
8260
8261                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8262                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8263                         if (_curPost.RetweetedId != null)
8264                         {
8265                             _reply_to_id = _curPost.RetweetedId.Value;
8266                         }
8267                         else
8268                         {
8269                             _reply_to_id = _curPost.StatusId;
8270                         }
8271                         _reply_to_name = _curPost.ScreenName;
8272                     }
8273                     else
8274                     {
8275                         //何か入力済の場合
8276
8277                         if (isAuto)
8278                         {
8279                             //1件選んでEnter or DoubleClick
8280                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8281                             {
8282                                 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8283                                 {
8284                                     //返信先書き換え
8285                                     if (_curPost.RetweetedId != null)
8286                                     {
8287                                         _reply_to_id = _curPost.RetweetedId.Value;
8288                                     }
8289                                     else
8290                                     {
8291                                         _reply_to_id = _curPost.StatusId;
8292                                     }
8293                                     _reply_to_name = _curPost.ScreenName;
8294                                 }
8295                                 return;
8296                             }
8297                             if (!StatusText.Text.StartsWith("@"))
8298                             {
8299                                 //文頭@以外
8300                                 if (StatusText.Text.StartsWith(". "))
8301                                 {
8302                                     // 複数リプライ
8303                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8304                                     _reply_to_id = null;
8305                                     _reply_to_name = null;
8306                                 }
8307                                 else
8308                                 {
8309                                     // 単独リプライ
8310                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8311                                     if (_curPost.RetweetedId != null)
8312                                     {
8313                                         _reply_to_id = _curPost.RetweetedId.Value;
8314                                     }
8315                                     else
8316                                     {
8317                                         _reply_to_id = _curPost.StatusId;
8318                                     }
8319                                     _reply_to_name = _curPost.ScreenName;
8320                                 }
8321                             }
8322                             else
8323                             {
8324                                 //文頭@
8325                                 // 複数リプライ
8326                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8327                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8328                                 _reply_to_id = null;
8329                                 _reply_to_name = null;
8330                             }
8331                         }
8332                         else
8333                         {
8334                             //1件選んでCtrl-Rの場合(返信先操作せず)
8335                             int sidx = StatusText.SelectionStart;
8336                             string id = "@" + _curPost.ScreenName + " ";
8337                             if (sidx > 0)
8338                             {
8339                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8340                                 {
8341                                     id = " " + id;
8342                                 }
8343                             }
8344                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8345                             sidx += id.Length;
8346                             //if (StatusText.Text.StartsWith("@"))
8347                             //{
8348                             //    //複数リプライ
8349                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8350                             //    sidx += 5 + _curPost.ScreenName.Length;
8351                             //}
8352                             //else
8353                             //{
8354                             //    // 複数リプライ
8355                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8356                             //    sidx += 3 + _curPost.ScreenName.Length;
8357                             //}
8358                             StatusText.SelectionStart = sidx;
8359                             StatusText.Focus();
8360                             //_reply_to_id = 0;
8361                             //_reply_to_name = null;
8362                             return;
8363                         }
8364                     }
8365                 }
8366                 else
8367                 {
8368                     // 複数リプライ
8369                     if (!isAuto && !isReply) return;
8370
8371                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8372
8373                     if (isAuto)
8374                     {
8375                         //Enter or DoubleClick
8376
8377                         string sTxt = StatusText.Text;
8378                         if (!sTxt.StartsWith(". "))
8379                         {
8380                             sTxt = ". " + sTxt;
8381                             _reply_to_id = null;
8382                             _reply_to_name = null;
8383                         }
8384                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8385                         {
8386                             PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8387                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8388                             {
8389                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8390                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8391                             }
8392                         }
8393                         StatusText.Text = sTxt;
8394                     }
8395                     else
8396                     {
8397                         //C-S-r or C-r
8398                         if (_curList.SelectedIndices.Count > 1)
8399                         {
8400                             //複数ポスト選択
8401
8402                             string ids = "";
8403                             int sidx = StatusText.SelectionStart;
8404                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8405                             {
8406                                 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8407                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8408                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8409                                 {
8410                                     ids += "@" + post.ScreenName + " ";
8411                                 }
8412                                 if (isAll)
8413                                 {
8414                                     foreach (string nm in post.ReplyToList)
8415                                     {
8416                                         if (!ids.Contains("@" + nm + " ") &&
8417                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8418                                         {
8419                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8420                                             if (m.Success)
8421                                                 ids += "@" + m.Result("${id}") + " ";
8422                                             else
8423                                                 ids += "@" + nm + " ";
8424                                         }
8425                                     }
8426                                 }
8427                             }
8428                             if (ids.Length == 0) return;
8429                             if (!StatusText.Text.StartsWith(". "))
8430                             {
8431                                 StatusText.Text = ". " + StatusText.Text;
8432                                 sidx += 2;
8433                                 _reply_to_id = null;
8434                                 _reply_to_name = null;
8435                             }
8436                             if (sidx > 0)
8437                             {
8438                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8439                                 {
8440                                     ids = " " + ids;
8441                                 }
8442                             }
8443                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8444                             sidx += ids.Length;
8445                             //if (StatusText.Text.StartsWith("@"))
8446                             //{
8447                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8448                             //    sidx += 2 + ids.Length;
8449                             //}
8450                             //else
8451                             //{
8452                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8453                             //    sidx += 1 + ids.Length;
8454                             //}
8455                             StatusText.SelectionStart = sidx;
8456                             StatusText.Focus();
8457                             return;
8458                         }
8459                         else
8460                         {
8461                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8462
8463                             string ids = "";
8464                             int sidx = StatusText.SelectionStart;
8465                             PostClass post = _curPost;
8466                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8467                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8468                             {
8469                                 ids += "@" + post.ScreenName + " ";
8470                             }
8471                             foreach (string nm in post.ReplyToList)
8472                             {
8473                                 if (!ids.Contains("@" + nm + " ") &&
8474                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8475                                 {
8476                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8477                                     if (m.Success)
8478                                         ids += "@" + m.Result("${id}") + " ";
8479                                     else
8480                                         ids += "@" + nm + " ";
8481                                 }
8482                             }
8483                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8484                             {
8485                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8486                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8487                                 {
8488                                     ids += "@" + post.RetweetedBy + " ";
8489                                 }
8490                             }
8491                             if (ids.Length == 0) return;
8492                             if (string.IsNullOrEmpty(StatusText.Text))
8493                             {
8494                                 //未入力の場合のみ返信先付加
8495                                 StatusText.Text = ids;
8496                                 StatusText.SelectionStart = ids.Length;
8497                                 StatusText.Focus();
8498                                 if (post.RetweetedId != null)
8499                                 {
8500                                     _reply_to_id = post.RetweetedId.Value;
8501                                 }
8502                                 else
8503                                 {
8504                                     _reply_to_id = post.StatusId;
8505                                 }
8506                                 _reply_to_name = post.ScreenName;
8507                                 return;
8508                             }
8509
8510                             if (sidx > 0)
8511                             {
8512                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8513                                 {
8514                                     ids = " " + ids;
8515                                 }
8516                             }
8517                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8518                             sidx += ids.Length;
8519                             StatusText.SelectionStart = sidx;
8520                             StatusText.Focus();
8521                             return;
8522                         }
8523                     }
8524                 }
8525                 StatusText.SelectionStart = StatusText.Text.Length;
8526                 StatusText.Focus();
8527             }
8528         }
8529
8530         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8531         {
8532             _tabDrag = false;
8533         }
8534
8535         private static int iconCnt = 0;
8536         private static int blinkCnt = 0;
8537         private static bool blink = false;
8538         private static bool idle = false;
8539
8540         private void RefreshTasktrayIcon(bool forceRefresh)
8541         {
8542             if (_colorize) Colorize();
8543             if (!TimerRefreshIcon.Enabled) return;
8544             //Static usCheckCnt As int = 0
8545
8546             //Static iconDlListTopItem As ListViewItem = null
8547
8548             if (forceRefresh) idle = false;
8549
8550             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8551             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8552             //else
8553             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8554             //
8555             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8556
8557             iconCnt += 1;
8558             blinkCnt += 1;
8559             //usCheckCnt += 1;
8560
8561             //if (usCheckCnt > 300)    //1min
8562             //{
8563             //    usCheckCnt = 0;
8564             //    if (!this.IsReceivedUserStream)
8565             //    {
8566             //        TraceOut("ReconnectUserStream");
8567             //        tw.ReconnectUserStream();
8568             //    }
8569             //}
8570
8571             bool busy = false;
8572             foreach (BackgroundWorker bw in this._bw)
8573             {
8574                 if (bw != null && bw.IsBusy)
8575                 {
8576                     busy = true;
8577                     break;
8578                 }
8579             }
8580
8581             if (iconCnt > 3)
8582             {
8583                 iconCnt = 0;
8584             }
8585             if (blinkCnt > 10)
8586             {
8587                 blinkCnt = 0;
8588                 //未保存の変更を保存
8589                 SaveConfigsAll(true);
8590             }
8591
8592             if (busy)
8593             {
8594                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8595                 idle = false;
8596                 _myStatusError = false;
8597                 return;
8598             }
8599
8600             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8601             if (SettingDialog.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8602             {
8603                 if (blinkCnt > 0) return;
8604                 blink = !blink;
8605                 if (blink || SettingDialog.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8606                 {
8607                     NotifyIcon1.Icon = ReplyIcon;
8608                 }
8609                 else
8610                 {
8611                     NotifyIcon1.Icon = ReplyIconBlink;
8612                 }
8613                 idle = false;
8614                 return;
8615             }
8616
8617             if (idle) return;
8618             idle = true;
8619             //優先度:エラー→オフライン→アイドル
8620             //エラーは更新アイコンでクリアされる
8621             if (_myStatusError)
8622             {
8623                 NotifyIcon1.Icon = NIconAtRed;
8624                 return;
8625             }
8626             if (_myStatusOnline)
8627             {
8628                 NotifyIcon1.Icon = NIconAt;
8629             }
8630             else
8631             {
8632                 NotifyIcon1.Icon = NIconAtSmoke;
8633             }
8634         }
8635
8636         private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8637         {
8638             //200ms
8639             this.RefreshTasktrayIcon(false);
8640         }
8641
8642         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8643         {
8644             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8645             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8646             {
8647                 if (ListTab != null && ListTab.SelectedTab != null)
8648                     _rclickTabName = ListTab.SelectedTab.Text;
8649                 else
8650                     return;
8651             }
8652
8653             if (_statuses == null) return;
8654             if (_statuses.Tabs == null) return;
8655
8656             TabClass tb = _statuses.Tabs[_rclickTabName];
8657             if (tb == null) return;
8658
8659             NotifyDispMenuItem.Checked = tb.Notify;
8660             this.NotifyTbMenuItem.Checked = tb.Notify;
8661
8662             soundfileListup = true;
8663             SoundFileComboBox.Items.Clear();
8664             this.SoundFileTbComboBox.Items.Clear();
8665             SoundFileComboBox.Items.Add("");
8666             this.SoundFileTbComboBox.Items.Add("");
8667             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8668             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8669             {
8670                 oDir = oDir.GetDirectories("Sounds")[0];
8671             }
8672             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8673             {
8674                 SoundFileComboBox.Items.Add(oFile.Name);
8675                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8676             }
8677             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8678             if (idx == -1) idx = 0;
8679             SoundFileComboBox.SelectedIndex = idx;
8680             this.SoundFileTbComboBox.SelectedIndex = idx;
8681             soundfileListup = false;
8682             UreadManageMenuItem.Checked = tb.UnreadManage;
8683             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8684
8685             TabMenuControl(_rclickTabName);
8686         }
8687
8688         private void TabMenuControl(string tabName)
8689         {
8690             this.FilterEditMenuItem.Enabled = true;
8691             this.EditRuleTbMenuItem.Enabled = true;
8692
8693             if (_statuses.IsDefaultTab(tabName))
8694             {
8695                 this.ProtectTabMenuItem.Enabled = false;
8696                 this.ProtectTbMenuItem.Enabled = false;
8697             }
8698             else
8699             {
8700                 this.ProtectTabMenuItem.Enabled = true;
8701                 this.ProtectTbMenuItem.Enabled = true;
8702             }
8703
8704             if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8705             {
8706                 this.ProtectTabMenuItem.Checked = true;
8707                 this.ProtectTbMenuItem.Checked = true;
8708                 this.DeleteTabMenuItem.Enabled = false;
8709                 this.DeleteTbMenuItem.Enabled = false;
8710             }
8711             else
8712             {
8713                 this.ProtectTabMenuItem.Checked = false;
8714                 this.ProtectTbMenuItem.Checked = false;
8715                 this.DeleteTabMenuItem.Enabled = true;
8716                 this.DeleteTbMenuItem.Enabled = true;
8717             }
8718         }
8719
8720         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8721         {
8722             var checkState = ((ToolStripMenuItem)sender).Checked;
8723
8724             // チェック状態を同期
8725             this.ProtectTbMenuItem.Checked = checkState;
8726             this.ProtectTabMenuItem.Checked = checkState;
8727
8728             // ロック中はタブの削除を無効化
8729             this.DeleteTabMenuItem.Enabled = !checkState;
8730             this.DeleteTbMenuItem.Enabled = !checkState;
8731
8732             if (string.IsNullOrEmpty(_rclickTabName)) return;
8733             _statuses.Tabs[_rclickTabName].Protected = checkState;
8734
8735             SaveConfigsTabs();
8736         }
8737
8738         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8739         {
8740             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8741             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8742
8743             if (string.IsNullOrEmpty(_rclickTabName)) return;
8744             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8745
8746             SaveConfigsTabs();
8747         }
8748
8749         public void ChangeTabUnreadManage(string tabName, bool isManage)
8750         {
8751             int idx;
8752             for (idx = 0; idx < ListTab.TabCount; idx++)
8753             {
8754                 if (ListTab.TabPages[idx].Text == tabName) break;
8755             }
8756
8757             _statuses.SetTabUnreadManage(tabName, isManage);
8758             if (SettingDialog.TabIconDisp)
8759             {
8760                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8761                     ListTab.TabPages[idx].ImageIndex = 0;
8762                 else
8763                     ListTab.TabPages[idx].ImageIndex = -1;
8764             }
8765
8766             if (_curTab.Text == tabName)
8767             {
8768                 this.PurgeListViewItemCache();
8769                 _curList.Refresh();
8770             }
8771
8772             SetMainWindowTitle();
8773             SetStatusLabelUrl();
8774             if (!SettingDialog.TabIconDisp) ListTab.Refresh();
8775         }
8776
8777         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8778         {
8779             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8781
8782             if (string.IsNullOrEmpty(_rclickTabName)) return;
8783
8784             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8785
8786             SaveConfigsTabs();
8787         }
8788
8789         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8790         {
8791             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8792
8793             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8794
8795             SaveConfigsTabs();
8796         }
8797
8798         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8799         {
8800             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8801
8802             RemoveSpecifiedTab(_rclickTabName, true);
8803             SaveConfigsTabs();
8804         }
8805
8806         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8807         {
8808             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8809             fltDialog.SetCurrent(_rclickTabName);
8810             fltDialog.ShowDialog(this);
8811             this.TopMost = SettingDialog.AlwaysTop;
8812
8813             this.ApplyPostFilters();
8814             SaveConfigsTabs();
8815         }
8816
8817         private void AddTabMenuItem_Click(object sender, EventArgs e)
8818         {
8819             string tabName = null;
8820             MyCommon.TabUsageType tabUsage;
8821             using (InputTabName inputName = new InputTabName())
8822             {
8823                 inputName.TabName = _statuses.GetUniqueTabName();
8824                 inputName.IsShowUsage = true;
8825                 inputName.ShowDialog();
8826                 if (inputName.DialogResult == DialogResult.Cancel) return;
8827                 tabName = inputName.TabName;
8828                 tabUsage = inputName.Usage;
8829             }
8830             this.TopMost = SettingDialog.AlwaysTop;
8831             if (!string.IsNullOrEmpty(tabName))
8832             {
8833                 //List対応
8834                 ListElement list = null;
8835                 if (tabUsage == MyCommon.TabUsageType.Lists)
8836                 {
8837                     using (ListAvailable listAvail = new ListAvailable())
8838                     {
8839                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8840                         if (listAvail.SelectedList == null) return;
8841                         list = listAvail.SelectedList;
8842                     }
8843                 }
8844                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8845                 {
8846                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8847                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8848                 }
8849                 else
8850                 {
8851                     //成功
8852                     SaveConfigsTabs();
8853                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8854                     {
8855                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8856                         ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8857                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8858                     }
8859                     if (tabUsage == MyCommon.TabUsageType.Lists)
8860                     {
8861                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8862                         ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8863                         GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, tabName);
8864                     }
8865                 }
8866             }
8867         }
8868
8869         private void TabMenuItem_Click(object sender, EventArgs e)
8870         {
8871             //選択発言を元にフィルタ追加
8872             foreach (int idx in _curList.SelectedIndices)
8873             {
8874                 string tabName;
8875                 //タブ選択(or追加)
8876                 if (!SelectTab(out tabName)) return;
8877
8878                 fltDialog.SetCurrent(tabName);
8879                 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8880                 {
8881                     fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8882                 }
8883                 else
8884                 {
8885                     fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8886                 }
8887                 fltDialog.ShowDialog(this);
8888                 this.TopMost = SettingDialog.AlwaysTop;
8889             }
8890
8891             this.ApplyPostFilters();
8892             SaveConfigsTabs();
8893             if (this.ListTab.SelectedTab != null &&
8894                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8895             {
8896                 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8897             }
8898         }
8899
8900         protected override bool ProcessDialogKey(Keys keyData)
8901         {
8902             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8903             if ((keyData & Keys.KeyCode) == Keys.Enter)
8904             {
8905                 if (StatusText.Focused)
8906                 {
8907                     bool _NewLine = false;
8908                     bool _Post = false;
8909
8910                     if (SettingDialog.PostCtrlEnter) //Ctrl+Enter投稿時
8911                     {
8912                         if (StatusText.Multiline)
8913                         {
8914                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8915
8916                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8917                         }
8918                         else
8919                         {
8920                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8921                         }
8922
8923                     }
8924                     else if (SettingDialog.PostShiftEnter) //SHift+Enter投稿時
8925                     {
8926                         if (StatusText.Multiline)
8927                         {
8928                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8929
8930                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8931                         }
8932                         else
8933                         {
8934                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8935                         }
8936
8937                     }
8938                     else //Enter投稿時
8939                     {
8940                         if (StatusText.Multiline)
8941                         {
8942                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8943
8944                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8945                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8946                         }
8947                         else
8948                         {
8949                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8950                                 (((keyData & Keys.Control) != Keys.Control) &&
8951                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8952                         }
8953                     }
8954
8955                     if (_NewLine)
8956                     {
8957                         int pos1 = StatusText.SelectionStart;
8958                         if (StatusText.SelectionLength > 0)
8959                         {
8960                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8961                         }
8962                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
8963                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
8964                         return true;
8965                     }
8966                     else if (_Post)
8967                     {
8968                         PostButton_Click(null, null);
8969                         return true;
8970                     }
8971                 }
8972                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8973                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8974                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8975                 {
8976                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8977                     return true;
8978                 }
8979             }
8980
8981             return base.ProcessDialogKey(keyData);
8982         }
8983
8984         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8985         {
8986             MakeReplyOrDirectStatus(false, true, true);
8987         }
8988
8989         private void IDRuleMenuItem_Click(object sender, EventArgs e)
8990         {
8991             string tabName;
8992
8993             //未選択なら処理終了
8994             if (_curList.SelectedIndices.Count == 0) return;
8995
8996             //タブ選択(or追加)
8997             if (!SelectTab(out tabName)) return;
8998
8999             bool mv = false;
9000             bool mk = false;
9001             MoveOrCopy(ref mv, ref mk);
9002
9003             List<string> ids = new List<string>();
9004             foreach (int idx in _curList.SelectedIndices)
9005             {
9006                 PostClass post = _statuses[_curTab.Text, idx];
9007                 if (!ids.Contains(post.ScreenName))
9008                 {
9009                     PostFilterRule fc = new PostFilterRule();
9010                     ids.Add(post.ScreenName);
9011                     if (post.RetweetedId == null)
9012                     {
9013                         fc.FilterName = post.ScreenName;
9014                     }
9015                     else
9016                     {
9017                         fc.FilterName = post.RetweetedBy;
9018                     }
9019                     fc.UseNameField = true;
9020                     fc.MoveMatches = mv;
9021                     fc.MarkMatches = mk;
9022                     fc.UseRegex = false;
9023                     fc.FilterByUrl = false;
9024                     _statuses.Tabs[tabName].AddFilter(fc);
9025                 }
9026             }
9027             if (ids.Count != 0)
9028             {
9029                 List<string> atids = new List<string>();
9030                 foreach (string id in ids)
9031                 {
9032                     atids.Add("@" + id);
9033                 }
9034                 int cnt = AtIdSupl.ItemCount;
9035                 AtIdSupl.AddRangeItem(atids.ToArray());
9036                 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9037             }
9038
9039             this.ApplyPostFilters();
9040             SaveConfigsTabs();
9041         }
9042
9043         private bool SelectTab(out string tabName)
9044         {
9045             do
9046             {
9047                 tabName = null;
9048
9049                 //振り分け先タブ選択
9050                 using (var dialog = new TabsDialog(_statuses))
9051                 {
9052                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9053
9054                     var selectedTab = dialog.SelectedTab;
9055                     tabName = selectedTab == null ? null : selectedTab.TabName;
9056                 }
9057
9058                 ListTab.SelectedTab.Focus();
9059                 //新規タブを選択→タブ作成
9060                 if (tabName == null)
9061                 {
9062                     using (InputTabName inputName = new InputTabName())
9063                     {
9064                         inputName.TabName = _statuses.GetUniqueTabName();
9065                         inputName.ShowDialog();
9066                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9067                         tabName = inputName.TabName;
9068                     }
9069                     this.TopMost = SettingDialog.AlwaysTop;
9070                     if (!string.IsNullOrEmpty(tabName))
9071                     {
9072                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9073                         {
9074                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9075                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9076                             //もう一度タブ名入力
9077                         }
9078                         else
9079                         {
9080                             return true;
9081                         }
9082                     }
9083                 }
9084                 else
9085                 {
9086                     //既存タブを選択
9087                     return true;
9088                 }
9089             }
9090             while (true);
9091         }
9092
9093         private void MoveOrCopy(ref bool move, ref bool mark)
9094         {
9095             {
9096                 //移動するか?
9097                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9098                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9099                     move = false;
9100                 else
9101                     move = true;
9102             }
9103             if (!move)
9104             {
9105                 //マークするか?
9106                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9107                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9108                     mark = true;
9109                 else
9110                     mark = false;
9111             }
9112         }
9113         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9114         {
9115             this.CopyStot();
9116         }
9117
9118         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9119         {
9120             this.CopyIdUri();
9121         }
9122
9123         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9124         {
9125             if (StatusText.Focused)
9126             {
9127                 // 発言欄でのCtrl+A
9128                 StatusText.SelectAll();
9129             }
9130             else
9131             {
9132                 // ListView上でのCtrl+A
9133                 for (int i = 0; i < _curList.VirtualListSize; i++)
9134                 {
9135                     _curList.SelectedIndices.Add(i);
9136                 }
9137             }
9138         }
9139
9140         private void MoveMiddle()
9141         {
9142             ListViewItem _item;
9143             int idx1;
9144             int idx2;
9145
9146             if (_curList.SelectedIndices.Count == 0) return;
9147
9148             int idx = _curList.SelectedIndices[0];
9149
9150             _item = _curList.GetItemAt(0, 25);
9151             if (_item == null)
9152                 idx1 = 0;
9153             else
9154                 idx1 = _item.Index;
9155
9156             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9157             if (_item == null)
9158                 idx2 = _curList.VirtualListSize - 1;
9159             else
9160                 idx2 = _item.Index;
9161
9162             idx -= Math.Abs(idx1 - idx2) / 2;
9163             if (idx < 0) idx = 0;
9164
9165             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9166             _curList.EnsureVisible(idx);
9167         }
9168
9169         private void OpenURLMenuItem_Click(object sender, EventArgs e)
9170         {
9171             if (PostBrowser.Document.Links.Count > 0)
9172             {
9173                 UrlDialog.ClearUrl();
9174
9175                 string openUrlStr = "";
9176
9177                 if (PostBrowser.Document.Links.Count == 1)
9178                 {
9179                     string urlStr = "";
9180                     try
9181                     {
9182                         urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9183                     }
9184                     catch (ArgumentException)
9185                     {
9186                         //変なHTML?
9187                         return;
9188                     }
9189                     catch (Exception)
9190                     {
9191                         return;
9192                     }
9193                     if (string.IsNullOrEmpty(urlStr)) return;
9194                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9195                 }
9196                 else
9197                 {
9198                     foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9199                     {
9200                         string urlStr = "";
9201                         string linkText = "";
9202                         string href = "";
9203                         try
9204                         {
9205                             urlStr = linkElm.GetAttribute("title");
9206                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9207                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9208                             linkText = linkElm.InnerText;
9209                             if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9210                             {
9211                                 linkText = "@" + linkText;
9212                             }
9213                         }
9214                         catch (ArgumentException)
9215                         {
9216                             //変なHTML?
9217                             return;
9218                         }
9219                         catch (Exception)
9220                         {
9221                             return;
9222                         }
9223                         if (string.IsNullOrEmpty(urlStr)) continue;
9224                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9225                     }
9226                     try
9227                     {
9228                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9229                         {
9230                             openUrlStr = UrlDialog.SelectedUrl;
9231                         }
9232                     }
9233                     catch (Exception)
9234                     {
9235                         return;
9236                     }
9237                     this.TopMost = SettingDialog.AlwaysTop;
9238                 }
9239                 if (string.IsNullOrEmpty(openUrlStr)) return;
9240
9241                 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9242                     openUrlStr.StartsWith("https://twitter.com/search?q="))
9243                 {
9244                     //ハッシュタグの場合は、タブで開く
9245                     string urlStr = Uri.UnescapeDataString(openUrlStr);
9246                     string hash = urlStr.Substring(urlStr.IndexOf("#"));
9247                     HashSupl.AddItem(hash);
9248                     HashMgr.AddHashToHistory(hash.Trim(), false);
9249                     AddNewTabForSearch(hash);
9250                     return;
9251                 }
9252                 else
9253                 {
9254                     Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9255                     if (SettingDialog.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9256                         this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9257                     else
9258                         OpenUriAsync(openUrlStr);
9259                     return;
9260                 }
9261             }
9262         }
9263
9264         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9265         {
9266             if (string.IsNullOrEmpty(_rclickTabName)) return;
9267             ClearTab(_rclickTabName, true);
9268         }
9269
9270         private void ClearTab(string tabName, bool showWarning)
9271         {
9272             if (showWarning)
9273             {
9274                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9275                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9276                 {
9277                     return;
9278                 }
9279             }
9280
9281             _statuses.ClearTabIds(tabName);
9282             if (ListTab.SelectedTab.Text == tabName)
9283             {
9284                 _anchorPost = null;
9285                 _anchorFlag = false;
9286                 this.PurgeListViewItemCache();
9287                 _curItemIndex = -1;
9288                 _curPost = null;
9289             }
9290             foreach (TabPage tb in ListTab.TabPages)
9291             {
9292                 if (tb.Text == tabName)
9293                 {
9294                     tb.ImageIndex = -1;
9295                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9296                     break;
9297                 }
9298             }
9299             if (!SettingDialog.TabIconDisp) ListTab.Refresh();
9300
9301             SetMainWindowTitle();
9302             SetStatusLabelUrl();
9303         }
9304
9305         private static long followers = 0;
9306
9307         private void SetMainWindowTitle()
9308         {
9309             //メインウインドウタイトルの書き換え
9310             StringBuilder ttl = new StringBuilder(256);
9311             int ur = 0;
9312             int al = 0;
9313             if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
9314                 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9315                 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9316                 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9317             {
9318                 foreach (var tab in _statuses.Tabs.Values)
9319                 {
9320                     ur += tab.UnreadCount;
9321                     al += tab.AllCount;
9322                 }
9323             }
9324
9325             if (SettingDialog.DispUsername) ttl.Append(tw.Username).Append(" - ");
9326             ttl.Append(Application.ProductName);
9327             ttl.Append("  ");
9328             switch (SettingDialog.DispLatestPost)
9329             {
9330                 case MyCommon.DispTitleEnum.Ver:
9331                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9332                     break;
9333                 case MyCommon.DispTitleEnum.Post:
9334                     if (_history != null && _history.Count > 1)
9335                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9336                     break;
9337                 case MyCommon.DispTitleEnum.UnreadRepCount:
9338                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9339                     break;
9340                 case MyCommon.DispTitleEnum.UnreadAllCount:
9341                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9342                     break;
9343                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9344                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9345                     break;
9346                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9347                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9348                     break;
9349                 case MyCommon.DispTitleEnum.OwnStatus:
9350                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9351                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9352                     break;
9353             }
9354
9355             try
9356             {
9357                 this.Text = ttl.ToString();
9358             }
9359             catch (AccessViolationException)
9360             {
9361                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9362             }
9363         }
9364
9365         private string GetStatusLabelText()
9366         {
9367             //ステータス欄にカウント表示
9368             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9369             if (_statuses == null) return "";
9370             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9371             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9372             if (tbRep == null || tbDm == null) return "";
9373             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9374             int ur = 0;
9375             int al = 0;
9376             int tur = 0;
9377             int tal = 0;
9378             StringBuilder slbl = new StringBuilder(256);
9379             try
9380             {
9381                 foreach (var tab in _statuses.Tabs.Values)
9382                 {
9383                     ur += tab.UnreadCount;
9384                     al += tab.AllCount;
9385                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9386                     {
9387                         tur = tab.UnreadCount;
9388                         tal = tab.AllCount;
9389                     }
9390                 }
9391             }
9392             catch (Exception)
9393             {
9394                 return "";
9395             }
9396
9397             UnreadCounter = ur;
9398             UnreadAtCounter = urat;
9399
9400             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9401             if (SettingDialog.TimelinePeriodInt == 0)
9402             {
9403                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9404             }
9405             else
9406             {
9407                 slbl.Append(SettingDialog.TimelinePeriodInt.ToString() + Properties.Resources.SetStatusLabelText3);
9408             }
9409             return slbl.ToString();
9410         }
9411
9412         private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9413         {
9414             try
9415             {
9416                 if (this.InvokeRequired && !this.IsDisposed)
9417                 {
9418                     this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9419                 }
9420                 else
9421                 {
9422                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9423                     if (endpointName == "/statuses/home_timeline" || endpointName == null)
9424                     {
9425                         this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9426                     }
9427                 }
9428             }
9429             catch (ObjectDisposedException)
9430             {
9431                 return;
9432             }
9433             catch (InvalidOperationException)
9434             {
9435                 return;
9436             }
9437         }
9438
9439         private void SetStatusLabelUrl()
9440         {
9441             StatusLabelUrl.Text = GetStatusLabelText();
9442         }
9443
9444         public void SetStatusLabel(string text)
9445         {
9446             StatusLabel.Text = text;
9447         }
9448
9449         private static StringBuilder ur = new StringBuilder(64);
9450
9451         private void SetNotifyIconText()
9452         {
9453             // タスクトレイアイコンのツールチップテキスト書き換え
9454             // Tween [未読/@]
9455             ur.Remove(0, ur.Length);
9456             if (SettingDialog.DispUsername)
9457             {
9458                 ur.Append(tw.Username);
9459                 ur.Append(" - ");
9460             }
9461             ur.Append(Application.ProductName);
9462 #if DEBUG
9463             ur.Append("(Debug Build)");
9464 #endif
9465             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9466             {
9467                 ur.Append(" [");
9468                 ur.Append(UnreadCounter);
9469                 ur.Append("/@");
9470                 ur.Append(UnreadAtCounter);
9471                 ur.Append("]");
9472             }
9473             NotifyIcon1.Text = ur.ToString();
9474         }
9475
9476         internal void CheckReplyTo(string StatusText)
9477         {
9478             MatchCollection m;
9479             //ハッシュタグの保存
9480             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9481             string hstr = "";
9482             foreach (Match hm in m)
9483             {
9484                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9485                 {
9486                     hstr += "#" + hm.Result("$3") + " ";
9487                     HashSupl.AddItem("#" + hm.Result("$3"));
9488                 }
9489             }
9490             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9491             {
9492                 hstr += HashMgr.UseHash;
9493             }
9494             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9495
9496             // 本当にリプライ先指定すべきかどうかの判定
9497             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9498
9499             if (SettingDialog.UseAtIdSupplement)
9500             {
9501                 int bCnt = AtIdSupl.ItemCount;
9502                 foreach (Match mid in m)
9503                 {
9504                     AtIdSupl.AddItem(mid.Result("${id}"));
9505                 }
9506                 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9507             }
9508
9509             // リプライ先ステータスIDの指定がない場合は指定しない
9510             if (_reply_to_id == null) return;
9511
9512             // リプライ先ユーザー名がない場合も指定しない
9513             if (string.IsNullOrEmpty(_reply_to_name))
9514             {
9515                 _reply_to_id = null;
9516                 return;
9517             }
9518
9519             // 通常Reply
9520             // 次の条件を満たす場合に in_reply_to_status_id 指定
9521             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9522             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9523             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9524
9525             if (m != null)
9526             {
9527                 if (StatusText.StartsWith("@"))
9528                 {
9529                     if (StatusText.StartsWith("@" + _reply_to_name)) return;
9530                 }
9531                 else
9532                 {
9533                     foreach (Match mid in m)
9534                     {
9535                         if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9536                     }
9537                 }
9538             }
9539
9540             _reply_to_id = null;
9541             _reply_to_name = null;
9542
9543         }
9544
9545         private void TweenMain_Resize(object sender, EventArgs e)
9546         {
9547             if (!_initialLayout && SettingDialog.MinimizeToTray && WindowState == FormWindowState.Minimized)
9548             {
9549                 this.Visible = false;
9550             }
9551             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9552             {
9553                 this.ClientSize = _cfgLocal.FormSize;
9554                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9555                 this.DesktopLocation = _cfgLocal.FormLocation;
9556                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9557                 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9558                     _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9559                 {
9560                     this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9561                 }
9562                 //発言欄複数行
9563                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9564                 if (StatusText.Multiline)
9565                 {
9566                     int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9567                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9568                     {
9569                         SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9570                     }
9571                     StatusText.Height = _cfgLocal.StatusTextHeight;
9572                 }
9573                 else
9574                 {
9575                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9576                     {
9577                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9578                     }
9579                 }
9580                 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9581                 {
9582                     this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9583                 }
9584                 _initialLayout = false;
9585             }
9586             if (this.WindowState != FormWindowState.Minimized)
9587             {
9588                 _formWindowState = this.WindowState;
9589             }
9590         }
9591
9592         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9593         {
9594             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9595             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9596             if (PlaySoundMenuItem.Checked)
9597             {
9598                 SettingDialog.PlaySound = true;
9599             }
9600             else
9601             {
9602                 SettingDialog.PlaySound = false;
9603             }
9604             _modifySettingCommon = true;
9605         }
9606
9607         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9608         {
9609             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9610             {
9611                 _mySpDis = SplitContainer1.SplitterDistance;
9612                 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9613                 _modifySettingLocal = true;
9614             }
9615         }
9616
9617         private void doRepliedStatusOpen()
9618         {
9619             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9620             {
9621                 if (MyCommon.IsKeyDown(Keys.Shift))
9622                 {
9623                     OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9624                     return;
9625                 }
9626                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9627                 {
9628                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9629                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9630                 }
9631                 else
9632                 {
9633                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9634                     {
9635                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9636                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9637                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9638                         return;
9639                     }
9640                     OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9641                 }
9642             }
9643         }
9644
9645         private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9646         {
9647             doRepliedStatusOpen();
9648         }
9649
9650         /// <summary>
9651         /// UserPicture.Image に設定されている画像を破棄します。
9652         /// </summary>
9653         private void ClearUserPicture()
9654         {
9655             if (this.UserPicture.Image != null)
9656             {
9657                 var oldImage = this.UserPicture.Image;
9658                 this.UserPicture.Image = null;
9659                 oldImage.Dispose();
9660             }
9661         }
9662
9663         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9664         {
9665             //発言詳細のアイコン右クリック時のメニュー制御
9666             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9667             {
9668                 string name = _curPost.ImageUrl;
9669                 if (name != null && name.Length > 0)
9670                 {
9671                     int idx = name.LastIndexOf('/');
9672                     if (idx != -1)
9673                     {
9674                         name = Path.GetFileName(name.Substring(idx));
9675                         if (name.Contains("_normal.") || name.EndsWith("_normal"))
9676                         {
9677                             name = name.Replace("_normal", "");
9678                             this.IconNameToolStripMenuItem.Text = name;
9679                             this.IconNameToolStripMenuItem.Enabled = true;
9680                         }
9681                         else
9682                         {
9683                             this.IconNameToolStripMenuItem.Enabled = false;
9684                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9685                         }
9686                     }
9687                     else
9688                     {
9689                         this.IconNameToolStripMenuItem.Enabled = false;
9690                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9691                     }
9692
9693                     this.ReloadIconToolStripMenuItem.Enabled = true;
9694
9695                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9696                     {
9697                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9698                     }
9699                     else
9700                     {
9701                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9702                     }
9703                 }
9704                 else
9705                 {
9706                     this.IconNameToolStripMenuItem.Enabled = false;
9707                     this.ReloadIconToolStripMenuItem.Enabled = false;
9708                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9709                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9710                 }
9711             }
9712             else
9713             {
9714                 this.IconNameToolStripMenuItem.Enabled = false;
9715                 this.ReloadIconToolStripMenuItem.Enabled = false;
9716                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9717                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9718             }
9719             if (NameLabel.Tag != null)
9720             {
9721                 string id = (string)NameLabel.Tag;
9722                 if (id == tw.Username)
9723                 {
9724                     FollowToolStripMenuItem.Enabled = false;
9725                     UnFollowToolStripMenuItem.Enabled = false;
9726                     ShowFriendShipToolStripMenuItem.Enabled = false;
9727                     ShowUserStatusToolStripMenuItem.Enabled = true;
9728                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9729                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9730                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9731                 }
9732                 else
9733                 {
9734                     FollowToolStripMenuItem.Enabled = true;
9735                     UnFollowToolStripMenuItem.Enabled = true;
9736                     ShowFriendShipToolStripMenuItem.Enabled = true;
9737                     ShowUserStatusToolStripMenuItem.Enabled = true;
9738                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9739                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9740                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9741                 }
9742             }
9743             else
9744             {
9745                 FollowToolStripMenuItem.Enabled = false;
9746                 UnFollowToolStripMenuItem.Enabled = false;
9747                 ShowFriendShipToolStripMenuItem.Enabled = false;
9748                 ShowUserStatusToolStripMenuItem.Enabled = false;
9749                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9750                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9751                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9752             }
9753         }
9754
9755         private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9756         {
9757             if (_curPost == null) return;
9758             string name = _curPost.ImageUrl;
9759             OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9760         }
9761
9762         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9763         {
9764             if (this._curPost == null) return;
9765
9766             var imageUrl = this._curPost.ImageUrl;
9767             try
9768             {
9769                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true);
9770
9771                 this.ClearUserPicture();
9772                 this.UserPicture.Image = image.Clone();
9773             }
9774             catch (Exception)
9775             {
9776                 this.UserPicture.ShowErrorImage();
9777                 try
9778                 {
9779                     throw;
9780                 }
9781                 catch (HttpRequestException) { }
9782                 catch (InvalidImageException) { }
9783                 catch (TaskCanceledException) { }
9784             }
9785         }
9786
9787         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9788         {
9789             if (_curPost == null) return;
9790             string name = _curPost.ImageUrl;
9791             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9792
9793             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9794
9795             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9796             {
9797                 // STUB
9798             }
9799         }
9800
9801         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9802         {
9803             if (_curPost == null) return;
9804             string name = _curPost.ImageUrl;
9805
9806             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9807
9808             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9809             {
9810                 try
9811                 {
9812                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9813                     {
9814                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9815                         {
9816                             using (Graphics g = Graphics.FromImage(bmp2))
9817                             {
9818                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9819                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9820                             }
9821                             bmp2.Save(this.SaveFileDialog1.FileName);
9822                         }
9823                     }
9824                 }
9825                 catch (Exception)
9826                 {
9827                     //処理中にキャッシュアウトする可能性あり
9828                 }
9829             }
9830         }
9831
9832         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9833         {
9834             this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9835             MultiLineMenuItem.Checked = this.StatusText.Multiline;
9836             _modifySettingLocal = true;
9837         }
9838
9839         private void StatusText_MultilineChanged(object sender, EventArgs e)
9840         {
9841             if (this.StatusText.Multiline)
9842                 this.StatusText.ScrollBars = ScrollBars.Vertical;
9843             else
9844                 this.StatusText.ScrollBars = ScrollBars.None;
9845
9846             _modifySettingLocal = true;
9847         }
9848
9849         private void MultiLineMenuItem_Click(object sender, EventArgs e)
9850         {
9851             //発言欄複数行
9852             StatusText.Multiline = MultiLineMenuItem.Checked;
9853             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9854             if (MultiLineMenuItem.Checked)
9855             {
9856                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9857                     SplitContainer2.SplitterDistance = 0;
9858                 else
9859                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9860             }
9861             else
9862             {
9863                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9864             }
9865             _modifySettingLocal = true;
9866         }
9867
9868         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9869         {
9870             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9871             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9872
9873             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9874             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9875             //Appendix A.  Collected ABNF for URI
9876             //http://www.ietf.org/rfc/rfc3986.txt
9877
9878             string result = "";
9879
9880             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9881
9882             if (StatusText.SelectionLength > 0)
9883             {
9884                 string tmp = StatusText.SelectedText;
9885                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9886                 if (tmp.StartsWith("http"))
9887                 {
9888                     // 文字列が選択されている場合はその文字列について処理
9889
9890                     //nico.ms使用、nicovideoにマッチしたら変換
9891                     if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9892                     {
9893                         result = nicoms.Shorten(tmp);
9894                     }
9895                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9896                     {
9897                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9898                         try
9899                         {
9900                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9901                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9902                             result = resultUri.ToString();
9903                         }
9904                         catch (WebApiException e)
9905                         {
9906                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9907                             return false;
9908                         }
9909                         catch (UriFormatException e)
9910                         {
9911                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9912                             return false;
9913                         }
9914                     }
9915                     else
9916                     {
9917                         return true;
9918                     }
9919
9920                     if (!string.IsNullOrEmpty(result))
9921                     {
9922                         urlUndo undotmp = new urlUndo();
9923
9924                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9925                         StatusText.SelectedText = result;
9926
9927                         //undoバッファにセット
9928                         undotmp.Before = tmp;
9929                         undotmp.After = result;
9930
9931                         if (urlUndoBuffer == null)
9932                         {
9933                             urlUndoBuffer = new List<urlUndo>();
9934                             UrlUndoToolStripMenuItem.Enabled = true;
9935                         }
9936
9937                         urlUndoBuffer.Add(undotmp);
9938                     }
9939                 }
9940             }
9941             else
9942             {
9943                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9944                                    @"(?<url>(?<protocol>https?://)" +
9945                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9946                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9947                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9948                 // 正規表現にマッチしたURL文字列をtinyurl化
9949                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9950                 {
9951                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9952                     string tmp = mt.Result("${url}");
9953                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9954                     urlUndo undotmp = new urlUndo();
9955
9956                     //選んだURLを選択(?)
9957                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9958
9959                     //nico.ms使用、nicovideoにマッチしたら変換
9960                     if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9961                     {
9962                         result = nicoms.Shorten(tmp);
9963                     }
9964                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9965                     {
9966                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9967                         try
9968                         {
9969                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9970                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9971                             result = resultUri.ToString();
9972                         }
9973                         catch (WebApiException e)
9974                         {
9975                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9976                             continue;
9977                         }
9978                         catch (UriFormatException e)
9979                         {
9980                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9981                             continue;
9982                         }
9983                     }
9984                     else
9985                     {
9986                         continue;
9987                     }
9988
9989                     if (!string.IsNullOrEmpty(result))
9990                     {
9991                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9992                         StatusText.SelectedText = result;
9993                         //undoバッファにセット
9994                         undotmp.Before = mt.Result("${url}");
9995                         undotmp.After = result;
9996
9997                         if (urlUndoBuffer == null)
9998                         {
9999                             urlUndoBuffer = new List<urlUndo>();
10000                             UrlUndoToolStripMenuItem.Enabled = true;
10001                         }
10002
10003                         urlUndoBuffer.Add(undotmp);
10004                     }
10005                 }
10006             }
10007
10008             return true;
10009         }
10010
10011         private void doUrlUndo()
10012         {
10013             if (urlUndoBuffer != null)
10014             {
10015                 string tmp = StatusText.Text;
10016                 foreach (urlUndo data in urlUndoBuffer)
10017                 {
10018                     tmp = tmp.Replace(data.After, data.Before);
10019                 }
10020                 StatusText.Text = tmp;
10021                 urlUndoBuffer = null;
10022                 UrlUndoToolStripMenuItem.Enabled = false;
10023                 StatusText.SelectionStart = 0;
10024                 StatusText.SelectionLength = 0;
10025             }
10026         }
10027
10028         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10029         {
10030             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10031         }
10032
10033         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10034         {
10035             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10036         }
10037
10038         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10039         {
10040             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10041         }
10042
10043         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10044         {
10045             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10046         }
10047
10048         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10049         {
10050             if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
10051             {
10052                 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
10053                 Random rnd = new Random();
10054                 // 前回使用した短縮URLサービス以外を選択する
10055                 do
10056                 {
10057                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10058                 }
10059                 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10060                 await UrlConvertAsync(svc);
10061             }
10062         }
10063
10064         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10065         {
10066             doUrlUndo();
10067         }
10068
10069         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10070         {
10071             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10072             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10073             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10074             _modifySettingCommon = true;
10075         }
10076
10077         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10078         {
10079             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10080             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10081             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10082             _modifySettingCommon = true;
10083         }
10084
10085         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10086         {
10087             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10088             MenuStrip1.Tag = new Object();
10089             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10090         }
10091
10092         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10093         {
10094             if (this.Tag != null) // 設定された戻り先へ遷移
10095             {
10096                 if (this.Tag == this.ListTab.SelectedTab)
10097                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10098                 else
10099                     ((Control)this.Tag).Select();
10100             }
10101             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10102             {
10103                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10104                 {
10105                     this.Tag = ListTab.SelectedTab.Tag;
10106                     ((Control)this.Tag).Select();
10107                 }
10108             }
10109             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10110             MenuStrip1.Tag = null;
10111         }
10112
10113         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10114         {
10115             DetailsListView lst = (DetailsListView)sender;
10116             if (_cfgLocal == null) return;
10117
10118             if (_iconCol)
10119             {
10120                 _cfgLocal.Width1 = lst.Columns[0].Width;
10121                 _cfgLocal.Width3 = lst.Columns[1].Width;
10122             }
10123             else
10124             {
10125                 int[] darr = new int[lst.Columns.Count];
10126                 for (int i = 0; i < lst.Columns.Count; i++)
10127                 {
10128                     darr[lst.Columns[i].DisplayIndex] = i;
10129                 }
10130                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10131
10132                 for (int i = 0; i < lst.Columns.Count; i++)
10133                 {
10134                     switch (darr[i])
10135                     {
10136                         case 0:
10137                             _cfgLocal.DisplayIndex1 = i;
10138                             break;
10139                         case 1:
10140                             _cfgLocal.DisplayIndex2 = i;
10141                             break;
10142                         case 2:
10143                             _cfgLocal.DisplayIndex3 = i;
10144                             break;
10145                         case 3:
10146                             _cfgLocal.DisplayIndex4 = i;
10147                             break;
10148                         case 4:
10149                             _cfgLocal.DisplayIndex5 = i;
10150                             break;
10151                         case 5:
10152                             _cfgLocal.DisplayIndex6 = i;
10153                             break;
10154                         case 6:
10155                             _cfgLocal.DisplayIndex7 = i;
10156                             break;
10157                         case 7:
10158                             _cfgLocal.DisplayIndex8 = i;
10159                             break;
10160                     }
10161                 }
10162                 _cfgLocal.Width1 = lst.Columns[0].Width;
10163                 _cfgLocal.Width2 = lst.Columns[1].Width;
10164                 _cfgLocal.Width3 = lst.Columns[2].Width;
10165                 _cfgLocal.Width4 = lst.Columns[3].Width;
10166                 _cfgLocal.Width5 = lst.Columns[4].Width;
10167                 _cfgLocal.Width6 = lst.Columns[5].Width;
10168                 _cfgLocal.Width7 = lst.Columns[6].Width;
10169                 _cfgLocal.Width8 = lst.Columns[7].Width;
10170             }
10171             _modifySettingLocal = true;
10172             _isColumnChanged = true;
10173         }
10174
10175         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10176         {
10177             DetailsListView lst = (DetailsListView)sender;
10178             if (_cfgLocal == null) return;
10179             if (_iconCol)
10180             {
10181                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10182                 {
10183                     _cfgLocal.Width1 = lst.Columns[0].Width;
10184                     _modifySettingLocal = true;
10185                     _isColumnChanged = true;
10186                 }
10187                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10188                 {
10189                     _cfgLocal.Width3 = lst.Columns[1].Width;
10190                     _modifySettingLocal = true;
10191                     _isColumnChanged = true;
10192                 }
10193             }
10194             else
10195             {
10196                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10197                 {
10198                     _cfgLocal.Width1 = lst.Columns[0].Width;
10199                     _modifySettingLocal = true;
10200                     _isColumnChanged = true;
10201                 }
10202                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10203                 {
10204                     _cfgLocal.Width2 = lst.Columns[1].Width;
10205                     _modifySettingLocal = true;
10206                     _isColumnChanged = true;
10207                 }
10208                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10209                 {
10210                     _cfgLocal.Width3 = lst.Columns[2].Width;
10211                     _modifySettingLocal = true;
10212                     _isColumnChanged = true;
10213                 }
10214                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10215                 {
10216                     _cfgLocal.Width4 = lst.Columns[3].Width;
10217                     _modifySettingLocal = true;
10218                     _isColumnChanged = true;
10219                 }
10220                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10221                 {
10222                     _cfgLocal.Width5 = lst.Columns[4].Width;
10223                     _modifySettingLocal = true;
10224                     _isColumnChanged = true;
10225                 }
10226                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10227                 {
10228                     _cfgLocal.Width6 = lst.Columns[5].Width;
10229                     _modifySettingLocal = true;
10230                     _isColumnChanged = true;
10231                 }
10232                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10233                 {
10234                     _cfgLocal.Width7 = lst.Columns[6].Width;
10235                     _modifySettingLocal = true;
10236                     _isColumnChanged = true;
10237                 }
10238                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10239                 {
10240                     _cfgLocal.Width8 = lst.Columns[7].Width;
10241                     _modifySettingLocal = true;
10242                     _isColumnChanged = true;
10243                 }
10244             }
10245             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10246             //if (changed)
10247             //{
10248             //    SaveConfigsLocal();
10249             //}
10250         }
10251
10252         public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10253         {
10254             //発言詳細で「選択文字列をコピー」を行う
10255             //WebBrowserコンポーネントのインスタンスを渡す
10256             Type typ = ComponentInstance.ActiveXInstance.GetType();
10257             object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10258             object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10259             return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10260         }
10261
10262         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10263         {
10264             //発言詳細で「選択文字列をコピー」
10265             string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10266             try
10267             {
10268                 Clipboard.SetDataObject(_selText, false, 5, 100);
10269             }
10270             catch (Exception ex)
10271             {
10272                 MessageBox.Show(ex.Message);
10273             }
10274         }
10275
10276         private void doSearchToolStrip(string url)
10277         {
10278             //発言詳細で「選択文字列で検索」(選択文字列取得)
10279             string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10280
10281             if (_selText != null)
10282             {
10283                 if (url == Properties.Resources.SearchItem4Url)
10284                 {
10285                     //公式検索
10286                     AddNewTabForSearch(_selText);
10287                     return;
10288                 }
10289
10290                 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10291                 OpenUriAsync(tmp);
10292             }
10293         }
10294
10295         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10296         {
10297             //発言詳細ですべて選択
10298             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10299         }
10300
10301         private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10302         {
10303             doSearchToolStrip(Properties.Resources.SearchItem1Url);
10304         }
10305
10306         private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10307         {
10308             doSearchToolStrip(Properties.Resources.SearchItem2Url);
10309         }
10310
10311         private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10312         {
10313             doSearchToolStrip(Properties.Resources.SearchItem4Url);
10314         }
10315
10316         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10317         {
10318             try
10319             {
10320                 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10321                 foreach (Match m in mc)
10322                 {
10323                     if (m.Groups["url"].Value == this._postBrowserStatusText)
10324                     {
10325                         Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10326                         break;
10327                     }
10328                 }
10329                 if (mc.Count == 0)
10330                 {
10331                     Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10332                 }
10333                 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10334             }
10335             catch (Exception ex)
10336             {
10337                 MessageBox.Show(ex.Message);
10338             }
10339         }
10340
10341         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10342         {
10343             // URLコピーの項目の表示/非表示
10344             if (PostBrowser.StatusText.StartsWith("http"))
10345             {
10346                 this._postBrowserStatusText = PostBrowser.StatusText;
10347                 string name = GetUserId();
10348                 UrlCopyContextMenuItem.Enabled = true;
10349                 if (name != null)
10350                 {
10351                     FollowContextMenuItem.Enabled = true;
10352                     RemoveContextMenuItem.Enabled = true;
10353                     FriendshipContextMenuItem.Enabled = true;
10354                     ShowUserStatusContextMenuItem.Enabled = true;
10355                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10356                     IdFilterAddMenuItem.Enabled = true;
10357                     ListManageUserContextToolStripMenuItem.Enabled = true;
10358                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10359                 }
10360                 else
10361                 {
10362                     FollowContextMenuItem.Enabled = false;
10363                     RemoveContextMenuItem.Enabled = false;
10364                     FriendshipContextMenuItem.Enabled = false;
10365                     ShowUserStatusContextMenuItem.Enabled = false;
10366                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10367                     IdFilterAddMenuItem.Enabled = false;
10368                     ListManageUserContextToolStripMenuItem.Enabled = false;
10369                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10370                 }
10371
10372                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10373                     UseHashtagMenuItem.Enabled = true;
10374                 else
10375                     UseHashtagMenuItem.Enabled = false;
10376             }
10377             else
10378             {
10379                 this._postBrowserStatusText = "";
10380                 UrlCopyContextMenuItem.Enabled = false;
10381                 FollowContextMenuItem.Enabled = false;
10382                 RemoveContextMenuItem.Enabled = false;
10383                 FriendshipContextMenuItem.Enabled = false;
10384                 ShowUserStatusContextMenuItem.Enabled = false;
10385                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10386                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10387                 UseHashtagMenuItem.Enabled = false;
10388                 IdFilterAddMenuItem.Enabled = false;
10389                 ListManageUserContextToolStripMenuItem.Enabled = false;
10390             }
10391             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10392             string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10393             if (_selText == null)
10394             {
10395                 SelectionSearchContextMenuItem.Enabled = false;
10396                 SelectionCopyContextMenuItem.Enabled = false;
10397                 SelectionTranslationToolStripMenuItem.Enabled = false;
10398             }
10399             else
10400             {
10401                 SelectionSearchContextMenuItem.Enabled = true;
10402                 SelectionCopyContextMenuItem.Enabled = true;
10403                 SelectionTranslationToolStripMenuItem.Enabled = true;
10404             }
10405             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10406             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10407             bool fAllFlag = false;
10408             foreach (Match mu in ma)
10409             {
10410                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10411                 {
10412                     fAllFlag = true;
10413                     break;
10414                 }
10415             }
10416             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10417
10418             if (_curPost == null)
10419                 TranslationToolStripMenuItem.Enabled = false;
10420             else
10421                 TranslationToolStripMenuItem.Enabled = true;
10422
10423             e.Cancel = false;
10424         }
10425
10426         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10427         {
10428             //発言詳細の選択文字列で現在のタブを検索
10429             string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10430
10431             if (_selText != null)
10432             {
10433                 var searchOptions = new SearchWordDialog.SearchOptions(
10434                     SearchWordDialog.SearchType.Timeline,
10435                     _selText,
10436                     newTab: false,
10437                     caseSensitive: false,
10438                     useRegex: false);
10439
10440                 this.SearchDialog.ResultOptions = searchOptions;
10441
10442                 this.DoTabSearch(
10443                     searchOptions.Query,
10444                     searchOptions.CaseSensitive,
10445                     searchOptions.UseRegex,
10446                     SEARCHTYPE.NextSearch);
10447             }
10448         }
10449
10450         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10451         {
10452             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10453             _modifySettingLocal = true;
10454         }
10455
10456         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10457         {
10458             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10459             {
10460                 SelectMedia_DragDrop(e);
10461             }
10462             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10463             {
10464                 var url = GetUrlFromDataObject(e.Data);
10465
10466                 string appendText;
10467                 if (url.Item2 == null)
10468                     appendText = url.Item1;
10469                 else
10470                     appendText = url.Item2 + " " + url.Item1;
10471
10472                 if (this.StatusText.TextLength == 0)
10473                     this.StatusText.Text = appendText;
10474                 else
10475                     this.StatusText.Text += " " + appendText;
10476             }
10477             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10478             {
10479                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10480                 if (data != null) StatusText.Text += data;
10481             }
10482         }
10483
10484         /// <summary>
10485         /// IDataObject から URL とタイトルの対を取得します
10486         /// </summary>
10487         /// <remarks>
10488         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10489         /// </remarks>
10490         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10491         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10492         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10493         {
10494             if (data.GetDataPresent("text/x-moz-url"))
10495             {
10496                 // Firefox, Google Chrome で利用可能
10497                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10498
10499                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10500                 {
10501                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10502                     if (lines.Length < 2)
10503                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10504
10505                     return new Tuple<string, string>(lines[0], lines[1]);
10506                 }
10507             }
10508             else if (data.GetDataPresent("IESiteModeToUrl"))
10509             {
10510                 // Internet Exproler 用
10511                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10512
10513                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10514                 {
10515                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10516                     if (lines.Length < 2)
10517                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10518
10519                     return new Tuple<string, string>(lines[0], lines[1]);
10520                 }
10521             }
10522             else if (data.GetDataPresent("UniformResourceLocatorW"))
10523             {
10524                 // それ以外のブラウザ向け
10525
10526                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10527                 {
10528                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10529                     return new Tuple<string, string>(url, null);
10530                 }
10531             }
10532
10533             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10534         }
10535
10536         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10537         {
10538             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10539             {
10540                 SelectMedia_DragEnter(e);
10541             }
10542         }
10543
10544         private void TweenMain_DragOver(object sender, DragEventArgs e)
10545         {
10546             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10547             {
10548                 SelectMedia_DragOver(e);
10549             }
10550             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10551             {
10552                 e.Effect = DragDropEffects.Copy;
10553             }
10554             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10555             {
10556                 e.Effect = DragDropEffects.Copy;
10557             }
10558             else
10559             {
10560                 e.Effect = DragDropEffects.None;
10561             }
10562         }
10563
10564         public bool IsNetworkAvailable()
10565         {
10566             bool nw = true;
10567             nw = MyCommon.IsNetworkAvailable();
10568             _myStatusOnline = nw;
10569             return nw;
10570         }
10571
10572         public Task OpenUriAsync(string UriString)
10573         {
10574             return Task.Run(() =>
10575             {
10576                 string myPath = UriString;
10577
10578                 try
10579                 {
10580                     var configBrowserPath = SettingDialog.BrowserPath;
10581                     if (!string.IsNullOrEmpty(configBrowserPath))
10582                     {
10583                         if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10584                         {
10585                             int sep = configBrowserPath.IndexOf("\"", 2);
10586                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10587                             string arg = "";
10588                             if (sep < configBrowserPath.Length - 1)
10589                             {
10590                                 arg = configBrowserPath.Substring(sep + 1);
10591                             }
10592                             myPath = arg + " " + myPath;
10593                             System.Diagnostics.Process.Start(browserPath, myPath);
10594                         }
10595                         else
10596                         {
10597                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10598                         }
10599                     }
10600                     else
10601                     {
10602                         System.Diagnostics.Process.Start(myPath);
10603                     }
10604                 }
10605                 catch (Exception)
10606                 {
10607                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10608                 }
10609             });
10610         }
10611
10612         private void ListTabSelect(TabPage _tab)
10613         {
10614             SetListProperty();
10615
10616             this.PurgeListViewItemCache();
10617
10618             _curTab = _tab;
10619             _curList = (DetailsListView)_tab.Tag;
10620             if (_curList.SelectedIndices.Count > 0)
10621             {
10622                 _curItemIndex = _curList.SelectedIndices[0];
10623                 _curPost = GetCurTabPost(_curItemIndex);
10624             }
10625             else
10626             {
10627                 _curItemIndex = -1;
10628                 _curPost = null;
10629             }
10630
10631             _anchorPost = null;
10632             _anchorFlag = false;
10633
10634             if (_iconCol)
10635             {
10636                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10637             }
10638             else
10639             {
10640                 for (int i = 0; i < _curList.Columns.Count; i++)
10641                 {
10642                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10643                 }
10644             }
10645         }
10646
10647         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10648         {
10649             ListTabSelect(e.TabPage);
10650         }
10651
10652         private void SelectListItem(DetailsListView LView, int Index)
10653         {
10654             //単一
10655             Rectangle bnd = new Rectangle();
10656             bool flg = false;
10657             var item = LView.FocusedItem;
10658             if (item != null)
10659             {
10660                 bnd = item.Bounds;
10661                 flg = true;
10662             }
10663
10664             do
10665             {
10666                 LView.SelectedIndices.Clear();
10667             }
10668             while (LView.SelectedIndices.Count > 0);
10669             item = LView.Items[Index];
10670             item.Selected = true;
10671             item.Focused = true;
10672
10673             if (flg) LView.Invalidate(bnd);
10674         }
10675
10676         private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10677         {
10678             //複数
10679             Rectangle bnd = new Rectangle();
10680             bool flg = false;
10681             var item = LView.FocusedItem;
10682             if (item != null)
10683             {
10684                 bnd = item.Bounds;
10685                 flg = true;
10686             }
10687
10688             int fIdx = -1;
10689             if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10690             {
10691                 do
10692                 {
10693                     LView.SelectedIndices.Clear();
10694                 }
10695                 while (LView.SelectedIndices.Count > 0);
10696                 foreach (int idx in Index)
10697                 {
10698                     if (idx > -1 && LView.VirtualListSize > idx)
10699                     {
10700                         LView.SelectedIndices.Add(idx);
10701                         if (fIdx == -1) fIdx = idx;
10702                     }
10703                 }
10704             }
10705             if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10706             {
10707                 LView.SelectionMark = FocusedIndex[1];
10708             }
10709             if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10710             {
10711                 LView.Items[FocusedIndex[0]].Focused = true;
10712             }
10713             else if (fIdx > -1)
10714             {
10715                 LView.Items[fIdx].Focused = true;
10716             }
10717
10718             if (flg) LView.Invalidate(bnd);
10719         }
10720
10721         private void RunAsync(GetWorkerArg args)
10722         {
10723             BackgroundWorker bw = null;
10724             if (args.type != MyCommon.WORKERTYPE.Follower)
10725             {
10726                 for (int i = 0; i < _bw.Length; i++)
10727                 {
10728                     if (_bw[i] != null && !_bw[i].IsBusy)
10729                     {
10730                         bw = _bw[i];
10731                         break;
10732                     }
10733                 }
10734                 if (bw == null)
10735                 {
10736                     for (int i = 0; i < _bw.Length; i++)
10737                     {
10738                         if (_bw[i] == null)
10739                         {
10740                             _bw[i] = new BackgroundWorker();
10741                             bw = _bw[i];
10742                             bw.WorkerReportsProgress = true;
10743                             bw.WorkerSupportsCancellation = true;
10744                             bw.DoWork += GetTimelineWorker_DoWork;
10745                             bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10746                             bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10747                             break;
10748                         }
10749                     }
10750                 }
10751             }
10752             else
10753             {
10754                 if (_bwFollower == null)
10755                 {
10756                     _bwFollower = new BackgroundWorker();
10757                     bw = _bwFollower;
10758                     bw.WorkerReportsProgress = true;
10759                     bw.WorkerSupportsCancellation = true;
10760                     bw.DoWork += GetTimelineWorker_DoWork;
10761                     bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10762                     bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10763                 }
10764                 else
10765                 {
10766                     if (_bwFollower.IsBusy == false)
10767                         bw = _bwFollower;
10768                 }
10769             }
10770             if (bw == null) return;
10771
10772             bw.RunWorkerAsync(args);
10773         }
10774
10775         private void StartUserStream()
10776         {
10777             tw.NewPostFromStream += tw_NewPostFromStream;
10778             tw.UserStreamStarted += tw_UserStreamStarted;
10779             tw.UserStreamStopped += tw_UserStreamStopped;
10780             tw.PostDeleted += tw_PostDeleted;
10781             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10782
10783             MenuItemUserStream.Text = "&UserStream ■";
10784             MenuItemUserStream.Enabled = true;
10785             StopToolStripMenuItem.Text = "&Start";
10786             StopToolStripMenuItem.Enabled = true;
10787             if (SettingDialog.UserstreamStartup) tw.StartUserStream();
10788         }
10789
10790         private async void TweenMain_Shown(object sender, EventArgs e)
10791         {
10792             try
10793             {
10794                 PostBrowser.Url = new Uri("about:blank");
10795                 PostBrowser.DocumentText = "";       //発言詳細部初期化
10796             }
10797             catch (Exception)
10798             {
10799             }
10800
10801             NotifyIcon1.Visible = true;
10802
10803             if (this.IsNetworkAvailable())
10804             {
10805                 this.RefreshMuteUserIdsAsync();
10806                 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, 0, "");
10807                 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10808                 if (SettingDialog.StartupFollowers)
10809                 {
10810                     GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10811                 }
10812                 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10813                 StartUserStream();
10814                 _waitTimeline = true;
10815                 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 1, "");
10816                 _waitReply = true;
10817                 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 1, "");
10818                 _waitDm = true;
10819                 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 1, "");
10820                 if (SettingDialog.GetFav)
10821                 {
10822                     _waitFav = true;
10823                     GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 1, "");
10824                 }
10825                 _waitPubSearch = true;
10826                 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");  //tabname="":全タブ
10827                 _waitUserTimeline = true;
10828                 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");  //tabname="":全タブ
10829                 _waitLists = true;
10830                 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");  //tabname="":全タブ
10831
10832                 var i = 0;
10833                 while (this.IsInitialRead())
10834                 {
10835                     await Task.Delay(5000);
10836
10837                     i += 1;
10838                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10839
10840                     if (MyCommon._endingFlag)
10841                         return;
10842                 }
10843
10844                 if (MyCommon._endingFlag) return;
10845
10846                 if (ApplicationSettings.VersionInfoUrl != null)
10847                 {
10848                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10849                     if (SettingDialog.StartupVersion)
10850                         await this.CheckNewVersion(true);
10851                 }
10852                 else
10853                 {
10854                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10855                     this.VerUpMenuItem.Enabled = false;
10856                     this.VerUpMenuItem.Available = false;
10857                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10858                 }
10859
10860                 // 取得失敗の場合は再試行する
10861                 if (!tw.GetFollowersSuccess && SettingDialog.StartupFollowers)
10862                     GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10863
10864                 // 取得失敗の場合は再試行する
10865                 if (!tw.GetNoRetweetSuccess)
10866                     GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10867
10868                 // 取得失敗の場合は再試行する
10869                 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10870                     GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10871
10872                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10873                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10874                 {
10875                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
10876                     SettingStripMenuItem_Click(null, null);
10877                 }
10878
10879                 //
10880             }
10881             _initial = false;
10882
10883             TimerTimeline.Enabled = true;
10884         }
10885
10886         private bool IsInitialRead()
10887         {
10888             return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10889         }
10890
10891         private void doGetFollowersMenu()
10892         {
10893             GetTimeline(MyCommon.WORKERTYPE.Follower, 1, 0, "");
10894             DispSelectedPost(true);
10895         }
10896
10897         private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10898         {
10899             doGetFollowersMenu();
10900         }
10901
10902         private void doReTweetUnofficial()
10903         {
10904             //RT @id:内容
10905             if (this.ExistCurrentPost)
10906             {
10907                 if (_curPost.IsDm ||
10908                     !StatusText.Enabled) return;
10909
10910                 if (_curPost.IsProtect)
10911                 {
10912                     MessageBox.Show("Protected.");
10913                     return;
10914                 }
10915                 string rtdata = _curPost.Text;
10916                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10917
10918                 this._reply_to_id = null;
10919                 this._reply_to_name = null;
10920
10921                 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10922
10923                 StatusText.SelectionStart = 0;
10924                 StatusText.Focus();
10925             }
10926         }
10927
10928         private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10929         {
10930             doReTweetUnofficial();
10931         }
10932
10933         private void doReTweetOfficial(bool isConfirm)
10934         {
10935             //公式RT
10936             if (this.ExistCurrentPost)
10937             {
10938                 if (_curPost.IsProtect)
10939                 {
10940                     MessageBox.Show("Protected.");
10941                     _DoFavRetweetFlags = false;
10942                     return;
10943                 }
10944                 if (_curList.SelectedIndices.Count > 15)
10945                 {
10946                     MessageBox.Show(Properties.Resources.RetweetLimitText);
10947                     _DoFavRetweetFlags = false;
10948                     return;
10949                 }
10950                 else if (_curList.SelectedIndices.Count > 1)
10951                 {
10952                     string QuestionText = Properties.Resources.RetweetQuestion2;
10953                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10954                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10955                     {
10956                         case DialogResult.Cancel:
10957                         case DialogResult.No:
10958                             _DoFavRetweetFlags = false;
10959                             return;
10960                     }
10961                 }
10962                 else
10963                 {
10964                     if (_curPost.IsDm || _curPost.IsMe)
10965                     {
10966                         _DoFavRetweetFlags = false;
10967                         return;
10968                     }
10969                     if (!SettingDialog.RetweetNoConfirm)
10970                     {
10971                         string Questiontext = Properties.Resources.RetweetQuestion1;
10972                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10973                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10974                         {
10975                             _DoFavRetweetFlags = false;
10976                             return;
10977                         }
10978                     }
10979                 }
10980                 GetWorkerArg args = new GetWorkerArg();
10981                 args.ids = new List<long>();
10982                 args.sIds = new List<long>();
10983                 args.tName = _curTab.Text;
10984                 args.type = MyCommon.WORKERTYPE.Retweet;
10985                 foreach (int idx in _curList.SelectedIndices)
10986                 {
10987                     PostClass post = GetCurTabPost(idx);
10988                     if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10989                 }
10990                 RunAsync(args);
10991             }
10992         }
10993
10994         private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10995         {
10996             doReTweetOfficial(true);
10997         }
10998
10999         private void FavoritesRetweetOriginal()
11000         {
11001             if (!this.ExistCurrentPost) return;
11002             _DoFavRetweetFlags = true;
11003             doReTweetOfficial(true);
11004             if (_DoFavRetweetFlags)
11005             {
11006                 _DoFavRetweetFlags = false;
11007                 FavoriteChange(true, false);
11008             }
11009         }
11010
11011         private void FavoritesRetweetUnofficial()
11012         {
11013             if (this.ExistCurrentPost && !_curPost.IsDm)
11014             {
11015                 _DoFavRetweetFlags = true;
11016                 FavoriteChange(true);
11017                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11018                 {
11019                     _DoFavRetweetFlags = false;
11020                     doReTweetUnofficial();
11021                 }
11022             }
11023         }
11024
11025         /// <summary>
11026         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11027         /// </summary>
11028         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11029         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11030         /// <returns>復元されたツイート本文</returns>
11031         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11032         {
11033             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11034
11035             // 通常の URL
11036             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11037             // メンション
11038             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11039             // ハッシュタグ
11040             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11041
11042             // <br> 除去
11043             if (multiline)
11044                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11045             else
11046                 statusHtml = statusHtml.Replace("<br>", " ");
11047
11048             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11049             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11050             statusHtml = statusHtml.Replace("&nbsp;", " ");
11051
11052             return WebUtility.HtmlDecode(statusHtml);
11053         }
11054
11055         private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11056         {
11057             if (_curPost != null)
11058                 DispSelectedPost(true);
11059         }
11060
11061         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11062         {
11063             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11064                 DebugModeToolStripMenuItem.Visible = true;
11065             else
11066                 DebugModeToolStripMenuItem.Visible = false;
11067         }
11068
11069         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11070         {
11071             SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11072         }
11073
11074         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11075         {
11076             ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
11077         }
11078
11079         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11080         {
11081             if (TraceOutToolStripMenuItem.Checked)
11082                 MyCommon.TraceFlag = true;
11083             else
11084                 MyCommon.TraceFlag = false;
11085         }
11086
11087         private void TweenMain_Deactivate(object sender, EventArgs e)
11088         {
11089             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11090             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11091         }
11092
11093         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11094         {
11095             if (string.IsNullOrEmpty(_rclickTabName)) return;
11096             TabRename(ref _rclickTabName);
11097         }
11098
11099         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11100         {
11101             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11102         }
11103
11104         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11105         {
11106             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11107         }
11108
11109
11110         private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11111         {
11112             e.Result = tw.GetInfoApi();
11113         }
11114
11115         private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11116         {
11117             StringBuilder tmp = new StringBuilder();
11118
11119             using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11120             {
11121                 dlg.ShowDialog();
11122
11123                 var result = (TwitterApiStatus)dlg.Result;
11124
11125                 if (result == null)
11126                 {
11127                     var accessLevel = result.AccessLevel;
11128                     var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11129                     var mediaLimit = result.MediaUploadLimit;
11130
11131                     tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11132                     tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11133                     tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11134                     tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11135
11136                     tmp.AppendLine();
11137                     tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11138                     SetStatusLabelUrl();
11139
11140                     tmp.AppendLine();
11141                     tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11142                     tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11143                     tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11144                 }
11145                 else
11146                 {
11147                     tmp.Append(Properties.Resources.ApiInfo5);
11148                 }
11149             }
11150
11151             MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11152         }
11153
11154         private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11155         {
11156             string id = "";
11157             if (_curPost != null) id = _curPost.ScreenName;
11158             FollowCommand(id);
11159         }
11160
11161         private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11162         {
11163             FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11164             e.Result = arg.tw.PostFollowCommand(arg.id);
11165         }
11166
11167         private void FollowCommand(string id)
11168         {
11169             using (InputTabName inputName = new InputTabName())
11170             {
11171                 inputName.FormTitle = "Follow";
11172                 inputName.FormDescription = Properties.Resources.FRMessage1;
11173                 inputName.TabName = id;
11174                 if (inputName.ShowDialog() == DialogResult.OK &&
11175                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
11176                 {
11177                     FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11178                     arg.tw = tw;
11179                     arg.id = inputName.TabName.Trim();
11180                     using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11181                                                          FollowCommand_DoWork,
11182                                                          null,
11183                                                          arg))
11184                     {
11185                         _info.ShowDialog();
11186                         string ret = (string)_info.Result;
11187                         if (!string.IsNullOrEmpty(ret))
11188                             MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11189                         else
11190                             MessageBox.Show(Properties.Resources.FRMessage3);
11191                     }
11192                 }
11193             }
11194         }
11195
11196         private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11197         {
11198             string id = "";
11199             if (_curPost != null) id = _curPost.ScreenName;
11200             RemoveCommand(id, false);
11201         }
11202
11203         private class FollowRemoveCommandArgs
11204         {
11205             public Twitter tw;
11206             public string id;
11207         }
11208
11209         private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11210         {
11211             FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11212             e.Result = arg.tw.PostRemoveCommand(arg.id);
11213         }
11214
11215         private void RemoveCommand(string id, bool skipInput)
11216         {
11217             FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11218             arg.tw = tw;
11219             arg.id = id;
11220             if (!skipInput)
11221             {
11222                 using (InputTabName inputName = new InputTabName())
11223                 {
11224                     inputName.FormTitle = "Unfollow";
11225                     inputName.FormDescription = Properties.Resources.FRMessage1;
11226                     inputName.TabName = id;
11227                     if (inputName.ShowDialog() == DialogResult.OK &&
11228                         !string.IsNullOrEmpty(inputName.TabName.Trim()))
11229                     {
11230                         arg.tw = tw;
11231                         arg.id = inputName.TabName.Trim();
11232                     }
11233                     else
11234                     {
11235                         return;
11236                     }
11237                 }
11238             }
11239
11240             using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11241                                                  RemoveCommand_DoWork,
11242                                                  null,
11243                                                  arg))
11244             {
11245                 _info.ShowDialog();
11246                 string ret = (string)_info.Result;
11247                 if (!string.IsNullOrEmpty(ret))
11248                     MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11249                 else
11250                     MessageBox.Show(Properties.Resources.FRMessage3);
11251             }
11252         }
11253
11254         private void FriendshipMenuItem_Click(object sender, EventArgs e)
11255         {
11256             string id = "";
11257             if (_curPost != null)
11258                 id = _curPost.ScreenName;
11259
11260             ShowFriendship(id);
11261         }
11262
11263         private class ShowFriendshipArgs
11264         {
11265             public Twitter tw;
11266             public class FriendshipInfo
11267             {
11268                 public string id = "";
11269                 public bool isFollowing = false;
11270                 public bool isFollowed = false;
11271                 public bool isError = false;
11272                 public FriendshipInfo(string id)
11273                 {
11274                     this.id = id;
11275                 }
11276             }
11277             public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11278         }
11279
11280         private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11281         {
11282             ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11283             string result = "";
11284             foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11285             {
11286                 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11287                 if (!string.IsNullOrEmpty(rt))
11288                 {
11289                     if (string.IsNullOrEmpty(result)) result = rt;
11290                     fInfo.isError = true;
11291                 }
11292             }
11293             e.Result = result;
11294         }
11295
11296         private void ShowFriendship(string id)
11297         {
11298             ShowFriendshipArgs args = new ShowFriendshipArgs();
11299             args.tw = tw;
11300             using (InputTabName inputName = new InputTabName())
11301             {
11302                 inputName.FormTitle = "Show Friendships";
11303                 inputName.FormDescription = Properties.Resources.FRMessage1;
11304                 inputName.TabName = id;
11305                 if (inputName.ShowDialog() == DialogResult.OK &&
11306                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
11307                 {
11308                     string ret = "";
11309                     args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11310                     using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11311                                                          ShowFriendship_DoWork,
11312                                                          null,
11313                                                          args))
11314                     {
11315                         _info.ShowDialog();
11316                         ret = (string)_info.Result;
11317                     }
11318                     string result = "";
11319                     if (string.IsNullOrEmpty(ret))
11320                     {
11321                         if (args.ids[0].isFollowing)
11322                         {
11323                             result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11324                         }
11325                         else
11326                         {
11327                             result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11328                         }
11329                         if (args.ids[0].isFollowed)
11330                         {
11331                             result += Properties.Resources.GetFriendshipInfo3;
11332                         }
11333                         else
11334                         {
11335                             result += Properties.Resources.GetFriendshipInfo4;
11336                         }
11337                         result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11338                     }
11339                     else
11340                     {
11341                         result = ret;
11342                     }
11343                     MessageBox.Show(result);
11344                 }
11345             }
11346         }
11347
11348         private void ShowFriendship(string[] ids)
11349         {
11350             foreach (string id in ids)
11351             {
11352                 string ret = "";
11353                 ShowFriendshipArgs args = new ShowFriendshipArgs();
11354                 args.tw = tw;
11355                 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11356                 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11357                                                      ShowFriendship_DoWork,
11358                                                      null,
11359                                                      args))
11360                 {
11361                     _info.ShowDialog();
11362                     ret = (string)_info.Result;
11363                 }
11364                 string result = "";
11365                 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11366                 string ff = "";
11367                 if (string.IsNullOrEmpty(ret))
11368                 {
11369                     ff = "  ";
11370                     if (fInfo.isFollowing)
11371                     {
11372                         ff += Properties.Resources.GetFriendshipInfo1;
11373                     }
11374                     else
11375                     {
11376                         ff += Properties.Resources.GetFriendshipInfo2;
11377                     }
11378
11379                     ff += System.Environment.NewLine + "  ";
11380                     if (fInfo.isFollowed)
11381                     {
11382                         ff += Properties.Resources.GetFriendshipInfo3;
11383                     }
11384                     else
11385                     {
11386                         ff += Properties.Resources.GetFriendshipInfo4;
11387                     }
11388                     result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11389                     if (fInfo.isFollowing)
11390                     {
11391                         if (MessageBox.Show(
11392                             Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11393                             MessageBoxButtons.YesNo,
11394                             MessageBoxIcon.Question,
11395                             MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11396                         {
11397                             RemoveCommand(fInfo.id, true);
11398                         }
11399                     }
11400                     else
11401                     {
11402                         MessageBox.Show(result);
11403                     }
11404                 }
11405                 else
11406                 {
11407                     MessageBox.Show(ret);
11408                 }
11409             }
11410         }
11411
11412         private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11413         {
11414             doShowUserStatus(tw.Username, false);
11415             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11416             //{
11417             //    doShowUserStatus(tw.Username, false);
11418             //}
11419             //else
11420             //{
11421             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11422             //    return;
11423             //}
11424         }
11425
11426         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11427         // URLから切り出した文字列を渡す
11428
11429         public bool IsTwitterId(string name)
11430         {
11431             if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11432                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11433             else
11434                 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11435         }
11436
11437         private string GetUserId()
11438         {
11439             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11440             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11441                 return m.Result("${ScreenName}");
11442             else
11443                 return null;
11444         }
11445
11446         private void FollowContextMenuItem_Click(object sender, EventArgs e)
11447         {
11448             string name = GetUserId();
11449             if (name != null) FollowCommand(name);
11450         }
11451
11452         private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11453         {
11454             string name = GetUserId();
11455             if (name != null) RemoveCommand(name, false);
11456         }
11457
11458         private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11459         {
11460             string name = GetUserId();
11461             if (name != null) ShowFriendship(name);
11462         }
11463
11464         private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11465         {
11466             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11467             List<string> ids = new List<string>();
11468             foreach (Match mu in ma)
11469             {
11470                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11471                 {
11472                     ids.Add(mu.Result("${ScreenName}"));
11473                 }
11474             }
11475             ShowFriendship(ids.ToArray());
11476         }
11477
11478         private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11479         {
11480             string name = GetUserId();
11481             if (name != null) ShowUserStatus(name);
11482         }
11483
11484         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11485         {
11486             string name = GetUserId();
11487             if (name != null) AddNewTabForUserTimeline(name);
11488         }
11489
11490         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11491         {
11492             string name = GetUserId();
11493             if (name != null) AddNewTabForSearch("@" + name);
11494         }
11495
11496         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11497         {
11498             _modifySettingCommon = true;
11499         }
11500
11501         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11502         {
11503             _modifySettingCommon = true;
11504         }
11505
11506         private void doQuote()
11507         {
11508             //QT @id:内容
11509             //返信先情報付加
11510             if (this.ExistCurrentPost)
11511             {
11512                 if (_curPost.IsDm ||
11513                     !StatusText.Enabled) return;
11514
11515                 if (_curPost.IsProtect)
11516                 {
11517                     MessageBox.Show("Protected.");
11518                     return;
11519                 }
11520                 string rtdata = _curPost.Text;
11521                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11522
11523                 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11524                 if (_curPost.RetweetedId == null)
11525                 {
11526                     _reply_to_id = _curPost.StatusId;
11527                 }
11528                 else
11529                 {
11530                     _reply_to_id = _curPost.RetweetedId.Value;
11531                 }
11532                 _reply_to_name = _curPost.ScreenName;
11533
11534                 StatusText.SelectionStart = 0;
11535                 StatusText.Focus();
11536             }
11537         }
11538
11539         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11540         {
11541             doQuote();
11542         }
11543
11544         private void SearchButton_Click(object sender, EventArgs e)
11545         {
11546             //公式検索
11547             Control pnl = ((Control)sender).Parent;
11548             if (pnl == null) return;
11549             string tbName = pnl.Parent.Text;
11550             TabClass tb = _statuses.Tabs[tbName];
11551             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11552             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11553             ComboBox cmbusline = (ComboBox)pnl.Controls["comboUserline"];
11554             cmb.Text = cmb.Text.Trim();
11555             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11556             bool Quote = false;
11557             StringBuilder buf = new StringBuilder();
11558             char[] c = cmb.Text.ToCharArray();
11559             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11560             {
11561                 if (cnt > cmb.Text.Length - 4)
11562                 {
11563                     buf.Append(cmb.Text.Substring(cnt));
11564                     break;
11565                 }
11566                 if (c[cnt] == '"')
11567                 {
11568                     Quote = !Quote;
11569                 }
11570                 else
11571                 {
11572                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11573                     {
11574                         buf.Append(" OR ");
11575                         cnt += 3;
11576                         continue;
11577                     }
11578                 }
11579                 buf.Append(c[cnt]);
11580             }
11581             cmb.Text = buf.ToString();
11582
11583             tb.SearchWords = cmb.Text;
11584             tb.SearchLang = cmbLang.Text;
11585             if (string.IsNullOrEmpty(cmb.Text))
11586             {
11587                 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11588                 SaveConfigsTabs();
11589                 return;
11590             }
11591             if (tb.IsQueryChanged())
11592             {
11593                 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11594                 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11595                 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11596                 cmb.Text = tb.SearchWords;
11597                 cmb.SelectAll();
11598                 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11599                 this.PurgeListViewItemCache();
11600                 lst.VirtualListSize = 0;
11601                 _statuses.ClearTabIds(tbName);
11602                 SaveConfigsTabs();   //検索条件の保存
11603             }
11604
11605             GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, tbName);
11606             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11607         }
11608
11609         private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11610         {
11611             //もっと前を取得
11612             DoRefreshMore();
11613         }
11614
11615         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11616         {
11617             if (_statuses.RemovedTab.Count == 0)
11618             {
11619                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11620                 return;
11621             }
11622             else
11623             {
11624                 TabClass tb = _statuses.RemovedTab.Pop();
11625                 if (tb.TabType == MyCommon.TabUsageType.Related)
11626                 {
11627                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11628                     if (relatedTab != null)
11629                     {
11630                         // 関連発言なら既存のタブを置き換える
11631                         tb.TabName = relatedTab.TabName;
11632                         this.ClearTab(tb.TabName, false);
11633                         _statuses.Tabs[tb.TabName] = tb;
11634                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11635                         {
11636                             if (tb.TabName == ListTab.TabPages[i].Text)
11637                             {
11638                                 ListTab.SelectedIndex = i;
11639                                 ListTabSelect(ListTab.TabPages[i]);
11640                                 break;
11641                             }
11642                         }
11643                     }
11644                     else
11645                     {
11646                         const string TabName = "Related Tweets";
11647                         string renamed = TabName;
11648                         for (int i = 2; i <= 100; i++)
11649                         {
11650                             if (!_statuses.ContainsTab(renamed)) break;
11651                             renamed = TabName + i.ToString();
11652                         }
11653                         tb.TabName = renamed;
11654                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11655                         _statuses.Tabs.Add(renamed, tb);  // 後に
11656                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11657                         ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11658                     }
11659                 }
11660                 else
11661                 {
11662                     string renamed = tb.TabName;
11663                     for (int i = 1; i < int.MaxValue; i++)
11664                     {
11665                         if (!_statuses.ContainsTab(renamed)) break;
11666                         renamed = tb.TabName + "(" + i.ToString() + ")";
11667                     }
11668                     tb.TabName = renamed;
11669                     _statuses.Tabs.Add(renamed, tb);  // 先に
11670                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11671                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11672                     ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11673                 }
11674                 SaveConfigsTabs();
11675             }
11676         }
11677
11678         private void doMoveToRTHome()
11679         {
11680             if (_curList.SelectedIndices.Count > 0)
11681             {
11682                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11683                 if (post.RetweetedId != null)
11684                 {
11685                     OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11686                 }
11687             }
11688         }
11689
11690         private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11691         {
11692             doMoveToRTHome();
11693         }
11694
11695         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11696         {
11697             string name = GetUserId();
11698             if (name != null)
11699             {
11700                 string tabName;
11701
11702                 //未選択なら処理終了
11703                 if (_curList.SelectedIndices.Count == 0) return;
11704
11705                 //タブ選択(or追加)
11706                 if (!SelectTab(out tabName)) return;
11707
11708                 bool mv = false;
11709                 bool mk = false;
11710                 MoveOrCopy(ref mv, ref mk);
11711
11712                 PostFilterRule fc = new PostFilterRule();
11713                 fc.FilterName = name;
11714                 fc.UseNameField = true;
11715                 fc.MoveMatches = mv;
11716                 fc.MarkMatches = mk;
11717                 fc.UseRegex = false;
11718                 fc.FilterByUrl = false;
11719                 _statuses.Tabs[tabName].AddFilter(fc);
11720
11721                 this.ApplyPostFilters();
11722                 SaveConfigsTabs();
11723             }
11724         }
11725
11726         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11727         {
11728             string user;
11729
11730             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11731
11732             if (menuItem.Owner == this.ContextMenuPostBrowser)
11733             {
11734                 user = GetUserId();
11735                 if (user == null) return;
11736             }
11737             else if (this._curPost != null)
11738             {
11739                 user = this._curPost.ScreenName;
11740             }
11741             else
11742             {
11743                 return;
11744             }
11745
11746             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11747             {
11748                 string res = this.tw.GetListsApi();
11749
11750                 if (!string.IsNullOrEmpty(res))
11751                 {
11752                     MessageBox.Show("Failed to get lists. (" + res + ")");
11753                     return;
11754                 }
11755             }
11756
11757             using (MyLists listSelectForm = new MyLists(user, this.tw))
11758             {
11759                 listSelectForm.ShowDialog(this);
11760             }
11761         }
11762
11763         private void SearchControls_Enter(object sender, EventArgs e)
11764         {
11765             Control pnl = (Control)sender;
11766             foreach (Control ctl in pnl.Controls)
11767             {
11768                 ctl.TabStop = true;
11769             }
11770         }
11771
11772         private void SearchControls_Leave(object sender, EventArgs e)
11773         {
11774             Control pnl = (Control)sender;
11775             foreach (Control ctl in pnl.Controls)
11776             {
11777                 ctl.TabStop = false;
11778             }
11779         }
11780
11781         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11782         {
11783             if (ListTab.SelectedTab != null)
11784             {
11785                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11786                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11787             }
11788         }
11789
11790         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11791         {
11792             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11793             if (m.Success)
11794             {
11795                 HashMgr.SetPermanentHash("#" + m.Result("${hash}"));
11796                 HashStripSplitButton.Text = HashMgr.UseHash;
11797                 HashToggleMenuItem.Checked = true;
11798                 HashToggleToolStripMenuItem.Checked = true;
11799                 //使用ハッシュタグとして設定
11800                 _modifySettingCommon = true;
11801             }
11802         }
11803
11804         private void StatusLabel_DoubleClick(object sender, EventArgs e)
11805         {
11806             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11807         }
11808
11809         private void HashManageMenuItem_Click(object sender, EventArgs e)
11810         {
11811             DialogResult rslt = DialogResult.Cancel;
11812             try
11813             {
11814                 rslt = HashMgr.ShowDialog();
11815             }
11816             catch (Exception)
11817             {
11818                 return;
11819             }
11820             this.TopMost = SettingDialog.AlwaysTop;
11821             if (rslt == DialogResult.Cancel) return;
11822             if (!string.IsNullOrEmpty(HashMgr.UseHash))
11823             {
11824                 HashStripSplitButton.Text = HashMgr.UseHash;
11825                 HashToggleMenuItem.Checked = true;
11826                 HashToggleToolStripMenuItem.Checked = true;
11827             }
11828             else
11829             {
11830                 HashStripSplitButton.Text = "#[-]";
11831                 HashToggleMenuItem.Checked = false;
11832                 HashToggleToolStripMenuItem.Checked = false;
11833             }
11834             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11835             //{
11836             //    int sidx = StatusText.SelectionStart;
11837             //    string hash = HashMgr.UseHash + " ";
11838             //    if (sidx > 0)
11839             //    {
11840             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11841             //            hash = " " + hash;
11842             //    }
11843             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
11844             //    sidx += hash.Length;
11845             //    StatusText.SelectionStart = sidx;
11846             //    StatusText.Focus();
11847             //}
11848             _modifySettingCommon = true;
11849             this.StatusText_TextChanged(null, null);
11850         }
11851
11852         private void HashToggleMenuItem_Click(object sender, EventArgs e)
11853         {
11854             HashMgr.ToggleHash();
11855             if (!string.IsNullOrEmpty(HashMgr.UseHash))
11856             {
11857                 HashStripSplitButton.Text = HashMgr.UseHash;
11858                 HashToggleMenuItem.Checked = true;
11859                 HashToggleToolStripMenuItem.Checked = true;
11860             }
11861             else
11862             {
11863                 HashStripSplitButton.Text = "#[-]";
11864                 HashToggleMenuItem.Checked = false;
11865                 HashToggleToolStripMenuItem.Checked = false;
11866             }
11867             _modifySettingCommon = true;
11868             this.StatusText_TextChanged(null, null);
11869         }
11870
11871         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11872         {
11873             HashToggleMenuItem_Click(null, null);
11874         }
11875
11876         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11877         {
11878             if (ListTab.SelectedTab == null) return;
11879             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11880             if (!this.ExistCurrentPost)
11881             {
11882                 this.ReplyOpMenuItem.Enabled = false;
11883                 this.ReplyAllOpMenuItem.Enabled = false;
11884                 this.DmOpMenuItem.Enabled = false;
11885                 this.ShowProfMenuItem.Enabled = false;
11886                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11887                 this.ListManageMenuItem.Enabled = false;
11888                 this.OpenFavOpMenuItem.Enabled = false;
11889                 this.CreateTabRuleOpMenuItem.Enabled = false;
11890                 this.CreateIdRuleOpMenuItem.Enabled = false;
11891                 this.ReadOpMenuItem.Enabled = false;
11892                 this.UnreadOpMenuItem.Enabled = false;
11893             }
11894             else
11895             {
11896                 this.ReplyOpMenuItem.Enabled = true;
11897                 this.ReplyAllOpMenuItem.Enabled = true;
11898                 this.DmOpMenuItem.Enabled = true;
11899                 this.ShowProfMenuItem.Enabled = true;
11900                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11901                 this.ListManageMenuItem.Enabled = true;
11902                 this.OpenFavOpMenuItem.Enabled = true;
11903                 this.CreateTabRuleOpMenuItem.Enabled = true;
11904                 this.CreateIdRuleOpMenuItem.Enabled = true;
11905                 this.ReadOpMenuItem.Enabled = true;
11906                 this.UnreadOpMenuItem.Enabled = true;
11907             }
11908
11909             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11910             {
11911                 this.FavOpMenuItem.Enabled = false;
11912                 this.UnFavOpMenuItem.Enabled = false;
11913                 this.OpenStatusOpMenuItem.Enabled = false;
11914                 this.OpenFavotterOpMenuItem.Enabled = false;
11915                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11916                 this.RtOpMenuItem.Enabled = false;
11917                 this.RtUnOpMenuItem.Enabled = false;
11918                 this.QtOpMenuItem.Enabled = false;
11919                 this.FavoriteRetweetMenuItem.Enabled = false;
11920                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11921                 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11922             }
11923             else
11924             {
11925                 this.FavOpMenuItem.Enabled = true;
11926                 this.UnFavOpMenuItem.Enabled = true;
11927                 this.OpenStatusOpMenuItem.Enabled = true;
11928                 this.OpenFavotterOpMenuItem.Enabled = true;
11929                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
11930
11931                 if (_curPost.IsMe)
11932                 {
11933                     this.RtOpMenuItem.Enabled = false;
11934                     this.FavoriteRetweetMenuItem.Enabled = false;
11935                     this.DelOpMenuItem.Enabled = true;
11936                 }
11937                 else
11938                 {
11939                     this.DelOpMenuItem.Enabled = false;
11940                     if (_curPost.IsProtect)
11941                     {
11942                         this.RtOpMenuItem.Enabled = false;
11943                         this.RtUnOpMenuItem.Enabled = false;
11944                         this.QtOpMenuItem.Enabled = false;
11945                         this.FavoriteRetweetMenuItem.Enabled = false;
11946                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11947                     }
11948                     else
11949                     {
11950                         this.RtOpMenuItem.Enabled = true;
11951                         this.RtUnOpMenuItem.Enabled = true;
11952                         this.QtOpMenuItem.Enabled = true;
11953                         this.FavoriteRetweetMenuItem.Enabled = true;
11954                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11955                     }
11956                 }
11957             }
11958
11959             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11960             {
11961                 this.RefreshPrevOpMenuItem.Enabled = true;
11962             }
11963             else
11964             {
11965                 this.RefreshPrevOpMenuItem.Enabled = false;
11966             }
11967             if (!this.ExistCurrentPost
11968                 || _curPost.InReplyToStatusId == null)
11969             {
11970                 OpenRepSourceOpMenuItem.Enabled = false;
11971             }
11972             else
11973             {
11974                 OpenRepSourceOpMenuItem.Enabled = true;
11975             }
11976             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11977             {
11978                 OpenRterHomeMenuItem.Enabled = false;
11979             }
11980             else
11981             {
11982                 OpenRterHomeMenuItem.Enabled = true;
11983             }
11984         }
11985
11986         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11987         {
11988             ContextMenuTabProperty_Opening(sender, null);
11989         }
11990
11991         public Twitter TwitterInstance
11992         {
11993             get { return tw; }
11994         }
11995
11996         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11997         {
11998             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
11999             {
12000                 _mySpDis3 = SplitContainer3.SplitterDistance;
12001                 _modifySettingLocal = true;
12002             }
12003         }
12004
12005         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12006         {
12007             if (_statuses.RemovedTab.Count == 0)
12008             {
12009                 UndoRemoveTabMenuItem.Enabled = false;
12010             }
12011             else
12012             {
12013                 UndoRemoveTabMenuItem.Enabled = true;
12014             }
12015             if (ListTab.SelectedTab != null)
12016             {
12017                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12018                     PublicSearchQueryMenuItem.Enabled = true;
12019                 else
12020                     PublicSearchQueryMenuItem.Enabled = false;
12021             }
12022             else
12023             {
12024                 PublicSearchQueryMenuItem.Enabled = false;
12025             }
12026             if (!this.ExistCurrentPost)
12027             {
12028                 this.CopySTOTMenuItem.Enabled = false;
12029                 this.CopyURLMenuItem.Enabled = false;
12030                 this.CopyUserIdStripMenuItem.Enabled = false;
12031             }
12032             else
12033             {
12034                 this.CopySTOTMenuItem.Enabled = true;
12035                 this.CopyURLMenuItem.Enabled = true;
12036                 this.CopyUserIdStripMenuItem.Enabled = true;
12037                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12038                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12039             }
12040         }
12041
12042         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12043         {
12044             SetNotifyIconText();
12045         }
12046
12047         private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12048         {
12049             string id = "";
12050             if (_curPost != null)
12051             {
12052                 id = _curPost.ScreenName;
12053             }
12054             ShowUserStatus(id);
12055         }
12056
12057         private class GetUserInfoArgs
12058         {
12059             public Twitter tw;
12060             public string id;
12061             public TwitterUser user;
12062         }
12063
12064         private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
12065         {
12066             GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
12067             e.Result = args.tw.GetUserInfo(args.id, ref args.user);
12068         }
12069
12070         private void doShowUserStatus(string id, bool ShowInputDialog)
12071         {
12072             TwitterUser user = null;
12073             GetUserInfoArgs args = new GetUserInfoArgs();
12074             if (ShowInputDialog)
12075             {
12076                 using (InputTabName inputName = new InputTabName())
12077                 {
12078                     inputName.FormTitle = "Show UserStatus";
12079                     inputName.FormDescription = Properties.Resources.FRMessage1;
12080                     inputName.TabName = id;
12081                     if (inputName.ShowDialog() == DialogResult.OK &&
12082                         !string.IsNullOrEmpty(inputName.TabName.Trim()))
12083                     {
12084                         id = inputName.TabName.Trim();
12085                         args.tw = tw;
12086                         args.id = id;
12087                         args.user = user;
12088                         using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12089                                                              GetUserInfo_DoWork,
12090                                                              null,
12091                                                              args))
12092                         {
12093                             _info.ShowDialog();
12094                             string ret = (string)_info.Result;
12095                             if (string.IsNullOrEmpty(ret))
12096                                 doShowUserStatus(args.user);
12097                             else
12098                                 MessageBox.Show(ret);
12099                         }
12100                     }
12101                 }
12102             }
12103             else
12104             {
12105                 args.tw = tw;
12106                 args.id = id;
12107                 args.user = user;
12108                 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12109                                                      GetUserInfo_DoWork,
12110                                                      null,
12111                                                      args))
12112                 {
12113                     _info.ShowDialog();
12114                     string ret = (string)_info.Result;
12115                     if (string.IsNullOrEmpty(ret))
12116                     {
12117                         doShowUserStatus(args.user);
12118                     }
12119                     else
12120                     {
12121                         MessageBox.Show(ret);
12122                     }
12123                 }
12124             }
12125         }
12126
12127         private void doShowUserStatus(TwitterUser user)
12128         {
12129             using (var userinfo = new UserInfoDialog())
12130             {
12131                 userinfo.Owner = this;
12132                 userinfo.DisplayUser = user;
12133                 userinfo.ShowDialog(this);
12134                 this.Activate();
12135                 this.BringToFront();
12136             }
12137         }
12138
12139         private void ShowUserStatus(string id, bool ShowInputDialog)
12140         {
12141             doShowUserStatus(id, ShowInputDialog);
12142         }
12143
12144         private void ShowUserStatus(string id)
12145         {
12146             doShowUserStatus(id, true);
12147         }
12148
12149         private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12150         {
12151             if (NameLabel.Tag != null)
12152             {
12153                 string id = (string)NameLabel.Tag;
12154                 if (id != tw.Username)
12155                 {
12156                     FollowCommand(id);
12157                 }
12158             }
12159         }
12160
12161         private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12162         {
12163             if (NameLabel.Tag != null)
12164             {
12165                 string id = (string)NameLabel.Tag;
12166                 if (id != tw.Username)
12167                 {
12168                     RemoveCommand(id, false);
12169                 }
12170             }
12171         }
12172
12173         private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12174         {
12175             if (NameLabel.Tag != null)
12176             {
12177                 string id = (string)NameLabel.Tag;
12178                 if (id != tw.Username)
12179                 {
12180                     ShowFriendship(id);
12181                 }
12182             }
12183         }
12184
12185         private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12186         {
12187             if (NameLabel.Tag != null)
12188             {
12189                 string id = (string)NameLabel.Tag;
12190                 ShowUserStatus(id, false);
12191             }
12192         }
12193
12194         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12195         {
12196             if (NameLabel.Tag != null)
12197             {
12198                 string id = (string)NameLabel.Tag;
12199                 AddNewTabForUserTimeline(id);
12200             }
12201         }
12202
12203         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12204         {
12205             if (NameLabel.Tag != null)
12206             {
12207                 string id = (string)NameLabel.Tag;
12208                 AddNewTabForSearch("@" + id);
12209             }
12210         }
12211
12212         private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12213         {
12214             if (_curPost != null)
12215             {
12216                 ShowUserStatus(_curPost.ScreenName, false);
12217             }
12218         }
12219
12220         private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12221         {
12222             int counter = 0;
12223
12224             long statusid;
12225             if (_curPost.RetweetedId != null)
12226             {
12227                 statusid = _curPost.RetweetedId.Value;
12228             }
12229             else
12230             {
12231                 statusid = _curPost.StatusId;
12232             }
12233             tw.GetStatus_Retweeted_Count(statusid, ref counter);
12234
12235             e.Result = counter;
12236         }
12237
12238         private void RtCountMenuItem_Click(object sender, EventArgs e)
12239         {
12240             if (this.ExistCurrentPost)
12241             {
12242                 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12243                                                      GetRetweet_DoWork))
12244                 {
12245                     int retweet_count = 0;
12246
12247                     // ダイアログ表示
12248                     _info.ShowDialog();
12249                     retweet_count = (int)_info.Result;
12250                     if (retweet_count < 0)
12251                     {
12252                         MessageBox.Show(Properties.Resources.RtCountText2);
12253                     }
12254                     else
12255                     {
12256                         MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12257                     }
12258                 }
12259             }
12260         }
12261
12262         private HookGlobalHotkey _hookGlobalHotkey;
12263         public TweenMain()
12264         {
12265             this.http = MyCommon.CreateHttpClient();
12266             _hookGlobalHotkey = new HookGlobalHotkey(this);
12267
12268             // この呼び出しは、Windows フォーム デザイナで必要です。
12269             InitializeComponent();
12270
12271             // InitializeComponent() 呼び出しの後で初期化を追加します。
12272
12273             this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12274             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12275             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12276             this.gh.NotifyClicked += GrowlHelper_Callback;
12277
12278             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12279             this.ListTab.HandleCreated += (s, e) => Win32Api.SetMinTabWidth((TabControl)s, 40);
12280
12281             this._apiGauge = new ToolStripAPIGauge();
12282             this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12283             this.StatusStrip1.Items.Insert(2, this._apiGauge);
12284
12285             this.ImageSelectedPicture.InitialImage = Properties.Resources.InitialImage;
12286
12287             this.ReplaceAppName();
12288         }
12289
12290         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12291         {
12292             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12293             {
12294                 //アイコン化
12295                 this.Visible = false;
12296             }
12297             else if (Form.ActiveForm == null)
12298             {
12299                 this.Visible = true;
12300                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12301                 this.Activate();
12302                 this.BringToFront();
12303                 this.StatusText.Focus();
12304             }
12305         }
12306
12307         private void UserPicture_MouseEnter(object sender, EventArgs e)
12308         {
12309             this.UserPicture.Cursor = Cursors.Hand;
12310         }
12311
12312         private void UserPicture_MouseLeave(object sender, EventArgs e)
12313         {
12314             this.UserPicture.Cursor = Cursors.Default;
12315         }
12316
12317         private void UserPicture_DoubleClick(object sender, EventArgs e)
12318         {
12319             if (NameLabel.Tag != null)
12320             {
12321                 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12322             }
12323         }
12324
12325         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12326         {
12327             this.MultiLineMenuItem.PerformClick();
12328         }
12329
12330         public PostClass CurPost
12331         {
12332             get { return _curPost; }
12333         }
12334
12335         public bool IsPreviewEnable
12336         {
12337             get { return SettingDialog.PreviewEnable; }
12338         }
12339
12340 #region "画像投稿"
12341         private void CreatePictureServices()
12342         {
12343             if (this.pictureService != null) this.pictureService.Clear();
12344             this.pictureService = null;
12345             this.pictureService = new Dictionary<string, IMultimediaShareService> {
12346                 {"TwitPic", new TwitPic(tw)},
12347                 {"img.ly", new imgly(tw)},
12348                 {"yfrog", new yfrog(tw)},
12349                 {"Twitter", new TwitterPhoto(tw)},
12350                 {"ついっぷるフォト", new TwipplePhoto(tw)},
12351                 {"Imgur", new Imgur(tw)},
12352             };
12353         }
12354
12355         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12356         {
12357             if (ImageSelectionPanel.Visible)
12358             {
12359                 CloseImageSelectionPanel();
12360             }
12361             else
12362             {
12363                 OpenImageSelectionPanel();
12364                 ImageFromSelectedFile(true);
12365                 ImagefilePathText.Focus();
12366             }
12367         }
12368
12369         private void OpenImageSelectionPanel()
12370         {
12371             ImageSelectionPanel.Visible = true;
12372             ImageSelectionPanel.Enabled = true;
12373             TimelinePanel.Visible = false;
12374             TimelinePanel.Enabled = false;
12375         }
12376
12377         private void CloseImageSelectionPanel()
12378         {
12379             ImagefilePathText.CausesValidation = false;
12380             TimelinePanel.Visible = true;
12381             TimelinePanel.Enabled = true;
12382             ImageSelectionPanel.Visible = false;
12383             ImageSelectionPanel.Enabled = false;
12384             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12385             ClearImageSelectedPicture();
12386             ImagefilePathText.CausesValidation = true;
12387         }
12388
12389         private void SelectMedia_DragEnter(DragEventArgs e)
12390         {
12391             string filename = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12392             FileInfo fl = new FileInfo(filename);
12393             string ext = fl.Extension;
12394
12395             if (!string.IsNullOrEmpty(this.ImageService) &&
12396                 this.pictureService[this.ImageService].CheckValidFilesize(ext, fl.Length))
12397             {
12398                 e.Effect = DragDropEffects.Copy;
12399                 return;
12400             }
12401             foreach (string svc in ImageServiceCombo.Items)
12402             {
12403                 if (!string.IsNullOrEmpty(svc) &&
12404                     this.pictureService[svc].CheckValidFilesize(ext, fl.Length))
12405                 {
12406                     //ImageServiceCombo.SelectedItem = svc;
12407                     e.Effect = DragDropEffects.Copy;
12408                     return;
12409                 }
12410             }
12411             e.Effect = DragDropEffects.None;
12412         }
12413
12414         private void SelectMedia_DragOver(DragEventArgs e)
12415         {
12416             //何も触らない
12417         }
12418
12419         private void SelectMedia_DragDrop(DragEventArgs e)
12420         {
12421             this.Activate();
12422             this.BringToFront();
12423             OpenImageSelectionPanel();
12424             ImagefilePathText.Text = ((string[])e.Data.GetData(DataFormats.FileDrop, false))[0];
12425             ImageFromSelectedFile(false);
12426             StatusText.Focus();
12427         }
12428
12429         private void FilePickButton_Click(object sender, EventArgs e)
12430         {
12431             if (string.IsNullOrEmpty(this.ImageService)) return;
12432             OpenFileDialog1.Filter = this.pictureService[this.ImageService].GetFileOpenDialogFilter();
12433             OpenFileDialog1.Title = Properties.Resources.PickPictureDialog1;
12434             OpenFileDialog1.FileName = "";
12435
12436             try
12437             {
12438                 this.AllowDrop = false;
12439                 if (OpenFileDialog1.ShowDialog() == DialogResult.Cancel) return;
12440             }
12441             finally
12442             {
12443                 this.AllowDrop = true;
12444             }
12445
12446             ImagefilePathText.Text = OpenFileDialog1.FileName;
12447             ImageFromSelectedFile(false);
12448         }
12449
12450         private void ImagefilePathText_Validating(object sender, CancelEventArgs e)
12451         {
12452             if (ImageCancelButton.Focused)
12453             {
12454                 ImagefilePathText.CausesValidation = false;
12455                 return;
12456             }
12457
12458             ImageFromSelectedFile(false);
12459         }
12460
12461         private void ImageFromSelectedFile(bool suppressMsgBox)
12462         {
12463             this.ClearImageSelectedPicture();
12464
12465             try
12466             {
12467                 ImagefilePathText.Text = ImagefilePathText.Text.Trim();
12468                 if (string.IsNullOrEmpty(ImagefilePathText.Text) || string.IsNullOrEmpty(this.ImageService))
12469                 {
12470                     ImagefilePathText.Text = "";
12471                     return;
12472                 }
12473
12474                 FileInfo fl = new FileInfo(ImagefilePathText.Text);
12475                 string ext = fl.Extension;
12476                 var imageService = this.pictureService[this.ImageService];
12477
12478                 if (!imageService.CheckValidExtension(ext))
12479                 {
12480                     //画像以外の形式
12481                     ImagefilePathText.Text = "";
12482                     if (!suppressMsgBox)
12483                     {
12484                         MessageBox.Show(
12485                             string.Format(Properties.Resources.PostPictureWarn3, this.ImageService, MakeAvailableServiceText(ext, fl.Length), ext),
12486                             Properties.Resources.PostPictureWarn4,
12487                             MessageBoxButtons.OK,
12488                             MessageBoxIcon.Warning);
12489                     }
12490                     return;
12491                 }
12492
12493                 if (!imageService.CheckValidFilesize(ext, fl.Length))
12494                 {
12495                     // ファイルサイズが大きすぎる
12496                     ImagefilePathText.Text = "";
12497                     if (!suppressMsgBox)
12498                     {
12499                         MessageBox.Show(
12500                             string.Format(Properties.Resources.PostPictureWarn5, this.ImageService, MakeAvailableServiceText(ext, fl.Length)),
12501                             Properties.Resources.PostPictureWarn4,
12502                             MessageBoxButtons.OK,
12503                             MessageBoxIcon.Warning);
12504                     }
12505                     return;
12506                 }
12507
12508                 switch (imageService.GetFileType(ext))
12509                 {
12510                     case MyCommon.UploadFileType.Picture:
12511                         using (var fs = File.OpenRead(ImagefilePathText.Text))
12512                         {
12513                             ImageSelectedPicture.Image = MemoryImage.CopyFromStream(fs);
12514                         }
12515                         ImageSelectedPicture.Tag = MyCommon.UploadFileType.Picture;
12516                         break;
12517                     case MyCommon.UploadFileType.MultiMedia:
12518                         ImageSelectedPicture.Tag = MyCommon.UploadFileType.MultiMedia;
12519                         break;
12520                     default:
12521                         ImagefilePathText.Text = "";
12522                         break;
12523                 }
12524             }
12525             catch (FileNotFoundException)
12526             {
12527                 ImagefilePathText.Text = "";
12528                 if (!suppressMsgBox) MessageBox.Show("File not found.");
12529             }
12530             catch (Exception)
12531             {
12532                 ImagefilePathText.Text = "";
12533                 if (!suppressMsgBox) MessageBox.Show("The type of this file is not image.");
12534             }
12535         }
12536
12537         private string MakeAvailableServiceText(string ext, long fileSize)
12538         {
12539             StringBuilder sb = new StringBuilder();
12540
12541             foreach (string svc in ImageServiceCombo.Items)
12542             {
12543                 if (!string.IsNullOrEmpty(svc) &&
12544                     this.pictureService[svc].CheckValidFilesize(ext, fileSize))
12545                 {
12546                     if (sb.Length > 0) sb.Append(", ");
12547                     sb.Append(svc);
12548                 }
12549             }
12550             if (sb.Length == 0)
12551                 return Properties.Resources.PostPictureWarn6;
12552
12553             return sb.ToString();
12554         }
12555
12556         private void ClearImageSelectedPicture()
12557         {
12558             var oldImage = this.ImageSelectedPicture.Image;
12559             if (oldImage != null)
12560             {
12561                 this.ImageSelectedPicture.Image = null;
12562                 oldImage.Dispose();
12563             }
12564
12565             this.ImageSelectedPicture.Tag = null;
12566             this.ImageSelectedPicture.ShowInitialImage();
12567         }
12568
12569         private void ImageCancelButton_Click(object sender, EventArgs e)
12570         {
12571             CloseImageSelectionPanel();
12572         }
12573
12574         private void ImageSelection_KeyDown(object sender, KeyEventArgs e)
12575         {
12576             if (e.KeyCode == Keys.Escape)
12577             {
12578                 CloseImageSelectionPanel();
12579             }
12580         }
12581
12582         private void ImageSelection_KeyPress(object sender, KeyPressEventArgs e)
12583         {
12584             if (Convert.ToInt32(e.KeyChar) == 0x1B)
12585             {
12586                 ImagefilePathText.CausesValidation = false;
12587                 e.Handled = true;
12588             }
12589         }
12590
12591         private void ImageSelection_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
12592         {
12593             if (e.KeyCode == Keys.Escape)
12594             {
12595                 ImagefilePathText.CausesValidation = false;
12596             }
12597         }
12598
12599         private bool TryGetSelectedMedia(out string imageService, out string imagePath)
12600         {
12601             if (ImageSelectedPicture.Tag != null &&
12602                 ImageServiceCombo.SelectedIndex > -1 &&
12603                 !string.IsNullOrEmpty(ImagefilePathText.Text))
12604             {
12605                 if (MessageBox.Show(string.Format(Properties.Resources.PostPictureConfirm1, this.ImageService),
12606                                    Properties.Resources.PostPictureConfirm2,
12607                                    MessageBoxButtons.OKCancel,
12608                                    MessageBoxIcon.Question,
12609                                    MessageBoxDefaultButton.Button1)
12610                                == DialogResult.OK)
12611                 {
12612                     imageService = ImageServiceCombo.Text;
12613                     imagePath = ImagefilePathText.Text;
12614                     CloseImageSelectionPanel();
12615                     ImagefilePathText.Text = "";
12616                     return true;
12617                 }
12618             }
12619             else
12620             {
12621                 MessageBox.Show(Properties.Resources.PostPictureWarn1, Properties.Resources.PostPictureWarn2);
12622             }
12623
12624             CloseImageSelectionPanel();
12625             imageService = null;
12626             imagePath = null;
12627             return false;
12628         }
12629
12630         private void SetImageServiceCombo()
12631         {
12632             string svc = "";
12633             if (ImageServiceCombo.SelectedIndex > -1) svc = ImageServiceCombo.SelectedItem.ToString();
12634             ImageServiceCombo.Items.Clear();
12635             
12636             // Add service names to combobox
12637             foreach (var key in pictureService.Keys)
12638             {
12639                 ImageServiceCombo.Items.Add(key);
12640             }
12641
12642             SelectImageServiceComboItem(svc);
12643         }
12644
12645         private void SelectImageServiceComboItem(string svc, int? index = null)
12646         {
12647             int idx;
12648             if (string.IsNullOrEmpty(svc))
12649             {
12650                 idx = index ?? 0;
12651             }
12652             else
12653             {
12654                 idx = ImageServiceCombo.Items.IndexOf(svc);
12655                 if (idx == -1) idx = index ?? 0;
12656             }
12657
12658             try
12659             {
12660                 ImageServiceCombo.SelectedIndex = idx;
12661             }
12662             catch (ArgumentOutOfRangeException)
12663             {
12664                 ImageServiceCombo.SelectedIndex = 0;
12665             }
12666         }
12667
12668         private string ImageService
12669         {
12670             get { return ImageServiceCombo.SelectedItem.ToString(); }
12671         }
12672
12673         private void ImageServiceCombo_SelectedIndexChanged(object sender, EventArgs e)
12674         {
12675             if (ImageSelectedPicture.Tag != null && !string.IsNullOrEmpty(this.ImageService))
12676             {
12677                 try
12678                 {
12679                     FileInfo fi = new FileInfo(ImagefilePathText.Text.Trim());
12680                     string ext = fi.Extension;
12681                     var imageService = this.pictureService[this.ImageService];
12682                     if (!imageService.CheckValidFilesize(ext, fi.Length))
12683                     {
12684                         ClearImageSelectedPicture();
12685                         ImagefilePathText.Text = "";
12686                     }
12687                 }
12688                 catch (Exception)
12689                 {
12690                     ClearImageSelectedPicture();
12691                     ImagefilePathText.Text = "";
12692                 }
12693                 _modifySettingCommon = true;
12694                 SaveConfigsAll(true);
12695                 if (this.ImageService == "Twitter")
12696                 {
12697                     this.StatusText_TextChanged(null, null);
12698                 }
12699             }
12700         }
12701
12702         private void ImageSelectionPanel_VisibleChanged(object sender, EventArgs e)
12703         {
12704             this.StatusText_TextChanged(null, null);
12705         }
12706 #endregion
12707
12708         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12709         {
12710             using (ListManage form = new ListManage(tw))
12711             {
12712                 form.ShowDialog(this);
12713             }
12714         }
12715
12716         public bool ModifySettingCommon
12717         {
12718             set { _modifySettingCommon = value; }
12719         }
12720
12721         public bool ModifySettingLocal
12722         {
12723             set { _modifySettingLocal = value; }
12724         }
12725
12726         public bool ModifySettingAtId
12727         {
12728             set { _modifySettingAtId = value; }
12729         }
12730
12731         private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12732         {
12733             string link = (string)SourceLinkLabel.Tag;
12734             if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12735             {
12736                 OpenUriAsync(link);
12737             }
12738         }
12739
12740         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12741         {
12742             string link = (string)SourceLinkLabel.Tag;
12743             if (!string.IsNullOrEmpty(link))
12744             {
12745                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12746             }
12747         }
12748
12749         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12750         {
12751             SetStatusLabelUrl();
12752         }
12753
12754         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12755         {
12756             if (this.ExistCurrentPost && !_curPost.IsDm)
12757                 RtCountMenuItem.Enabled = true;
12758             else
12759                 RtCountMenuItem.Enabled = false;
12760
12761             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12762             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12763             //else
12764             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12765         }
12766
12767         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12768         {
12769             CopyUserId();
12770         }
12771
12772         private void CopyUserId()
12773         {
12774             if (_curPost == null) return;
12775             string clstr = _curPost.ScreenName;
12776             try
12777             {
12778                 Clipboard.SetDataObject(clstr, false, 5, 100);
12779             }
12780             catch (Exception ex)
12781             {
12782                 MessageBox.Show(ex.Message);
12783             }
12784         }
12785
12786         private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12787         {
12788             if (this.ExistCurrentPost && !_curPost.IsDm)
12789             {
12790                 try
12791                 {
12792                     this.OpenRelatedTab(this._curPost);
12793                 }
12794                 catch (TabException ex)
12795                 {
12796                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12797                 }
12798             }
12799         }
12800
12801         /// <summary>
12802         /// 指定されたツイートに対する関連発言タブを開きます
12803         /// </summary>
12804         /// <param name="post">表示する対象となるツイート</param>
12805         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12806         private void OpenRelatedTab(PostClass post)
12807         {
12808             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12809             string tabName;
12810
12811             if (tabRelated == null)
12812             {
12813                 tabName = this._statuses.MakeTabName("Related Tweets");
12814
12815                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12816                 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12817
12818                 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12819                 tabRelated.UnreadManage = false;
12820                 tabRelated.Notify = false;
12821             }
12822             else
12823             {
12824                 tabName = tabRelated.TabName;
12825             }
12826
12827             tabRelated.RelationTargetPost = post;
12828             this.ClearTab(tabName, false);
12829
12830             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12831             {
12832                 var tabPage = this.ListTab.TabPages[i];
12833                 if (tabName == tabPage.Text)
12834                 {
12835                     this.ListTab.SelectedIndex = i;
12836                     this.ListTabSelect(tabPage);
12837                     break;
12838                 }
12839             }
12840
12841             this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, 1, tabName);
12842         }
12843
12844         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12845         {
12846             StringBuilder buf = new StringBuilder();
12847             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12848             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12849             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12850             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12851             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12852         }
12853
12854         private void tw_UserIdChanged()
12855         {
12856             this._modifySettingCommon = true;
12857         }
12858
12859 #region "Userstream"
12860         private bool _isActiveUserstream = false;
12861
12862         private void tw_PostDeleted(long id)
12863         {
12864             try
12865             {
12866                 if (InvokeRequired && !IsDisposed)
12867                 {
12868                     Invoke((Action) (() =>
12869                            {
12870                                _statuses.RemovePostReserve(id);
12871                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(id))
12872                                {
12873                                    this.PurgeListViewItemCache();
12874                                    ((DetailsListView)_curTab.Tag).Update();
12875                                    if (_curPost != null && _curPost.StatusId == id) DispSelectedPost(true);
12876                                }
12877                            }));
12878                     return;
12879                 }
12880             }
12881             catch (ObjectDisposedException)
12882             {
12883                 return;
12884             }
12885             catch (InvalidOperationException)
12886             {
12887                 return;
12888             }
12889         }
12890
12891         private void tw_NewPostFromStream()
12892         {
12893             if (SettingDialog.ReadOldPosts)
12894             {
12895                 _statuses.SetRead(); //新着時未読クリア
12896             }
12897
12898             int rsltAddCount = _statuses.DistributePosts();
12899             lock (_syncObject)
12900             {
12901                 DateTime tm = DateTime.Now;
12902                 if (_tlTimestamps.ContainsKey(tm))
12903                 {
12904                     _tlTimestamps[tm] += rsltAddCount;
12905                 }
12906                 else
12907                 {
12908                     _tlTimestamps.Add(tm, rsltAddCount);
12909                 }
12910                 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12911                 List<DateTime> keys = new List<DateTime>();
12912                 _tlCount = 0;
12913                 foreach (DateTime key in _tlTimestamps.Keys)
12914                 {
12915                     if (key.CompareTo(oneHour) < 0)
12916                         keys.Add(key);
12917                     else
12918                         _tlCount += _tlTimestamps[key];
12919                 }
12920                 foreach (DateTime key in keys)
12921                 {
12922                     _tlTimestamps.Remove(key);
12923                 }
12924                 keys.Clear();
12925
12926                 //Static DateTime before = Now;
12927                 //if (before.Subtract(Now).Seconds > -5) return;
12928                 //before = Now;
12929             }
12930
12931             if (SettingDialog.UserstreamPeriodInt > 0) return;
12932
12933             try
12934             {
12935                 if (InvokeRequired && !IsDisposed)
12936                 {
12937                     Invoke(new Action<bool>(RefreshTimeline), true);
12938                     return;
12939                 }
12940             }
12941             catch (ObjectDisposedException)
12942             {
12943                 return;
12944             }
12945             catch (InvalidOperationException)
12946             {
12947                 return;
12948             }
12949         }
12950
12951         private void tw_UserStreamStarted()
12952         {
12953             this._isActiveUserstream = true;
12954             try
12955             {
12956                 if (InvokeRequired && !IsDisposed)
12957                 {
12958                     Invoke(new MethodInvoker(tw_UserStreamStarted));
12959                     return;
12960                 }
12961             }
12962             catch (ObjectDisposedException)
12963             {
12964                 return;
12965             }
12966             catch (InvalidOperationException)
12967             {
12968                 return;
12969             }
12970
12971             MenuItemUserStream.Text = "&UserStream ▶";
12972             MenuItemUserStream.Enabled = true;
12973             StopToolStripMenuItem.Text = "&Stop";
12974             StopToolStripMenuItem.Enabled = true;
12975
12976             StatusLabel.Text = "UserStream Started.";
12977         }
12978
12979         private void tw_UserStreamStopped()
12980         {
12981             this._isActiveUserstream = false;
12982             try
12983             {
12984                 if (InvokeRequired && !IsDisposed)
12985                 {
12986                     Invoke(new MethodInvoker(tw_UserStreamStopped));
12987                     return;
12988                 }
12989             }
12990             catch (ObjectDisposedException)
12991             {
12992                 return;
12993             }
12994             catch (InvalidOperationException)
12995             {
12996                 return;
12997             }
12998
12999             MenuItemUserStream.Text = "&UserStream ■";
13000             MenuItemUserStream.Enabled = true;
13001             StopToolStripMenuItem.Text = "&Start";
13002             StopToolStripMenuItem.Enabled = true;
13003
13004             StatusLabel.Text = "UserStream Stopped.";
13005         }
13006
13007         private void tw_UserStreamEventArrived(Twitter.FormattedEvent ev)
13008         {
13009             try
13010             {
13011                 if (InvokeRequired && !IsDisposed)
13012                 {
13013                     Invoke(new Action<Twitter.FormattedEvent>(tw_UserStreamEventArrived), ev);
13014                     return;
13015                 }
13016             }
13017             catch (ObjectDisposedException)
13018             {
13019                 return;
13020             }
13021             catch (InvalidOperationException)
13022             {
13023                 return;
13024             }
13025             StatusLabel.Text = "Event: " + ev.Event;
13026             //if (ev.Event == "favorite")
13027             //{
13028             //    NotifyFavorite(ev);
13029             //}
13030             NotifyEvent(ev);
13031             if (ev.Event == "favorite" || ev.Event == "unfavorite")
13032             {
13033                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13034                 {
13035                     this.PurgeListViewItemCache();
13036                     ((DetailsListView)_curTab.Tag).Update();
13037                 }
13038                 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13039                 {
13040                     RemovePostFromFavTab(new long[] {ev.Id});
13041                 }
13042             }
13043         }
13044
13045         private void NotifyEvent(Twitter.FormattedEvent ev)
13046         {
13047             //新着通知 
13048             if (BalloonRequired(ev))
13049             {
13050                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13051                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13052                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13053                 StringBuilder title = new StringBuilder();
13054                 if (SettingDialog.DispUsername)
13055                 {
13056                     title.Append(tw.Username);
13057                     title.Append(" - ");
13058                 }
13059                 else
13060                 {
13061                     //title.Clear();
13062                 }
13063                 title.Append(Application.ProductName);
13064                 title.Append(" [");
13065                 title.Append(ev.Event.ToUpper());
13066                 title.Append("] by ");
13067                 if (!string.IsNullOrEmpty(ev.Username))
13068                 {
13069                     title.Append(ev.Username.ToString());
13070                 }
13071                 else
13072                 {
13073                     //title.Append("");
13074                 }
13075                 string text;
13076                 if (!string.IsNullOrEmpty(ev.Target))
13077                 {
13078                     //NotifyIcon1.BalloonTipText = ev.Target;
13079                     text = ev.Target;
13080                 }
13081                 else
13082                 {
13083                     //NotifyIcon1.BalloonTipText = " ";
13084                     text = " ";
13085                 }
13086                 //NotifyIcon1.ShowBalloonTip(500);
13087                 if (SettingDialog.IsNotifyUseGrowl)
13088                 {
13089                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13090                               ev.Id.ToString(), title.ToString(), text);
13091                 }
13092                 else
13093                 {
13094                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
13095                     NotifyIcon1.BalloonTipTitle = title.ToString();
13096                     NotifyIcon1.BalloonTipText = text;
13097                     NotifyIcon1.ShowBalloonTip(500);
13098                 }
13099             }
13100
13101             //サウンド再生
13102             string snd = SettingDialog.EventSoundFile;
13103             if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(snd))
13104             {
13105                 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13106                 {
13107                     try
13108                     {
13109                         string dir = Application.StartupPath;
13110                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13111                         {
13112                             dir = Path.Combine(dir, "Sounds");
13113                         }
13114                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13115                         {
13116                             player.Play();
13117                         }
13118                     }
13119                     catch (Exception)
13120                     {
13121                     }
13122                 }
13123             }
13124         }
13125
13126         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13127         {
13128             MenuItemUserStream.Enabled = false;
13129             if (StopRefreshAllMenuItem.Checked)
13130             {
13131                 StopRefreshAllMenuItem.Checked = false;
13132                 return;
13133             }
13134             if (this._isActiveUserstream)
13135             {
13136                 tw.StopUserStream();
13137             }
13138             else
13139             {
13140                 tw.StartUserStream();
13141             }
13142         }
13143
13144         private static string inputTrack = "";
13145
13146         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13147         {
13148             if (TrackToolStripMenuItem.Checked)
13149             {
13150                 using (InputTabName inputForm = new InputTabName())
13151                 {
13152                     inputForm.TabName = inputTrack;
13153                     inputForm.FormTitle = "Input track word";
13154                     inputForm.FormDescription = "Track word";
13155                     if (inputForm.ShowDialog() != DialogResult.OK)
13156                     {
13157                         TrackToolStripMenuItem.Checked = false;
13158                         return;
13159                     }
13160                     inputTrack = inputForm.TabName.Trim();
13161                 }
13162                 if (!inputTrack.Equals(tw.TrackWord))
13163                 {
13164                     tw.TrackWord = inputTrack;
13165                     this._modifySettingCommon = true;
13166                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13167                     tw.ReconnectUserStream();
13168                 }
13169             }
13170             else
13171             {
13172                 tw.TrackWord = "";
13173                 tw.ReconnectUserStream();
13174             }
13175             this._modifySettingCommon = true;
13176         }
13177
13178         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13179         {
13180             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13181             this._modifySettingCommon = true;
13182             tw.ReconnectUserStream();
13183         }
13184
13185         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13186         {
13187             if (evtDialog == null || evtDialog.IsDisposed)
13188             {
13189                 evtDialog = null;
13190                 evtDialog = new EventViewerDialog();
13191                 evtDialog.Owner = this;
13192                 //親の中央に表示
13193                 Point pos = evtDialog.Location;
13194                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13195                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13196                 evtDialog.Location = pos;
13197             }
13198             evtDialog.EventSource = tw.StoredEvent;
13199             if (!evtDialog.Visible)
13200             {
13201                 evtDialog.Show(this);
13202             }
13203             else
13204             {
13205                 evtDialog.Activate();
13206             }
13207             this.TopMost = this.SettingDialog.AlwaysTop;
13208         }
13209 #endregion
13210
13211         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13212         {
13213             MyCommon._endingFlag = true;
13214             try
13215             {
13216                 this.Close();
13217                 Application.Restart();
13218             }
13219             catch (Exception)
13220             {
13221                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13222             }
13223         }
13224
13225         private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13226         {
13227             if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13228         }
13229
13230         private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13231         {
13232             OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
13233         }
13234
13235         private async Task doTranslation(string str)
13236         {
13237             if (string.IsNullOrEmpty(str))
13238                 return;
13239
13240             var bing = new Bing(this.http);
13241             try
13242             {
13243                 var translatedText = await bing.TranslateAsync(str,
13244                     langFrom: null,
13245                     langTo: this.SettingDialog.TranslateLanguage);
13246
13247                 this.PostBrowser.DocumentText = translatedText;
13248             }
13249             catch (HttpRequestException e)
13250             {
13251                 this.StatusLabel.Text = "Err:" + e.Message;
13252             }
13253         }
13254
13255         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13256         {
13257             if (!this.ExistCurrentPost)
13258                 return;
13259
13260             await this.doTranslation(this._curPost.TextFromApi);
13261         }
13262
13263         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13264         {
13265             var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
13266             await this.doTranslation(text);
13267         }
13268
13269         private bool ExistCurrentPost
13270         {
13271             get
13272             {
13273                 if (_curPost == null) return false;
13274                 if (_curPost.IsDeleted) return false;
13275                 return true;
13276             }
13277         }
13278
13279         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13280         {
13281             ShowUserTimeline();
13282         }
13283
13284         public bool FavEventChangeUnread
13285         {
13286             get { return SettingDialog.FavEventUnread; }
13287         }
13288
13289         private string GetUserIdFromCurPostOrInput(string caption)
13290         {
13291             string id = "";
13292             if (_curPost != null)
13293             {
13294                 id = _curPost.ScreenName;
13295             }
13296             using (InputTabName inputName = new InputTabName())
13297             {
13298                 inputName.FormTitle = caption;
13299                 inputName.FormDescription = Properties.Resources.FRMessage1;
13300                 inputName.TabName = id;
13301                 if (inputName.ShowDialog() == DialogResult.OK &&
13302                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13303                 {
13304                     id = inputName.TabName.Trim();
13305                 }
13306                 else
13307                 {
13308                     id = "";
13309                 }
13310             }
13311             return id;
13312         }
13313
13314         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13315         {
13316             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13317             if (!string.IsNullOrEmpty(id))
13318             {
13319                 AddNewTabForUserTimeline(id);
13320             }
13321         }
13322
13323         private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13324         {
13325             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13326             if (!string.IsNullOrEmpty(id))
13327             {
13328                 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13329             }
13330         }
13331
13332         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13333         {
13334             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13335         }
13336
13337         private void TimelineRefreshEnableChange(bool isEnable)
13338         {
13339             if (isEnable)
13340             {
13341                 tw.StartUserStream();
13342             }
13343             else
13344             {
13345                 tw.StopUserStream();
13346             }
13347             TimerTimeline.Enabled = isEnable;
13348         }
13349
13350         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13351         {
13352             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13353         }
13354
13355         private void OpenUserAppointUrl()
13356         {
13357             if (SettingDialog.UserAppointUrl != null)
13358             {
13359                 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
13360                 {
13361                     if (_curPost != null)
13362                     {
13363                         string xUrl = SettingDialog.UserAppointUrl;
13364                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13365                         if (_curPost.RetweetedId != null)
13366                         {
13367                             xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
13368                         }
13369                         else
13370                         {
13371                             xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
13372                         }
13373                         OpenUriAsync(xUrl);
13374                     }
13375                 }
13376                 else
13377                 {
13378                     OpenUriAsync(SettingDialog.UserAppointUrl);
13379                 }
13380             }
13381         }
13382
13383         private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13384         {
13385             OpenUserAppointUrl();
13386         }
13387
13388         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13389         {
13390             string selText = SourceLinkLabel.Text;
13391             try
13392             {
13393                 Clipboard.SetDataObject(selText, false, 5, 100);
13394             }
13395             catch (Exception ex)
13396             {
13397                 MessageBox.Show(ex.Message);
13398             }
13399         }
13400
13401         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13402         {
13403             string selText = (string)SourceLinkLabel.Tag;
13404             try
13405             {
13406                 Clipboard.SetDataObject(selText, false, 5, 100);
13407             }
13408             catch (Exception ex)
13409             {
13410                 MessageBox.Show(ex.Message);
13411             }
13412         }
13413
13414         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13415         {
13416             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13417             {
13418                 SourceCopyMenuItem.Enabled = false;
13419                 SourceUrlCopyMenuItem.Enabled = false;
13420             }
13421             else
13422             {
13423                 SourceCopyMenuItem.Enabled = true;
13424                 SourceUrlCopyMenuItem.Enabled = true;
13425             }
13426         }
13427
13428         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13429         {
13430             if (Form.ActiveForm == null)
13431             {
13432                 this.BeginInvoke((Action) (() =>
13433                 {
13434                     this.Visible = true;
13435                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13436                     this.Activate();
13437                     this.BringToFront();
13438                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13439                     {
13440                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13441                     }
13442                     else
13443                     {
13444                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13445                     }
13446                 }));
13447             }
13448         }
13449
13450         private void ReplaceAppName()
13451         {
13452             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13453             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13454         }
13455
13456         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13457         {
13458             this.SplitContainer3.Panel2Collapsed = false;
13459
13460             // PreviewDistance が起動のたびに広がっていく問題の回避策
13461             // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13462             // None で開いた後に設定するようにする
13463             if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13464                 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13465         }
13466
13467         private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13468         {
13469             this.OpenThumbnailPicture(e.Thumbnail);
13470         }
13471
13472         private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13473         {
13474             this.OpenUriAsync(e.ImageUrl);
13475         }
13476
13477         private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13478         {
13479             this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13480         }
13481
13482         private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13483         {
13484             this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13485         }
13486
13487         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13488         {
13489             if (e.KeyCode == Keys.Space)
13490             {
13491                 this.JumpUnreadMenuItem_Click(null, null);
13492
13493                 e.SuppressKeyPress = true;
13494             }
13495         }
13496
13497         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13498         {
13499             this.IconSizeNoneToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.IconNone;
13500             this.IconSize16ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon16;
13501             this.IconSize24ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon24;
13502             this.IconSize48ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48;
13503             this.IconSize48_2ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48_2;
13504
13505             this.LockListSortOrderToolStripMenuItem.Checked = SettingDialog.SortOrderLock;
13506         }
13507
13508         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13509         {
13510             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13511         }
13512
13513         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13514         {
13515             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13516         }
13517
13518         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13519         {
13520             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13521         }
13522
13523         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13524         {
13525             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13526         }
13527
13528         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13529         {
13530             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13531         }
13532
13533         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13534         {
13535             if (SettingDialog.IconSz == iconSize) return;
13536
13537             var oldIconCol = _iconCol;
13538
13539             SettingDialog.IconSz = iconSize;
13540             ApplyListViewIconSize(iconSize);
13541
13542             if (_iconCol != oldIconCol)
13543             {
13544                 foreach (TabPage tp in ListTab.TabPages)
13545                 {
13546                     ResetColumns((DetailsListView)tp.Tag);
13547                 }
13548             }
13549
13550             if (_curList != null) _curList.Refresh();
13551
13552             _modifySettingCommon = true;
13553         }
13554
13555         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13556         {
13557             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13558             if (SettingDialog.SortOrderLock == state) return;
13559
13560             SettingDialog.SortOrderLock = state;
13561
13562             _modifySettingCommon = true;
13563         }
13564     }
13565 }