OSDN Git Service

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