OSDN Git Service

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