OSDN Git Service

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