OSDN Git Service

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