OSDN Git Service

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