OSDN Git Service

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