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.
10 // This file is part of OpenTween.
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)
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
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.
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)"
32 using System.Collections.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
40 using System.Net.Http;
41 using System.Reflection;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
54 public partial class TweenMain : OTBaseForm
56 private readonly HttpClient http;
59 private Size _mySize; //画面サイズ
60 private Point _myLoc; //画面位置
61 private int _mySpDis; //区切り位置
62 private int _mySpDis2; //発言欄区切り位置
63 private int _mySpDis3; //プレビュー区切り位置
64 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
65 private bool _iconCol; //1列表示の時true(48サイズのとき)
68 private bool _initial; //true:起動時処理中
69 private bool _initialLayout = true;
70 private bool _ignoreConfigSave; //true:起動時処理中
71 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
72 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
73 private Point _tabMouseDownPoint;
74 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
75 private readonly object _syncObject = new object(); //ロック用
76 private const string detailHtmlFormatMono1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- pre {font-family: \"";
77 private const string detailHtmlFormat2 = "\", sans-serif; font-size: ";
78 private const string detailHtmlFormat3 = "pt; margin: 0; word-wrap: break-word; white-space: pre-wrap; color:rgb(";
79 private const string detailHtmlFormat4 = ");} a:link, a:visited, a:active, a:hover {color:rgb(";
80 private const string detailHtmlFormat5 = "); } --></style></head><body style=\"margin:0px; background-color:rgb(";
81 private const string detailHtmlFormatMono6 = ");\"><pre>";
82 private const string detailHtmlFormatMono7 = "</pre></body></html>";
83 private const string detailHtmlFormat1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- p {font-family: \"";
84 private const string detailHtmlFormat6 = ");\"><p><span style=\"vertical-align:text-bottom\">";
85 private const string detailHtmlFormat7 = "</span></p></body></html>";
86 private string detailHtmlFormatHeader;
87 private string detailHtmlFormatFooter;
88 private bool _myStatusError = false;
89 private bool _myStatusOnline = false;
90 private bool soundfileListup = false;
91 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
94 //private SettingToConfig _cfg; //旧
95 private SettingLocal _cfgLocal;
96 private SettingCommon _cfgCommon;
97 private bool _modifySettingLocal = false;
98 private bool _modifySettingCommon = false;
99 private bool _modifySettingAtId = false;
102 private Twitter tw = new Twitter();
105 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
108 private AppendSettingDialog SettingDialog = AppendSettingDialog.Instance; //設定画面インスタンス
109 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
110 private FilterDialog fltDialog = new FilterDialog(); //フィルター編集画面
111 private OpenURL UrlDialog = new OpenURL();
112 public AtIdSupplement AtIdSupl; //@id補助
113 public AtIdSupplement HashSupl; //Hashtag補助
114 public HashtagManage HashMgr;
115 private EventViewerDialog evtDialog;
118 private Font _fntUnread; //未読用フォント
119 private Color _clUnread; //未読用文字色
120 private Font _fntReaded; //既読用フォント
121 private Color _clReaded; //既読用文字色
122 private Color _clFav; //Fav用文字色
123 private Color _clOWL; //片思い用文字色
124 private Color _clRetweet; //Retweet用文字色
125 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
126 private Font _fntDetail; //発言詳細部用フォント
127 private Color _clDetail; //発言詳細部用色
128 private Color _clDetailLink; //発言詳細部用リンク文字色
129 private Color _clDetailBackcolor; //発言詳細部用背景色
130 private Color _clSelf; //自分の発言用背景色
131 private Color _clAtSelf; //自分宛返信用背景色
132 private Color _clTarget; //選択発言者の他の発言用背景色
133 private Color _clAtTarget; //選択発言中の返信先用背景色
134 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
135 private Color _clAtTo; //選択発言の唯一@先
136 private Color _clListBackcolor; //リスト部通常発言背景色
137 private Color _clInputBackcolor; //入力欄背景色
138 private Color _clInputFont; //入力欄文字色
139 private Font _fntInputFont; //入力欄フォント
140 private ImageCache IconCache; //アイコン画像リスト
141 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
142 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
143 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
144 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
145 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
146 private Icon MainIcon; //Main.ico 画面左上のアイコン
147 private Icon ReplyIcon; //5g
148 private Icon ReplyIconBlink; //6g
150 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
152 private PostClass _anchorPost;
153 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
155 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
156 private int _hisIdx; //発言履歴カレントインデックス
158 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
159 private long? _reply_to_id; // リプライ先のステータスID 0の場合はリプライではない 注:複数あてのものはリプライではない
160 private string _reply_to_name; // リプライ先ステータスの書き込み者の名前
163 private List<DateTime> _postTimestamps = new List<DateTime>();
164 private List<DateTime> _favTimestamps = new List<DateTime>();
165 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
166 private int _tlCount;
169 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
170 private SolidBrush _brsBackColorMine;
171 private SolidBrush _brsBackColorAt;
172 private SolidBrush _brsBackColorYou;
173 private SolidBrush _brsBackColorAtYou;
174 private SolidBrush _brsBackColorAtFromTarget;
175 private SolidBrush _brsBackColorAtTo;
176 private SolidBrush _brsBackColorNone;
177 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
178 private StringFormat sfTab = new StringFormat();
180 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 private ToolStripAPIGauge _apiGauge;
182 private TabInformations _statuses;
184 // ListViewItem のキャッシュ関連
185 private int _itemCacheIndex;
186 private ListViewItem[] _itemCache;
187 private PostClass[] _postCache;
188 private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
190 private TabPage _curTab;
191 private int _curItemIndex;
192 private DetailsListView _curList;
193 private PostClass _curPost;
194 private bool _isColumnChanged = false;
195 private bool _waitTimeline = false;
196 private bool _waitReply = false;
197 private bool _waitDm = false;
198 private bool _waitFav = false;
199 private bool _waitPubSearch = false;
200 private bool _waitUserTimeline = false;
201 private bool _waitLists = false;
202 private BackgroundWorker[] _bw = new BackgroundWorker[20];
203 private BackgroundWorker _bwFollower;
204 private InternetSecurityManager SecurityManager;
206 private int UnreadCounter = -1;
207 private int UnreadAtCounter = -1;
209 private string[] ColumnOrgText = new string[9];
210 private string[] ColumnText = new string[9];
212 private bool _DoFavRetweetFlags = false;
213 private bool osResumed = false;
215 //////////////////////////////////////////////////////////////////////////////////////////////////////////
216 private string _postBrowserStatusText = "";
218 private bool _colorize = false;
220 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
222 private ImageListViewItem displayItem;
225 /// デザイン時の DPI (96dpi) と実際の表示時の DPI との比を表します
227 protected SizeF currentScaleFactor = new SizeF();
230 private struct urlUndo
232 public string Before;
236 private List<urlUndo> urlUndoBuffer = null;
238 private struct ReplyChain
240 public long OriginalId;
241 public long InReplyToId;
242 public TabPage OriginalTab;
244 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
246 this.OriginalId = originalId;
247 this.InReplyToId = inReplyToId;
248 this.OriginalTab = originalTab;
252 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
253 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
255 //Backgroundworkerの処理結果通知用引数構造体
256 private class GetWorkerResult
258 public string retMsg = ""; //処理結果詳細メッセージ。エラー時に値がセットされる
259 public int page; //取得対象ページ番号
260 public int endPage = 0; //取得終了ページ番号(継続可能ならインクリメントされて返る。pageと比較して継続判定)
261 public MyCommon.WORKERTYPE type; //処理種別
262 public Dictionary<string, Image> imgs = null; //新規取得したアイコンイメージ
263 public string tName = ""; //Fav追加・削除時のタブ名
264 public List<long> ids = null; //Fav追加・削除時のID
265 public List<long> sIds = null; //Fav追加・削除成功分のID
266 public bool newDM = false;
268 public PostingStatus status;
271 //Backgroundworkerへ処理内容を通知するための引数用構造体
272 private class GetWorkerArg
274 public int page; //処理対象ページ番号
275 public int endPage; //処理終了ページ番号(起動時の読み込みページ数。通常時はpageと同じ値をセット)
276 public MyCommon.WORKERTYPE type; //処理種別
277 public string url = ""; //URLをブラウザで開くときのアドレス
278 public PostingStatus status = new PostingStatus(); //発言POST時の発言内容
279 public List<long> ids; //Fav追加・削除時のItemIndex
280 public List<long> sIds; //Fav追加・削除成功分のItemIndex
281 public string tName = ""; //Fav追加・削除時のタブ名
285 private enum SEARCHTYPE
292 private class PostingStatus
294 public string status = "";
295 public long? inReplyToId = null;
296 public string inReplyToName = null;
297 public string imageService = ""; //画像投稿サービス名
298 public string[] imagePath = null;
299 public PostingStatus()
302 public PostingStatus(string status, long? replyToId, string replyToName)
304 this.status = status;
305 this.inReplyToId = replyToId;
306 this.inReplyToName = replyToName;
310 private void TweenMain_Activated(object sender, EventArgs e)
312 //画面がアクティブになったら、発言欄の背景色戻す
313 if (StatusText.Focused)
315 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
319 private void TweenMain_Disposed(object sender, EventArgs e)
322 SettingDialog.Dispose();
323 SearchDialog.Dispose();
326 if (NIconAt != null) NIconAt.Dispose();
327 if (NIconAtRed != null) NIconAtRed.Dispose();
328 if (NIconAtSmoke != null) NIconAtSmoke.Dispose();
329 if (NIconRefresh[0] != null) NIconRefresh[0].Dispose();
330 if (NIconRefresh[1] != null) NIconRefresh[1].Dispose();
331 if (NIconRefresh[2] != null) NIconRefresh[2].Dispose();
332 if (NIconRefresh[3] != null) NIconRefresh[3].Dispose();
333 if (TabIcon != null) TabIcon.Dispose();
334 if (MainIcon != null) MainIcon.Dispose();
335 if (ReplyIcon != null) ReplyIcon.Dispose();
336 if (ReplyIconBlink != null) ReplyIconBlink.Dispose();
337 _listViewImageList.Dispose();
338 _brsHighLight.Dispose();
339 if (_brsBackColorMine != null) _brsBackColorMine.Dispose();
340 if (_brsBackColorAt != null) _brsBackColorAt.Dispose();
341 if (_brsBackColorYou != null) _brsBackColorYou.Dispose();
342 if (_brsBackColorAtYou != null) _brsBackColorAtYou.Dispose();
343 if (_brsBackColorAtFromTarget != null) _brsBackColorAtFromTarget.Dispose();
344 if (_brsBackColorAtTo != null) _brsBackColorAtTo.Dispose();
345 if (_brsBackColorNone != null) _brsBackColorNone.Dispose();
346 if (_brsDeactiveSelection != null) _brsDeactiveSelection.Dispose();
349 foreach (BackgroundWorker bw in _bw)
354 if (_bwFollower != null)
356 _bwFollower.Dispose();
358 this._apiGauge.Dispose();
359 if (IconCache != null)
361 this.IconCache.CancelAsync();
362 this.IconCache.Dispose();
367 // 終了時にRemoveHandlerしておかないとメモリリークする
368 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
369 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
372 private void LoadIcon(ref Icon IconInstance, string FileName)
374 string dir = Application.StartupPath;
375 if (File.Exists(Path.Combine(dir, FileName)))
379 IconInstance = new Icon(Path.Combine(dir, FileName));
387 private void LoadIcons()
391 string dir = Application.StartupPath;
393 NIconAt = Properties.Resources.At;
394 NIconAtRed = Properties.Resources.AtRed;
395 NIconAtSmoke = Properties.Resources.AtSmoke;
396 NIconRefresh[0] = Properties.Resources.Refresh;
397 NIconRefresh[1] = Properties.Resources.Refresh2;
398 NIconRefresh[2] = Properties.Resources.Refresh3;
399 NIconRefresh[3] = Properties.Resources.Refresh4;
400 TabIcon = Properties.Resources.TabIcon;
401 MainIcon = Properties.Resources.MIcon;
402 ReplyIcon = Properties.Resources.Reply;
403 ReplyIconBlink = Properties.Resources.ReplyBlink;
405 if (!Directory.Exists(Path.Combine(dir, "Icons")))
408 LoadIcon(ref NIconAt, "Icons\\At.ico");
411 LoadIcon(ref NIconAtRed, "Icons\\AtRed.ico");
414 LoadIcon(ref NIconAtSmoke, "Icons\\AtSmoke.ico");
417 //アニメーション対応により4種類読み込み
418 LoadIcon(ref NIconRefresh[0], "Icons\\Refresh.ico");
419 LoadIcon(ref NIconRefresh[1], "Icons\\Refresh2.ico");
420 LoadIcon(ref NIconRefresh[2], "Icons\\Refresh3.ico");
421 LoadIcon(ref NIconRefresh[3], "Icons\\Refresh4.ico");
424 LoadIcon(ref TabIcon, "Icons\\Tab.ico");
427 LoadIcon(ref MainIcon, "Icons\\MIcon.ico");
430 LoadIcon(ref ReplyIcon, "Icons\\Reply.ico");
433 LoadIcon(ref ReplyIconBlink, "Icons\\ReplyBlink.ico");
436 private void InitColumns(ListView list, bool startup)
438 ColumnHeader _colHd1 = new ColumnHeader(); //アイコン
439 ColumnHeader _colHd2 = new ColumnHeader(); //ニックネーム
440 ColumnHeader _colHd3 = new ColumnHeader(); //本文
441 ColumnHeader _colHd4 = new ColumnHeader(); //日付
442 ColumnHeader _colHd5 = new ColumnHeader(); //ユーザID
443 ColumnHeader _colHd6 = new ColumnHeader(); //未読
444 ColumnHeader _colHd7 = new ColumnHeader(); //マーク&プロテクト
445 ColumnHeader _colHd8 = new ColumnHeader(); //ソース
449 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
453 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
457 _colHd1.Text = ColumnText[0];
459 _colHd2.Text = ColumnText[1];
461 _colHd3.Text = ColumnText[2];
463 _colHd4.Text = ColumnText[3];
465 _colHd5.Text = ColumnText[4];
467 _colHd6.Text = ColumnText[5];
469 _colHd7.Text = ColumnText[6];
471 _colHd8.Text = ColumnText[7];
474 int[] dispOrder = new int[8];
477 for (int i = 0; i < _curList.Columns.Count; i++)
479 for (int j = 0; j < _curList.Columns.Count; j++)
481 if (_curList.Columns[j].DisplayIndex == i)
488 for (int i = 0; i < _curList.Columns.Count; i++)
490 list.Columns[i].Width = _curList.Columns[i].Width;
491 list.Columns[dispOrder[i]].DisplayIndex = i;
498 list.Columns[0].Width = _cfgLocal.Width1;
499 list.Columns[1].Width = _cfgLocal.Width3;
500 list.Columns[0].DisplayIndex = 0;
501 list.Columns[1].DisplayIndex = 1;
505 for (int i = 0; i <= 7; i++)
507 if (_cfgLocal.DisplayIndex1 == i)
509 else if (_cfgLocal.DisplayIndex2 == i)
511 else if (_cfgLocal.DisplayIndex3 == i)
513 else if (_cfgLocal.DisplayIndex4 == i)
515 else if (_cfgLocal.DisplayIndex5 == i)
517 else if (_cfgLocal.DisplayIndex6 == i)
519 else if (_cfgLocal.DisplayIndex7 == i)
521 else if (_cfgLocal.DisplayIndex8 == i)
524 list.Columns[0].Width = _cfgLocal.Width1;
525 list.Columns[1].Width = _cfgLocal.Width2;
526 list.Columns[2].Width = _cfgLocal.Width3;
527 list.Columns[3].Width = _cfgLocal.Width4;
528 list.Columns[4].Width = _cfgLocal.Width5;
529 list.Columns[5].Width = _cfgLocal.Width6;
530 list.Columns[6].Width = _cfgLocal.Width7;
531 list.Columns[7].Width = _cfgLocal.Width8;
532 for (int i = 0; i <= 7; i++)
534 list.Columns[dispOrder[i]].DisplayIndex = i;
540 private void InitColumnText()
543 ColumnText[1] = Properties.Resources.AddNewTabText2;
544 ColumnText[2] = Properties.Resources.AddNewTabText3;
545 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
546 ColumnText[4] = Properties.Resources.AddNewTabText5;
549 ColumnText[7] = "Source";
551 ColumnOrgText[0] = "";
552 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
553 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
554 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
555 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
556 ColumnOrgText[5] = "";
557 ColumnOrgText[6] = "";
558 ColumnOrgText[7] = "Source";
561 switch (_statuses.SortMode)
563 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
566 case IdComparerClass.ComparerMode.Data: //本文
569 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
572 case IdComparerClass.ComparerMode.Name: //名前
575 case IdComparerClass.ComparerMode.Source: //Source
582 if (_statuses.SortOrder == SortOrder.Descending)
584 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
585 ColumnText[2] = ColumnOrgText[2] + "▾";
589 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
590 ColumnText[2] = ColumnOrgText[2] + "▴";
595 if (_statuses.SortOrder == SortOrder.Descending)
597 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
598 ColumnText[c] = ColumnOrgText[c] + "▾";
602 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
603 ColumnText[c] = ColumnOrgText[c] + "▴";
608 private void InitializeTraceFrag()
611 TraceOutToolStripMenuItem.Checked = true;
612 MyCommon.TraceFlag = true;
614 if (!MyCommon.FileVersion.EndsWith("0"))
616 TraceOutToolStripMenuItem.Checked = true;
617 MyCommon.TraceFlag = true;
621 private void TweenMain_Load(object sender, EventArgs e)
623 _ignoreConfigSave = true;
624 this.Visible = false;
626 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
628 SecurityManager = new InternetSecurityManager(PostBrowser);
629 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
631 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
632 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
634 if (MyApplication.StartupOptions.ContainsKey("d"))
635 MyCommon.TraceFlag = true;
637 Regex.CacheSize = 100;
639 InitializeTraceFrag();
640 LoadIcons(); // アイコン読み込み
643 _statuses = TabInformations.GetInstance();
646 this.Icon = MainIcon; //メインフォーム(TweenMain)
647 NotifyIcon1.Icon = NIconAt; //タスクトレイ
648 TabImage.Images.Add(TabIcon); //タブ見出し
650 SettingDialog.Owner = this;;
651 SearchDialog.Owner = this;
652 fltDialog.Owner = this;
653 UrlDialog.Owner = this;
655 _history.Add(new PostingStatus());
658 _reply_to_name = null;
660 //<<<<<<<<<設定関連>>>>>>>>>
667 ThumbnailGenerator.InitializeGenerator(this.http);
669 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
670 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
671 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
673 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
674 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
675 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
678 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
679 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
682 _fntUnread = _cfgLocal.FontUnread;
683 _clUnread = _cfgLocal.ColorUnread;
684 _fntReaded = _cfgLocal.FontRead;
685 _clReaded = _cfgLocal.ColorRead;
686 _clFav = _cfgLocal.ColorFav;
687 _clOWL = _cfgLocal.ColorOWL;
688 _clRetweet = _cfgLocal.ColorRetweet;
689 _fntDetail = _cfgLocal.FontDetail;
690 _clDetail = _cfgLocal.ColorDetail;
691 _clDetailLink = _cfgLocal.ColorDetailLink;
692 _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
693 _clSelf = _cfgLocal.ColorSelf;
694 _clAtSelf = _cfgLocal.ColorAtSelf;
695 _clTarget = _cfgLocal.ColorTarget;
696 _clAtTarget = _cfgLocal.ColorAtTarget;
697 _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
698 _clAtTo = _cfgLocal.ColorAtTo;
699 _clListBackcolor = _cfgLocal.ColorListBackcolor;
700 _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
701 _clInputFont = _cfgLocal.ColorInputFont;
702 _fntInputFont = _cfgLocal.FontInputFont;
704 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
705 if (fontUIGlobal != null)
707 OTBaseForm.GlobalFont = fontUIGlobal;
708 this.Font = fontUIGlobal;
711 // StringFormatオブジェクトへの事前設定
712 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
713 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
714 //sf.FormatFlags = StringFormatFlags.LineLimit; //
715 sfTab.Alignment = StringAlignment.Center;
716 sfTab.LineAlignment = StringAlignment.Center;
719 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
720 SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
723 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
724 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
726 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
728 SettingDialog.TimelinePeriodInt = _cfgCommon.TimelinePeriod;
729 SettingDialog.ReplyPeriodInt = _cfgCommon.ReplyPeriod;
730 SettingDialog.DMPeriodInt = _cfgCommon.DMPeriod;
731 SettingDialog.PubSearchPeriodInt = _cfgCommon.PubSearchPeriod;
732 SettingDialog.UserTimelinePeriodInt = _cfgCommon.UserTimelinePeriod;
733 SettingDialog.ListsPeriodInt = _cfgCommon.ListsPeriod;
735 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
737 if (SettingDialog.TimelinePeriodInt < 15 && SettingDialog.TimelinePeriodInt > 0) SettingDialog.TimelinePeriodInt = 15;
738 if (SettingDialog.ReplyPeriodInt < 15 && SettingDialog.ReplyPeriodInt > 0) SettingDialog.ReplyPeriodInt = 15;
739 if (SettingDialog.DMPeriodInt < 15 && SettingDialog.DMPeriodInt > 0) SettingDialog.DMPeriodInt = 15;
740 if (SettingDialog.PubSearchPeriodInt < 30 && SettingDialog.PubSearchPeriodInt > 0) SettingDialog.PubSearchPeriodInt = 30;
741 if (SettingDialog.UserTimelinePeriodInt < 15 && SettingDialog.UserTimelinePeriodInt > 0) SettingDialog.UserTimelinePeriodInt = 15;
742 if (SettingDialog.ListsPeriodInt < 15 && SettingDialog.ListsPeriodInt > 0) SettingDialog.ListsPeriodInt = 15;
745 //起動時読み込み分を既読にするか。trueなら既読として処理
746 SettingDialog.Readed = _cfgCommon.Read;
747 //新着取得時のリストスクロールをするか。trueならスクロールしない
748 ListLockMenuItem.Checked = _cfgCommon.ListLock;
749 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
750 SettingDialog.IconSz = _cfgCommon.IconSize;
752 SettingDialog.Status = _cfgLocal.StatusText;
754 SettingDialog.UnreadManage = _cfgCommon.UnreadManage;
756 SettingDialog.PlaySound = _cfgCommon.PlaySound;
757 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
758 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
759 //片思い表示。trueなら片思い表示する
760 SettingDialog.OneWayLove = _cfgCommon.OneWayLove;
762 SettingDialog.FontUnread = _fntUnread;
763 SettingDialog.ColorUnread = _clUnread;
764 SettingDialog.FontReaded = _fntReaded;
765 SettingDialog.ColorReaded = _clReaded;
766 SettingDialog.ColorFav = _clFav;
767 SettingDialog.ColorOWL = _clOWL;
768 SettingDialog.ColorRetweet = _clRetweet;
769 SettingDialog.FontDetail = _fntDetail;
770 SettingDialog.ColorDetail = _clDetail;
771 SettingDialog.ColorDetailLink = _clDetailLink;
772 SettingDialog.ColorDetailBackcolor = _clDetailBackcolor;
773 SettingDialog.ColorSelf = _clSelf;
774 SettingDialog.ColorAtSelf = _clAtSelf;
775 SettingDialog.ColorTarget = _clTarget;
776 SettingDialog.ColorAtTarget = _clAtTarget;
777 SettingDialog.ColorAtFromTarget = _clAtFromTarget;
778 SettingDialog.ColorAtTo = _clAtTo;
779 SettingDialog.ColorListBackcolor = _clListBackcolor;
780 SettingDialog.ColorInputBackcolor = _clInputBackcolor;
781 SettingDialog.ColorInputFont = _clInputFont;
782 SettingDialog.FontInputFont = _fntInputFont;
784 SettingDialog.NameBalloon = _cfgCommon.NameBalloon;
785 SettingDialog.PostCtrlEnter = _cfgCommon.PostCtrlEnter;
786 SettingDialog.PostShiftEnter = _cfgCommon.PostShiftEnter;
788 SettingDialog.CountApi = _cfgCommon.CountApi;
789 SettingDialog.CountApiReply = _cfgCommon.CountApiReply;
790 if (SettingDialog.CountApi < 20 || SettingDialog.CountApi > 200) SettingDialog.CountApi = 60;
791 if (SettingDialog.CountApiReply < 20 || SettingDialog.CountApiReply > 200) SettingDialog.CountApiReply = 40;
793 SettingDialog.BrowserPath = _cfgLocal.BrowserPath;
794 SettingDialog.PostAndGet = _cfgCommon.PostAndGet;
795 SettingDialog.UseRecommendStatus = _cfgLocal.UseRecommendStatus;
796 SettingDialog.DispUsername = _cfgCommon.DispUsername;
797 SettingDialog.CloseToExit = _cfgCommon.CloseToExit;
798 SettingDialog.MinimizeToTray = _cfgCommon.MinimizeToTray;
799 SettingDialog.DispLatestPost = _cfgCommon.DispLatestPost;
800 SettingDialog.SortOrderLock = _cfgCommon.SortOrderLock;
801 SettingDialog.ViewTabBottom = _cfgCommon.ViewTabBottom;
802 SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
804 SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
805 SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
806 SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
807 SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
808 SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
810 SettingDialog.StartupVersion = _cfgCommon.StartupVersion;
811 SettingDialog.StartupFollowers = _cfgCommon.StartupFollowers;
812 SettingDialog.RestrictFavCheck = _cfgCommon.RestrictFavCheck;
813 SettingDialog.AlwaysTop = _cfgCommon.AlwaysTop;
814 SettingDialog.UrlConvertAuto = false;
815 //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
817 SettingDialog.UseUnreadStyle = _cfgCommon.UseUnreadStyle;
818 SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
819 SettingDialog.RetweetNoConfirm = _cfgCommon.RetweetNoConfirm;
820 SettingDialog.PlaySound = _cfgCommon.PlaySound;
821 SettingDialog.DateTimeFormat = _cfgCommon.DateTimeFormat;
822 SettingDialog.LimitBalloon = _cfgCommon.LimitBalloon;
823 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
824 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
825 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
826 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
827 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
828 SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
829 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
831 //廃止サービスが選択されていた場合bit.lyへ読み替え
832 if (_cfgCommon.AutoShortUrlFirst < 0)
833 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
835 SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
836 SettingDialog.TabIconDisp = _cfgCommon.TabIconDisp;
837 SettingDialog.ReplyIconState = _cfgCommon.ReplyIconState;
838 SettingDialog.ReadOwnPost = _cfgCommon.ReadOwnPost;
839 SettingDialog.GetFav = _cfgCommon.GetFav;
840 SettingDialog.ReadOldPosts = _cfgCommon.ReadOldPosts;
841 SettingDialog.BitlyUser = _cfgCommon.BilyUser;
842 SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
843 SettingDialog.ShowGrid = _cfgCommon.ShowGrid;
844 SettingDialog.Language = _cfgCommon.Language;
845 SettingDialog.UseAtIdSupplement = _cfgCommon.UseAtIdSupplement;
846 SettingDialog.UseHashSupplement = _cfgCommon.UseHashSupplement;
847 SettingDialog.PreviewEnable = _cfgCommon.PreviewEnable;
848 SettingDialog.StatusAreaAtBottom = _cfgCommon.StatusAreaAtBottom;
849 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
851 SettingDialog.IsMonospace = _cfgCommon.IsMonospace;
853 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
854 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
856 //Regex statregex = new Regex("^0*");
857 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
862 if (DateTime.Now.ToString(SettingDialog.DateTimeFormat).Length == 0)
864 // このブロックは絶対に実行されないはず
865 // 変換が成功した場合にLengthが0にならない
866 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
869 catch (FormatException)
871 // FormatExceptionが発生したら初期値を設定 (=yyyy/MM/dd H:mm:ssとみなされる)
872 SettingDialog.DateTimeFormat = "yyyy/MM/dd H:mm:ss";
875 SettingDialog.Nicoms = _cfgCommon.Nicoms;
876 SettingDialog.HotkeyEnabled = _cfgCommon.HotkeyEnabled;
877 SettingDialog.HotkeyMod = _cfgCommon.HotkeyModifier;
878 SettingDialog.HotkeyKey = _cfgCommon.HotkeyKey;
879 SettingDialog.HotkeyValue = _cfgCommon.HotkeyValue;
881 SettingDialog.BlinkNewMentions = _cfgCommon.BlinkNewMentions;
883 SettingDialog.UseAdditionalCount = _cfgCommon.UseAdditionalCount;
884 SettingDialog.MoreCountApi = _cfgCommon.MoreCountApi;
885 SettingDialog.FirstCountApi = _cfgCommon.FirstCountApi;
886 SettingDialog.SearchCountApi = _cfgCommon.SearchCountApi;
887 SettingDialog.FavoritesCountApi = _cfgCommon.FavoritesCountApi;
888 SettingDialog.UserTimelineCountApi = _cfgCommon.UserTimelineCountApi;
889 SettingDialog.ListCountApi = _cfgCommon.ListCountApi;
891 SettingDialog.UserstreamStartup = _cfgCommon.UserstreamStartup;
892 SettingDialog.UserstreamPeriodInt = _cfgCommon.UserstreamPeriod;
893 SettingDialog.OpenUserTimeline = _cfgCommon.OpenUserTimeline;
894 SettingDialog.ListDoubleClickAction = _cfgCommon.ListDoubleClickAction;
895 SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
896 SettingDialog.HideDuplicatedRetweets = _cfgCommon.HideDuplicatedRetweets;
898 SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
899 SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
900 SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
901 SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
902 SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
903 SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
904 SettingDialog.IsListStatusesIncludeRts = _cfgCommon.IsListsIncludeRts;
905 SettingDialog.TabMouseLock = _cfgCommon.TabMouseLock;
906 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
907 SettingDialog.IsNotifyUseGrowl = _cfgCommon.IsUseNotifyGrowl;
910 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
911 HashMgr = new HashtagManage(HashSupl,
912 _cfgCommon.HashTags.ToArray(),
913 _cfgCommon.HashSelected,
914 _cfgCommon.HashIsPermanent,
915 _cfgCommon.HashIsHead,
916 _cfgCommon.HashIsNotAddToAtReply);
917 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
922 this.IconCache = new ImageCache(this.http);
924 bool saveRequired = false;
925 bool firstRun = false;
927 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
928 if (string.IsNullOrEmpty(tw.Username))
932 SettingDialog.ShowInTaskbar = true;
934 //設定せずにキャンセルされた場合はプログラム終了
935 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
937 Application.Exit(); //強制終了
940 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
941 if (string.IsNullOrEmpty(tw.Username))
943 Application.Exit(); //強制終了
946 SettingDialog.ShowInTaskbar = false;
950 _fntUnread = SettingDialog.FontUnread;
951 _clUnread = SettingDialog.ColorUnread;
952 _fntReaded = SettingDialog.FontReaded;
953 _clReaded = SettingDialog.ColorReaded;
954 _clFav = SettingDialog.ColorFav;
955 _clOWL = SettingDialog.ColorOWL;
956 _clRetweet = SettingDialog.ColorRetweet;
957 _fntDetail = SettingDialog.FontDetail;
958 _clDetail = SettingDialog.ColorDetail;
959 _clDetailLink = SettingDialog.ColorDetailLink;
960 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
961 _clSelf = SettingDialog.ColorSelf;
962 _clAtSelf = SettingDialog.ColorAtSelf;
963 _clTarget = SettingDialog.ColorTarget;
964 _clAtTarget = SettingDialog.ColorAtTarget;
965 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
966 _clAtTo = SettingDialog.ColorAtTo;
967 _clListBackcolor = SettingDialog.ColorListBackcolor;
968 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
969 _clInputFont = SettingDialog.ColorInputFont;
970 _fntInputFont = SettingDialog.FontInputFont;
972 //他の設定項目は、随時設定画面で保持している値を読み出して使用
975 _brsBackColorMine = new SolidBrush(_clSelf);
976 _brsBackColorAt = new SolidBrush(_clAtSelf);
977 _brsBackColorYou = new SolidBrush(_clTarget);
978 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
979 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
980 _brsBackColorAtTo = new SolidBrush(_clAtTo);
981 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
982 _brsBackColorNone = new SolidBrush(_clListBackcolor);
984 InitDetailHtmlFormat();
986 if (SettingDialog.HotkeyEnabled)
989 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
990 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
991 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
992 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
993 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
995 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
999 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
1000 SettingDialog.SelectedProxyType,
1001 SettingDialog.ProxyAddress,
1002 SettingDialog.ProxyPort,
1003 SettingDialog.ProxyUser,
1004 SettingDialog.ProxyPassword);
1006 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
1007 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
1008 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
1009 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
1010 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
1011 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
1012 tw.TrackWord = _cfgCommon.TrackWord;
1013 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
1014 tw.AllAtReply = _cfgCommon.AllAtReply;
1015 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
1018 ImageSelector.Initialize(tw, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
1021 this.ClientSize = _cfgLocal.FormSize;
1022 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1023 _myLoc = _cfgLocal.FormLocation;
1025 if (this.WindowState != FormWindowState.Minimized)
1027 this.DesktopLocation = _cfgLocal.FormLocation;
1028 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1029 bool outOfScreen = true;
1030 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1032 foreach (Screen scr in Screen.AllScreens)
1034 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1036 outOfScreen = false;
1042 this.DesktopLocation = new Point(0, 0);
1043 _myLoc = this.DesktopLocation;
1047 this.TopMost = SettingDialog.AlwaysTop;
1048 _mySpDis = _cfgLocal.SplitterDistance;
1049 _mySpDis2 = _cfgLocal.StatusTextHeight;
1050 _mySpDis3 = _cfgLocal.PreviewDistance;
1051 if (_mySpDis3 == -1)
1053 _mySpDis3 = _mySize.Width - 150;
1054 if (_mySpDis3 < 1) _mySpDis3 = 50;
1055 _cfgLocal.PreviewDistance = _mySpDis3;
1057 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
1058 //this.Tween_ClientSizeChanged(this, null);
1059 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
1060 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
1062 StatusText.Font = _fntInputFont;
1063 StatusText.ForeColor = _clInputFont;
1065 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
1066 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
1068 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1069 SplitContainer1.IsPanelInverted = !SettingDialog.StatusAreaAtBottom;
1071 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1072 if (SettingDialog.UnreadManage == false)
1074 ReadedStripMenuItem.Enabled = false;
1075 UnreadStripMenuItem.Enabled = false;
1078 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
1081 TimerTimeline.AutoReset = true;
1082 TimerTimeline.SynchronizingObject = this;
1084 TimerTimeline.Interval = 1000;
1085 TimerTimeline.Enabled = true;
1088 TimerRefreshIcon.Interval = 200;
1089 TimerRefreshIcon.Enabled = true;
1092 StatusLabel.Text = "";
1093 StatusLabel.AutoToolTip = false;
1094 StatusLabel.ToolTipText = "";
1096 lblLen.Text = GetRestStatusCount(true, false).ToString();
1098 ////////////////////////////////////////////////////////////////////////////////
1099 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1100 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1101 switch (_cfgCommon.SortColumn)
1103 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1107 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1110 mode = IdComparerClass.ComparerMode.Nickname;
1113 mode = IdComparerClass.ComparerMode.Data;
1116 mode = IdComparerClass.ComparerMode.Id;
1119 mode = IdComparerClass.ComparerMode.Name;
1122 mode = IdComparerClass.ComparerMode.Source;
1125 _statuses.SortMode = mode;
1126 ////////////////////////////////////////////////////////////////////////////////
1128 ApplyListViewIconSize(SettingDialog.IconSz);
1130 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
1132 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1133 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1134 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1135 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1136 SourceLinkLabel.Text = ""; //Source部分初期化
1138 //<<<<<<<<タブ関連>>>>>>>
1139 //デフォルトタブの存在チェック、ない場合には追加
1140 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1143 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1145 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1149 tab.TabType = MyCommon.TabUsageType.Home;
1152 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1155 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1157 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1161 tab.TabType = MyCommon.TabUsageType.Mentions;
1164 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1167 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1169 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1173 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1176 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1179 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1181 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1185 tab.TabType = MyCommon.TabUsageType.Favorites;
1188 foreach (var tab in _statuses.Tabs.Values)
1190 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1192 tab.TabType = MyCommon.TabUsageType.UserDefined;
1194 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo)) throw new Exception(Properties.Resources.TweenMain_LoadText1);
1197 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1198 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1199 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1200 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1202 if (SettingDialog.MinimizeToTray == false || this.WindowState != FormWindowState.Minimized)
1204 this.Visible = true;
1206 _curTab = ListTab.SelectedTab;
1208 _curList = (DetailsListView)_curTab.Tag;
1209 SetMainWindowTitle();
1210 SetNotifyIconText();
1212 if (SettingDialog.TabIconDisp)
1214 ListTab.DrawMode = TabDrawMode.Normal;
1218 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1219 ListTab.DrawItem += ListTab_DrawItem;
1220 ListTab.ImageList = null;
1223 _ignoreConfigSave = false;
1224 this.TweenMain_Resize(null, null);
1225 if (saveRequired) SaveConfigsAll(false);
1229 tw.VerifyCredentials();
1230 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1232 if (ua.Username.ToLower() == tw.Username.ToLower())
1234 ua.UserId = tw.UserId;
1239 foreach (UserAccount ua in SettingDialog.UserAccounts)
1241 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1243 ua.UserId = tw.UserId;
1250 // 初回起動時だけ右下のメニューを目立たせる
1251 HashStripSplitButton.ShowDropDown();
1258 private void InitDetailHtmlFormat()
1260 if (SettingDialog.IsMonospace)
1262 detailHtmlFormatHeader = detailHtmlFormatMono1;
1263 detailHtmlFormatFooter = detailHtmlFormatMono7;
1267 detailHtmlFormatHeader = detailHtmlFormat1;
1268 detailHtmlFormatFooter = detailHtmlFormat7;
1270 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();
1271 if (SettingDialog.IsMonospace)
1273 detailHtmlFormatHeader += detailHtmlFormatMono6;
1277 detailHtmlFormatHeader += detailHtmlFormat6;
1281 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1286 txt = ListTab.TabPages[e.Index].Text;
1293 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1294 if (e.State == DrawItemState.Selected)
1296 e.DrawFocusRectangle();
1301 if (_statuses.Tabs[txt].UnreadCount > 0)
1304 fore = System.Drawing.SystemBrushes.ControlText;
1308 fore = System.Drawing.SystemBrushes.ControlText;
1310 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1313 private void LoadConfig()
1315 _cfgCommon = SettingCommon.Load();
1316 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1318 _cfgCommon.UserAccounts = new List<UserAccount>();
1319 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1321 UserAccount account = new UserAccount();
1322 account.Username = _cfgCommon.UserName;
1323 account.UserId = _cfgCommon.UserId;
1324 account.Token = _cfgCommon.Token;
1325 account.TokenSecret = _cfgCommon.TokenSecret;
1327 _cfgCommon.UserAccounts.Add(account);
1330 _cfgLocal = SettingLocal.Load();
1331 List<TabClass> tabs = SettingTabs.Load().Tabs;
1332 foreach (TabClass tb in tabs)
1336 _statuses.Tabs.Add(tb.TabName, tb);
1340 tb.TabName = _statuses.GetUniqueTabName();
1341 _statuses.Tabs.Add(tb.TabName, tb);
1344 if (_statuses.Tabs.Count == 0)
1346 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1347 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1348 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1349 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1353 private void TimerInterval_Changed(object sender, AppendSettingDialog.IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1355 if (!TimerTimeline.Enabled) return;
1359 private AppendSettingDialog.IntervalChangedEventArgs ResetTimers = new AppendSettingDialog.IntervalChangedEventArgs();
1361 private static int homeCounter = 0;
1362 private static int mentionCounter = 0;
1363 private static int dmCounter = 0;
1364 private static int pubSearchCounter = 0;
1365 private static int userTimelineCounter = 0;
1366 private static int listsCounter = 0;
1367 private static int usCounter = 0;
1368 private static int ResumeWait = 0;
1369 private static int refreshFollowers = 0;
1371 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1373 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1374 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1375 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1376 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1377 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1378 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1379 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1380 Interlocked.Increment(ref refreshFollowers);
1383 if (ResetTimers.Timeline || homeCounter <= 0 && SettingDialog.TimelinePeriodInt > 0)
1385 Interlocked.Exchange(ref homeCounter, SettingDialog.TimelinePeriodInt);
1386 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1387 ResetTimers.Timeline = false;
1389 if (ResetTimers.Reply || mentionCounter <= 0 && SettingDialog.ReplyPeriodInt > 0)
1391 Interlocked.Exchange(ref mentionCounter, SettingDialog.ReplyPeriodInt);
1392 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1393 ResetTimers.Reply = false;
1395 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingDialog.DMPeriodInt > 0)
1397 Interlocked.Exchange(ref dmCounter, SettingDialog.DMPeriodInt);
1398 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1399 ResetTimers.DirectMessage = false;
1401 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingDialog.PubSearchPeriodInt > 0)
1403 Interlocked.Exchange(ref pubSearchCounter, SettingDialog.PubSearchPeriodInt);
1404 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1405 ResetTimers.PublicSearch = false;
1407 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingDialog.UserTimelinePeriodInt > 0)
1409 Interlocked.Exchange(ref userTimelineCounter, SettingDialog.UserTimelinePeriodInt);
1410 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1411 ResetTimers.UserTimeline = false;
1413 if (ResetTimers.Lists || listsCounter <= 0 && SettingDialog.ListsPeriodInt > 0)
1415 Interlocked.Exchange(ref listsCounter, SettingDialog.ListsPeriodInt);
1416 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1417 ResetTimers.Lists = false;
1419 if (ResetTimers.UserStream || usCounter <= 0 && SettingDialog.UserstreamPeriodInt > 0)
1421 Interlocked.Exchange(ref usCounter, SettingDialog.UserstreamPeriodInt);
1422 if (this._isActiveUserstream) RefreshTimeline(true);
1423 ResetTimers.UserStream = false;
1425 if (refreshFollowers > 6 * 3600)
1427 Interlocked.Exchange(ref refreshFollowers, 0);
1428 doGetFollowersMenu();
1429 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
1430 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1434 Interlocked.Increment(ref ResumeWait);
1435 if (ResumeWait > 30)
1438 Interlocked.Exchange(ref ResumeWait, 0);
1439 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
1440 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
1441 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
1442 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, "");
1443 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, "");
1444 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, "");
1445 doGetFollowersMenu();
1446 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
1451 private void RefreshTimeline(bool isUserStream)
1453 if (isUserStream) this.RefreshTasktrayIcon(true);
1455 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1456 long topId = GetScrollPos(ref smode);
1457 int befCnt = _curList.VirtualListSize;
1460 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1461 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1462 SaveSelectedStatus(selId, focusedId);
1465 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1468 PostClass[] notifyPosts = null;
1469 string soundFile = "";
1471 bool isMention = false;
1472 bool isDelete = false;
1473 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1475 if (MyCommon._endingFlag) return;
1480 foreach (TabPage tab in ListTab.TabPages)
1482 DetailsListView lst = (DetailsListView)tab.Tag;
1483 TabClass tabInfo = _statuses.Tabs[tab.Text];
1484 using (ControlTransaction.Update(lst))
1486 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1488 if (lst.Equals(_curList))
1490 this.PurgeListViewItemCache();
1494 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1500 this.SelectListItem(lst,
1501 _statuses.IndexOf(tab.Text, selId[tab.Text]),
1502 _statuses.IndexOf(tab.Text, focusedId[tab.Text]));
1505 if (tabInfo.UnreadCount > 0)
1506 if (SettingDialog.TabIconDisp)
1507 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1509 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
1513 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1522 if (befCnt != _curList.VirtualListSize)
1528 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1532 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1539 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1541 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1542 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1548 catch (Exception ex)
1550 ex.Data["Msg"] = "Ref2";
1556 NotifyNewPosts(notifyPosts,
1559 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1561 SetMainWindowTitle();
1562 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1564 HashSupl.AddRangeItem(tw.GetHashList());
1568 private long GetScrollPos(ref int smode)
1571 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1573 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1575 if (_statuses.SortOrder == SortOrder.Ascending)
1578 if (ListLockMenuItem.Checked)
1583 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1588 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1590 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1591 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1592 if (_item.Index == _curList.VirtualListSize - 1)
1599 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1607 if (ListLockMenuItem.Checked)
1610 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1615 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1618 _item = _curList.GetItemAt(0, 10); //一番上
1619 if (_item == null) _item = _curList.Items[0];
1620 if (_item.Index == 0)
1626 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1635 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1646 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1648 if (MyCommon._endingFlag) return;
1649 foreach (TabPage tab in ListTab.TabPages)
1651 DetailsListView lst = (DetailsListView)tab.Tag;
1652 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1654 selId.Add(tab.Text, _statuses.GetId(tab.Text, lst.SelectedIndices));
1658 selId.Add(tab.Text, new long[1] {-2});
1661 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1662 var item = lst.FocusedItem;
1663 fIds[0] = (item != null) ? _statuses.GetId(tab.Text, item.Index) : -2;
1664 var mIdx = lst.SelectionMark;
1665 fIds[1] = (mIdx > -1) ? _statuses.GetId(tab.Text, mIdx) : -2;
1666 focusedId.Add(tab.Text, fIds);
1671 private bool BalloonRequired()
1673 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1674 ev.Eventtype = MyCommon.EVENTTYPE.None;
1676 return BalloonRequired(ev);
1679 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1681 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1684 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1686 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1689 private bool BalloonRequired(Twitter.FormattedEvent ev)
1692 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1693 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1697 SettingDialog.LimitBalloon &&
1699 this.WindowState == FormWindowState.Minimized ||
1701 Form.ActiveForm == null
1704 !SettingDialog.LimitBalloon
1707 !Win32Api.IsScreenSaverRunning())
1717 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1719 if (notifyPosts != null &&
1720 notifyPosts.Length > 0 &&
1721 this.SettingDialog.ReadOwnPost &&
1722 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1728 if (BalloonRequired())
1730 if (notifyPosts != null && notifyPosts.Length > 0)
1732 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1733 if (SettingDialog.IsNotifyUseGrowl)
1735 StringBuilder sb = new StringBuilder();
1739 foreach (PostClass post in notifyPosts)
1741 if (!(notifyPosts.Length > 3))
1747 if (post.IsReply && !post.IsExcludeReply) reply = true;
1748 if (post.IsDm) dm = true;
1749 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1750 switch (SettingDialog.NameBalloon)
1752 case MyCommon.NameBalloonEnum.UserID:
1753 sb.Append(post.ScreenName).Append(" : ");
1755 case MyCommon.NameBalloonEnum.NickName:
1756 sb.Append(post.Nickname).Append(" : ");
1759 sb.Append(post.TextFromApi);
1760 if (notifyPosts.Length > 3)
1762 if (notifyPosts.Last() != post) continue;
1765 StringBuilder title = new StringBuilder();
1766 GrowlHelper.NotifyType nt;
1767 if (SettingDialog.DispUsername)
1769 title.Append(tw.Username);
1770 title.Append(" - ");
1778 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1779 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1780 title.Append(Application.ProductName);
1781 title.Append(" [DM] ");
1782 title.Append(Properties.Resources.RefreshDirectMessageText1);
1784 title.Append(addCount);
1785 title.Append(Properties.Resources.RefreshDirectMessageText2);
1786 nt = GrowlHelper.NotifyType.DirectMessage;
1790 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1791 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1792 title.Append(Application.ProductName);
1793 title.Append(" [Reply!] ");
1794 title.Append(Properties.Resources.RefreshTimelineText1);
1796 title.Append(addCount);
1797 title.Append(Properties.Resources.RefreshTimelineText2);
1798 nt = GrowlHelper.NotifyType.Reply;
1802 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1803 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1804 title.Append(Application.ProductName);
1806 title.Append(Properties.Resources.RefreshTimelineText1);
1808 title.Append(addCount);
1809 title.Append(Properties.Resources.RefreshTimelineText2);
1810 nt = GrowlHelper.NotifyType.Notify;
1812 string bText = sb.ToString();
1813 if (string.IsNullOrEmpty(bText)) return;
1815 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1816 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1821 StringBuilder sb = new StringBuilder();
1824 foreach (PostClass post in notifyPosts)
1826 if (post.IsReply && !post.IsExcludeReply) reply = true;
1827 if (post.IsDm) dm = true;
1828 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1829 switch (SettingDialog.NameBalloon)
1831 case MyCommon.NameBalloonEnum.UserID:
1832 sb.Append(post.ScreenName).Append(" : ");
1834 case MyCommon.NameBalloonEnum.NickName:
1835 sb.Append(post.Nickname).Append(" : ");
1838 sb.Append(post.TextFromApi);
1841 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1842 StringBuilder title = new StringBuilder();
1844 if (SettingDialog.DispUsername)
1846 title.Append(tw.Username);
1847 title.Append(" - ");
1855 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1856 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1857 ntIcon = ToolTipIcon.Warning;
1858 title.Append(Application.ProductName);
1859 title.Append(" [DM] ");
1860 title.Append(Properties.Resources.RefreshDirectMessageText1);
1862 title.Append(addCount);
1863 title.Append(Properties.Resources.RefreshDirectMessageText2);
1867 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1868 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1869 ntIcon = ToolTipIcon.Warning;
1870 title.Append(Application.ProductName);
1871 title.Append(" [Reply!] ");
1872 title.Append(Properties.Resources.RefreshTimelineText1);
1874 title.Append(addCount);
1875 title.Append(Properties.Resources.RefreshTimelineText2);
1879 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1880 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1881 ntIcon = ToolTipIcon.Info;
1882 title.Append(Application.ProductName);
1884 title.Append(Properties.Resources.RefreshTimelineText1);
1886 title.Append(addCount);
1887 title.Append(Properties.Resources.RefreshTimelineText2);
1889 string bText = sb.ToString();
1890 if (string.IsNullOrEmpty(bText)) return;
1891 //NotifyIcon1.BalloonTipText = sb.ToString();
1892 //NotifyIcon1.ShowBalloonTip(500);
1893 NotifyIcon1.BalloonTipTitle = title.ToString();
1894 NotifyIcon1.BalloonTipText = bText;
1895 NotifyIcon1.BalloonTipIcon = ntIcon;
1896 NotifyIcon1.ShowBalloonTip(500);
1902 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(soundFile))
1906 string dir = Application.StartupPath;
1907 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1909 dir = Path.Combine(dir, "Sounds");
1911 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1921 //mentions新着時に画面ブリンク
1922 if (!_initial && SettingDialog.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1924 Win32Api.FlashMyWindow(this.Handle, Win32Api.FlashSpecification.FlashTray, 3);
1928 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1930 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1932 _curItemIndex = _curList.SelectedIndices[0];
1933 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1937 _curPost = GetCurTabPost(_curItemIndex);
1939 catch (ArgumentException)
1944 this.PushSelectPostChain();
1946 if (SettingDialog.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1948 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1954 private void ChangeCacheStyleRead(bool Read, int Index)
1956 //Read:true=既読 false=未読
1957 //未読管理していなかったら既読として扱う
1958 if (!_statuses.Tabs[_curTab.Text].UnreadManage ||
1959 !SettingDialog.UnreadManage) Read = true;
1962 ListViewItem itm = null;
1963 PostClass post = null;
1965 this.TryGetListViewItemCache(Index, out itm, out post);
1967 if (itm == null || post == null)
1969 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1970 post = _statuses[_curTab.Text, Index];
1973 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1976 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1983 Item.SubItems[5].Text = "";
1988 Item.SubItems[5].Text = "★";
1994 else if (Post.RetweetedId != null)
1996 else if (Post.IsOwl && (Post.IsDm || SettingDialog.OneWayLove))
1998 else if (Read || !SettingDialog.UseUnreadStyle)
2003 if (DList == null || Item.Index == -1)
2005 Item.ForeColor = cl;
2006 if (SettingDialog.UseUnreadStyle)
2012 if (SettingDialog.UseUnreadStyle)
2013 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2015 DList.ChangeItemForeColor(Item.Index, cl);
2016 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2020 private void ColorizeList()
2022 //Index:更新対象のListviewItem.Index。Colorを返す。
2023 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2026 _post = _anchorPost;
2030 if (_post == null) return;
2032 var itemColors = new Color[] { };
2035 this.itemCacheLock.EnterReadLock();
2038 if (this._itemCache == null) return;
2041 from i in Enumerable.Range(0, this._itemCache.Length)
2042 select this.JudgeColor(_post, this._postCache[i]);
2044 itemColors = query.ToArray();
2045 itemIndex = _itemCacheIndex;
2047 finally { this.itemCacheLock.ExitReadLock(); }
2049 if (itemIndex < 0) return;
2051 foreach (var backColor in itemColors)
2053 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
2054 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
2055 _curList.ChangeItemBackColor(itemIndex++, backColor);
2059 private void ColorizeList(ListViewItem Item, int Index)
2061 //Index:更新対象のListviewItem.Index。Colorを返す。
2062 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2065 _post = _anchorPost;
2069 PostClass tPost = GetCurTabPost(Index);
2071 if (_post == null) return;
2073 if (Item.Index == -1)
2074 Item.BackColor = JudgeColor(_post, tPost);
2076 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2079 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2082 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2085 else if (TargetPost.IsMe)
2088 else if (TargetPost.IsReply)
2091 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2093 cl = _clAtFromTarget;
2094 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2097 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2102 cl = _clListBackcolor;
2107 private async void PostButton_Click(object sender, EventArgs e)
2109 if (StatusText.Text.Trim().Length == 0)
2111 if (!ImageSelector.Enabled)
2118 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2120 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2122 MessageBoxButtons.YesNoCancel,
2123 MessageBoxIcon.Question);
2126 case DialogResult.Yes:
2127 doReTweetOfficial(false);
2128 StatusText.Text = "";
2130 case DialogResult.Cancel:
2135 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2137 if (SettingDialog.Nicoms)
2139 StatusText.SelectionStart = StatusText.Text.Length;
2140 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2142 //if (SettingDialog.UrlConvertAuto)
2144 // StatusText.SelectionStart = StatusText.Text.Length;
2145 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2147 //else if (SettingDialog.Nicoms)
2149 // StatusText.SelectionStart = StatusText.Text.Length;
2150 // UrlConvert(UrlConverter.Nicoms);
2152 StatusText.SelectionStart = StatusText.Text.Length;
2153 GetWorkerArg args = new GetWorkerArg();
2156 args.type = MyCommon.WORKERTYPE.PostMessage;
2157 CheckReplyTo(StatusText.Text);
2160 int adjustCount = 0;
2161 string tmpStatus = StatusText.Text.Trim();
2162 if (ToolStripMenuItemApiCommandEvasion.Checked)
2165 if (Regex.IsMatch(tmpStatus,
2166 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2167 RegexOptions.IgnoreCase)
2168 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2171 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2174 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2177 bool isCutOff = false;
2178 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2179 if (StatusText.Multiline && !SettingDialog.PostCtrlEnter)
2181 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2182 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2184 if (SettingDialog.PostShiftEnter)
2186 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2188 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2190 isRemoveFooter = true;
2192 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2194 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2197 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2198 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2200 isRemoveFooter = true;
2211 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2219 if (HashMgr.IsNotAddToAtReply)
2221 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2224 header = HashMgr.UseHash + " ";
2226 footer = " " + HashMgr.UseHash;
2231 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2234 header = HashMgr.UseHash + " ";
2236 footer = " " + HashMgr.UseHash;
2239 if (!isRemoveFooter)
2241 if (SettingDialog.UseRecommendStatus)
2243 footer += SettingDialog.RecommendStatusText;
2245 // テキストボックスに入力されている文字列を使用する
2246 footer += " " + SettingDialog.Status.Trim();
2249 args.status.status = header + StatusText.Text + footer;
2251 if (ToolStripMenuItemApiCommandEvasion.Checked)
2254 if (Regex.IsMatch(args.status.status,
2255 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2256 RegexOptions.IgnoreCase)
2257 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2260 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2263 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2264 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2267 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2269 // 文中の全角スペースを半角スペース1個にする
2270 args.status.status = args.status.status.Replace(" ", " ");
2273 if (isCutOff && args.status.status.Length > 140)
2275 args.status.status = args.status.status.Substring(0, 140);
2276 string AtId = @"(@|@)[a-z0-9_/]+$";
2277 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2278 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2279 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2280 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2283 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2284 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2286 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2289 args.status.inReplyToId = _reply_to_id;
2290 args.status.inReplyToName = _reply_to_name;
2291 if (ImageSelector.Visible)
2294 if (!ImageSelector.TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2300 _reply_to_id = null;
2301 _reply_to_name = null;
2302 StatusText.Text = "";
2303 _history.Add(new PostingStatus());
2304 _hisIdx = _history.Count - 1;
2305 if (!ToolStripFocusLockMenuItem.Checked)
2306 ((Control)ListTab.SelectedTab.Tag).Focus();
2307 urlUndoBuffer = null;
2308 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2311 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2313 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2314 await this.OpenUriAsync(tmp);
2318 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2320 MyCommon._endingFlag = true;
2324 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2326 if (!SettingDialog.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2328 //_endingFlag=false:フォームの×ボタン
2330 this.Visible = false;
2334 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2335 _ignoreConfigSave = true;
2336 MyCommon._endingFlag = true;
2337 TimerTimeline.Enabled = false;
2338 TimerRefreshIcon.Enabled = false;
2342 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2344 this.Visible = true;
2345 if (this.WindowState == FormWindowState.Minimized)
2347 this.WindowState = FormWindowState.Normal;
2350 this.BringToFront();
2353 private static int errorCount = 0;
2355 private static bool CheckAccountValid()
2357 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2363 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2372 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2374 BackgroundWorker bw = (BackgroundWorker)sender;
2375 if (bw.CancellationPending || MyCommon._endingFlag)
2381 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2383 MyApplication.InitCulture();
2386 GetWorkerResult rslt = new GetWorkerResult();
2388 bool read = !SettingDialog.UnreadManage;
2389 if (_initial && SettingDialog.UnreadManage) read = SettingDialog.Readed;
2391 GetWorkerArg args = (GetWorkerArg)e.Argument;
2393 if (!CheckAccountValid())
2395 rslt.retMsg = "Auth error. Check your account";
2396 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2397 rslt.tName = args.tName;
2402 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2406 case MyCommon.WORKERTYPE.Timeline:
2407 case MyCommon.WORKERTYPE.Reply:
2408 bw.ReportProgress(50, MakeStatusMessage(args, false));
2409 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2411 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && SettingDialog.ReadOldPosts)
2412 _statuses.SetRead();
2414 rslt.addCount = _statuses.DistributePosts();
2416 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2417 bw.ReportProgress(50, MakeStatusMessage(args, false));
2418 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2419 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2420 rslt.addCount = _statuses.DistributePosts();
2423 case MyCommon.WORKERTYPE.FavAdd:
2427 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2429 for (int i = 0; i <= args.ids.Count - 1; i++)
2431 var post = tab.Posts[args.ids[i]];
2434 bw.ReportProgress(50, MakeStatusMessage(args, false));
2437 if (post.RetweetedId == null)
2438 ret = tw.PostFavAdd(post.StatusId);
2440 ret = tw.PostFavAdd(post.RetweetedId.Value);
2442 if (ret.Length == 0)
2444 args.sIds.Add(post.StatusId);
2445 post.IsFav = true; //リスト再描画必要
2446 _favTimestamps.Add(DateTime.Now);
2447 if (string.IsNullOrEmpty(post.RelTabName))
2449 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2450 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2454 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2455 if (_statuses.ContainsKey(post.StatusId))
2457 PostClass postTl = _statuses[post.StatusId];
2458 postTl.IsFav = true;
2459 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2462 //検索,リスト,UserTimeline,Relatedの各タブに反映
2463 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2465 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2471 rslt.sIds = args.sIds;
2475 case MyCommon.WORKERTYPE.FavRemove:
2479 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2481 for (int i = 0; i <= args.ids.Count - 1; i++)
2483 var post = tab.Posts[args.ids[i]];
2486 bw.ReportProgress(50, MakeStatusMessage(args, false));
2489 if (post.RetweetedId == null)
2490 ret = tw.PostFavRemove(post.StatusId);
2492 ret = tw.PostFavRemove(post.RetweetedId.Value);
2494 if (ret.Length == 0)
2496 args.sIds.Add(post.StatusId);
2497 post.IsFav = false; //リスト再描画必要
2498 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2499 //検索,リスト,UserTimeline,Relatedの各タブに反映
2500 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2502 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2508 rslt.sIds = args.sIds;
2512 case MyCommon.WORKERTYPE.PostMessage:
2513 bw.ReportProgress(200);
2514 if (args.status.imagePath == null || args.status.imagePath.Length == 0 || string.IsNullOrEmpty(args.status.imagePath[0]))
2516 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2520 var service = ImageSelector.GetService(args.status.imageService);
2521 if (args.status.imagePath.Length > 1 &&
2522 args.status.imageService.Equals("Twitter"))
2525 ret = ((TwitterPhoto)service).Upload(ref args.status.imagePath,
2526 ref args.status.status,
2527 args.status.inReplyToId);
2531 ret = service.Upload(ref args.status.imagePath[0],
2532 ref args.status.status,
2533 args.status.inReplyToId);
2536 bw.ReportProgress(300);
2537 rslt.status = args.status;
2539 case MyCommon.WORKERTYPE.Retweet:
2540 bw.ReportProgress(200);
2541 for (int i = 0; i <= args.ids.Count - 1; i++)
2543 ret = tw.PostRetweet(args.ids[i], read);
2545 bw.ReportProgress(300);
2547 case MyCommon.WORKERTYPE.Follower:
2548 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2551 tw.RefreshFollowerIds();
2553 catch (WebApiException ex) { ret = ex.Message; }
2555 case MyCommon.WORKERTYPE.NoRetweetIds:
2558 tw.RefreshNoRetweetIds();
2560 catch (WebApiException ex) { ret = ex.Message; }
2562 case MyCommon.WORKERTYPE.Configuration:
2565 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2567 catch (WebApiException ex) { ret = ex.Message; }
2569 case MyCommon.WORKERTYPE.Favorites:
2570 bw.ReportProgress(50, MakeStatusMessage(args, false));
2571 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2572 rslt.addCount = _statuses.DistributePosts();
2574 case MyCommon.WORKERTYPE.PublicSearch:
2575 bw.ReportProgress(50, MakeStatusMessage(args, false));
2576 if (string.IsNullOrEmpty(args.tName))
2578 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2580 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2581 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2586 TabClass tb = _statuses.GetTabByName(args.tName);
2589 //ret = tw.GetPhoenixSearch(read, tb, false);
2590 ret = tw.GetSearch(read, tb, false);
2591 if (string.IsNullOrEmpty(ret) && args.page == -1)
2593 //ret = tw.GetPhoenixSearch(read, tb, true)
2594 ret = tw.GetSearch(read, tb, true);
2599 rslt.addCount = _statuses.DistributePosts();
2601 case MyCommon.WORKERTYPE.UserTimeline:
2602 bw.ReportProgress(50, MakeStatusMessage(args, false));
2604 if (SettingDialog.UseAdditionalCount) count = SettingDialog.UserTimelineCountApi;
2605 if (string.IsNullOrEmpty(args.tName))
2607 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2609 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2614 TabClass tb = _statuses.GetTabByName(args.tName);
2617 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2621 rslt.addCount = _statuses.DistributePosts();
2623 case MyCommon.WORKERTYPE.List:
2624 bw.ReportProgress(50, MakeStatusMessage(args, false));
2625 if (string.IsNullOrEmpty(args.tName))
2628 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2630 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2636 TabClass tb = _statuses.GetTabByName(args.tName);
2639 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2643 rslt.addCount = _statuses.DistributePosts();
2646 case MyCommon.WORKERTYPE.Related:
2648 bw.ReportProgress(50, MakeStatusMessage(args, false));
2649 TabClass tab = _statuses.GetTabByName(args.tName);
2650 ret = tw.GetRelatedResult(read, tab);
2651 rslt.addCount = _statuses.DistributePosts();
2655 case MyCommon.WORKERTYPE.BlockIds:
2656 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2659 tw.RefreshBlockIds();
2661 catch (WebApiException ex) { ret = ex.Message; }
2665 if (bw.CancellationPending)
2672 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2674 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2675 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2677 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2679 _favTimestamps.RemoveAt(i);
2683 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2687 DateTime tm = DateTime.Now;
2688 if (_tlTimestamps.ContainsKey(tm))
2689 _tlTimestamps[tm] += rslt.addCount;
2691 _tlTimestamps.Add(tm, rslt.addCount);
2693 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2694 List<DateTime> keys = new List<DateTime>();
2696 foreach (DateTime key in _tlTimestamps.Keys)
2698 if (key.CompareTo(oneHour) < 0)
2704 _tlCount += _tlTimestamps[key];
2707 foreach (DateTime key in keys)
2709 _tlTimestamps.Remove(key);
2716 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2719 rslt.type = args.type;
2720 rslt.tName = args.tName;
2721 if (args.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2722 args.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2723 args.type == MyCommon.WORKERTYPE.Reply ||
2724 args.type == MyCommon.WORKERTYPE.Timeline ||
2725 args.type == MyCommon.WORKERTYPE.Favorites)
2727 rslt.page = args.page - 1; //値が正しいか後でチェック。10ページ毎の継続確認
2733 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2739 switch (AsyncArg.type)
2741 case MyCommon.WORKERTYPE.Timeline:
2742 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2744 case MyCommon.WORKERTYPE.Reply:
2745 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2747 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2748 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2750 case MyCommon.WORKERTYPE.FavAdd:
2751 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2752 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2754 case MyCommon.WORKERTYPE.FavRemove:
2755 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2756 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2758 case MyCommon.WORKERTYPE.Favorites:
2759 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2761 case MyCommon.WORKERTYPE.PublicSearch:
2762 smsg = "Search refreshing...";
2764 case MyCommon.WORKERTYPE.List:
2765 smsg = "List refreshing...";
2767 case MyCommon.WORKERTYPE.Related:
2768 smsg = "Related refreshing...";
2770 case MyCommon.WORKERTYPE.UserTimeline:
2771 smsg = "UserTimeline refreshing...";
2778 switch (AsyncArg.type)
2780 case MyCommon.WORKERTYPE.Timeline:
2781 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2783 case MyCommon.WORKERTYPE.Reply:
2784 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2786 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2787 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2789 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2790 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2792 case MyCommon.WORKERTYPE.FavAdd:
2795 case MyCommon.WORKERTYPE.FavRemove:
2798 case MyCommon.WORKERTYPE.Favorites:
2799 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2801 case MyCommon.WORKERTYPE.Follower:
2802 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2804 case MyCommon.WORKERTYPE.NoRetweetIds:
2805 smsg = "NoRetweetIds refreshed";
2807 case MyCommon.WORKERTYPE.Configuration:
2810 case MyCommon.WORKERTYPE.PublicSearch:
2811 smsg = "Search refreshed";
2813 case MyCommon.WORKERTYPE.List:
2814 smsg = "List refreshed";
2816 case MyCommon.WORKERTYPE.Related:
2817 smsg = "Related refreshed";
2819 case MyCommon.WORKERTYPE.UserTimeline:
2820 smsg = "UserTimeline refreshed";
2822 case MyCommon.WORKERTYPE.BlockIds:
2823 smsg = Properties.Resources.UpdateBlockUserText3;
2830 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2832 if (MyCommon._endingFlag) return;
2833 if (e.ProgressPercentage > 100)
2836 if (e.ProgressPercentage == 200) //開始
2837 StatusLabel.Text = "Posting...";
2838 if (e.ProgressPercentage == 300) //終了
2839 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2843 string smsg = (string)e.UserState;
2844 if (smsg.Length > 0) StatusLabel.Text = smsg;
2848 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2850 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2852 if (e.Error != null)
2854 _myStatusError = true;
2855 _waitTimeline = false;
2859 _waitPubSearch = false;
2860 _waitUserTimeline = false;
2862 throw new Exception("BackgroundWorker Exception", e.Error);
2865 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2868 if (rslt.retMsg.Length > 0)
2870 _myStatusError = true;
2871 StatusLabel.Text = rslt.retMsg;
2874 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2876 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2878 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2882 //bool busy = false;
2883 //foreach (BackgroundWorker bw in _bw)
2885 // if (bw != null && bw.IsBusy)
2891 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2892 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2893 rslt.type == MyCommon.WORKERTYPE.Reply ||
2894 rslt.type == MyCommon.WORKERTYPE.List ||
2895 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2896 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2897 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2898 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2899 rslt.type == MyCommon.WORKERTYPE.Follower ||
2900 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2901 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2902 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2903 rslt.type == MyCommon.WORKERTYPE.Related ||
2904 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2905 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2906 rslt.type == MyCommon.WORKERTYPE.Configuration)
2908 RefreshTimeline(false); //リスト反映
2913 case MyCommon.WORKERTYPE.Timeline:
2914 _waitTimeline = false;
2917 // //API使用時の取得調整は別途考える(カウント調整?)
2920 case MyCommon.WORKERTYPE.Reply:
2922 if (rslt.newDM && !_initial)
2924 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
2927 case MyCommon.WORKERTYPE.Favorites:
2930 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2933 case MyCommon.WORKERTYPE.FavAdd:
2934 case MyCommon.WORKERTYPE.FavRemove:
2935 if (_curList != null && _curTab != null)
2937 using (ControlTransaction.Update(this._curList))
2939 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2945 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2947 if (_curTab.Text.Equals(rslt.tName))
2949 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2952 PostClass post = null;
2953 TabClass tb = _statuses.Tabs[rslt.tName];
2956 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2958 post = tb.Posts[rslt.sIds[i]];
2962 post = _statuses[rslt.sIds[i]];
2964 ChangeCacheStyleRead(post.IsRead, idx);
2966 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2974 case MyCommon.WORKERTYPE.PostMessage:
2975 if (string.IsNullOrEmpty(rslt.retMsg) ||
2976 rslt.retMsg.StartsWith("OK:") ||
2977 rslt.retMsg == "Warn:Status is a duplicate.")
2979 _postTimestamps.Add(DateTime.Now);
2980 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2981 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2983 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2985 _postTimestamps.RemoveAt(i);
2989 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2991 HashMgr.ClearHashtag();
2992 this.HashStripSplitButton.Text = "#[-]";
2993 this.HashToggleMenuItem.Checked = false;
2994 this.HashToggleToolStripMenuItem.Checked = false;
2996 SetMainWindowTitle();
3004 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
3005 Properties.Resources.StatusUpdateFailed1,
3006 Properties.Resources.StatusUpdateFailed2),
3007 "Failed to update status",
3008 MessageBoxButtons.RetryCancel,
3009 MessageBoxIcon.Question);
3013 retry = DialogResult.Abort;
3015 if (retry == DialogResult.Retry)
3017 GetWorkerArg args = new GetWorkerArg();
3020 args.type = MyCommon.WORKERTYPE.PostMessage;
3021 args.status = rslt.status;
3026 if (ToolStripFocusLockMenuItem.Checked)
3028 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3029 StatusText_Enter(StatusText, new EventArgs());
3033 if (rslt.retMsg.Length == 0 && SettingDialog.PostAndGet)
3035 if (_isActiveUserstream)
3037 RefreshTimeline(true);
3041 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3045 case MyCommon.WORKERTYPE.Retweet:
3046 if (rslt.retMsg.Length == 0)
3048 _postTimestamps.Add(DateTime.Now);
3049 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
3050 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
3052 if (_postTimestamps[i].CompareTo(oneHour) < 0)
3054 _postTimestamps.RemoveAt(i);
3057 if (!_isActiveUserstream && SettingDialog.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3060 case MyCommon.WORKERTYPE.Follower:
3061 //_waitFollower = false;
3062 this.PurgeListViewItemCache();
3063 if (_curList != null) _curList.Refresh();
3065 case MyCommon.WORKERTYPE.NoRetweetIds:
3067 case MyCommon.WORKERTYPE.Configuration:
3068 //_waitFollower = false
3069 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
3071 var service = ImageSelector.GetService("Twitter");
3072 if (service != null)
3073 service.Configuration("MaxUploadFilesize", SettingDialog.TwitterConfiguration.PhotoSizeLimit);
3075 this.PurgeListViewItemCache();
3076 if (_curList != null) _curList.Refresh();
3078 case MyCommon.WORKERTYPE.PublicSearch:
3079 _waitPubSearch = false;
3081 case MyCommon.WORKERTYPE.UserTimeline:
3082 _waitUserTimeline = false;
3084 case MyCommon.WORKERTYPE.List:
3087 case MyCommon.WORKERTYPE.Related:
3088 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
3089 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3091 foreach (TabPage tp in ListTab.TabPages)
3093 if (tp.Text == tab.TabName)
3095 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3096 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3105 private async Task RefreshMuteUserIdsAsync()
3107 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3111 await tw.RefreshMuteUserIdsAsync();
3113 catch (WebApiException ex)
3115 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3119 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3122 private void RemovePostFromFavTab(Int64[] ids)
3124 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3126 if (_curTab.Text.Equals(favTabName))
3128 if (_curList.FocusedItem != null)
3129 fidx = _curList.FocusedItem.Index;
3130 else if (_curList.TopItem != null)
3131 fidx = _curList.TopItem.Index;
3136 foreach (long i in ids)
3140 _statuses.RemoveFavPost(i);
3147 if (_curTab != null && _curTab.Text.Equals(favTabName))
3149 this.PurgeListViewItemCache();
3151 //_curItemIndex = -1;
3153 foreach (TabPage tp in ListTab.TabPages)
3155 if (tp.Text == favTabName)
3157 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3161 if (_curTab.Text.Equals(favTabName))
3165 _curList.SelectedIndices.Clear();
3167 while (_curList.SelectedIndices.Count > 0);
3169 if (_statuses.Tabs[favTabName].AllCount > 0)
3171 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3173 _curList.SelectedIndices.Add(fidx);
3177 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3179 if (_curList.SelectedIndices.Count > 0)
3181 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3182 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3188 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3190 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, int toPage, string tabName)
3192 if (!this.IsNetworkAvailable()) return;
3195 GetWorkerArg args = new GetWorkerArg();
3196 args.page = fromPage;
3197 args.endPage = toPage;
3199 args.tName = tabName;
3201 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3202 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3203 if (period > 1 || period < -1)
3205 lastTime[WkType] = DateTime.Now;
3209 //Timeline取得モードの場合はReplyも同時に取得
3210 //if (!SettingDialog.UseAPI &&
3212 // WkType == MyCommon.WORKERTYPE.Timeline &&
3213 // SettingDialog.CheckReply)
3215 // //TimerReply.Enabled = false;
3216 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3217 // GetWorkerArg _args = new GetWorkerArg();
3218 // _args.page = fromPage;
3219 // _args.endPage = toPage;
3220 // _args.type = MyCommon.WORKERTYPE.Reply;
3225 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3227 if (e.Button == MouseButtons.Left)
3229 this.Visible = true;
3230 if (this.WindowState == FormWindowState.Minimized)
3232 this.WindowState = _formWindowState;
3235 this.BringToFront();
3239 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3241 switch (SettingDialog.ListDoubleClickAction)
3244 MakeReplyOrDirectStatus();
3247 FavoriteChange(true);
3250 if (_curPost != null)
3251 ShowUserStatus(_curPost.ScreenName, false);
3257 ShowRelatedStatusesMenuItem_Click(null, null);
3260 MoveToHomeToolStripMenuItem_Click(null, null);
3263 StatusOpenMenuItem_Click(null, null);
3271 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3273 FavoriteChange(true);
3276 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3278 FavoriteChange(false);
3282 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3284 FavoritesRetweetOriginal();
3287 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3289 FavoritesRetweetUnofficial();
3292 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3294 //trueでFavAdd,falseでFavRemove
3295 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3296 || !this.ExistCurrentPost) return;
3299 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3301 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3302 _DoFavRetweetFlags = false;
3305 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3309 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3310 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3311 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3312 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3314 _DoFavRetweetFlags = false;
3320 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3321 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3328 GetWorkerArg args = new GetWorkerArg();
3329 args.ids = new List<long>();
3330 args.sIds = new List<long>();
3331 args.tName = _curTab.Text;
3334 args.type = MyCommon.WORKERTYPE.FavAdd;
3338 args.type = MyCommon.WORKERTYPE.FavRemove;
3340 foreach (int idx in _curList.SelectedIndices)
3342 PostClass post = GetCurTabPost(idx);
3345 if (!post.IsFav) args.ids.Add(post.StatusId);
3349 if (post.IsFav) args.ids.Add(post.StatusId);
3352 if (args.ids.Count == 0)
3355 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3357 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3365 private PostClass GetCurTabPost(int Index)
3367 this.itemCacheLock.EnterReadLock();
3370 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3371 return _postCache[Index - _itemCacheIndex];
3373 finally { this.itemCacheLock.ExitReadLock(); }
3375 return _statuses[_curTab.Text, Index];
3379 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3381 if (_curList.SelectedIndices.Count > 0)
3382 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3383 else if (_curList.SelectedIndices.Count == 0)
3384 OpenUriAsync(MyCommon.TwitterUrl);
3387 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3389 if (_curList.SelectedIndices.Count > 0)
3390 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3393 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3395 if ((!_initialLayout) && this.Visible)
3397 if (this.WindowState == FormWindowState.Normal)
3399 _mySize = this.ClientSize;
3400 _mySpDis = this.SplitContainer1.SplitterDistance;
3401 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3402 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3403 _modifySettingLocal = true;
3408 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3410 if (SettingDialog.SortOrderLock) return;
3411 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3414 mode = IdComparerClass.ComparerMode.Id;
3422 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3426 mode = IdComparerClass.ComparerMode.Nickname;
3429 mode = IdComparerClass.ComparerMode.Data;
3432 mode = IdComparerClass.ComparerMode.Id;
3435 mode = IdComparerClass.ComparerMode.Name;
3438 mode = IdComparerClass.ComparerMode.Source;
3442 _statuses.ToggleSortOrder(mode);
3445 DetailsListView list = (DetailsListView)sender;
3448 list.Columns[0].Text = ColumnOrgText[0];
3449 list.Columns[1].Text = ColumnText[2];
3453 for (int i = 0; i <= 7; i++)
3455 list.Columns[i].Text = ColumnOrgText[i];
3457 list.Columns[e.Column].Text = ColumnText[e.Column];
3460 this.PurgeListViewItemCache();
3462 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3464 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3467 SelectListItem(_curList, idx);
3468 _curList.EnsureVisible(idx);
3472 _modifySettingCommon = true;
3475 private void TweenMain_LocationChanged(object sender, EventArgs e)
3477 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3479 _myLoc = this.DesktopLocation;
3480 _modifySettingLocal = true;
3484 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3486 if (ListTab.SelectedTab == null) return;
3487 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3488 if (!this.ExistCurrentPost)
3490 ReplyStripMenuItem.Enabled = false;
3491 ReplyAllStripMenuItem.Enabled = false;
3492 DMStripMenuItem.Enabled = false;
3493 ShowProfileMenuItem.Enabled = false;
3494 ShowUserTimelineContextMenuItem.Enabled = false;
3495 ListManageUserContextToolStripMenuItem2.Enabled = false;
3496 MoveToFavToolStripMenuItem.Enabled = false;
3497 TabMenuItem.Enabled = false;
3498 IDRuleMenuItem.Enabled = false;
3499 ReadedStripMenuItem.Enabled = false;
3500 UnreadStripMenuItem.Enabled = false;
3504 ShowProfileMenuItem.Enabled = true;
3505 ListManageUserContextToolStripMenuItem2.Enabled = true;
3506 ReplyStripMenuItem.Enabled = true;
3507 ReplyAllStripMenuItem.Enabled = true;
3508 DMStripMenuItem.Enabled = true;
3509 ShowUserTimelineContextMenuItem.Enabled = true;
3510 MoveToFavToolStripMenuItem.Enabled = true;
3511 TabMenuItem.Enabled = true;
3512 IDRuleMenuItem.Enabled = true;
3513 ReadedStripMenuItem.Enabled = true;
3514 UnreadStripMenuItem.Enabled = true;
3516 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3517 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3519 FavAddToolStripMenuItem.Enabled = false;
3520 FavRemoveToolStripMenuItem.Enabled = false;
3521 StatusOpenMenuItem.Enabled = false;
3522 FavorareMenuItem.Enabled = false;
3523 ShowRelatedStatusesMenuItem.Enabled = false;
3525 ReTweetStripMenuItem.Enabled = false;
3526 ReTweetOriginalStripMenuItem.Enabled = false;
3527 QuoteStripMenuItem.Enabled = false;
3528 FavoriteRetweetContextMenu.Enabled = false;
3529 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3530 if (this.ExistCurrentPost && _curPost.IsDm)
3531 DeleteStripMenuItem.Enabled = true;
3533 DeleteStripMenuItem.Enabled = false;
3537 FavAddToolStripMenuItem.Enabled = true;
3538 FavRemoveToolStripMenuItem.Enabled = true;
3539 StatusOpenMenuItem.Enabled = true;
3540 FavorareMenuItem.Enabled = true;
3541 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3545 ReTweetOriginalStripMenuItem.Enabled = false;
3546 FavoriteRetweetContextMenu.Enabled = false;
3547 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3549 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3553 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3555 DeleteStripMenuItem.Enabled = true;
3559 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3561 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3565 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3567 DeleteStripMenuItem.Enabled = false;
3568 if (_curPost.IsProtect)
3570 ReTweetOriginalStripMenuItem.Enabled = false;
3571 ReTweetStripMenuItem.Enabled = false;
3572 QuoteStripMenuItem.Enabled = false;
3573 FavoriteRetweetContextMenu.Enabled = false;
3574 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3578 ReTweetOriginalStripMenuItem.Enabled = true;
3579 ReTweetStripMenuItem.Enabled = true;
3580 QuoteStripMenuItem.Enabled = true;
3581 FavoriteRetweetContextMenu.Enabled = true;
3582 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3586 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3588 // RefreshMoreStripMenuItem.Enabled = true;
3592 // RefreshMoreStripMenuItem.Enabled = false;
3594 if (!this.ExistCurrentPost
3595 || _curPost.InReplyToStatusId == null)
3597 RepliedStatusOpenMenuItem.Enabled = false;
3601 RepliedStatusOpenMenuItem.Enabled = true;
3603 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3605 MoveToRTHomeMenuItem.Enabled = false;
3609 MoveToRTHomeMenuItem.Enabled = true;
3613 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3615 MakeReplyOrDirectStatus(false, true);
3618 private void DMStripMenuItem_Click(object sender, EventArgs e)
3620 MakeReplyOrDirectStatus(false, false);
3623 private void doStatusDelete()
3625 if (_curTab == null || _curList == null) return;
3626 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3628 bool myPost = false;
3629 foreach (int idx in _curList.SelectedIndices)
3631 if (GetCurTabPost(idx).IsMe ||
3632 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3638 if (!myPost) return;
3642 if (_curList.SelectedIndices.Count == 0)
3646 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3648 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3649 MessageBoxButtons.OKCancel,
3650 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3653 if (_curList.FocusedItem != null)
3654 fidx = _curList.FocusedItem.Index;
3655 else if (_curList.TopItem != null)
3656 fidx = _curList.TopItem.Index;
3662 this.Cursor = Cursors.WaitCursor;
3665 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3668 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3670 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3674 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3675 rtn = tw.RemoveStatus(Id);
3686 _statuses.RemovePost(Id);
3691 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3693 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3695 this.PurgeListViewItemCache();
3698 foreach (TabPage tb in ListTab.TabPages)
3700 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3701 if (_curTab.Equals(tb))
3705 _curList.SelectedIndices.Clear();
3707 while (_curList.SelectedIndices.Count > 0);
3709 if (_statuses.Tabs[tb.Text].AllCount > 0)
3711 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3712 _curList.SelectedIndices.Add(fidx);
3714 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3716 if (_curList.SelectedIndices.Count > 0)
3718 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3719 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3723 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3725 if (SettingDialog.TabIconDisp)
3727 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3731 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3735 this.Cursor = Cursors.Default;
3739 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3744 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3746 using (ControlTransaction.Update(this._curList))
3748 if (SettingDialog.UnreadManage)
3750 foreach (int idx in _curList.SelectedIndices)
3752 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3755 foreach (int idx in _curList.SelectedIndices)
3757 ChangeCacheStyleRead(true, idx);
3761 foreach (TabPage tb in ListTab.TabPages)
3763 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3765 if (SettingDialog.TabIconDisp)
3767 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3771 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3774 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3776 using (ControlTransaction.Update(this._curList))
3778 if (SettingDialog.UnreadManage)
3780 foreach (int idx in _curList.SelectedIndices)
3782 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3785 foreach (int idx in _curList.SelectedIndices)
3787 ChangeCacheStyleRead(false, idx);
3791 foreach (TabPage tb in ListTab.TabPages)
3793 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3795 if (SettingDialog.TabIconDisp)
3797 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3801 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3804 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3809 private void DoRefresh()
3811 if (_curTab != null)
3813 switch (_statuses.Tabs[_curTab.Text].TabType)
3815 case MyCommon.TabUsageType.Mentions:
3816 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
3818 case MyCommon.TabUsageType.DirectMessage:
3819 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
3821 case MyCommon.TabUsageType.Favorites:
3822 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 0, "");
3824 //case MyCommon.TabUsageType.Profile:
3826 case MyCommon.TabUsageType.PublicSearch:
3828 TabClass tb = _statuses.Tabs[_curTab.Text];
3829 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3830 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, _curTab.Text);
3832 case MyCommon.TabUsageType.UserTimeline:
3833 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, _curTab.Text);
3835 case MyCommon.TabUsageType.Lists:
3837 TabClass tab = _statuses.Tabs[_curTab.Text];
3838 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3839 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, _curTab.Text);
3842 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3848 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 0, "");
3852 private void DoRefreshMore()
3855 if (_curTab != null)
3857 switch (_statuses.Tabs[_curTab.Text].TabType)
3859 case MyCommon.TabUsageType.Mentions:
3860 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
3862 case MyCommon.TabUsageType.DirectMessage:
3863 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
3865 case MyCommon.TabUsageType.Favorites:
3866 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, 0, "");
3868 case MyCommon.TabUsageType.Profile:
3871 case MyCommon.TabUsageType.PublicSearch:
3873 TabClass tb = _statuses.Tabs[_curTab.Text];
3874 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3875 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, 0, _curTab.Text);
3877 case MyCommon.TabUsageType.UserTimeline:
3878 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, 0, _curTab.Text);
3880 case MyCommon.TabUsageType.Lists:
3882 TabClass tab = _statuses.Tabs[_curTab.Text];
3883 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3884 GetTimeline(MyCommon.WORKERTYPE.List, -1, 0, _curTab.Text);
3887 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3893 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, 0, "");
3897 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3899 DialogResult result;
3900 string uid = tw.Username.ToLower();
3901 var oldIconSz = SettingDialog.IconSz;
3905 result = SettingDialog.ShowDialog(this);
3912 if (result == DialogResult.OK)
3916 tw.TinyUrlResolve = SettingDialog.TinyUrlResolve;
3917 tw.RestrictFavCheck = SettingDialog.RestrictFavCheck;
3918 tw.ReadOwnPost = SettingDialog.ReadOwnPost;
3919 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3920 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3921 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3922 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3924 HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut,
3925 SettingDialog.SelectedProxyType,
3926 SettingDialog.ProxyAddress,
3927 SettingDialog.ProxyPort,
3928 SettingDialog.ProxyUser,
3929 SettingDialog.ProxyPassword);
3931 ImageSelector.Reset(tw);
3935 if (SettingDialog.TabIconDisp)
3937 ListTab.DrawItem -= ListTab_DrawItem;
3938 ListTab.DrawMode = TabDrawMode.Normal;
3939 ListTab.ImageList = this.TabImage;
3943 ListTab.DrawItem -= ListTab_DrawItem;
3944 ListTab.DrawItem += ListTab_DrawItem;
3945 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3946 ListTab.ImageList = null;
3949 catch (Exception ex)
3951 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3952 ex.Data["IsTerminatePermission"] = false;
3958 if (!SettingDialog.UnreadManage)
3960 ReadedStripMenuItem.Enabled = false;
3961 UnreadStripMenuItem.Enabled = false;
3962 if (SettingDialog.TabIconDisp)
3964 foreach (TabPage myTab in ListTab.TabPages)
3966 myTab.ImageIndex = -1;
3972 ReadedStripMenuItem.Enabled = true;
3973 UnreadStripMenuItem.Enabled = true;
3976 catch (Exception ex)
3978 ex.Data["Instance"] = "ListTab(UnreadManage)";
3979 ex.Data["IsTerminatePermission"] = false;
3986 SplitContainer1.IsPanelInverted = !SettingDialog.StatusAreaAtBottom;
3988 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3989 imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3990 imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3992 PlaySoundMenuItem.Checked = SettingDialog.PlaySound;
3993 this.PlaySoundFileMenuItem.Checked = SettingDialog.PlaySound;
3994 _fntUnread = SettingDialog.FontUnread;
3995 _clUnread = SettingDialog.ColorUnread;
3996 _fntReaded = SettingDialog.FontReaded;
3997 _clReaded = SettingDialog.ColorReaded;
3998 _clFav = SettingDialog.ColorFav;
3999 _clOWL = SettingDialog.ColorOWL;
4000 _clRetweet = SettingDialog.ColorRetweet;
4001 _fntDetail = SettingDialog.FontDetail;
4002 _clDetail = SettingDialog.ColorDetail;
4003 _clDetailLink = SettingDialog.ColorDetailLink;
4004 _clDetailBackcolor = SettingDialog.ColorDetailBackcolor;
4005 _clSelf = SettingDialog.ColorSelf;
4006 _clAtSelf = SettingDialog.ColorAtSelf;
4007 _clTarget = SettingDialog.ColorTarget;
4008 _clAtTarget = SettingDialog.ColorAtTarget;
4009 _clAtFromTarget = SettingDialog.ColorAtFromTarget;
4010 _clAtTo = SettingDialog.ColorAtTo;
4011 _clListBackcolor = SettingDialog.ColorListBackcolor;
4012 _clInputBackcolor = SettingDialog.ColorInputBackcolor;
4013 _clInputFont = SettingDialog.ColorInputFont;
4014 _fntInputFont = SettingDialog.FontInputFont;
4015 _brsBackColorMine.Dispose();
4016 _brsBackColorAt.Dispose();
4017 _brsBackColorYou.Dispose();
4018 _brsBackColorAtYou.Dispose();
4019 _brsBackColorAtFromTarget.Dispose();
4020 _brsBackColorAtTo.Dispose();
4021 _brsBackColorNone.Dispose();
4022 _brsBackColorMine = new SolidBrush(_clSelf);
4023 _brsBackColorAt = new SolidBrush(_clAtSelf);
4024 _brsBackColorYou = new SolidBrush(_clTarget);
4025 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4026 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4027 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4028 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4032 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4033 StatusText.Font = _fntInputFont;
4034 StatusText.ForeColor = _clInputFont;
4036 catch (Exception ex)
4038 MessageBox.Show(ex.Message);
4043 InitDetailHtmlFormat();
4045 catch (Exception ex)
4047 ex.Data["Instance"] = "Font";
4048 ex.Data["IsTerminatePermission"] = false;
4054 _statuses.SetUnreadManage(SettingDialog.UnreadManage);
4056 catch (Exception ex)
4058 ex.Data["Instance"] = "_statuses";
4059 ex.Data["IsTerminatePermission"] = false;
4065 foreach (TabPage tb in ListTab.TabPages)
4067 if (SettingDialog.TabIconDisp)
4069 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4076 catch (Exception ex)
4078 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4079 ex.Data["IsTerminatePermission"] = false;
4085 var oldIconCol = _iconCol;
4087 if (SettingDialog.IconSz != oldIconSz)
4088 ApplyListViewIconSize(SettingDialog.IconSz);
4090 foreach (TabPage tp in ListTab.TabPages)
4092 DetailsListView lst = (DetailsListView)tp.Tag;
4094 using (ControlTransaction.Update(lst))
4096 lst.GridLines = SettingDialog.ShowGrid;
4097 lst.Font = _fntReaded;
4098 lst.BackColor = _clListBackcolor;
4100 if (_iconCol != oldIconCol)
4105 catch (Exception ex)
4107 ex.Data["Instance"] = "ListView(IconSize)";
4108 ex.Data["IsTerminatePermission"] = false;
4112 SetMainWindowTitle();
4113 SetNotifyIconText();
4115 this.PurgeListViewItemCache();
4116 if (_curList != null) _curList.Refresh();
4119 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4120 if (SettingDialog.HotkeyEnabled)
4122 ///グローバルホットキーの登録。設定で変更可能にするかも
4123 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4124 if ((SettingDialog.HotkeyMod & Keys.Alt) == Keys.Alt) modKey = modKey | HookGlobalHotkey.ModKeys.Alt;
4125 if ((SettingDialog.HotkeyMod & Keys.Control) == Keys.Control) modKey = modKey | HookGlobalHotkey.ModKeys.Ctrl;
4126 if ((SettingDialog.HotkeyMod & Keys.Shift) == Keys.Shift) modKey = modKey | HookGlobalHotkey.ModKeys.Shift;
4127 if ((SettingDialog.HotkeyMod & Keys.LWin) == Keys.LWin) modKey = modKey | HookGlobalHotkey.ModKeys.Win;
4129 _hookGlobalHotkey.RegisterOriginalHotkey(SettingDialog.HotkeyKey, SettingDialog.HotkeyValue, modKey);
4132 if (uid != tw.Username) this.doGetFollowersMenu();
4134 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
4137 StatusText_TextChanged(null, null);
4145 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4147 this.TopMost = SettingDialog.AlwaysTop;
4148 SaveConfigsAll(false);
4154 private void SetTabAlignment()
4156 var newAlignment = SettingDialog.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4157 if (ListTab.Alignment == newAlignment) return;
4160 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
4161 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
4162 SaveSelectedStatus(selId, focusedId);
4164 ListTab.Alignment = newAlignment;
4167 foreach (TabPage tab in ListTab.TabPages)
4169 DetailsListView lst = (DetailsListView)tab.Tag;
4170 using (ControlTransaction.Update(lst))
4172 this.SelectListItem(lst,
4173 _statuses.IndexOf(tab.Text, selId[tab.Text]),
4174 _statuses.IndexOf(tab.Text, focusedId[tab.Text]));
4179 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4185 case MyCommon.IconSizes.IconNone:
4188 case MyCommon.IconSizes.Icon16:
4191 case MyCommon.IconSizes.Icon24:
4194 case MyCommon.IconSizes.Icon48:
4197 case MyCommon.IconSizes.Icon48_2:
4205 // ディスプレイの DPI 設定を考慮したサイズを設定する
4206 _listViewImageList.ImageSize = new Size(
4208 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4212 _listViewImageList.ImageSize = new Size(1, 1);
4216 private void ResetColumns(DetailsListView list)
4218 using (ControlTransaction.Update(list))
4219 using (ControlTransaction.Layout(list, false))
4222 list.ColumnClick -= MyList_ColumnClick;
4223 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4224 list.ColumnReordered -= MyList_ColumnReordered;
4225 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4227 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4228 list.Columns.Clear();
4229 cols.ForEach(col => col.Dispose());
4232 InitColumns(list, true);
4234 list.ColumnClick += MyList_ColumnClick;
4235 list.DrawColumnHeader += MyList_DrawColumnHeader;
4236 list.ColumnReordered += MyList_ColumnReordered;
4237 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4241 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4243 if (e.Url.AbsoluteUri != "about:blank")
4246 OpenUriAsync(e.Url.OriginalString);
4250 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4252 if (e.Url.Scheme == "data")
4254 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4256 else if (e.Url.AbsoluteUri != "about:blank")
4260 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4261 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4264 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4265 int i = urlStr.IndexOf('#');
4266 if (i == -1) return;
4268 string hash = urlStr.Substring(i);
4269 HashSupl.AddItem(hash);
4270 HashMgr.AddHashToHistory(hash.Trim(), false);
4271 AddNewTabForSearch(hash);
4276 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4277 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4279 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4280 if (SettingDialog.OpenUserTimeline)
4282 if (MyCommon.IsKeyDown(Keys.Control))
4283 OpenUriAsync(e.Url.OriginalString);
4285 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4289 if (MyCommon.IsKeyDown(Keys.Control))
4290 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4292 OpenUriAsync(e.Url.OriginalString);
4297 OpenUriAsync(e.Url.OriginalString);
4303 public void AddNewTabForSearch(string searchWord)
4305 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4306 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4308 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4310 foreach (TabPage tp in ListTab.TabPages)
4312 if (tb.TabName == tp.Text)
4314 ListTab.SelectedTab = tp;
4321 string tabName = searchWord;
4322 for (int i = 0; i <= 100; i++)
4324 if (_statuses.ContainsTab(tabName))
4330 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4331 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4333 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4335 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4336 cmb.Items.Add(searchWord);
4337 cmb.Text = searchWord;
4340 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4343 private void ShowUserTimeline()
4345 if (!this.ExistCurrentPost) return;
4346 AddNewTabForUserTimeline(_curPost.ScreenName);
4349 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4351 if (e.KeyCode == Keys.Escape)
4353 TabPage relTp = ListTab.SelectedTab;
4354 RemoveSpecifiedTab(relTp.Text, false);
4356 e.SuppressKeyPress = true;
4360 public void AddNewTabForUserTimeline(string user)
4362 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4363 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4365 if (tb.User == user)
4367 foreach (TabPage tp in ListTab.TabPages)
4369 if (tb.TabName == tp.Text)
4371 ListTab.SelectedTab = tp;
4378 string tabName = "user:" + user;
4379 while (_statuses.ContainsTab(tabName))
4384 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4385 _statuses.Tabs[tabName].User = user;
4386 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4388 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4392 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, tabName);
4395 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4398 foreach (TabPage tb in ListTab.TabPages)
4400 if (tb.Text == tabName) return false;
4404 if (tabName == Properties.Resources.AddNewTabText1) return false;
4409 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4410 tabType == MyCommon.TabUsageType.Favorites ||
4411 tabType == MyCommon.TabUsageType.Home ||
4412 tabType == MyCommon.TabUsageType.Mentions ||
4413 tabType == MyCommon.TabUsageType.Related)
4415 if (_statuses.GetTabByType(tabType) != null) return false;
4419 TabPage _tabPage = new TabPage();
4420 DetailsListView _listCustom = new DetailsListView();
4422 int cnt = ListTab.TabPages.Count;
4424 ///ToDo:Create and set controls follow tabtypes
4426 using (ControlTransaction.Update(_listCustom))
4427 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4428 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4429 using (ControlTransaction.Layout(this.SplitContainer1, false))
4430 using (ControlTransaction.Layout(this.ListTab, false))
4431 using (ControlTransaction.Layout(this))
4432 using (ControlTransaction.Layout(_tabPage, false))
4436 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4438 label = new Label();
4439 label.Dock = DockStyle.Top;
4440 label.Name = "labelUser";
4441 if (tabType == MyCommon.TabUsageType.Lists)
4443 label.Text = listInfo.ToString();
4447 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4449 label.TextAlign = ContentAlignment.MiddleLeft;
4450 using (ComboBox tmpComboBox = new ComboBox())
4452 label.Height = tmpComboBox.Height;
4454 _tabPage.Controls.Add(label);
4459 if (tabType == MyCommon.TabUsageType.PublicSearch)
4463 Label lbl = new Label();
4464 ComboBox cmb = new ComboBox();
4465 Button btn = new Button();
4466 ComboBox cmbLang = new ComboBox();
4468 pnl.SuspendLayout();
4470 pnl.Controls.Add(cmb);
4471 pnl.Controls.Add(cmbLang);
4472 pnl.Controls.Add(btn);
4473 pnl.Controls.Add(lbl);
4474 pnl.Name = "panelSearch";
4475 pnl.Dock = DockStyle.Top;
4476 pnl.Height = cmb.Height;
4477 pnl.Enter += SearchControls_Enter;
4478 pnl.Leave += SearchControls_Leave;
4481 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4482 cmb.Dock = DockStyle.Fill;
4483 cmb.Name = "comboSearch";
4484 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4485 cmb.ImeMode = ImeMode.NoControl;
4486 cmb.TabStop = false;
4487 cmb.AutoCompleteMode = AutoCompleteMode.None;
4488 cmb.KeyDown += SearchComboBox_KeyDown;
4490 if (_statuses.ContainsTab(tabName))
4492 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4493 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4497 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4498 cmbLang.Dock = DockStyle.Right;
4500 cmbLang.Name = "comboLang";
4501 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4502 cmbLang.TabStop = false;
4503 cmbLang.Items.Add("");
4504 cmbLang.Items.Add("ja");
4505 cmbLang.Items.Add("en");
4506 cmbLang.Items.Add("ar");
4507 cmbLang.Items.Add("da");
4508 cmbLang.Items.Add("nl");
4509 cmbLang.Items.Add("fa");
4510 cmbLang.Items.Add("fi");
4511 cmbLang.Items.Add("fr");
4512 cmbLang.Items.Add("de");
4513 cmbLang.Items.Add("hu");
4514 cmbLang.Items.Add("is");
4515 cmbLang.Items.Add("it");
4516 cmbLang.Items.Add("no");
4517 cmbLang.Items.Add("pl");
4518 cmbLang.Items.Add("pt");
4519 cmbLang.Items.Add("ru");
4520 cmbLang.Items.Add("es");
4521 cmbLang.Items.Add("sv");
4522 cmbLang.Items.Add("th");
4523 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4525 lbl.Text = "Search(C-S-f)";
4526 lbl.Name = "label1";
4527 lbl.Dock = DockStyle.Left;
4529 lbl.Height = cmb.Height;
4530 lbl.TextAlign = ContentAlignment.MiddleLeft;
4532 btn.Text = "Search";
4533 btn.Name = "buttonSearch";
4534 btn.UseVisualStyleBackColor = true;
4535 btn.Dock = DockStyle.Right;
4536 btn.TabStop = false;
4537 btn.Click += SearchButton_Click;
4540 this.ListTab.Controls.Add(_tabPage);
4541 _tabPage.Controls.Add(_listCustom);
4543 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4544 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4546 _tabPage.Location = new Point(4, 4);
4547 _tabPage.Name = "CTab" + cnt.ToString();
4548 _tabPage.Size = new Size(380, 260);
4549 _tabPage.TabIndex = 2 + cnt;
4550 _tabPage.Text = tabName;
4551 _tabPage.UseVisualStyleBackColor = true;
4553 _listCustom.AllowColumnReorder = true;
4554 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4555 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4556 _listCustom.Dock = DockStyle.Fill;
4557 _listCustom.FullRowSelect = true;
4558 _listCustom.HideSelection = false;
4559 _listCustom.Location = new Point(0, 0);
4560 _listCustom.Margin = new Padding(0);
4561 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4562 _listCustom.ShowItemToolTips = true;
4563 _listCustom.Size = new Size(380, 260);
4564 _listCustom.UseCompatibleStateImageBehavior = false;
4565 _listCustom.View = View.Details;
4566 _listCustom.OwnerDraw = true;
4567 _listCustom.VirtualMode = true;
4568 _listCustom.Font = _fntReaded;
4569 _listCustom.BackColor = _clListBackcolor;
4571 _listCustom.GridLines = SettingDialog.ShowGrid;
4572 _listCustom.AllowDrop = true;
4574 _listCustom.SmallImageList = _listViewImageList;
4576 InitColumns(_listCustom, startup);
4578 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4579 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4580 _listCustom.ColumnClick += MyList_ColumnClick;
4581 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4582 _listCustom.DragDrop += TweenMain_DragDrop;
4583 _listCustom.DragEnter += TweenMain_DragEnter;
4584 _listCustom.DragOver += TweenMain_DragOver;
4585 _listCustom.DrawItem += MyList_DrawItem;
4586 _listCustom.MouseClick += MyList_MouseClick;
4587 _listCustom.ColumnReordered += MyList_ColumnReordered;
4588 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4589 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4590 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4591 _listCustom.DrawSubItem += MyList_DrawSubItem;
4592 _listCustom.HScrolled += MyList_HScrolled;
4594 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4597 _tabPage.Tag = _listCustom;
4601 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4603 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4607 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4608 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4609 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4615 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4616 if (_tabPage == null) return false;
4618 SetListProperty(); //他のタブに列幅等を反映
4620 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4623 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4624 _tabPage.Tag = null;
4626 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4627 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4628 using (ControlTransaction.Layout(this.SplitContainer1, false))
4629 using (ControlTransaction.Layout(this.ListTab, false))
4630 using (ControlTransaction.Layout(this))
4631 using (ControlTransaction.Layout(_tabPage, false))
4633 if (this.ListTab.SelectedTab == _tabPage)
4635 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4636 this._beforeSelectedTab = null;
4638 this.ListTab.Controls.Remove(_tabPage);
4641 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4643 using (Control label = _tabPage.Controls["labelUser"])
4645 _tabPage.Controls.Remove(label);
4648 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4650 using (Control pnl = _tabPage.Controls["panelSearch"])
4652 pnl.Enter -= SearchControls_Enter;
4653 pnl.Leave -= SearchControls_Leave;
4654 _tabPage.Controls.Remove(pnl);
4656 foreach (Control ctrl in pnl.Controls)
4658 if (ctrl.Name == "buttonSearch")
4660 ctrl.Click -= SearchButton_Click;
4662 else if (ctrl.Name == "comboSearch")
4664 ctrl.KeyDown -= SearchComboBox_KeyDown;
4666 pnl.Controls.Remove(ctrl);
4672 _tabPage.Controls.Remove(_listCustom);
4674 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4675 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4676 _listCustom.ColumnClick -= MyList_ColumnClick;
4677 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4678 _listCustom.DragDrop -= TweenMain_DragDrop;
4679 _listCustom.DragEnter -= TweenMain_DragEnter;
4680 _listCustom.DragOver -= TweenMain_DragOver;
4681 _listCustom.DrawItem -= MyList_DrawItem;
4682 _listCustom.MouseClick -= MyList_MouseClick;
4683 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4684 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4685 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4686 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4687 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4688 _listCustom.HScrolled -= MyList_HScrolled;
4690 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4691 _listCustom.Columns.Clear();
4692 cols.ForEach(col => col.Dispose());
4695 _listCustom.ContextMenuStrip = null;
4696 _listCustom.ColumnHeaderContextMenuStrip = null;
4697 _listCustom.Font = null;
4699 _listCustom.SmallImageList = null;
4700 _listCustom.ListViewItemSorter = null;
4703 if (_curTab.Equals(_tabPage))
4710 this.PurgeListViewItemCache();
4714 _listCustom.Dispose();
4715 _statuses.RemoveTab(TabName);
4717 foreach (TabPage tp in ListTab.TabPages)
4719 DetailsListView lst = (DetailsListView)tp.Tag;
4720 var count = _statuses.Tabs[tp.Text].AllCount;
4721 if (lst.VirtualListSize != count)
4723 lst.VirtualListSize = count;
4730 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4732 this.PurgeListViewItemCache();
4733 _beforeSelectedTab = e.TabPage;
4736 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4740 if (!SettingDialog.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4743 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4744 if (!dragEnableRectangle.Contains(e.Location))
4746 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4747 tn = ListTab.SelectedTab.Text;
4750 if (string.IsNullOrEmpty(tn)) return;
4752 foreach (TabPage tb in ListTab.TabPages)
4756 ListTab.DoDragDrop(tb, DragDropEffects.All);
4766 Point cpos = new Point(e.X, e.Y);
4767 for (int i = 0; i < ListTab.TabPages.Count; i++)
4769 Rectangle rect = ListTab.GetTabRect(i);
4770 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4771 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4773 _rclickTabName = ListTab.TabPages[i].Text;
4779 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4781 //_curList.Refresh();
4783 SetMainWindowTitle();
4784 SetStatusLabelUrl();
4785 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4786 TabMenuControl(ListTab.SelectedTab.Text);
4787 this.PushSelectPostChain();
4790 private void SetListProperty()
4792 //削除などで見つからない場合は処理せず
4793 if (_curList == null) return;
4794 if (!_isColumnChanged) return;
4796 int[] dispOrder = new int[_curList.Columns.Count];
4797 for (int i = 0; i < _curList.Columns.Count; i++)
4799 for (int j = 0; j < _curList.Columns.Count; j++)
4801 if (_curList.Columns[j].DisplayIndex == i)
4810 foreach (TabPage tb in ListTab.TabPages)
4812 if (!tb.Equals(_curTab))
4814 if (tb.Tag != null && tb.Controls.Count > 0)
4816 DetailsListView lst = (DetailsListView)tb.Tag;
4817 for (int i = 0; i < lst.Columns.Count; i++)
4819 lst.Columns[dispOrder[i]].DisplayIndex = i;
4820 lst.Columns[i].Width = _curList.Columns[i].Width;
4826 _isColumnChanged = false;
4829 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4833 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4834 || PostBrowser.StatusText.StartsWith("data"))
4836 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4838 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4840 SetStatusLabelUrl();
4848 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4850 if (e.KeyChar == '@')
4852 if (!SettingDialog.UseAtIdSupplement) return;
4854 int cnt = AtIdSupl.ItemCount;
4855 ShowSuplDialog(StatusText, AtIdSupl);
4856 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4859 else if (e.KeyChar == '#')
4861 if (!SettingDialog.UseHashSupplement) return;
4862 ShowSuplDialog(StatusText, HashSupl);
4867 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4869 ShowSuplDialog(owner, dialog, 0, "");
4872 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4874 ShowSuplDialog(owner, dialog, offset, "");
4877 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4879 dialog.StartsWith = startswith;
4886 dialog.ShowDialog();
4888 this.TopMost = SettingDialog.AlwaysTop;
4889 int selStart = owner.SelectionStart;
4892 if (dialog.DialogResult == DialogResult.OK)
4894 if (!string.IsNullOrEmpty(dialog.inputText))
4898 fHalf = owner.Text.Substring(0, selStart - offset);
4900 if (selStart < owner.Text.Length)
4902 eHalf = owner.Text.Substring(selStart);
4904 owner.Text = fHalf + dialog.inputText + eHalf;
4905 owner.SelectionStart = selStart + dialog.inputText.Length;
4912 fHalf = owner.Text.Substring(0, selStart);
4914 if (selStart < owner.Text.Length)
4916 eHalf = owner.Text.Substring(selStart);
4918 owner.Text = fHalf + eHalf;
4921 owner.SelectionStart = selStart;
4927 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4930 if (!e.Alt && !e.Control && !e.Shift)
4932 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4934 bool isSpace = false;
4935 foreach (char c in StatusText.Text.ToCharArray())
4937 if (c == ' ' || c == ' ')
4950 StatusText.Text = "";
4951 JumpUnreadMenuItem_Click(null, null);
4955 this.StatusText_TextChanged(null, null);
4958 private void StatusText_TextChanged(object sender, EventArgs e)
4961 int pLen = GetRestStatusCount(true, false);
4962 lblLen.Text = pLen.ToString();
4965 StatusText.ForeColor = Color.Red;
4969 StatusText.ForeColor = _clInputFont;
4971 if (string.IsNullOrEmpty(StatusText.Text))
4973 _reply_to_id = null;
4974 _reply_to_name = null;
4978 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4981 var statusText = this.StatusText.Text;
4982 statusText = statusText.Replace("\r\n", "\n");
4984 int pLen = 140 - statusText.Length;
4985 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4986 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && SettingDialog.PostShiftEnter) ||
4987 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !SettingDialog.PostShiftEnter) ||
4988 (!isAuto && isAddFooter))
4990 if (SettingDialog.UseRecommendStatus)
4991 pLen -= SettingDialog.RecommendStatusText.Length;
4992 else if (SettingDialog.Status.Length > 0)
4993 pLen -= SettingDialog.Status.Length + 1;
4995 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4997 pLen -= HashMgr.UseHash.Length + 1;
4999 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
5001 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5003 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
5005 string before = m.Result("${before}");
5006 string url = m.Result("${url}");
5007 string protocol = m.Result("${protocol}");
5008 string domain = m.Result("${domain}");
5009 string path = m.Result("${path}");
5010 if (protocol.Length == 0)
5012 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
5017 bool last_url_invalid_match = false;
5018 string lasturl = null;
5019 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
5021 lasturl = mm.ToString();
5022 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
5023 if (!last_url_invalid_match)
5025 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5029 if (path.Length != 0)
5031 if (last_url_invalid_match)
5033 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5035 pLen += path.Length;
5040 int shortUrlLength = protocol == "https://"
5041 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
5042 : SettingDialog.TwitterConfiguration.ShortUrlLength;
5044 pLen += url.Length - shortUrlLength;
5047 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5049 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5052 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
5054 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
5059 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5061 this.itemCacheLock.EnterUpgradeableReadLock();
5064 if (_curList.Equals(sender))
5066 if (_itemCache != null &&
5067 e.StartIndex >= _itemCacheIndex &&
5068 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5070 //If the newly requested cache is a subset of the old cache,
5071 //no need to rebuild everything, so do nothing.
5075 //Now we need to rebuild the cache.
5076 CreateCache(e.StartIndex, e.EndIndex);
5079 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5082 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5084 ListViewItem item = null;
5085 PostClass cacheItemPost = null;
5087 if (_curList.Equals(sender))
5088 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5092 //A cache miss, so create a new ListViewItem and pass it back.
5093 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5096 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5101 string[] sitem = {"", "", "", "", "", "", "", ""};
5102 item = new ImageListViewItem(sitem);
5106 // e.Item に値をセットする前に await しないこと
5109 await ((ImageListViewItem)item).GetImageAsync();
5112 private void CreateCache(int StartIndex, int EndIndex)
5114 this.itemCacheLock.EnterWriteLock();
5117 //キャッシュ要求(要求範囲±30を作成)
5119 if (StartIndex < 0) StartIndex = 0;
5121 if (EndIndex >= _statuses.Tabs[_curTab.Text].AllCount) EndIndex = _statuses.Tabs[_curTab.Text].AllCount - 1;
5122 _postCache = _statuses[_curTab.Text, StartIndex, EndIndex]; //配列で取得
5123 _itemCacheIndex = StartIndex;
5125 _itemCache = new ListViewItem[0] {};
5126 Array.Resize(ref _itemCache, _postCache.Length);
5128 for (int i = 0; i < _postCache.Length; i++)
5130 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5135 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5137 _itemCacheIndex = -1;
5140 finally { this.itemCacheLock.ExitWriteLock(); }
5144 /// DetailsListView のための ListViewItem のキャッシュを消去する
5146 private void PurgeListViewItemCache()
5148 this.itemCacheLock.EnterWriteLock();
5151 this._itemCache = null;
5152 this._itemCacheIndex = -1;
5153 this._postCache = null;
5155 finally { this.itemCacheLock.ExitWriteLock(); }
5158 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5160 this.itemCacheLock.EnterReadLock();
5163 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5165 item = this._itemCache[index - _itemCacheIndex];
5166 post = this._postCache[index - _itemCacheIndex];
5170 finally { this.itemCacheLock.ExitReadLock(); }
5177 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5179 StringBuilder mk = new StringBuilder();
5180 //if (Post.IsDeleted) mk.Append("×");
5181 //if (Post.IsMark) mk.Append("♪");
5182 //if (Post.IsProtect) mk.Append("Ю");
5183 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5184 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5185 ImageListViewItem itm;
5186 if (Post.RetweetedId == null)
5188 string[] sitem= {"",
5190 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5191 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5196 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5200 string[] sitem = {"",
5202 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5203 Post.CreatedAt.ToString(SettingDialog.DateTimeFormat),
5204 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5208 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5210 itm.StateImageIndex = Post.StateIndex;
5212 bool read = Post.IsRead;
5213 //未読管理していなかったら既読として扱う
5214 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingDialog.UnreadManage) read = true;
5215 ChangeItemStyleRead(read, itm, Post, null);
5216 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5221 /// 全てのタブの振り分けルールを反映し直します
5223 private void ApplyPostFilters()
5227 this.Cursor = Cursors.WaitCursor;
5229 this.PurgeListViewItemCache();
5230 this._curPost = null;
5231 this._curItemIndex = -1;
5232 this._statuses.FilterAll();
5234 foreach (TabPage tabPage in this.ListTab.TabPages)
5236 var tab = this._statuses.Tabs[tabPage.Text];
5238 var listview = (DetailsListView)tabPage.Tag;
5239 listview.VirtualListSize = tab.AllCount;
5241 if (this.SettingDialog.TabIconDisp)
5243 if (tab.UnreadCount > 0)
5244 tabPage.ImageIndex = 0;
5246 tabPage.ImageIndex = -1;
5250 if (!this.SettingDialog.TabIconDisp)
5251 this.ListTab.Refresh();
5255 this.Cursor = Cursors.Default;
5259 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5261 e.DrawDefault = true;
5264 private void MyList_HScrolled(object sender, EventArgs e)
5266 DetailsListView listView = (DetailsListView)sender;
5270 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5272 if (e.State == 0) return;
5273 e.DrawDefault = false;
5275 SolidBrush brs2 = null;
5276 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5278 if (e.Item.BackColor == _clSelf)
5279 brs2 = _brsBackColorMine;
5280 else if (e.Item.BackColor == _clAtSelf)
5281 brs2 = _brsBackColorAt;
5282 else if (e.Item.BackColor == _clTarget)
5283 brs2 = _brsBackColorYou;
5284 else if (e.Item.BackColor == _clAtTarget)
5285 brs2 = _brsBackColorAtYou;
5286 else if (e.Item.BackColor == _clAtFromTarget)
5287 brs2 = _brsBackColorAtFromTarget;
5288 else if (e.Item.BackColor == _clAtTo)
5289 brs2 = _brsBackColorAtTo;
5291 brs2 = _brsBackColorNone;
5296 if (((Control)sender).Focused)
5297 brs2 = _brsHighLight;
5299 brs2 = _brsDeactiveSelection;
5301 e.Graphics.FillRectangle(brs2, e.Bounds);
5302 e.DrawFocusRectangle();
5303 this.DrawListViewItemIcon(e);
5306 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5308 if (e.ItemState == 0) return;
5310 if (e.ColumnIndex > 0)
5313 RectangleF rct = e.Bounds;
5314 rct.Width = e.Header.Width;
5315 int fontHeight = e.Item.Font.Height;
5318 rct.Y += fontHeight;
5319 rct.Height -= fontHeight;
5323 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5325 //if (heightDiff > fontHeight * 0.7)
5327 // rct.Height += fontHeight;
5328 // drawLineCount += 1;
5331 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5332 if (!_iconCol && drawLineCount <= 1)
5334 //rct.Inflate(0, heightDiff / -2);
5335 //rct.Height += fontHeight / 2;
5337 else if (heightDiff < fontHeight * 0.7)
5339 //最終行が70%以上欠けていたら、最終行は表示しない
5340 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5341 rct.Height = (fontHeight * drawLineCount) - 1;
5348 //if (!_iconCol && drawLineCount > 1)
5350 // rct.Y += fontHeight * 0.2;
5351 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5356 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5357 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5362 Rectangle rctB = e.Bounds;
5363 rctB.Width = e.Header.Width;
5364 rctB.Height = fontHeight;
5366 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5368 TextRenderer.DrawText(e.Graphics,
5369 e.Item.SubItems[2].Text,
5371 Rectangle.Round(rct),
5373 TextFormatFlags.WordBreak |
5374 TextFormatFlags.EndEllipsis |
5375 TextFormatFlags.GlyphOverhangPadding |
5376 TextFormatFlags.NoPrefix);
5377 TextRenderer.DrawText(e.Graphics,
5378 e.Item.SubItems[4].Text + " / " + e.Item.SubItems[1].Text + " (" + e.Item.SubItems[3].Text + ") " + e.Item.SubItems[5].Text + e.Item.SubItems[6].Text + " [" + e.Item.SubItems[7].Text + "]",
5382 TextFormatFlags.SingleLine |
5383 TextFormatFlags.EndEllipsis |
5384 TextFormatFlags.GlyphOverhangPadding |
5385 TextFormatFlags.NoPrefix);
5388 else if (drawLineCount == 1)
5390 TextRenderer.DrawText(e.Graphics,
5393 Rectangle.Round(rct),
5395 TextFormatFlags.SingleLine |
5396 TextFormatFlags.EndEllipsis |
5397 TextFormatFlags.GlyphOverhangPadding |
5398 TextFormatFlags.NoPrefix |
5399 TextFormatFlags.VerticalCenter);
5403 TextRenderer.DrawText(e.Graphics,
5406 Rectangle.Round(rct),
5408 TextFormatFlags.WordBreak |
5409 TextFormatFlags.EndEllipsis |
5410 TextFormatFlags.GlyphOverhangPadding |
5411 TextFormatFlags.NoPrefix);
5413 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5418 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5420 if (_iconSz == 0) return;
5422 ImageListViewItem item = (ImageListViewItem)e.Item;
5424 //e.Bounds.Leftが常に0を指すから自前で計算
5425 Rectangle itemRect = item.Bounds;
5426 var col0 = e.Item.ListView.Columns[0];
5427 itemRect.Width = col0.Width;
5429 if (col0.DisplayIndex > 0)
5431 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5433 if (clm.DisplayIndex < col0.DisplayIndex)
5434 itemRect.X += clm.Width;
5438 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5439 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5440 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5443 var img = item.Image;
5446 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5447 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5449 if (iconRect.Width > 0)
5451 e.Graphics.FillRectangle(Brushes.White, iconRect);
5452 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5455 e.Graphics.DrawImage(img.Image, iconRect);
5457 catch (ArgumentException)
5459 item.RefreshImageAsync();
5465 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5466 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5469 if (item.StateImageIndex > -1)
5471 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5472 if (stateRect.Width > 0)
5474 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5475 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5476 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateImageIndex], stateRect);
5481 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5483 base.ScaleControl(factor, specified);
5485 const int baseDpi = 96;
5487 // デザイン時の DPI (96dpi) との比を更新する
5488 this.currentScaleFactor = new SizeF(
5489 this.CurrentAutoScaleDimensions.Width / baseDpi,
5490 this.CurrentAutoScaleDimensions.Height / baseDpi);
5493 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5495 // ImageListViewItem item = (ImageListViewItem)e.Item;
5496 // if (item.StateImageIndex > -1)
5498 // ////e.Bounds.Leftが常に0を指すから自前で計算
5499 // //Rectangle itemRect = item.Bounds;
5500 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5502 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5504 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5506 // // itemRect.X += clm.Width;
5510 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5511 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5513 // if (rct.Width > 0)
5515 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5516 // //e.Graphics.FillRectangle(Brushes.White, rct);
5517 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5518 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5523 private void DoTabSearch(string _word,
5533 if (_curList.VirtualListSize == 0)
5535 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5538 if (_curList.SelectedIndices.Count > 0)
5540 cidx = _curList.SelectedIndices[0];
5542 toIdx = _curList.VirtualListSize;
5546 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5547 if (_curList.SelectedIndices.Count > 0)
5548 cidx = _curList.SelectedIndices[0];
5552 case SEARCHTYPE.NextSearch: //次を検索
5553 if (_curList.SelectedIndices.Count > 0)
5555 cidx = _curList.SelectedIndices[0] + 1;
5556 if (cidx > toIdx) cidx = toIdx;
5563 case SEARCHTYPE.PrevSearch: //前を検索
5564 if (_curList.SelectedIndices.Count > 0)
5566 cidx = _curList.SelectedIndices[0] - 1;
5567 if (cidx < 0) cidx = 0;
5578 RegexOptions regOpt = RegexOptions.None;
5579 StringComparison fndOpt = StringComparison.Ordinal;
5582 regOpt = RegexOptions.IgnoreCase;
5583 fndOpt = StringComparison.OrdinalIgnoreCase;
5594 _search = new Regex(_word, regOpt);
5595 for (int idx = cidx; idx != toIdx; idx += stp)
5600 post = _statuses[_curTab.Text, idx];
5606 if (_search.IsMatch(post.Nickname)
5607 || _search.IsMatch(post.TextFromApi)
5608 || _search.IsMatch(post.ScreenName))
5610 SelectListItem(_curList, idx);
5611 _curList.EnsureVisible(idx);
5616 catch (ArgumentException)
5618 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5625 for (int idx = cidx; idx != toIdx; idx += stp)
5630 post = _statuses[_curTab.Text, idx];
5636 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5637 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5638 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5640 SelectListItem(_curList, idx);
5641 _curList.EnsureVisible(idx);
5651 case SEARCHTYPE.DialogSearch:
5652 case SEARCHTYPE.NextSearch:
5656 case SEARCHTYPE.PrevSearch:
5658 cidx = _curList.VirtualListSize - 1;
5665 catch (ArgumentOutOfRangeException)
5668 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5671 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5674 this.ShowSearchDialog();
5677 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5679 var previousSearch = this.SearchDialog.ResultOptions;
5680 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5682 this.SearchDialog.Reset();
5683 this.ShowSearchDialog();
5689 previousSearch.Query,
5690 previousSearch.CaseSensitive,
5691 previousSearch.UseRegex,
5692 SEARCHTYPE.NextSearch);
5695 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5697 var previousSearch = this.SearchDialog.ResultOptions;
5698 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5700 this.SearchDialog.Reset();
5701 this.ShowSearchDialog();
5707 previousSearch.Query,
5708 previousSearch.CaseSensitive,
5709 previousSearch.UseRegex,
5710 SEARCHTYPE.PrevSearch);
5714 /// 検索ダイアログを表示し、検索を実行します
5716 private void ShowSearchDialog()
5718 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5719 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5720 this.SearchDialog.DisableNewTabButton = false;
5722 this.SearchDialog.DisableNewTabButton = true;
5724 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5726 this.TopMost = this.SettingDialog.AlwaysTop;
5729 this.TopMost = this.SettingDialog.AlwaysTop;
5731 var searchOptions = this.SearchDialog.ResultOptions;
5732 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5734 if (searchOptions.NewTab)
5736 var tabName = searchOptions.Query;
5740 tabName = this._statuses.MakeTabName(tabName);
5742 catch (TabException ex)
5744 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5747 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5748 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5750 var filter = new PostFilterRule
5752 FilterBody = new[] { searchOptions.Query },
5753 UseRegex = searchOptions.UseRegex,
5754 CaseSensitive = searchOptions.CaseSensitive,
5756 this._statuses.Tabs[tabName].AddFilter(filter);
5758 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5759 .First(x => x.Text == tabName);
5761 this.ListTab.SelectedTab = tabPage;
5762 this.ListTabSelect(tabPage);
5764 this.ApplyPostFilters();
5765 this.SaveConfigsTabs();
5770 searchOptions.Query,
5771 searchOptions.CaseSensitive,
5772 searchOptions.UseRegex,
5773 SEARCHTYPE.DialogSearch);
5776 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5778 this.AddNewTabForSearch(searchOptions.Query);
5782 private void AboutMenuItem_Click(object sender, EventArgs e)
5784 using (TweenAboutBox about = new TweenAboutBox())
5786 about.ShowDialog(this);
5788 this.TopMost = SettingDialog.AlwaysTop;
5791 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5793 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5795 DetailsListView lst = null;
5797 if (ImageSelector.Enabled)
5801 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5804 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5807 ListTab.SelectedIndex = i;
5808 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5809 //_curTab = ListTab.TabPages[i];
5814 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5815 if (idx == -1 && bgnIdx > 0)
5817 for (int i = 0; i < bgnIdx; i++)
5819 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5822 ListTab.SelectedIndex = i;
5823 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5824 //_curTab = ListTab.TabPages[i];
5830 //全部調べたが未読見つからず→先頭タブの最新発言へ
5833 ListTab.SelectedIndex = 0;
5834 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5835 //_curTab = ListTab.TabPages[0];
5836 if (_statuses.SortOrder == SortOrder.Ascending)
5837 idx = lst.VirtualListSize - 1;
5842 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5844 SelectListItem(lst, idx);
5845 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5847 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5848 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5854 lst.EnsureVisible(idx);
5859 lst.EnsureVisible(idx);
5865 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5867 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5869 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5870 OpenUriAsync(MyCommon.GetStatusUrl(post));
5874 private void FavorareMenuItem_Click(object sender, EventArgs e)
5876 if (_curList.SelectedIndices.Count > 0)
5878 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5879 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5883 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5885 await this.CheckNewVersion(false);
5888 private void RunTweenUp()
5890 ProcessStartInfo pinfo = new ProcessStartInfo();
5891 pinfo.UseShellExecute = true;
5892 pinfo.WorkingDirectory = MyCommon.settingPath;
5893 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5894 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5897 Process.Start(pinfo);
5901 MessageBox.Show("Failed to execute TweenUp3.exe.");
5905 public class VersionInfo
5907 public Version Version { get; set; }
5908 public Uri DownloadUri { get; set; }
5909 public string ReleaseNote { get; set; }
5913 /// OpenTween の最新バージョンの情報を取得します
5915 public async Task<VersionInfo> GetVersionInfoAsync()
5917 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5918 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5920 var responseText = await this.http.GetStringAsync(versionInfoUrl)
5921 .ConfigureAwait(false);
5923 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5924 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5926 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5927 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5929 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5931 return new VersionInfo
5933 Version = Version.Parse(msgHeader[0]),
5934 DownloadUri = new Uri(msgHeader[1]),
5935 ReleaseNote = msgBody,
5939 private async Task CheckNewVersion(bool startup = false)
5941 if (ApplicationSettings.VersionInfoUrl == null)
5942 return; // 更新チェック無効化
5946 var versionInfo = await this.GetVersionInfoAsync();
5948 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5953 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5954 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5955 msgtext = MyCommon.ReplaceAppName(msgtext);
5957 MessageBox.Show(msgtext,
5958 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5959 MessageBoxButtons.OK, MessageBoxIcon.Information);
5964 using (var dialog = new UpdateDialog())
5966 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5967 MyCommon.GetReadableVersion(versionInfo.Version));
5968 dialog.DetailsText = versionInfo.ReleaseNote;
5970 if (dialog.ShowDialog(this) == DialogResult.Yes)
5972 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5978 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5981 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5982 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5983 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5988 private void Colorize()
5992 //件数関連の場合、タイトル即時書き換え
5993 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
5994 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5995 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5996 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5998 SetMainWindowTitle();
6000 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6001 foreach (TabPage tb in ListTab.TabPages)
6003 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6005 if (SettingDialog.TabIconDisp)
6007 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6011 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
6014 public string createDetailHtml(string orgdata)
6016 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6019 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6021 if (sender.Equals(displayItem))
6023 this.ClearUserPicture();
6025 var img = displayItem.Image;
6029 img = await img.CloneAsync();
6031 UserPicture.Image = img;
6035 UserPicture.ShowErrorImage();
6040 private void DispSelectedPost()
6042 DispSelectedPost(false);
6045 private static PostClass displaypost = new PostClass();
6048 /// サムネイルの表示処理を表すタスク
6050 private Task thumbnailTask = null;
6053 /// サムネイル表示に使用する CancellationToken の生成元
6055 private CancellationTokenSource thumbnailTokenSource = null;
6057 private void DispSelectedPost(bool forceupdate)
6059 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6062 if (!forceupdate && _curPost.Equals(displaypost))
6065 displaypost = _curPost;
6066 if (displayItem != null)
6068 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6071 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6072 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6074 string dTxt = createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6077 SourceLinkLabel.Tag = null;
6078 SourceLinkLabel.Text = "";
6082 Match mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6085 string src = mc.Groups["sourceurl"].Value;
6086 SourceLinkLabel.Tag = mc.Groups["sourceurl"].Value;
6087 mc = Regex.Match(src, "^https?://");
6090 src = src.Insert(0, "https://twitter.com");
6092 SourceLinkLabel.Tag = src;
6096 SourceLinkLabel.Tag = null;
6098 if (string.IsNullOrEmpty(_curPost.Source))
6100 SourceLinkLabel.Text = "";
6101 //SourceLinkLabel.Visible = false;
6105 SourceLinkLabel.Text = _curPost.Source;
6106 //SourceLinkLabel.Visible = true;
6109 SourceLinkLabel.TabStop = false;
6111 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && !_curPost.IsOwl)
6113 NameLabel.Text = "DM TO -> ";
6115 else if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
6117 NameLabel.Text = "DM FROM <- ";
6121 NameLabel.Text = "";
6123 NameLabel.Text += _curPost.ScreenName + "/" + _curPost.Nickname;
6124 NameLabel.Tag = _curPost.ScreenName;
6125 if (!string.IsNullOrEmpty(_curPost.RetweetedBy))
6127 NameLabel.Text += " (RT:" + _curPost.RetweetedBy + ")";
6130 this.ClearUserPicture();
6132 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6134 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6137 UserPicture.Image = image != null ? image.Clone() : null;
6141 UserPicture.ShowErrorImage();
6145 NameLabel.ForeColor = System.Drawing.SystemColors.ControlText;
6146 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6147 if (_curPost.IsOwl && (SettingDialog.OneWayLove || _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)) NameLabel.ForeColor = _clOWL;
6148 if (_curPost.RetweetedId != null) NameLabel.ForeColor = _clRetweet;
6149 if (_curPost.IsFav) NameLabel.ForeColor = _clFav;
6151 if (DumpPostClassToolStripMenuItem.Checked)
6153 StringBuilder sb = new StringBuilder(512);
6155 sb.Append("-----Start PostClass Dump<br>");
6156 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6157 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6158 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6159 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6160 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6161 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6162 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6163 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6164 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6165 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6166 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6167 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6168 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6169 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6170 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6172 foreach (string nm in _curPost.ReplyToList)
6174 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6177 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6178 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6179 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6180 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6181 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6182 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6183 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6184 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6185 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6186 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6187 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6188 sb.Append("-----End PostClass Dump<br>");
6190 PostBrowser.Visible = false;
6191 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6192 PostBrowser.Visible = true;
6198 if (PostBrowser.DocumentText != dTxt)
6200 PostBrowser.Visible = false;
6201 PostBrowser.DocumentText = dTxt;
6203 this.SplitContainer3.Panel2Collapsed = true;
6205 if (this.IsPreviewEnable)
6207 if (this.thumbnailTokenSource != null)
6209 var oldTokenSource = this.thumbnailTokenSource;
6211 // TODO: キャンセルを行うとUIスレッドが阻害される問題を調査
6212 //oldTokenSource.Cancel();
6214 this.thumbnailTask.ContinueWith(_ => oldTokenSource.Dispose());
6217 this.thumbnailTokenSource = new CancellationTokenSource();
6219 var token = this.thumbnailTokenSource.Token;
6220 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6224 catch (System.Runtime.InteropServices.COMException)
6228 catch (UriFormatException)
6230 PostBrowser.DocumentText = dTxt;
6234 PostBrowser.Visible = true;
6239 private void MatomeMenuItem_Click(object sender, EventArgs e)
6241 OpenApplicationWebsite();
6244 private void OpenApplicationWebsite()
6246 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6249 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6251 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6254 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6256 if (ListTab.SelectedTab != null)
6258 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6260 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6261 if (pnl.Controls["comboSearch"].Focused ||
6262 pnl.Controls["comboLang"].Focused ||
6263 pnl.Controls["buttonSearch"].Focused) return;
6265 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6266 if (State == ModifierState.NotFlags) return;
6267 if (State != ModifierState.None) _anchorFlag = false;
6268 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6271 e.SuppressKeyPress = true;
6276 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6278 ModifierState state = ModifierState.None;
6279 if (sControl) state = state | ModifierState.Ctrl;
6280 if (sShift) state = state | ModifierState.Shift;
6281 if (sAlt) state = state | ModifierState.Alt;
6286 private enum ModifierState
6298 //PostBrowser = 102,
6302 private enum FocusedControl : int
6310 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6312 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6313 if (Focused == FocusedControl.ListTab)
6315 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6316 Modifier == ModifierState.Ctrl ||
6317 Modifier == ModifierState.None ||
6318 Modifier == ModifierState.Shift)
6320 if (KeyCode == Keys.J)
6322 SendKeys.Send("{DOWN}");
6325 else if (KeyCode == Keys.K)
6327 SendKeys.Send("{UP}");
6331 if (Modifier == ModifierState.Shift ||
6332 Modifier == ModifierState.None)
6334 if (KeyCode == Keys.F)
6336 SendKeys.Send("{PGDN}");
6339 else if (KeyCode == Keys.B)
6341 SendKeys.Send("{PGUP}");
6350 case ModifierState.None:
6355 OpenApplicationWebsite();
6358 MenuItemSearchNext_Click(null, null);
6364 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 0, "");
6367 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 0, "");
6370 if (Focused != FocusedControl.StatusText)
6376 case Keys.ProcessKey:
6377 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6378 JumpUnreadMenuItem_Click(null, null);
6381 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6382 ShowRelatedStatusesMenuItem_Click(null, null);
6386 if (Focused == FocusedControl.ListTab)
6399 case Keys.OemPeriod:
6403 if (this.StatusText.Enabled) this.StatusText.Focus();
6406 MakeReplyOrDirectStatus();
6413 _anchorFlag = false;
6433 // ] in_reply_to参照元へ戻る
6434 GoInReplyToPostTree();
6437 // [ in_reply_toへジャンプ
6438 GoBackInReplyToPostTree();
6441 if (ListTab.SelectedTab != null)
6443 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6444 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6446 TabPage relTp = ListTab.SelectedTab;
6447 RemoveSpecifiedTab(relTp.Text, false);
6455 else if (Focused == FocusedControl.PostBrowser)
6462 //スクロールを発生させるため、true を返す
6467 case ModifierState.Ctrl:
6472 MakeReplyOrDirectStatus(false, true);
6478 MakeReplyOrDirectStatus(false, false);
6481 FavoriteChange(true);
6484 doRepliedStatusOpen();
6490 ReadedStripMenuItem_Click(null, null);
6493 HashManageMenuItem_Click(null, null);
6496 UrlConvertAutoToolStripMenuItem_Click(null, null);
6499 if (Focused != FocusedControl.PostBrowser)
6501 MultiLineMenuItem_Click(null, null);
6506 MenuItemSubSearch_Click(null, null);
6513 MoveToHomeToolStripMenuItem_Click(null, null);
6517 MoveToFavToolStripMenuItem_Click(null, null);
6521 StatusOpenMenuItem_Click(null, null);
6525 OpenURLMenuItem_Click(null, null);
6529 if (Focused == FocusedControl.ListTab)
6536 return false; //スルーする
6554 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6555 int tabNo = KeyCode - Keys.D1;
6556 if (ListTab.TabPages.Count < tabNo)
6558 ListTab.SelectedIndex = tabNo;
6559 ListTabSelect(ListTab.TabPages[tabNo]);
6562 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6563 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6567 else if (Focused == FocusedControl.StatusText)
6573 StatusText.SelectAll();
6577 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6579 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6581 if (KeyCode == Keys.Up)
6584 if (_hisIdx < 0) _hisIdx = 0;
6589 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6591 StatusText.Text = _history[_hisIdx].status;
6592 _reply_to_id = _history[_hisIdx].inReplyToId;
6593 _reply_to_name = _history[_hisIdx].inReplyToName;
6594 StatusText.SelectionStart = StatusText.Text.Length;
6598 if (ListTab.SelectedIndex == 0)
6600 ListTab.SelectedIndex = ListTab.TabCount - 1;
6604 ListTab.SelectedIndex -= 1;
6610 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6612 ListTab.SelectedIndex = 0;
6616 ListTab.SelectedIndex += 1;
6624 //フォーカスPostBrowserもしくは関係なし
6628 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6632 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6633 if (!string.IsNullOrEmpty(_selText))
6637 Clipboard.SetDataObject(_selText, false, 5, 100);
6639 catch (Exception ex)
6641 MessageBox.Show(ex.Message);
6646 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6647 MultiLineMenuItem_Click(null, null);
6652 case ModifierState.Shift:
6657 MenuItemSearchPrev_Click(null, null);
6663 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, 0, "");
6666 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, 0, "");
6670 if (Focused != FocusedControl.StatusText)
6672 if (KeyCode == Keys.R)
6679 if (Focused == FocusedControl.ListTab)
6699 GoBackInReplyToPostTree(true, false);
6702 GoBackInReplyToPostTree(true, true);
6706 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6711 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6715 this.GoBackSelectPostChain();
6720 case ModifierState.Alt:
6724 doReTweetOfficial(true);
6727 if (_curPost != null)
6729 doShowUserStatus(_curPost.ScreenName, false);
6734 ScrollDownPostBrowser(false);
6737 ScrollDownPostBrowser(true);
6740 PageDownPostBrowser(false);
6743 PageDownPostBrowser(true);
6746 if (Focused == FocusedControl.ListTab)
6748 // 別タブの同じ書き込みへ(ALT+←/→)
6749 if (KeyCode == Keys.Right)
6751 GoSamePostToAnotherTab(false);
6754 else if (KeyCode == Keys.Left)
6756 GoSamePostToAnotherTab(true);
6761 case ModifierState.Ctrl | ModifierState.Shift:
6765 MakeReplyOrDirectStatus(false, true, true);
6771 if (ListTab.SelectedTab != null)
6773 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6775 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6781 FavoriteChange(false);
6784 UnreadStripMenuItem_Click(null, null);
6787 HashToggleMenuItem_Click(null, null);
6790 ImageSelectMenuItem_Click(null, null);
6796 FavorareMenuItem_Click(null, null);
6799 if (Focused == FocusedControl.StatusText)
6805 if (_curList != null && _curList.VirtualListSize != 0 &&
6806 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6808 idx = _curList.SelectedIndices[0] - 1;
6809 SelectListItem(_curList, idx);
6810 _curList.EnsureVisible(idx);
6815 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6816 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6818 idx = _curList.SelectedIndices[0] + 1;
6819 SelectListItem(_curList, idx);
6820 _curList.EnsureVisible(idx);
6825 if (StatusText.SelectionStart > 0)
6827 int endidx = StatusText.SelectionStart - 1;
6828 string startstr = "";
6829 bool pressed = false;
6830 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6832 char c = StatusText.Text[i];
6833 if (Char.IsLetterOrDigit(c) || c == '_')
6840 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6841 int cnt = AtIdSupl.ItemCount;
6842 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6843 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6848 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6849 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6861 else if (Focused == FocusedControl.ListTab)
6863 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6875 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6876 int colNo = KeyCode - Keys.D1;
6877 if (lst.Columns.Count < colNo) return false;
6878 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6879 if (col == null) return false;
6880 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6883 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6884 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6889 case ModifierState.Ctrl | ModifierState.Alt:
6890 if (KeyCode == Keys.S)
6892 FavoritesRetweetOriginal();
6895 else if (KeyCode == Keys.R)
6897 FavoritesRetweetUnofficial();
6900 else if (KeyCode == Keys.H)
6902 OpenUserAppointUrl();
6906 case ModifierState.Alt | ModifierState.Shift:
6907 if (Focused == FocusedControl.PostBrowser)
6909 if (KeyCode == Keys.R)
6910 doReTweetUnofficial();
6911 else if (KeyCode == Keys.C)
6918 if (!this.ExistCurrentPost) return false;
6919 doTranslation(_curPost.TextFromApi);
6922 doReTweetUnofficial();
6928 this.tweetThumbnail1.ScrollUp();
6931 this.tweetThumbnail1.ScrollDown();
6934 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6936 if (!this.SplitContainer3.Panel2Collapsed)
6938 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6948 private void ScrollDownPostBrowser(bool forward)
6950 var doc = PostBrowser.Document;
6951 if (doc == null) return;
6953 var tags = doc.GetElementsByTagName("html");
6957 tags[0].ScrollTop += SettingDialog.FontDetail.Height;
6959 tags[0].ScrollTop -= SettingDialog.FontDetail.Height;
6963 private void PageDownPostBrowser(bool forward)
6965 var doc = PostBrowser.Document;
6966 if (doc == null) return;
6968 var tags = doc.GetElementsByTagName("html");
6972 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6974 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - SettingDialog.FontDetail.Height;
6978 private void GoNextTab(bool forward)
6980 int idx = ListTab.SelectedIndex;
6984 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6989 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6991 ListTab.SelectedIndex = idx;
6992 ListTabSelect(ListTab.TabPages[idx]);
6995 private void CopyStot()
6998 StringBuilder sb = new StringBuilder();
6999 bool IsProtected = false;
7001 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7002 foreach (int idx in _curList.SelectedIndices)
7004 PostClass post = _statuses[_curTab.Text, idx];
7010 if (post.IsDeleted) continue;
7013 if (post.RetweetedId != null)
7014 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7016 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7020 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7025 MessageBox.Show(Properties.Resources.CopyStotText1);
7029 clstr = sb.ToString();
7032 Clipboard.SetDataObject(clstr, false, 5, 100);
7034 catch (Exception ex)
7036 MessageBox.Show(ex.Message);
7041 private void CopyIdUri()
7044 StringBuilder sb = new StringBuilder();
7045 if (this._curTab == null) return;
7046 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7047 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7048 foreach (int idx in _curList.SelectedIndices)
7050 var post = _statuses[_curTab.Text, idx];
7051 sb.Append(MyCommon.GetStatusUrl(post));
7052 sb.Append(Environment.NewLine);
7056 clstr = sb.ToString();
7059 Clipboard.SetDataObject(clstr, false, 5, 100);
7061 catch (Exception ex)
7063 MessageBox.Show(ex.Message);
7068 private void GoFav(bool forward)
7070 if (_curList.VirtualListSize == 0) return;
7077 if (_curList.SelectedIndices.Count == 0)
7083 fIdx = _curList.SelectedIndices[0] + 1;
7084 if (fIdx > _curList.VirtualListSize - 1) return;
7086 toIdx = _curList.VirtualListSize;
7091 if (_curList.SelectedIndices.Count == 0)
7093 fIdx = _curList.VirtualListSize - 1;
7097 fIdx = _curList.SelectedIndices[0] - 1;
7098 if (fIdx < 0) return;
7104 for (int idx = fIdx; idx != toIdx; idx += stp)
7106 if (_statuses[_curTab.Text, idx].IsFav)
7108 SelectListItem(_curList, idx);
7109 _curList.EnsureVisible(idx);
7115 private void GoSamePostToAnotherTab(bool left)
7117 if (_curList.VirtualListSize == 0) return;
7123 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7124 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7126 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7131 if (ListTab.SelectedIndex == 0)
7137 fIdx = ListTab.SelectedIndex - 1;
7145 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7151 fIdx = ListTab.SelectedIndex + 1;
7153 toIdx = ListTab.TabCount;
7158 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7160 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7161 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7163 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7165 ListTab.SelectedIndex = tabidx;
7166 ListTabSelect(ListTab.TabPages[tabidx]);
7167 SelectListItem(_curList, idx);
7168 _curList.EnsureVisible(idx);
7177 private void GoPost(bool forward)
7179 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7186 fIdx = _curList.SelectedIndices[0] + 1;
7187 if (fIdx > _curList.VirtualListSize - 1) return;
7188 toIdx = _curList.VirtualListSize;
7193 fIdx = _curList.SelectedIndices[0] - 1;
7194 if (fIdx < 0) return;
7200 if (_curPost.RetweetedId == null)
7202 name = _curPost.ScreenName;
7206 name = _curPost.RetweetedBy;
7208 for (int idx = fIdx; idx != toIdx; idx += stp)
7210 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7212 if (_statuses[_curTab.Text, idx].ScreenName == name)
7214 SelectListItem(_curList, idx);
7215 _curList.EnsureVisible(idx);
7221 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7223 SelectListItem(_curList, idx);
7224 _curList.EnsureVisible(idx);
7231 private void GoRelPost(bool forward)
7233 if (_curList.SelectedIndices.Count == 0) return;
7240 fIdx = _curList.SelectedIndices[0] + 1;
7241 if (fIdx > _curList.VirtualListSize - 1) return;
7242 toIdx = _curList.VirtualListSize;
7247 fIdx = _curList.SelectedIndices[0] - 1;
7248 if (fIdx < 0) return;
7255 if (_curPost == null) return;
7256 _anchorPost = _curPost;
7261 if (_anchorPost == null) return;
7264 for (int idx = fIdx; idx != toIdx; idx += stp)
7266 PostClass post = _statuses[_curTab.Text, idx];
7267 if (post.ScreenName == _anchorPost.ScreenName ||
7268 post.RetweetedBy == _anchorPost.ScreenName ||
7269 post.ScreenName == _anchorPost.RetweetedBy ||
7270 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7271 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7272 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7273 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7274 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7276 SelectListItem(_curList, idx);
7277 _curList.EnsureVisible(idx);
7283 private void GoAnchor()
7285 if (_anchorPost == null) return;
7286 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7287 if (idx == -1) return;
7289 SelectListItem(_curList, idx);
7290 _curList.EnsureVisible(idx);
7293 private void GoTopEnd(bool GoTop)
7300 _item = _curList.GetItemAt(0, 25);
7308 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7310 idx = _curList.VirtualListSize - 1;
7314 SelectListItem(_curList, idx);
7317 private void GoMiddle()
7324 _item = _curList.GetItemAt(0, 0);
7334 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7337 idx2 = _curList.VirtualListSize - 1;
7343 idx3 = (idx1 + idx2) / 2;
7345 SelectListItem(_curList, idx3);
7348 private void GoLast()
7350 if (_curList.VirtualListSize == 0) return;
7352 if (_statuses.SortOrder == SortOrder.Ascending)
7354 SelectListItem(_curList, _curList.VirtualListSize - 1);
7355 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7359 SelectListItem(_curList, 0);
7360 _curList.EnsureVisible(0);
7364 private void MoveTop()
7366 if (_curList.SelectedIndices.Count == 0) return;
7367 int idx = _curList.SelectedIndices[0];
7368 if (_statuses.SortOrder == SortOrder.Ascending)
7370 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7374 _curList.EnsureVisible(0);
7376 _curList.EnsureVisible(idx);
7379 private void GoInReplyToPostTree()
7381 if (_curPost == null) return;
7383 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7385 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7387 PostClass post = null;
7388 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7389 if (string.IsNullOrEmpty(r) && post != null)
7391 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7392 _curPost.InReplyToUser = post.InReplyToUser;
7393 _curPost.IsReply = post.IsReply;
7394 this.PurgeListViewItemCache();
7395 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7399 this.StatusLabel.Text = r;
7403 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7405 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7407 replyChains = new Stack<ReplyChain>();
7409 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7412 string inReplyToTabName;
7413 long inReplyToId = _curPost.InReplyToStatusId.Value;
7414 string inReplyToUser = _curPost.InReplyToUser;
7415 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7417 var inReplyToPosts = from tab in _statuses.Tabs.Values
7418 orderby tab != curTabClass
7419 from post in tab.Posts.Values
7420 where post.StatusId == inReplyToId
7421 let index = tab.IndexOf(post.StatusId)
7423 select new {Tab = tab, Index = index};
7427 var inReplyPost = inReplyToPosts.First();
7428 inReplyToTabName = inReplyPost.Tab.TabName;
7429 inReplyToIndex = inReplyPost.Index;
7431 catch (InvalidOperationException)
7433 PostClass post = null;
7434 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7435 if (string.IsNullOrEmpty(r) && post != null)
7438 _statuses.AddPost(post);
7439 _statuses.DistributePosts();
7440 //_statuses.SubmitUpdate(null, null, null, false);
7441 this.RefreshTimeline(false);
7444 var inReplyPost = inReplyToPosts.First();
7445 inReplyToTabName = inReplyPost.Tab.TabName;
7446 inReplyToIndex = inReplyPost.Index;
7448 catch (InvalidOperationException)
7450 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7456 this.StatusLabel.Text = r;
7457 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7462 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7463 DetailsListView listView = (DetailsListView)tabPage.Tag;
7465 if (_curTab != tabPage)
7467 this.ListTab.SelectTab(tabPage);
7470 this.SelectListItem(listView, inReplyToIndex);
7471 listView.EnsureVisible(inReplyToIndex);
7474 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7476 if (_curPost == null) return;
7478 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7479 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7483 if (_curPost.InReplyToStatusId != null)
7485 var posts = from t in _statuses.Tabs
7486 from p in t.Value.Posts
7487 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7488 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7490 orderby isForward ? indexOf : indexOf * -1
7491 orderby t.Value != curTabClass
7492 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7495 var postList = posts.ToList();
7496 for (int i = postList.Count - 1; i >= 0; i--)
7499 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7501 postList.RemoveAt(index);
7504 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7505 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7506 if (post == null) post = postList.First();
7507 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7508 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7509 SelectListItem(listView, post.Index);
7510 listView.EnsureVisible(post.Index);
7512 catch (InvalidOperationException)
7520 if (replyChains == null || replyChains.Count < 1)
7522 var posts = from t in _statuses.Tabs
7523 from p in t.Value.Posts
7524 where p.Value.InReplyToStatusId == _curPost.StatusId
7525 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7528 orderby t.Value != curTabClass
7529 select new {Tab = t.Value, Index = indexOf};
7532 var post = posts.First();
7533 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7534 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7535 SelectListItem(listView, post.Index);
7536 listView.EnsureVisible(post.Index);
7538 catch (InvalidOperationException)
7545 ReplyChain chainHead = replyChains.Pop();
7546 if (chainHead.InReplyToId == _curPost.StatusId)
7548 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7557 ListTab.SelectTab(chainHead.OriginalTab);
7563 SelectListItem(_curList, idx);
7564 _curList.EnsureVisible(idx);
7570 this.GoBackInReplyToPostTree(parallel);
7576 private void GoBackSelectPostChain()
7578 if (this.selectPostChains.Count > 1)
7587 this.selectPostChains.Pop();
7588 var tabPostPair = this.selectPostChains.Peek();
7590 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7592 if (tabPostPair.Item2 != null)
7594 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7595 if (idx == -1) continue; //該当ポストが存在しないので無視
7598 tp = tabPostPair.Item1;
7600 this.selectPostChains.Pop();
7602 catch (InvalidOperationException)
7608 while (this.selectPostChains.Count > 1);
7613 //履歴が残り1つであればクリアしておく
7614 if (this.selectPostChains.Count == 1)
7615 this.selectPostChains.Clear();
7619 DetailsListView lst = (DetailsListView)tp.Tag;
7620 this.ListTab.SelectedTab = tp;
7623 SelectListItem(lst, idx);
7624 lst.EnsureVisible(idx);
7630 private void PushSelectPostChain()
7632 int count = this.selectPostChains.Count;
7635 var p = this.selectPostChains.Peek();
7636 if (p.Item1 == this._curTab)
7638 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7639 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7642 if (count >= 2500) TrimPostChain();
7643 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7646 private void TrimPostChain()
7648 if (this.selectPostChains.Count <= 2000) return;
7649 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7650 for (int i = 0; i < 2000; i++)
7652 p.Push(this.selectPostChains.Pop());
7654 this.selectPostChains.Clear();
7655 for (int i = 0; i < 2000; i++)
7657 this.selectPostChains.Push(p.Pop());
7661 private bool GoStatus(long statusId)
7663 if (statusId == 0) return false;
7664 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7666 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7668 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7669 ListTab.SelectedIndex = tabidx;
7670 ListTabSelect(ListTab.TabPages[tabidx]);
7671 SelectListItem(_curList, idx);
7672 _curList.EnsureVisible(idx);
7679 private bool GoDirectMessage(long statusId)
7681 if (statusId == 0) return false;
7682 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7684 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7686 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7687 ListTab.SelectedIndex = tabidx;
7688 ListTabSelect(ListTab.TabPages[tabidx]);
7689 SelectListItem(_curList, idx);
7690 _curList.EnsureVisible(idx);
7697 private void MyList_MouseClick(object sender, MouseEventArgs e)
7699 _anchorFlag = false;
7702 private void StatusText_Enter(object sender, EventArgs e)
7704 // フォーカスの戻り先を StatusText に設定
7705 this.Tag = StatusText;
7706 StatusText.BackColor = _clInputBackcolor;
7709 public Color InputBackColor
7711 get { return _clInputBackcolor; }
7712 set { _clInputBackcolor = value; }
7715 private void StatusText_Leave(object sender, EventArgs e)
7717 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7718 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7719 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7722 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7724 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7725 if (State == ModifierState.NotFlags) return;
7726 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7729 e.SuppressKeyPress = true;
7732 this.StatusText_TextChanged(null, null);
7735 private void SaveConfigsAll(bool ifModified)
7739 SaveConfigsCommon();
7746 if (_modifySettingCommon) SaveConfigsCommon();
7747 if (_modifySettingLocal) SaveConfigsLocal();
7748 if (_modifySettingAtId) SaveConfigsAtId();
7752 private void SaveConfigsAtId()
7754 if (_ignoreConfigSave || !SettingDialog.UseAtIdSupplement && AtIdSupl == null) return;
7756 _modifySettingAtId = false;
7757 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7761 private void SaveConfigsCommon()
7763 if (_ignoreConfigSave) return;
7765 _modifySettingCommon = false;
7768 _cfgCommon.UserName = tw.Username;
7769 _cfgCommon.UserId = tw.UserId;
7770 _cfgCommon.Password = tw.Password;
7771 _cfgCommon.Token = tw.AccessToken;
7772 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7773 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7774 _cfgCommon.UserstreamStartup = SettingDialog.UserstreamStartup;
7775 _cfgCommon.UserstreamPeriod = SettingDialog.UserstreamPeriodInt;
7776 _cfgCommon.TimelinePeriod = SettingDialog.TimelinePeriodInt;
7777 _cfgCommon.ReplyPeriod = SettingDialog.ReplyPeriodInt;
7778 _cfgCommon.DMPeriod = SettingDialog.DMPeriodInt;
7779 _cfgCommon.PubSearchPeriod = SettingDialog.PubSearchPeriodInt;
7780 _cfgCommon.ListsPeriod = SettingDialog.ListsPeriodInt;
7781 _cfgCommon.UserTimelinePeriod = SettingDialog.UserTimelinePeriodInt;
7782 _cfgCommon.Read = SettingDialog.Readed;
7783 _cfgCommon.IconSize = SettingDialog.IconSz;
7784 _cfgCommon.UnreadManage = SettingDialog.UnreadManage;
7785 _cfgCommon.PlaySound = SettingDialog.PlaySound;
7786 _cfgCommon.OneWayLove = SettingDialog.OneWayLove;
7788 _cfgCommon.NameBalloon = SettingDialog.NameBalloon;
7789 _cfgCommon.PostCtrlEnter = SettingDialog.PostCtrlEnter;
7790 _cfgCommon.PostShiftEnter = SettingDialog.PostShiftEnter;
7791 _cfgCommon.CountApi = SettingDialog.CountApi;
7792 _cfgCommon.CountApiReply = SettingDialog.CountApiReply;
7793 _cfgCommon.PostAndGet = SettingDialog.PostAndGet;
7794 _cfgCommon.DispUsername = SettingDialog.DispUsername;
7795 _cfgCommon.MinimizeToTray = SettingDialog.MinimizeToTray;
7796 _cfgCommon.CloseToExit = SettingDialog.CloseToExit;
7797 _cfgCommon.DispLatestPost = SettingDialog.DispLatestPost;
7798 _cfgCommon.SortOrderLock = SettingDialog.SortOrderLock;
7799 _cfgCommon.ViewTabBottom = SettingDialog.ViewTabBottom;
7800 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7801 _cfgCommon.StartupVersion = SettingDialog.StartupVersion;
7802 _cfgCommon.StartupFollowers = SettingDialog.StartupFollowers;
7803 _cfgCommon.RestrictFavCheck = SettingDialog.RestrictFavCheck;
7804 _cfgCommon.AlwaysTop = SettingDialog.AlwaysTop;
7805 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7806 _cfgCommon.UseUnreadStyle = SettingDialog.UseUnreadStyle;
7807 _cfgCommon.DateTimeFormat = SettingDialog.DateTimeFormat;
7808 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7809 _cfgCommon.RetweetNoConfirm = SettingDialog.RetweetNoConfirm;
7810 _cfgCommon.LimitBalloon = SettingDialog.LimitBalloon;
7811 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7812 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7813 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7814 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7815 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7816 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7817 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7818 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7819 _cfgCommon.TabIconDisp = SettingDialog.TabIconDisp;
7820 _cfgCommon.ReplyIconState = SettingDialog.ReplyIconState;
7821 _cfgCommon.ReadOwnPost = SettingDialog.ReadOwnPost;
7822 _cfgCommon.GetFav = SettingDialog.GetFav;
7823 _cfgCommon.IsMonospace = SettingDialog.IsMonospace;
7824 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7825 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7827 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7829 _cfgCommon.ReadOldPosts = SettingDialog.ReadOldPosts;
7830 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7831 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7832 _cfgCommon.ShowGrid = SettingDialog.ShowGrid;
7833 _cfgCommon.UseAtIdSupplement = SettingDialog.UseAtIdSupplement;
7834 _cfgCommon.UseHashSupplement = SettingDialog.UseHashSupplement;
7835 _cfgCommon.PreviewEnable = SettingDialog.PreviewEnable;
7836 _cfgCommon.StatusAreaAtBottom = SettingDialog.StatusAreaAtBottom;
7837 _cfgCommon.Language = SettingDialog.Language;
7839 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7840 switch (_statuses.SortMode)
7842 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7843 _cfgCommon.SortColumn = 1;
7845 case IdComparerClass.ComparerMode.Data: //本文
7846 _cfgCommon.SortColumn = 2;
7848 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7849 _cfgCommon.SortColumn = 3;
7851 case IdComparerClass.ComparerMode.Name: //名前
7852 _cfgCommon.SortColumn = 4;
7854 case IdComparerClass.ComparerMode.Source: //Source
7855 _cfgCommon.SortColumn = 7;
7859 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7860 _cfgCommon.HashTags = HashMgr.HashHistories;
7861 if (HashMgr.IsPermanent)
7863 _cfgCommon.HashSelected = HashMgr.UseHash;
7867 _cfgCommon.HashSelected = "";
7869 _cfgCommon.HashIsHead = HashMgr.IsHead;
7870 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7871 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7872 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7873 _cfgCommon.HotkeyEnabled = SettingDialog.HotkeyEnabled;
7874 _cfgCommon.HotkeyModifier = SettingDialog.HotkeyMod;
7875 _cfgCommon.HotkeyKey = SettingDialog.HotkeyKey;
7876 _cfgCommon.HotkeyValue = SettingDialog.HotkeyValue;
7877 _cfgCommon.BlinkNewMentions = SettingDialog.BlinkNewMentions;
7878 if (ToolStripFocusLockMenuItem != null &&
7879 ToolStripFocusLockMenuItem.IsDisposed == false)
7881 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7883 _cfgCommon.UseAdditionalCount = SettingDialog.UseAdditionalCount;
7884 _cfgCommon.MoreCountApi = SettingDialog.MoreCountApi;
7885 _cfgCommon.FirstCountApi = SettingDialog.FirstCountApi;
7886 _cfgCommon.SearchCountApi = SettingDialog.SearchCountApi;
7887 _cfgCommon.FavoritesCountApi = SettingDialog.FavoritesCountApi;
7888 _cfgCommon.UserTimelineCountApi = SettingDialog.UserTimelineCountApi;
7889 _cfgCommon.TrackWord = tw.TrackWord;
7890 _cfgCommon.AllAtReply = tw.AllAtReply;
7891 _cfgCommon.OpenUserTimeline = SettingDialog.OpenUserTimeline;
7892 _cfgCommon.ListCountApi = SettingDialog.ListCountApi;
7893 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7894 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7895 _cfgCommon.ListDoubleClickAction = SettingDialog.ListDoubleClickAction;
7896 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7897 _cfgCommon.HideDuplicatedRetweets = SettingDialog.HideDuplicatedRetweets;
7898 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7899 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7900 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7901 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7902 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7903 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7904 _cfgCommon.IsListsIncludeRts = SettingDialog.IsListStatusesIncludeRts;
7905 _cfgCommon.TabMouseLock = SettingDialog.TabMouseLock;
7906 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7907 _cfgCommon.IsUseNotifyGrowl = SettingDialog.IsNotifyUseGrowl;
7913 private void SaveConfigsLocal()
7915 if (_ignoreConfigSave) return;
7918 _modifySettingLocal = false;
7919 _cfgLocal.FormSize = _mySize;
7920 _cfgLocal.FormLocation = _myLoc;
7921 _cfgLocal.SplitterDistance = _mySpDis;
7922 _cfgLocal.PreviewDistance = _mySpDis3;
7923 _cfgLocal.StatusMultiline = StatusText.Multiline;
7924 _cfgLocal.StatusTextHeight = _mySpDis2;
7925 _cfgLocal.StatusText = SettingDialog.Status;
7927 _cfgLocal.FontUnread = _fntUnread;
7928 _cfgLocal.ColorUnread = _clUnread;
7929 _cfgLocal.FontRead = _fntReaded;
7930 _cfgLocal.ColorRead = _clReaded;
7931 _cfgLocal.FontDetail = _fntDetail;
7932 _cfgLocal.ColorDetail = _clDetail;
7933 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7934 _cfgLocal.ColorDetailLink = _clDetailLink;
7935 _cfgLocal.ColorFav = _clFav;
7936 _cfgLocal.ColorOWL = _clOWL;
7937 _cfgLocal.ColorRetweet = _clRetweet;
7938 _cfgLocal.ColorSelf = _clSelf;
7939 _cfgLocal.ColorAtSelf = _clAtSelf;
7940 _cfgLocal.ColorTarget = _clTarget;
7941 _cfgLocal.ColorAtTarget = _clAtTarget;
7942 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7943 _cfgLocal.ColorAtTo = _clAtTo;
7944 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7945 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7946 _cfgLocal.ColorInputFont = _clInputFont;
7947 _cfgLocal.FontInputFont = _fntInputFont;
7949 _cfgLocal.BrowserPath = SettingDialog.BrowserPath;
7950 _cfgLocal.UseRecommendStatus = SettingDialog.UseRecommendStatus;
7951 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7952 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7953 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7954 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7955 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7956 if (_ignoreConfigSave) return;
7961 private void SaveConfigsTabs()
7963 SettingTabs tabSetting = new SettingTabs();
7964 for (int i = 0; i < ListTab.TabPages.Count; i++)
7966 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7971 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7974 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7975 if (ret != DialogResult.OK)
7978 var match = Twitter.StatusUrlRegex.Match(inputText);
7981 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7982 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7986 var statusId = long.Parse(match.Groups["StatusId"].Value);
7988 var post = this._statuses[statusId];
7993 post = await Task.Run(() =>
7995 PostClass newPost = null;
7997 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7998 if (!string.IsNullOrEmpty(err))
7999 throw new WebApiException(err);
8004 catch (WebApiException ex)
8006 var message = ex.Message;
8007 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
8008 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8015 this.OpenRelatedTab(post);
8017 catch (TabException ex)
8019 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8023 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8025 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8026 Properties.Resources.SaveLogMenuItem_ClickText2,
8027 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8028 if (rslt == DialogResult.Cancel) return;
8030 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8031 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8032 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8033 SaveFileDialog1.FilterIndex = 0;
8034 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8035 SaveFileDialog1.RestoreDirectory = true;
8037 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8039 if (!SaveFileDialog1.ValidateNames) return;
8040 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8042 if (rslt == DialogResult.Yes)
8045 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8047 PostClass post = _statuses[_curTab.Text, idx];
8048 string protect = "";
8049 if (post.IsProtect) protect = "Protect";
8050 sw.WriteLine(post.Nickname + "\t" +
8051 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8052 post.CreatedAt.ToString() + "\t" +
8053 post.ScreenName + "\t" +
8054 post.StatusId.ToString() + "\t" +
8055 post.ImageUrl + "\t" +
8056 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8062 foreach (int idx in _curList.SelectedIndices)
8064 PostClass post = _statuses[_curTab.Text, idx];
8065 string protect = "";
8066 if (post.IsProtect) protect = "Protect";
8067 sw.WriteLine(post.Nickname + "\t" +
8068 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8069 post.CreatedAt.ToString() + "\t" +
8070 post.ScreenName + "\t" +
8071 post.StatusId.ToString() + "\t" +
8072 post.ImageUrl + "\t" +
8073 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8079 this.TopMost = SettingDialog.AlwaysTop;
8082 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8084 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
8085 if (State == ModifierState.NotFlags) return;
8086 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
8089 e.IsInputKey = true;
8092 public bool TabRename(ref string tabName)
8095 string newTabText = null;
8096 using (InputTabName inputName = new InputTabName())
8098 inputName.TabName = tabName;
8099 inputName.ShowDialog();
8100 if (inputName.DialogResult == DialogResult.Cancel) return false;
8101 newTabText = inputName.TabName;
8103 this.TopMost = SettingDialog.AlwaysTop;
8104 if (!string.IsNullOrEmpty(newTabText))
8107 for (int i = 0; i < ListTab.TabCount; i++)
8109 if (ListTab.TabPages[i].Text == newTabText)
8111 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8112 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8116 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
8117 for (int i = 0; i < ListTab.TabCount; i++)
8119 if (ListTab.TabPages[i].Text == tabName)
8121 ListTab.TabPages[i].Text = newTabText;
8124 _statuses.RenameTab(tabName, newTabText);
8126 for (int i = 0; i < ListTab.TabCount; i++)
8128 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
8130 if (ListTab.TabPages[i].Text == tabName)
8132 ListTab.TabPages[i].Text = newTabText;
8136 SaveConfigsCommon();
8138 _rclickTabName = newTabText;
8139 tabName = newTabText;
8148 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8150 if (e.Button == MouseButtons.Middle)
8152 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8154 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8156 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8157 this.SaveConfigsTabs();
8164 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8166 string tn = ListTab.SelectedTab.Text;
8170 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8172 if (SettingDialog.TabMouseLock) return;
8173 Point cpos = new Point(e.X, e.Y);
8174 if (e.Button == MouseButtons.Left)
8176 for (int i = 0; i < ListTab.TabPages.Count; i++)
8178 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8181 _tabMouseDownPoint = e.Location;
8192 private void ListTab_DragEnter(object sender, DragEventArgs e)
8194 if (e.Data.GetDataPresent(typeof(TabPage)))
8195 e.Effect = DragDropEffects.Move;
8197 e.Effect = DragDropEffects.None;
8200 private void ListTab_DragDrop(object sender, DragEventArgs e)
8202 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8207 Point cpos = new Point(e.X, e.Y);
8208 Point spos = ListTab.PointToClient(cpos);
8210 for (i = 0; i < ListTab.TabPages.Count; i++)
8212 Rectangle rect = ListTab.GetTabRect(i);
8213 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8214 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8216 tn = ListTab.TabPages[i].Text;
8217 if (spos.X <= (rect.Left + rect.Right) / 2)
8226 //タブのないところにドロップ->最後尾へ移動
8227 if (string.IsNullOrEmpty(tn))
8229 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8231 i = ListTab.TabPages.Count - 1;
8234 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8235 if (tp.Text == tn) return;
8237 ReOrderTab(tp.Text, tn, bef);
8240 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8243 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8245 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8248 using (ControlTransaction.Layout(this.ListTab))
8251 for (int j = 0; j < ListTab.TabPages.Count; j++)
8253 if (ListTab.TabPages[j].Text == targetTabText)
8255 mTp = ListTab.TabPages[j];
8256 ListTab.TabPages.Remove(mTp);
8257 if (j < baseIndex) baseIndex -= 1;
8261 if (isBeforeBaseTab)
8262 ListTab.TabPages.Insert(baseIndex, mTp);
8264 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8270 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8272 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8273 //isReply:true=@,false=DM
8274 if (!StatusText.Enabled) return;
8275 if (_curList == null) return;
8276 if (_curTab == null) return;
8277 if (!this.ExistCurrentPost) return;
8279 // 複数あてリプライはReplyではなく通常ポスト
8280 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8281 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8282 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8284 if (_curList.SelectedIndices.Count > 0)
8287 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8290 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8293 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8294 StatusText.SelectionStart = StatusText.Text.Length;
8296 _reply_to_id = null;
8297 _reply_to_name = null;
8300 if (string.IsNullOrEmpty(StatusText.Text))
8304 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8305 StatusText.Text = "@" + _curPost.ScreenName + " ";
8306 if (_curPost.RetweetedId != null)
8308 _reply_to_id = _curPost.RetweetedId.Value;
8312 _reply_to_id = _curPost.StatusId;
8314 _reply_to_name = _curPost.ScreenName;
8322 //1件選んでEnter or DoubleClick
8323 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8325 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8328 if (_curPost.RetweetedId != null)
8330 _reply_to_id = _curPost.RetweetedId.Value;
8334 _reply_to_id = _curPost.StatusId;
8336 _reply_to_name = _curPost.ScreenName;
8340 if (!StatusText.Text.StartsWith("@"))
8343 if (StatusText.Text.StartsWith(". "))
8346 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8347 _reply_to_id = null;
8348 _reply_to_name = null;
8353 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8354 if (_curPost.RetweetedId != null)
8356 _reply_to_id = _curPost.RetweetedId.Value;
8360 _reply_to_id = _curPost.StatusId;
8362 _reply_to_name = _curPost.ScreenName;
8369 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8370 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8371 _reply_to_id = null;
8372 _reply_to_name = null;
8377 //1件選んでCtrl-Rの場合(返信先操作せず)
8378 int sidx = StatusText.SelectionStart;
8379 string id = "@" + _curPost.ScreenName + " ";
8382 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8387 StatusText.Text = StatusText.Text.Insert(sidx, id);
8389 //if (StatusText.Text.StartsWith("@"))
8392 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8393 // sidx += 5 + _curPost.ScreenName.Length;
8398 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8399 // sidx += 3 + _curPost.ScreenName.Length;
8401 StatusText.SelectionStart = sidx;
8404 //_reply_to_name = null;
8412 if (!isAuto && !isReply) return;
8414 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8418 //Enter or DoubleClick
8420 string sTxt = StatusText.Text;
8421 if (!sTxt.StartsWith(". "))
8424 _reply_to_id = null;
8425 _reply_to_name = null;
8427 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8429 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8430 if (!sTxt.Contains("@" + post.ScreenName + " "))
8432 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8433 //sTxt = "@" + post.ScreenName + " " + sTxt;
8436 StatusText.Text = sTxt;
8441 if (_curList.SelectedIndices.Count > 1)
8446 int sidx = StatusText.SelectionStart;
8447 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8449 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8450 if (!ids.Contains("@" + post.ScreenName + " ") &&
8451 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8453 ids += "@" + post.ScreenName + " ";
8457 foreach (string nm in post.ReplyToList)
8459 if (!ids.Contains("@" + nm + " ") &&
8460 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8462 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8464 ids += "@" + m.Result("${id}") + " ";
8466 ids += "@" + nm + " ";
8471 if (ids.Length == 0) return;
8472 if (!StatusText.Text.StartsWith(". "))
8474 StatusText.Text = ". " + StatusText.Text;
8476 _reply_to_id = null;
8477 _reply_to_name = null;
8481 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8486 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8488 //if (StatusText.Text.StartsWith("@"))
8490 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8491 // sidx += 2 + ids.Length;
8495 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8496 // sidx += 1 + ids.Length;
8498 StatusText.SelectionStart = sidx;
8504 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8507 int sidx = StatusText.SelectionStart;
8508 PostClass post = _curPost;
8509 if (!ids.Contains("@" + post.ScreenName + " ") &&
8510 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8512 ids += "@" + post.ScreenName + " ";
8514 foreach (string nm in post.ReplyToList)
8516 if (!ids.Contains("@" + nm + " ") &&
8517 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8519 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8521 ids += "@" + m.Result("${id}") + " ";
8523 ids += "@" + nm + " ";
8526 if (!string.IsNullOrEmpty(post.RetweetedBy))
8528 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8529 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8531 ids += "@" + post.RetweetedBy + " ";
8534 if (ids.Length == 0) return;
8535 if (string.IsNullOrEmpty(StatusText.Text))
8538 StatusText.Text = ids;
8539 StatusText.SelectionStart = ids.Length;
8541 if (post.RetweetedId != null)
8543 _reply_to_id = post.RetweetedId.Value;
8547 _reply_to_id = post.StatusId;
8549 _reply_to_name = post.ScreenName;
8555 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8560 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8562 StatusText.SelectionStart = sidx;
8568 StatusText.SelectionStart = StatusText.Text.Length;
8573 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8578 private static int iconCnt = 0;
8579 private static int blinkCnt = 0;
8580 private static bool blink = false;
8581 private static bool idle = false;
8583 private void RefreshTasktrayIcon(bool forceRefresh)
8585 if (_colorize) Colorize();
8586 if (!TimerRefreshIcon.Enabled) return;
8587 //Static usCheckCnt As int = 0
8589 //Static iconDlListTopItem As ListViewItem = null
8591 if (forceRefresh) idle = false;
8593 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8594 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8596 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8598 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8604 //if (usCheckCnt > 300) //1min
8607 // if (!this.IsReceivedUserStream)
8609 // TraceOut("ReconnectUserStream");
8610 // tw.ReconnectUserStream();
8615 foreach (BackgroundWorker bw in this._bw)
8617 if (bw != null && bw.IsBusy)
8632 SaveConfigsAll(true);
8637 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8639 _myStatusError = false;
8643 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8644 if (SettingDialog.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8646 if (blinkCnt > 0) return;
8648 if (blink || SettingDialog.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8650 NotifyIcon1.Icon = ReplyIcon;
8654 NotifyIcon1.Icon = ReplyIconBlink;
8662 //優先度:エラー→オフライン→アイドル
8666 NotifyIcon1.Icon = NIconAtRed;
8669 if (_myStatusOnline)
8671 NotifyIcon1.Icon = NIconAt;
8675 NotifyIcon1.Icon = NIconAtSmoke;
8679 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8682 this.RefreshTasktrayIcon(false);
8685 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8687 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8688 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8690 if (ListTab != null && ListTab.SelectedTab != null)
8691 _rclickTabName = ListTab.SelectedTab.Text;
8696 if (_statuses == null) return;
8697 if (_statuses.Tabs == null) return;
8699 TabClass tb = _statuses.Tabs[_rclickTabName];
8700 if (tb == null) return;
8702 NotifyDispMenuItem.Checked = tb.Notify;
8703 this.NotifyTbMenuItem.Checked = tb.Notify;
8705 soundfileListup = true;
8706 SoundFileComboBox.Items.Clear();
8707 this.SoundFileTbComboBox.Items.Clear();
8708 SoundFileComboBox.Items.Add("");
8709 this.SoundFileTbComboBox.Items.Add("");
8710 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8711 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8713 oDir = oDir.GetDirectories("Sounds")[0];
8715 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8717 SoundFileComboBox.Items.Add(oFile.Name);
8718 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8720 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8721 if (idx == -1) idx = 0;
8722 SoundFileComboBox.SelectedIndex = idx;
8723 this.SoundFileTbComboBox.SelectedIndex = idx;
8724 soundfileListup = false;
8725 UreadManageMenuItem.Checked = tb.UnreadManage;
8726 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8728 TabMenuControl(_rclickTabName);
8731 private void TabMenuControl(string tabName)
8733 this.FilterEditMenuItem.Enabled = true;
8734 this.EditRuleTbMenuItem.Enabled = true;
8736 if (_statuses.IsDefaultTab(tabName))
8738 this.ProtectTabMenuItem.Enabled = false;
8739 this.ProtectTbMenuItem.Enabled = false;
8743 this.ProtectTabMenuItem.Enabled = true;
8744 this.ProtectTbMenuItem.Enabled = true;
8747 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8749 this.ProtectTabMenuItem.Checked = true;
8750 this.ProtectTbMenuItem.Checked = true;
8751 this.DeleteTabMenuItem.Enabled = false;
8752 this.DeleteTbMenuItem.Enabled = false;
8756 this.ProtectTabMenuItem.Checked = false;
8757 this.ProtectTbMenuItem.Checked = false;
8758 this.DeleteTabMenuItem.Enabled = true;
8759 this.DeleteTbMenuItem.Enabled = true;
8763 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8765 var checkState = ((ToolStripMenuItem)sender).Checked;
8768 this.ProtectTbMenuItem.Checked = checkState;
8769 this.ProtectTabMenuItem.Checked = checkState;
8772 this.DeleteTabMenuItem.Enabled = !checkState;
8773 this.DeleteTbMenuItem.Enabled = !checkState;
8775 if (string.IsNullOrEmpty(_rclickTabName)) return;
8776 _statuses.Tabs[_rclickTabName].Protected = checkState;
8781 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8783 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8784 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8786 if (string.IsNullOrEmpty(_rclickTabName)) return;
8787 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8792 public void ChangeTabUnreadManage(string tabName, bool isManage)
8795 for (idx = 0; idx < ListTab.TabCount; idx++)
8797 if (ListTab.TabPages[idx].Text == tabName) break;
8800 _statuses.SetTabUnreadManage(tabName, isManage);
8801 if (SettingDialog.TabIconDisp)
8803 if (_statuses.Tabs[tabName].UnreadCount > 0)
8804 ListTab.TabPages[idx].ImageIndex = 0;
8806 ListTab.TabPages[idx].ImageIndex = -1;
8809 if (_curTab.Text == tabName)
8811 this.PurgeListViewItemCache();
8815 SetMainWindowTitle();
8816 SetStatusLabelUrl();
8817 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
8820 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8822 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8823 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8825 if (string.IsNullOrEmpty(_rclickTabName)) return;
8827 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8832 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8834 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8836 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8841 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8843 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8845 RemoveSpecifiedTab(_rclickTabName, true);
8849 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8851 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8852 fltDialog.SetCurrent(_rclickTabName);
8853 fltDialog.ShowDialog(this);
8854 this.TopMost = SettingDialog.AlwaysTop;
8856 this.ApplyPostFilters();
8860 private void AddTabMenuItem_Click(object sender, EventArgs e)
8862 string tabName = null;
8863 MyCommon.TabUsageType tabUsage;
8864 using (InputTabName inputName = new InputTabName())
8866 inputName.TabName = _statuses.GetUniqueTabName();
8867 inputName.IsShowUsage = true;
8868 inputName.ShowDialog();
8869 if (inputName.DialogResult == DialogResult.Cancel) return;
8870 tabName = inputName.TabName;
8871 tabUsage = inputName.Usage;
8873 this.TopMost = SettingDialog.AlwaysTop;
8874 if (!string.IsNullOrEmpty(tabName))
8877 ListElement list = null;
8878 if (tabUsage == MyCommon.TabUsageType.Lists)
8880 using (ListAvailable listAvail = new ListAvailable())
8882 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8883 if (listAvail.SelectedList == null) return;
8884 list = listAvail.SelectedList;
8887 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8889 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8890 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8896 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8898 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8899 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8900 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8902 if (tabUsage == MyCommon.TabUsageType.Lists)
8904 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8905 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8906 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, tabName);
8912 private void TabMenuItem_Click(object sender, EventArgs e)
8915 foreach (int idx in _curList.SelectedIndices)
8919 if (!SelectTab(out tabName)) return;
8921 fltDialog.SetCurrent(tabName);
8922 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8924 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8928 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8930 fltDialog.ShowDialog(this);
8931 this.TopMost = SettingDialog.AlwaysTop;
8934 this.ApplyPostFilters();
8936 if (this.ListTab.SelectedTab != null &&
8937 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8939 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8943 protected override bool ProcessDialogKey(Keys keyData)
8945 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8946 if ((keyData & Keys.KeyCode) == Keys.Enter)
8948 if (StatusText.Focused)
8950 bool _NewLine = false;
8953 if (SettingDialog.PostCtrlEnter) //Ctrl+Enter投稿時
8955 if (StatusText.Multiline)
8957 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8959 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8963 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8967 else if (SettingDialog.PostShiftEnter) //SHift+Enter投稿時
8969 if (StatusText.Multiline)
8971 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8973 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8977 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8983 if (StatusText.Multiline)
8985 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8987 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8988 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8992 if (((keyData & Keys.Shift) == Keys.Shift) ||
8993 (((keyData & Keys.Control) != Keys.Control) &&
8994 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9000 int pos1 = StatusText.SelectionStart;
9001 if (StatusText.SelectionLength > 0)
9003 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9005 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9006 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9011 PostButton_Click(null, null);
9015 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9016 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9017 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9019 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9024 return base.ProcessDialogKey(keyData);
9027 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9029 MakeReplyOrDirectStatus(false, true, true);
9032 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9037 if (_curList.SelectedIndices.Count == 0) return;
9040 if (!SelectTab(out tabName)) return;
9044 MoveOrCopy(ref mv, ref mk);
9046 List<string> ids = new List<string>();
9047 foreach (int idx in _curList.SelectedIndices)
9049 PostClass post = _statuses[_curTab.Text, idx];
9050 if (!ids.Contains(post.ScreenName))
9052 PostFilterRule fc = new PostFilterRule();
9053 ids.Add(post.ScreenName);
9054 if (post.RetweetedId == null)
9056 fc.FilterName = post.ScreenName;
9060 fc.FilterName = post.RetweetedBy;
9062 fc.UseNameField = true;
9063 fc.MoveMatches = mv;
9064 fc.MarkMatches = mk;
9065 fc.UseRegex = false;
9066 fc.FilterByUrl = false;
9067 _statuses.Tabs[tabName].AddFilter(fc);
9072 List<string> atids = new List<string>();
9073 foreach (string id in ids)
9075 atids.Add("@" + id);
9077 int cnt = AtIdSupl.ItemCount;
9078 AtIdSupl.AddRangeItem(atids.ToArray());
9079 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9082 this.ApplyPostFilters();
9086 private bool SelectTab(out string tabName)
9093 using (var dialog = new TabsDialog(_statuses))
9095 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9097 var selectedTab = dialog.SelectedTab;
9098 tabName = selectedTab == null ? null : selectedTab.TabName;
9101 ListTab.SelectedTab.Focus();
9103 if (tabName == null)
9105 using (InputTabName inputName = new InputTabName())
9107 inputName.TabName = _statuses.GetUniqueTabName();
9108 inputName.ShowDialog();
9109 if (inputName.DialogResult == DialogResult.Cancel) return false;
9110 tabName = inputName.TabName;
9112 this.TopMost = SettingDialog.AlwaysTop;
9113 if (!string.IsNullOrEmpty(tabName))
9115 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9117 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9118 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9136 private void MoveOrCopy(ref bool move, ref bool mark)
9140 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9141 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9149 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9150 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9156 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9161 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9166 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9168 if (StatusText.Focused)
9171 StatusText.SelectAll();
9175 // ListView上でのCtrl+A
9176 for (int i = 0; i < _curList.VirtualListSize; i++)
9178 _curList.SelectedIndices.Add(i);
9183 private void MoveMiddle()
9189 if (_curList.SelectedIndices.Count == 0) return;
9191 int idx = _curList.SelectedIndices[0];
9193 _item = _curList.GetItemAt(0, 25);
9199 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9201 idx2 = _curList.VirtualListSize - 1;
9205 idx -= Math.Abs(idx1 - idx2) / 2;
9206 if (idx < 0) idx = 0;
9208 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9209 _curList.EnsureVisible(idx);
9212 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9214 if (PostBrowser.Document.Links.Count > 0)
9216 UrlDialog.ClearUrl();
9218 string openUrlStr = "";
9220 if (PostBrowser.Document.Links.Count == 1)
9225 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9227 catch (ArgumentException)
9236 if (string.IsNullOrEmpty(urlStr)) return;
9237 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9241 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9244 string linkText = "";
9248 urlStr = linkElm.GetAttribute("title");
9249 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9250 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9251 linkText = linkElm.InnerText;
9252 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9254 linkText = "@" + linkText;
9257 catch (ArgumentException)
9266 if (string.IsNullOrEmpty(urlStr)) continue;
9267 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9271 if (UrlDialog.ShowDialog() == DialogResult.OK)
9273 openUrlStr = UrlDialog.SelectedUrl;
9280 this.TopMost = SettingDialog.AlwaysTop;
9282 if (string.IsNullOrEmpty(openUrlStr)) return;
9284 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9285 openUrlStr.StartsWith("https://twitter.com/search?q="))
9288 string urlStr = Uri.UnescapeDataString(openUrlStr);
9289 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9290 HashSupl.AddItem(hash);
9291 HashMgr.AddHashToHistory(hash.Trim(), false);
9292 AddNewTabForSearch(hash);
9297 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9298 if (SettingDialog.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9299 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9301 OpenUriAsync(openUrlStr);
9307 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9309 if (string.IsNullOrEmpty(_rclickTabName)) return;
9310 ClearTab(_rclickTabName, true);
9313 private void ClearTab(string tabName, bool showWarning)
9317 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9318 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9324 _statuses.ClearTabIds(tabName);
9325 if (ListTab.SelectedTab.Text == tabName)
9328 _anchorFlag = false;
9329 this.PurgeListViewItemCache();
9333 foreach (TabPage tb in ListTab.TabPages)
9335 if (tb.Text == tabName)
9338 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9342 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
9344 SetMainWindowTitle();
9345 SetStatusLabelUrl();
9348 private static long followers = 0;
9350 private void SetMainWindowTitle()
9353 StringBuilder ttl = new StringBuilder(256);
9356 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
9357 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9358 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9359 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9361 foreach (var tab in _statuses.Tabs.Values)
9363 ur += tab.UnreadCount;
9368 if (SettingDialog.DispUsername) ttl.Append(tw.Username).Append(" - ");
9369 ttl.Append(Application.ProductName);
9371 switch (SettingDialog.DispLatestPost)
9373 case MyCommon.DispTitleEnum.Ver:
9374 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9376 case MyCommon.DispTitleEnum.Post:
9377 if (_history != null && _history.Count > 1)
9378 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9380 case MyCommon.DispTitleEnum.UnreadRepCount:
9381 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9383 case MyCommon.DispTitleEnum.UnreadAllCount:
9384 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9386 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9387 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9389 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9390 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9392 case MyCommon.DispTitleEnum.OwnStatus:
9393 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9394 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9400 this.Text = ttl.ToString();
9402 catch (AccessViolationException)
9404 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9408 private string GetStatusLabelText()
9411 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9412 if (_statuses == null) return "";
9413 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9414 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9415 if (tbRep == null || tbDm == null) return "";
9416 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9421 StringBuilder slbl = new StringBuilder(256);
9424 foreach (var tab in _statuses.Tabs.Values)
9426 ur += tab.UnreadCount;
9428 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9430 tur = tab.UnreadCount;
9441 UnreadAtCounter = urat;
9443 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9444 if (SettingDialog.TimelinePeriodInt == 0)
9446 slbl.Append(Properties.Resources.SetStatusLabelText2);
9450 slbl.Append(SettingDialog.TimelinePeriodInt.ToString() + Properties.Resources.SetStatusLabelText3);
9452 return slbl.ToString();
9455 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9459 if (this.InvokeRequired && !this.IsDisposed)
9461 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9465 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9466 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9468 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9472 catch (ObjectDisposedException)
9476 catch (InvalidOperationException)
9482 private void SetStatusLabelUrl()
9484 StatusLabelUrl.Text = GetStatusLabelText();
9487 public void SetStatusLabel(string text)
9489 StatusLabel.Text = text;
9492 private static StringBuilder ur = new StringBuilder(64);
9494 private void SetNotifyIconText()
9496 // タスクトレイアイコンのツールチップテキスト書き換え
9498 ur.Remove(0, ur.Length);
9499 if (SettingDialog.DispUsername)
9501 ur.Append(tw.Username);
9504 ur.Append(Application.ProductName);
9506 ur.Append("(Debug Build)");
9508 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9511 ur.Append(UnreadCounter);
9513 ur.Append(UnreadAtCounter);
9516 NotifyIcon1.Text = ur.ToString();
9519 internal void CheckReplyTo(string StatusText)
9523 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9525 foreach (Match hm in m)
9527 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9529 hstr += "#" + hm.Result("$3") + " ";
9530 HashSupl.AddItem("#" + hm.Result("$3"));
9533 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9535 hstr += HashMgr.UseHash;
9537 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9539 // 本当にリプライ先指定すべきかどうかの判定
9540 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9542 if (SettingDialog.UseAtIdSupplement)
9544 int bCnt = AtIdSupl.ItemCount;
9545 foreach (Match mid in m)
9547 AtIdSupl.AddItem(mid.Result("${id}"));
9549 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9552 // リプライ先ステータスIDの指定がない場合は指定しない
9553 if (_reply_to_id == null) return;
9555 // リプライ先ユーザー名がない場合も指定しない
9556 if (string.IsNullOrEmpty(_reply_to_name))
9558 _reply_to_id = null;
9563 // 次の条件を満たす場合に in_reply_to_status_id 指定
9564 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9565 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9566 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9570 if (StatusText.StartsWith("@"))
9572 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9576 foreach (Match mid in m)
9578 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9583 _reply_to_id = null;
9584 _reply_to_name = null;
9588 private void TweenMain_Resize(object sender, EventArgs e)
9590 if (!_initialLayout && SettingDialog.MinimizeToTray && WindowState == FormWindowState.Minimized)
9592 this.Visible = false;
9594 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9596 this.ClientSize = _cfgLocal.FormSize;
9597 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9598 this.DesktopLocation = _cfgLocal.FormLocation;
9599 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9600 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9601 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9603 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9606 StatusText.Multiline = _cfgLocal.StatusMultiline;
9607 if (StatusText.Multiline)
9609 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9610 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9612 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9614 StatusText.Height = _cfgLocal.StatusTextHeight;
9618 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9620 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9623 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9625 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9627 _initialLayout = false;
9629 if (this.WindowState != FormWindowState.Minimized)
9631 _formWindowState = this.WindowState;
9635 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9637 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9638 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9639 if (PlaySoundMenuItem.Checked)
9641 SettingDialog.PlaySound = true;
9645 SettingDialog.PlaySound = false;
9647 _modifySettingCommon = true;
9650 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9652 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9654 _mySpDis = SplitContainer1.SplitterDistance;
9655 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9656 _modifySettingLocal = true;
9660 private void doRepliedStatusOpen()
9662 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9664 if (MyCommon.IsKeyDown(Keys.Shift))
9666 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9669 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9671 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9672 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9676 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9678 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9679 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9680 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9683 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9688 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9690 doRepliedStatusOpen();
9694 /// UserPicture.Image に設定されている画像を破棄します。
9696 private void ClearUserPicture()
9698 if (this.UserPicture.Image != null)
9700 var oldImage = this.UserPicture.Image;
9701 this.UserPicture.Image = null;
9706 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9708 //発言詳細のアイコン右クリック時のメニュー制御
9709 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9711 string name = _curPost.ImageUrl;
9712 if (name != null && name.Length > 0)
9714 int idx = name.LastIndexOf('/');
9717 name = Path.GetFileName(name.Substring(idx));
9718 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9720 name = name.Replace("_normal", "");
9721 this.IconNameToolStripMenuItem.Text = name;
9722 this.IconNameToolStripMenuItem.Enabled = true;
9726 this.IconNameToolStripMenuItem.Enabled = false;
9727 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9732 this.IconNameToolStripMenuItem.Enabled = false;
9733 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9736 this.ReloadIconToolStripMenuItem.Enabled = true;
9738 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9740 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9744 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9749 this.IconNameToolStripMenuItem.Enabled = false;
9750 this.ReloadIconToolStripMenuItem.Enabled = false;
9751 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9752 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9757 this.IconNameToolStripMenuItem.Enabled = false;
9758 this.ReloadIconToolStripMenuItem.Enabled = false;
9759 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9760 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9762 if (NameLabel.Tag != null)
9764 string id = (string)NameLabel.Tag;
9765 if (id == tw.Username)
9767 FollowToolStripMenuItem.Enabled = false;
9768 UnFollowToolStripMenuItem.Enabled = false;
9769 ShowFriendShipToolStripMenuItem.Enabled = false;
9770 ShowUserStatusToolStripMenuItem.Enabled = true;
9771 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9772 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9773 ListManageUserContextToolStripMenuItem3.Enabled = true;
9777 FollowToolStripMenuItem.Enabled = true;
9778 UnFollowToolStripMenuItem.Enabled = true;
9779 ShowFriendShipToolStripMenuItem.Enabled = true;
9780 ShowUserStatusToolStripMenuItem.Enabled = true;
9781 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9782 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9783 ListManageUserContextToolStripMenuItem3.Enabled = true;
9788 FollowToolStripMenuItem.Enabled = false;
9789 UnFollowToolStripMenuItem.Enabled = false;
9790 ShowFriendShipToolStripMenuItem.Enabled = false;
9791 ShowUserStatusToolStripMenuItem.Enabled = false;
9792 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9793 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9794 ListManageUserContextToolStripMenuItem3.Enabled = false;
9798 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9800 if (_curPost == null) return;
9801 string name = _curPost.ImageUrl;
9802 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9805 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9807 if (this._curPost == null) return;
9809 await this.UserPicture.SetImageFromTask(async () =>
9811 var imageUrl = this._curPost.ImageUrl;
9813 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9814 .ConfigureAwait(false);
9816 return await image.CloneAsync()
9817 .ConfigureAwait(false);
9821 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9823 if (_curPost == null) return;
9824 string name = _curPost.ImageUrl;
9825 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9827 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9829 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9835 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9837 if (_curPost == null) return;
9838 string name = _curPost.ImageUrl;
9840 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9842 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9846 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9848 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9850 using (Graphics g = Graphics.FromImage(bmp2))
9852 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9853 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9855 bmp2.Save(this.SaveFileDialog1.FileName);
9861 //処理中にキャッシュアウトする可能性あり
9866 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9868 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9869 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9870 _modifySettingLocal = true;
9873 private void StatusText_MultilineChanged(object sender, EventArgs e)
9875 if (this.StatusText.Multiline)
9876 this.StatusText.ScrollBars = ScrollBars.Vertical;
9878 this.StatusText.ScrollBars = ScrollBars.None;
9880 _modifySettingLocal = true;
9883 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9886 StatusText.Multiline = MultiLineMenuItem.Checked;
9887 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9888 if (MultiLineMenuItem.Checked)
9890 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9891 SplitContainer2.SplitterDistance = 0;
9893 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9897 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9899 _modifySettingLocal = true;
9902 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9904 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9905 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9907 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9908 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9909 //Appendix A. Collected ABNF for URI
9910 //http://www.ietf.org/rfc/rfc3986.txt
9914 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9916 if (StatusText.SelectionLength > 0)
9918 string tmp = StatusText.SelectedText;
9919 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9920 if (tmp.StartsWith("http"))
9922 // 文字列が選択されている場合はその文字列について処理
9924 //nico.ms使用、nicovideoにマッチしたら変換
9925 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9927 result = nicoms.Shorten(tmp);
9929 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9931 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9934 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9935 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9936 result = resultUri.ToString();
9938 catch (WebApiException e)
9940 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9943 catch (UriFormatException e)
9945 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9954 if (!string.IsNullOrEmpty(result))
9956 urlUndo undotmp = new urlUndo();
9958 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9959 StatusText.SelectedText = result;
9962 undotmp.Before = tmp;
9963 undotmp.After = result;
9965 if (urlUndoBuffer == null)
9967 urlUndoBuffer = new List<urlUndo>();
9968 UrlUndoToolStripMenuItem.Enabled = true;
9971 urlUndoBuffer.Add(undotmp);
9977 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9978 @"(?<url>(?<protocol>https?://)" +
9979 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9980 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9981 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9982 // 正規表現にマッチしたURL文字列をtinyurl化
9983 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9985 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9986 string tmp = mt.Result("${url}");
9987 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9988 urlUndo undotmp = new urlUndo();
9991 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9993 //nico.ms使用、nicovideoにマッチしたら変換
9994 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9996 result = nicoms.Shorten(tmp);
9998 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10000 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10003 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10004 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10005 result = resultUri.ToString();
10007 catch (WebApiException e)
10009 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10012 catch (UriFormatException e)
10014 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10023 if (!string.IsNullOrEmpty(result))
10025 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10026 StatusText.SelectedText = result;
10028 undotmp.Before = mt.Result("${url}");
10029 undotmp.After = result;
10031 if (urlUndoBuffer == null)
10033 urlUndoBuffer = new List<urlUndo>();
10034 UrlUndoToolStripMenuItem.Enabled = true;
10037 urlUndoBuffer.Add(undotmp);
10045 private void doUrlUndo()
10047 if (urlUndoBuffer != null)
10049 string tmp = StatusText.Text;
10050 foreach (urlUndo data in urlUndoBuffer)
10052 tmp = tmp.Replace(data.After, data.Before);
10054 StatusText.Text = tmp;
10055 urlUndoBuffer = null;
10056 UrlUndoToolStripMenuItem.Enabled = false;
10057 StatusText.SelectionStart = 0;
10058 StatusText.SelectionLength = 0;
10062 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10064 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10067 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10069 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10072 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10074 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10077 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10079 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10082 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10084 if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
10086 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
10087 Random rnd = new Random();
10088 // 前回使用した短縮URLサービス以外を選択する
10091 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10093 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10094 await UrlConvertAsync(svc);
10098 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10103 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10105 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10106 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10107 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10108 _modifySettingCommon = true;
10111 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10113 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10114 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10115 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10116 _modifySettingCommon = true;
10119 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10121 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10122 MenuStrip1.Tag = new Object();
10123 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10126 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10128 if (this.Tag != null) // 設定された戻り先へ遷移
10130 if (this.Tag == this.ListTab.SelectedTab)
10131 ((Control)this.ListTab.SelectedTab.Tag).Select();
10133 ((Control)this.Tag).Select();
10135 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10137 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10139 this.Tag = ListTab.SelectedTab.Tag;
10140 ((Control)this.Tag).Select();
10143 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10144 MenuStrip1.Tag = null;
10147 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10149 DetailsListView lst = (DetailsListView)sender;
10150 if (_cfgLocal == null) return;
10154 _cfgLocal.Width1 = lst.Columns[0].Width;
10155 _cfgLocal.Width3 = lst.Columns[1].Width;
10159 int[] darr = new int[lst.Columns.Count];
10160 for (int i = 0; i < lst.Columns.Count; i++)
10162 darr[lst.Columns[i].DisplayIndex] = i;
10164 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10166 for (int i = 0; i < lst.Columns.Count; i++)
10171 _cfgLocal.DisplayIndex1 = i;
10174 _cfgLocal.DisplayIndex2 = i;
10177 _cfgLocal.DisplayIndex3 = i;
10180 _cfgLocal.DisplayIndex4 = i;
10183 _cfgLocal.DisplayIndex5 = i;
10186 _cfgLocal.DisplayIndex6 = i;
10189 _cfgLocal.DisplayIndex7 = i;
10192 _cfgLocal.DisplayIndex8 = i;
10196 _cfgLocal.Width1 = lst.Columns[0].Width;
10197 _cfgLocal.Width2 = lst.Columns[1].Width;
10198 _cfgLocal.Width3 = lst.Columns[2].Width;
10199 _cfgLocal.Width4 = lst.Columns[3].Width;
10200 _cfgLocal.Width5 = lst.Columns[4].Width;
10201 _cfgLocal.Width6 = lst.Columns[5].Width;
10202 _cfgLocal.Width7 = lst.Columns[6].Width;
10203 _cfgLocal.Width8 = lst.Columns[7].Width;
10205 _modifySettingLocal = true;
10206 _isColumnChanged = true;
10209 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10211 DetailsListView lst = (DetailsListView)sender;
10212 if (_cfgLocal == null) return;
10215 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10217 _cfgLocal.Width1 = lst.Columns[0].Width;
10218 _modifySettingLocal = true;
10219 _isColumnChanged = true;
10221 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10223 _cfgLocal.Width3 = lst.Columns[1].Width;
10224 _modifySettingLocal = true;
10225 _isColumnChanged = true;
10230 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10232 _cfgLocal.Width1 = lst.Columns[0].Width;
10233 _modifySettingLocal = true;
10234 _isColumnChanged = true;
10236 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10238 _cfgLocal.Width2 = lst.Columns[1].Width;
10239 _modifySettingLocal = true;
10240 _isColumnChanged = true;
10242 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10244 _cfgLocal.Width3 = lst.Columns[2].Width;
10245 _modifySettingLocal = true;
10246 _isColumnChanged = true;
10248 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10250 _cfgLocal.Width4 = lst.Columns[3].Width;
10251 _modifySettingLocal = true;
10252 _isColumnChanged = true;
10254 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10256 _cfgLocal.Width5 = lst.Columns[4].Width;
10257 _modifySettingLocal = true;
10258 _isColumnChanged = true;
10260 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10262 _cfgLocal.Width6 = lst.Columns[5].Width;
10263 _modifySettingLocal = true;
10264 _isColumnChanged = true;
10266 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10268 _cfgLocal.Width7 = lst.Columns[6].Width;
10269 _modifySettingLocal = true;
10270 _isColumnChanged = true;
10272 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10274 _cfgLocal.Width8 = lst.Columns[7].Width;
10275 _modifySettingLocal = true;
10276 _isColumnChanged = true;
10279 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10282 // SaveConfigsLocal();
10286 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10288 //発言詳細で「選択文字列をコピー」を行う
10289 //WebBrowserコンポーネントのインスタンスを渡す
10290 Type typ = ComponentInstance.ActiveXInstance.GetType();
10291 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10292 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10293 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10296 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10299 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10302 Clipboard.SetDataObject(_selText, false, 5, 100);
10304 catch (Exception ex)
10306 MessageBox.Show(ex.Message);
10310 private void doSearchToolStrip(string url)
10312 //発言詳細で「選択文字列で検索」(選択文字列取得)
10313 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10315 if (_selText != null)
10317 if (url == Properties.Resources.SearchItem4Url)
10320 AddNewTabForSearch(_selText);
10324 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10329 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10332 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10335 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10337 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10340 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10342 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10345 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10347 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10350 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10354 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10355 foreach (Match m in mc)
10357 if (m.Groups["url"].Value == this._postBrowserStatusText)
10359 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10365 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10367 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10369 catch (Exception ex)
10371 MessageBox.Show(ex.Message);
10375 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10377 // URLコピーの項目の表示/非表示
10378 if (PostBrowser.StatusText.StartsWith("http"))
10380 this._postBrowserStatusText = PostBrowser.StatusText;
10381 string name = GetUserId();
10382 UrlCopyContextMenuItem.Enabled = true;
10385 FollowContextMenuItem.Enabled = true;
10386 RemoveContextMenuItem.Enabled = true;
10387 FriendshipContextMenuItem.Enabled = true;
10388 ShowUserStatusContextMenuItem.Enabled = true;
10389 SearchPostsDetailToolStripMenuItem.Enabled = true;
10390 IdFilterAddMenuItem.Enabled = true;
10391 ListManageUserContextToolStripMenuItem.Enabled = true;
10392 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10396 FollowContextMenuItem.Enabled = false;
10397 RemoveContextMenuItem.Enabled = false;
10398 FriendshipContextMenuItem.Enabled = false;
10399 ShowUserStatusContextMenuItem.Enabled = false;
10400 SearchPostsDetailToolStripMenuItem.Enabled = false;
10401 IdFilterAddMenuItem.Enabled = false;
10402 ListManageUserContextToolStripMenuItem.Enabled = false;
10403 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10406 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10407 UseHashtagMenuItem.Enabled = true;
10409 UseHashtagMenuItem.Enabled = false;
10413 this._postBrowserStatusText = "";
10414 UrlCopyContextMenuItem.Enabled = false;
10415 FollowContextMenuItem.Enabled = false;
10416 RemoveContextMenuItem.Enabled = false;
10417 FriendshipContextMenuItem.Enabled = false;
10418 ShowUserStatusContextMenuItem.Enabled = false;
10419 SearchPostsDetailToolStripMenuItem.Enabled = false;
10420 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10421 UseHashtagMenuItem.Enabled = false;
10422 IdFilterAddMenuItem.Enabled = false;
10423 ListManageUserContextToolStripMenuItem.Enabled = false;
10425 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10426 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10427 if (_selText == null)
10429 SelectionSearchContextMenuItem.Enabled = false;
10430 SelectionCopyContextMenuItem.Enabled = false;
10431 SelectionTranslationToolStripMenuItem.Enabled = false;
10435 SelectionSearchContextMenuItem.Enabled = true;
10436 SelectionCopyContextMenuItem.Enabled = true;
10437 SelectionTranslationToolStripMenuItem.Enabled = true;
10439 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10440 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10441 bool fAllFlag = false;
10442 foreach (Match mu in ma)
10444 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10450 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10452 if (_curPost == null)
10453 TranslationToolStripMenuItem.Enabled = false;
10455 TranslationToolStripMenuItem.Enabled = true;
10460 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10462 //発言詳細の選択文字列で現在のタブを検索
10463 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10465 if (_selText != null)
10467 var searchOptions = new SearchWordDialog.SearchOptions(
10468 SearchWordDialog.SearchType.Timeline,
10471 caseSensitive: false,
10474 this.SearchDialog.ResultOptions = searchOptions;
10477 searchOptions.Query,
10478 searchOptions.CaseSensitive,
10479 searchOptions.UseRegex,
10480 SEARCHTYPE.NextSearch);
10484 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10486 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10487 _modifySettingLocal = true;
10490 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10492 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10494 SelectMedia_DragDrop(e);
10496 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10498 var url = GetUrlFromDataObject(e.Data);
10501 if (url.Item2 == null)
10502 appendText = url.Item1;
10504 appendText = url.Item2 + " " + url.Item1;
10506 if (this.StatusText.TextLength == 0)
10507 this.StatusText.Text = appendText;
10509 this.StatusText.Text += " " + appendText;
10511 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10513 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10514 if (data != null) StatusText.Text += data;
10519 /// IDataObject から URL とタイトルの対を取得します
10522 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10524 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10525 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10526 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10528 if (data.GetDataPresent("text/x-moz-url"))
10530 // Firefox, Google Chrome で利用可能
10531 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10533 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10535 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10536 if (lines.Length < 2)
10537 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10539 return new Tuple<string, string>(lines[0], lines[1]);
10542 else if (data.GetDataPresent("IESiteModeToUrl"))
10544 // Internet Exproler 用
10545 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10547 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10549 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10550 if (lines.Length < 2)
10551 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10553 return new Tuple<string, string>(lines[0], lines[1]);
10556 else if (data.GetDataPresent("UniformResourceLocatorW"))
10560 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10562 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10563 return new Tuple<string, string>(url, null);
10567 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10570 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10572 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10574 SelectMedia_DragEnter(e);
10578 private void TweenMain_DragOver(object sender, DragEventArgs e)
10580 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10582 SelectMedia_DragOver(e);
10584 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10586 e.Effect = DragDropEffects.Copy;
10588 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10590 e.Effect = DragDropEffects.Copy;
10594 e.Effect = DragDropEffects.None;
10598 public bool IsNetworkAvailable()
10601 nw = MyCommon.IsNetworkAvailable();
10602 _myStatusOnline = nw;
10606 public Task OpenUriAsync(string UriString)
10608 return Task.Run(() =>
10610 string myPath = UriString;
10614 var configBrowserPath = SettingDialog.BrowserPath;
10615 if (!string.IsNullOrEmpty(configBrowserPath))
10617 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10619 int sep = configBrowserPath.IndexOf("\"", 2);
10620 string browserPath = configBrowserPath.Substring(1, sep - 1);
10622 if (sep < configBrowserPath.Length - 1)
10624 arg = configBrowserPath.Substring(sep + 1);
10626 myPath = arg + " " + myPath;
10627 System.Diagnostics.Process.Start(browserPath, myPath);
10631 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10636 System.Diagnostics.Process.Start(myPath);
10641 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10646 private void ListTabSelect(TabPage _tab)
10650 this.PurgeListViewItemCache();
10653 _curList = (DetailsListView)_tab.Tag;
10654 if (_curList.SelectedIndices.Count > 0)
10656 _curItemIndex = _curList.SelectedIndices[0];
10657 _curPost = GetCurTabPost(_curItemIndex);
10661 _curItemIndex = -1;
10665 _anchorPost = null;
10666 _anchorFlag = false;
10670 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10674 for (int i = 0; i < _curList.Columns.Count; i++)
10676 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10681 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10683 ListTabSelect(e.TabPage);
10686 private void SelectListItem(DetailsListView LView, int Index)
10689 Rectangle bnd = new Rectangle();
10691 var item = LView.FocusedItem;
10700 LView.SelectedIndices.Clear();
10702 while (LView.SelectedIndices.Count > 0);
10703 item = LView.Items[Index];
10704 item.Selected = true;
10705 item.Focused = true;
10707 if (flg) LView.Invalidate(bnd);
10710 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10713 Rectangle bnd = new Rectangle();
10715 var item = LView.FocusedItem;
10723 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10727 LView.SelectedIndices.Clear();
10729 while (LView.SelectedIndices.Count > 0);
10730 foreach (int idx in Index)
10732 if (idx > -1 && LView.VirtualListSize > idx)
10734 LView.SelectedIndices.Add(idx);
10735 if (fIdx == -1) fIdx = idx;
10739 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10741 LView.SelectionMark = FocusedIndex[1];
10743 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10745 LView.Items[FocusedIndex[0]].Focused = true;
10747 else if (fIdx > -1)
10749 LView.Items[fIdx].Focused = true;
10752 if (flg) LView.Invalidate(bnd);
10755 private void RunAsync(GetWorkerArg args)
10757 BackgroundWorker bw = null;
10758 if (args.type != MyCommon.WORKERTYPE.Follower)
10760 for (int i = 0; i < _bw.Length; i++)
10762 if (_bw[i] != null && !_bw[i].IsBusy)
10770 for (int i = 0; i < _bw.Length; i++)
10772 if (_bw[i] == null)
10774 _bw[i] = new BackgroundWorker();
10776 bw.WorkerReportsProgress = true;
10777 bw.WorkerSupportsCancellation = true;
10778 bw.DoWork += GetTimelineWorker_DoWork;
10779 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10780 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10788 if (_bwFollower == null)
10790 _bwFollower = new BackgroundWorker();
10792 bw.WorkerReportsProgress = true;
10793 bw.WorkerSupportsCancellation = true;
10794 bw.DoWork += GetTimelineWorker_DoWork;
10795 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10796 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10800 if (_bwFollower.IsBusy == false)
10804 if (bw == null) return;
10806 bw.RunWorkerAsync(args);
10809 private void StartUserStream()
10811 tw.NewPostFromStream += tw_NewPostFromStream;
10812 tw.UserStreamStarted += tw_UserStreamStarted;
10813 tw.UserStreamStopped += tw_UserStreamStopped;
10814 tw.PostDeleted += tw_PostDeleted;
10815 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10817 MenuItemUserStream.Text = "&UserStream ■";
10818 MenuItemUserStream.Enabled = true;
10819 StopToolStripMenuItem.Text = "&Start";
10820 StopToolStripMenuItem.Enabled = true;
10821 if (SettingDialog.UserstreamStartup) tw.StartUserStream();
10824 private async void TweenMain_Shown(object sender, EventArgs e)
10828 PostBrowser.Url = new Uri("about:blank");
10829 PostBrowser.DocumentText = ""; //発言詳細部初期化
10835 NotifyIcon1.Visible = true;
10837 if (this.IsNetworkAvailable())
10839 this.RefreshMuteUserIdsAsync();
10840 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, 0, "");
10841 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10842 if (SettingDialog.StartupFollowers)
10844 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10846 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10848 _waitTimeline = true;
10849 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, 1, "");
10851 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, 1, "");
10853 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, 1, "");
10854 if (SettingDialog.GetFav)
10857 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, 1, "");
10859 _waitPubSearch = true;
10860 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, ""); //tabname="":全タブ
10861 _waitUserTimeline = true;
10862 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, 0, ""); //tabname="":全タブ
10864 GetTimeline(MyCommon.WORKERTYPE.List, 1, 0, ""); //tabname="":全タブ
10867 while (this.IsInitialRead())
10869 await Task.Delay(5000);
10872 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10874 if (MyCommon._endingFlag)
10878 if (MyCommon._endingFlag) return;
10880 if (ApplicationSettings.VersionInfoUrl != null)
10882 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10883 if (SettingDialog.StartupVersion)
10884 await this.CheckNewVersion(true);
10888 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10889 this.VerUpMenuItem.Enabled = false;
10890 this.VerUpMenuItem.Available = false;
10891 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10895 if (!tw.GetFollowersSuccess && SettingDialog.StartupFollowers)
10896 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, 0, "");
10899 if (!tw.GetNoRetweetSuccess)
10900 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, 0, "");
10903 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10904 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, 0, "");
10906 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10907 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10909 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10910 SettingStripMenuItem_Click(null, null);
10917 TimerTimeline.Enabled = true;
10920 private bool IsInitialRead()
10922 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10925 private void doGetFollowersMenu()
10927 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, 0, "");
10928 DispSelectedPost(true);
10931 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10933 doGetFollowersMenu();
10936 private void doReTweetUnofficial()
10939 if (this.ExistCurrentPost)
10941 if (_curPost.IsDm ||
10942 !StatusText.Enabled) return;
10944 if (_curPost.IsProtect)
10946 MessageBox.Show("Protected.");
10949 string rtdata = _curPost.Text;
10950 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10952 this._reply_to_id = null;
10953 this._reply_to_name = null;
10955 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10957 StatusText.SelectionStart = 0;
10958 StatusText.Focus();
10962 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10964 doReTweetUnofficial();
10967 private void doReTweetOfficial(bool isConfirm)
10970 if (this.ExistCurrentPost)
10972 if (_curPost.IsProtect)
10974 MessageBox.Show("Protected.");
10975 _DoFavRetweetFlags = false;
10978 if (_curList.SelectedIndices.Count > 15)
10980 MessageBox.Show(Properties.Resources.RetweetLimitText);
10981 _DoFavRetweetFlags = false;
10984 else if (_curList.SelectedIndices.Count > 1)
10986 string QuestionText = Properties.Resources.RetweetQuestion2;
10987 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10988 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10990 case DialogResult.Cancel:
10991 case DialogResult.No:
10992 _DoFavRetweetFlags = false;
10998 if (_curPost.IsDm || _curPost.IsMe)
11000 _DoFavRetweetFlags = false;
11003 if (!SettingDialog.RetweetNoConfirm)
11005 string Questiontext = Properties.Resources.RetweetQuestion1;
11006 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11007 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11009 _DoFavRetweetFlags = false;
11014 GetWorkerArg args = new GetWorkerArg();
11015 args.ids = new List<long>();
11016 args.sIds = new List<long>();
11017 args.tName = _curTab.Text;
11018 args.type = MyCommon.WORKERTYPE.Retweet;
11019 foreach (int idx in _curList.SelectedIndices)
11021 PostClass post = GetCurTabPost(idx);
11022 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
11028 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
11030 doReTweetOfficial(true);
11033 private void FavoritesRetweetOriginal()
11035 if (!this.ExistCurrentPost) return;
11036 _DoFavRetweetFlags = true;
11037 doReTweetOfficial(true);
11038 if (_DoFavRetweetFlags)
11040 _DoFavRetweetFlags = false;
11041 FavoriteChange(true, false);
11045 private void FavoritesRetweetUnofficial()
11047 if (this.ExistCurrentPost && !_curPost.IsDm)
11049 _DoFavRetweetFlags = true;
11050 FavoriteChange(true);
11051 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11053 _DoFavRetweetFlags = false;
11054 doReTweetUnofficial();
11060 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11062 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11063 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11064 /// <returns>復元されたツイート本文</returns>
11065 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11067 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11070 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11072 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11074 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11078 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11080 statusHtml = statusHtml.Replace("<br>", " ");
11082 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11083 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11084 statusHtml = statusHtml.Replace(" ", " ");
11086 return WebUtility.HtmlDecode(statusHtml);
11089 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11091 if (_curPost != null)
11092 DispSelectedPost(true);
11095 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11097 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11098 DebugModeToolStripMenuItem.Visible = true;
11100 DebugModeToolStripMenuItem.Visible = false;
11103 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11105 SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11108 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11110 ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
11113 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11115 if (TraceOutToolStripMenuItem.Checked)
11116 MyCommon.TraceFlag = true;
11118 MyCommon.TraceFlag = false;
11121 private void TweenMain_Deactivate(object sender, EventArgs e)
11123 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11124 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11127 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11129 if (string.IsNullOrEmpty(_rclickTabName)) return;
11130 TabRename(ref _rclickTabName);
11133 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11135 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11138 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11140 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11144 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11146 e.Result = tw.GetInfoApi();
11149 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11151 StringBuilder tmp = new StringBuilder();
11153 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11157 var result = (TwitterApiStatus)dlg.Result;
11159 if (result == null)
11161 var accessLevel = result.AccessLevel;
11162 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11163 var mediaLimit = result.MediaUploadLimit;
11165 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11166 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11167 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11168 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11171 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11172 SetStatusLabelUrl();
11175 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11176 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11177 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11181 tmp.Append(Properties.Resources.ApiInfo5);
11185 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11188 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11191 if (_curPost != null) id = _curPost.ScreenName;
11195 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11197 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11198 e.Result = arg.tw.PostFollowCommand(arg.id);
11201 private void FollowCommand(string id)
11203 using (InputTabName inputName = new InputTabName())
11205 inputName.FormTitle = "Follow";
11206 inputName.FormDescription = Properties.Resources.FRMessage1;
11207 inputName.TabName = id;
11208 if (inputName.ShowDialog() == DialogResult.OK &&
11209 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11211 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11213 arg.id = inputName.TabName.Trim();
11214 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11215 FollowCommand_DoWork,
11219 _info.ShowDialog();
11220 string ret = (string)_info.Result;
11221 if (!string.IsNullOrEmpty(ret))
11222 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11224 MessageBox.Show(Properties.Resources.FRMessage3);
11230 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11233 if (_curPost != null) id = _curPost.ScreenName;
11234 RemoveCommand(id, false);
11237 private class FollowRemoveCommandArgs
11243 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11245 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11246 e.Result = arg.tw.PostRemoveCommand(arg.id);
11249 private void RemoveCommand(string id, bool skipInput)
11251 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11256 using (InputTabName inputName = new InputTabName())
11258 inputName.FormTitle = "Unfollow";
11259 inputName.FormDescription = Properties.Resources.FRMessage1;
11260 inputName.TabName = id;
11261 if (inputName.ShowDialog() == DialogResult.OK &&
11262 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11265 arg.id = inputName.TabName.Trim();
11274 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11275 RemoveCommand_DoWork,
11279 _info.ShowDialog();
11280 string ret = (string)_info.Result;
11281 if (!string.IsNullOrEmpty(ret))
11282 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11284 MessageBox.Show(Properties.Resources.FRMessage3);
11288 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11291 if (_curPost != null)
11292 id = _curPost.ScreenName;
11294 ShowFriendship(id);
11297 private class ShowFriendshipArgs
11300 public class FriendshipInfo
11302 public string id = "";
11303 public bool isFollowing = false;
11304 public bool isFollowed = false;
11305 public bool isError = false;
11306 public FriendshipInfo(string id)
11311 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11314 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11316 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11317 string result = "";
11318 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11320 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11321 if (!string.IsNullOrEmpty(rt))
11323 if (string.IsNullOrEmpty(result)) result = rt;
11324 fInfo.isError = true;
11330 private void ShowFriendship(string id)
11332 ShowFriendshipArgs args = new ShowFriendshipArgs();
11334 using (InputTabName inputName = new InputTabName())
11336 inputName.FormTitle = "Show Friendships";
11337 inputName.FormDescription = Properties.Resources.FRMessage1;
11338 inputName.TabName = id;
11339 if (inputName.ShowDialog() == DialogResult.OK &&
11340 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11343 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11344 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11345 ShowFriendship_DoWork,
11349 _info.ShowDialog();
11350 ret = (string)_info.Result;
11352 string result = "";
11353 if (string.IsNullOrEmpty(ret))
11355 if (args.ids[0].isFollowing)
11357 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11361 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11363 if (args.ids[0].isFollowed)
11365 result += Properties.Resources.GetFriendshipInfo3;
11369 result += Properties.Resources.GetFriendshipInfo4;
11371 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11377 MessageBox.Show(result);
11382 private void ShowFriendship(string[] ids)
11384 foreach (string id in ids)
11387 ShowFriendshipArgs args = new ShowFriendshipArgs();
11389 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11390 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11391 ShowFriendship_DoWork,
11395 _info.ShowDialog();
11396 ret = (string)_info.Result;
11398 string result = "";
11399 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11401 if (string.IsNullOrEmpty(ret))
11404 if (fInfo.isFollowing)
11406 ff += Properties.Resources.GetFriendshipInfo1;
11410 ff += Properties.Resources.GetFriendshipInfo2;
11413 ff += System.Environment.NewLine + " ";
11414 if (fInfo.isFollowed)
11416 ff += Properties.Resources.GetFriendshipInfo3;
11420 ff += Properties.Resources.GetFriendshipInfo4;
11422 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11423 if (fInfo.isFollowing)
11425 if (MessageBox.Show(
11426 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11427 MessageBoxButtons.YesNo,
11428 MessageBoxIcon.Question,
11429 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11431 RemoveCommand(fInfo.id, true);
11436 MessageBox.Show(result);
11441 MessageBox.Show(ret);
11446 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11448 doShowUserStatus(tw.Username, false);
11449 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11451 // doShowUserStatus(tw.Username, false);
11455 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11460 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11461 // URLから切り出した文字列を渡す
11463 public bool IsTwitterId(string name)
11465 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11466 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11468 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11471 private string GetUserId()
11473 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11474 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11475 return m.Result("${ScreenName}");
11480 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11482 string name = GetUserId();
11483 if (name != null) FollowCommand(name);
11486 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11488 string name = GetUserId();
11489 if (name != null) RemoveCommand(name, false);
11492 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11494 string name = GetUserId();
11495 if (name != null) ShowFriendship(name);
11498 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11500 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11501 List<string> ids = new List<string>();
11502 foreach (Match mu in ma)
11504 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11506 ids.Add(mu.Result("${ScreenName}"));
11509 ShowFriendship(ids.ToArray());
11512 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11514 string name = GetUserId();
11515 if (name != null) ShowUserStatus(name);
11518 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11520 string name = GetUserId();
11521 if (name != null) AddNewTabForUserTimeline(name);
11524 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11526 string name = GetUserId();
11527 if (name != null) AddNewTabForSearch("@" + name);
11530 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11532 _modifySettingCommon = true;
11535 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11537 _modifySettingCommon = true;
11540 private void doQuote()
11544 if (this.ExistCurrentPost)
11546 if (_curPost.IsDm ||
11547 !StatusText.Enabled) return;
11549 if (_curPost.IsProtect)
11551 MessageBox.Show("Protected.");
11554 string rtdata = _curPost.Text;
11555 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11557 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11558 if (_curPost.RetweetedId == null)
11560 _reply_to_id = _curPost.StatusId;
11564 _reply_to_id = _curPost.RetweetedId.Value;
11566 _reply_to_name = _curPost.ScreenName;
11568 StatusText.SelectionStart = 0;
11569 StatusText.Focus();
11573 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11578 private void SearchButton_Click(object sender, EventArgs e)
11581 Control pnl = ((Control)sender).Parent;
11582 if (pnl == null) return;
11583 string tbName = pnl.Parent.Text;
11584 TabClass tb = _statuses.Tabs[tbName];
11585 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11586 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11587 ComboBox cmbusline = (ComboBox)pnl.Controls["comboUserline"];
11588 cmb.Text = cmb.Text.Trim();
11589 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11590 bool Quote = false;
11591 StringBuilder buf = new StringBuilder();
11592 char[] c = cmb.Text.ToCharArray();
11593 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11595 if (cnt > cmb.Text.Length - 4)
11597 buf.Append(cmb.Text.Substring(cnt));
11606 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11608 buf.Append(" OR ");
11613 buf.Append(c[cnt]);
11615 cmb.Text = buf.ToString();
11617 tb.SearchWords = cmb.Text;
11618 tb.SearchLang = cmbLang.Text;
11619 if (string.IsNullOrEmpty(cmb.Text))
11621 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11625 if (tb.IsQueryChanged())
11627 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11628 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11629 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11630 cmb.Text = tb.SearchWords;
11632 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11633 this.PurgeListViewItemCache();
11634 lst.VirtualListSize = 0;
11635 _statuses.ClearTabIds(tbName);
11636 SaveConfigsTabs(); //検索条件の保存
11639 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, 0, tbName);
11640 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11643 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11649 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11651 if (_statuses.RemovedTab.Count == 0)
11653 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11658 TabClass tb = _statuses.RemovedTab.Pop();
11659 if (tb.TabType == MyCommon.TabUsageType.Related)
11661 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11662 if (relatedTab != null)
11664 // 関連発言なら既存のタブを置き換える
11665 tb.TabName = relatedTab.TabName;
11666 this.ClearTab(tb.TabName, false);
11667 _statuses.Tabs[tb.TabName] = tb;
11668 for (int i = 0; i < ListTab.TabPages.Count; i++)
11670 if (tb.TabName == ListTab.TabPages[i].Text)
11672 ListTab.SelectedIndex = i;
11673 ListTabSelect(ListTab.TabPages[i]);
11680 const string TabName = "Related Tweets";
11681 string renamed = TabName;
11682 for (int i = 2; i <= 100; i++)
11684 if (!_statuses.ContainsTab(renamed)) break;
11685 renamed = TabName + i.ToString();
11687 tb.TabName = renamed;
11688 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11689 _statuses.Tabs.Add(renamed, tb); // 後に
11690 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11691 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11696 string renamed = tb.TabName;
11697 for (int i = 1; i < int.MaxValue; i++)
11699 if (!_statuses.ContainsTab(renamed)) break;
11700 renamed = tb.TabName + "(" + i.ToString() + ")";
11702 tb.TabName = renamed;
11703 _statuses.Tabs.Add(renamed, tb); // 先に
11704 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11705 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11706 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11712 private void doMoveToRTHome()
11714 if (_curList.SelectedIndices.Count > 0)
11716 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11717 if (post.RetweetedId != null)
11719 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11724 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11729 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11731 string name = GetUserId();
11737 if (_curList.SelectedIndices.Count == 0) return;
11740 if (!SelectTab(out tabName)) return;
11744 MoveOrCopy(ref mv, ref mk);
11746 PostFilterRule fc = new PostFilterRule();
11747 fc.FilterName = name;
11748 fc.UseNameField = true;
11749 fc.MoveMatches = mv;
11750 fc.MarkMatches = mk;
11751 fc.UseRegex = false;
11752 fc.FilterByUrl = false;
11753 _statuses.Tabs[tabName].AddFilter(fc);
11755 this.ApplyPostFilters();
11760 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11764 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11766 if (menuItem.Owner == this.ContextMenuPostBrowser)
11768 user = GetUserId();
11769 if (user == null) return;
11771 else if (this._curPost != null)
11773 user = this._curPost.ScreenName;
11780 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11782 string res = this.tw.GetListsApi();
11784 if (!string.IsNullOrEmpty(res))
11786 MessageBox.Show("Failed to get lists. (" + res + ")");
11791 using (MyLists listSelectForm = new MyLists(user, this.tw))
11793 listSelectForm.ShowDialog(this);
11797 private void SearchControls_Enter(object sender, EventArgs e)
11799 Control pnl = (Control)sender;
11800 foreach (Control ctl in pnl.Controls)
11802 ctl.TabStop = true;
11806 private void SearchControls_Leave(object sender, EventArgs e)
11808 Control pnl = (Control)sender;
11809 foreach (Control ctl in pnl.Controls)
11811 ctl.TabStop = false;
11815 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11817 if (ListTab.SelectedTab != null)
11819 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11820 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11824 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11826 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11829 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
11830 HashStripSplitButton.Text = HashMgr.UseHash;
11831 HashToggleMenuItem.Checked = true;
11832 HashToggleToolStripMenuItem.Checked = true;
11834 _modifySettingCommon = true;
11838 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11840 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11843 private void HashManageMenuItem_Click(object sender, EventArgs e)
11845 DialogResult rslt = DialogResult.Cancel;
11848 rslt = HashMgr.ShowDialog();
11854 this.TopMost = SettingDialog.AlwaysTop;
11855 if (rslt == DialogResult.Cancel) return;
11856 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11858 HashStripSplitButton.Text = HashMgr.UseHash;
11859 HashToggleMenuItem.Checked = true;
11860 HashToggleToolStripMenuItem.Checked = true;
11864 HashStripSplitButton.Text = "#[-]";
11865 HashToggleMenuItem.Checked = false;
11866 HashToggleToolStripMenuItem.Checked = false;
11868 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11870 // int sidx = StatusText.SelectionStart;
11871 // string hash = HashMgr.UseHash + " ";
11874 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11875 // hash = " " + hash;
11877 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11878 // sidx += hash.Length;
11879 // StatusText.SelectionStart = sidx;
11880 // StatusText.Focus();
11882 _modifySettingCommon = true;
11883 this.StatusText_TextChanged(null, null);
11886 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11888 HashMgr.ToggleHash();
11889 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11891 HashStripSplitButton.Text = HashMgr.UseHash;
11892 HashToggleMenuItem.Checked = true;
11893 HashToggleToolStripMenuItem.Checked = true;
11897 HashStripSplitButton.Text = "#[-]";
11898 HashToggleMenuItem.Checked = false;
11899 HashToggleToolStripMenuItem.Checked = false;
11901 _modifySettingCommon = true;
11902 this.StatusText_TextChanged(null, null);
11905 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11907 HashToggleMenuItem_Click(null, null);
11910 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11912 if (ListTab.SelectedTab == null) return;
11913 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11914 if (!this.ExistCurrentPost)
11916 this.ReplyOpMenuItem.Enabled = false;
11917 this.ReplyAllOpMenuItem.Enabled = false;
11918 this.DmOpMenuItem.Enabled = false;
11919 this.ShowProfMenuItem.Enabled = false;
11920 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11921 this.ListManageMenuItem.Enabled = false;
11922 this.OpenFavOpMenuItem.Enabled = false;
11923 this.CreateTabRuleOpMenuItem.Enabled = false;
11924 this.CreateIdRuleOpMenuItem.Enabled = false;
11925 this.ReadOpMenuItem.Enabled = false;
11926 this.UnreadOpMenuItem.Enabled = false;
11930 this.ReplyOpMenuItem.Enabled = true;
11931 this.ReplyAllOpMenuItem.Enabled = true;
11932 this.DmOpMenuItem.Enabled = true;
11933 this.ShowProfMenuItem.Enabled = true;
11934 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11935 this.ListManageMenuItem.Enabled = true;
11936 this.OpenFavOpMenuItem.Enabled = true;
11937 this.CreateTabRuleOpMenuItem.Enabled = true;
11938 this.CreateIdRuleOpMenuItem.Enabled = true;
11939 this.ReadOpMenuItem.Enabled = true;
11940 this.UnreadOpMenuItem.Enabled = true;
11943 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11945 this.FavOpMenuItem.Enabled = false;
11946 this.UnFavOpMenuItem.Enabled = false;
11947 this.OpenStatusOpMenuItem.Enabled = false;
11948 this.OpenFavotterOpMenuItem.Enabled = false;
11949 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11950 this.RtOpMenuItem.Enabled = false;
11951 this.RtUnOpMenuItem.Enabled = false;
11952 this.QtOpMenuItem.Enabled = false;
11953 this.FavoriteRetweetMenuItem.Enabled = false;
11954 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11955 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11959 this.FavOpMenuItem.Enabled = true;
11960 this.UnFavOpMenuItem.Enabled = true;
11961 this.OpenStatusOpMenuItem.Enabled = true;
11962 this.OpenFavotterOpMenuItem.Enabled = true;
11963 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11967 this.RtOpMenuItem.Enabled = false;
11968 this.FavoriteRetweetMenuItem.Enabled = false;
11969 this.DelOpMenuItem.Enabled = true;
11973 this.DelOpMenuItem.Enabled = false;
11974 if (_curPost.IsProtect)
11976 this.RtOpMenuItem.Enabled = false;
11977 this.RtUnOpMenuItem.Enabled = false;
11978 this.QtOpMenuItem.Enabled = false;
11979 this.FavoriteRetweetMenuItem.Enabled = false;
11980 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11984 this.RtOpMenuItem.Enabled = true;
11985 this.RtUnOpMenuItem.Enabled = true;
11986 this.QtOpMenuItem.Enabled = true;
11987 this.FavoriteRetweetMenuItem.Enabled = true;
11988 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11993 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11995 this.RefreshPrevOpMenuItem.Enabled = true;
11999 this.RefreshPrevOpMenuItem.Enabled = false;
12001 if (!this.ExistCurrentPost
12002 || _curPost.InReplyToStatusId == null)
12004 OpenRepSourceOpMenuItem.Enabled = false;
12008 OpenRepSourceOpMenuItem.Enabled = true;
12010 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12012 OpenRterHomeMenuItem.Enabled = false;
12016 OpenRterHomeMenuItem.Enabled = true;
12020 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12022 ContextMenuTabProperty_Opening(sender, null);
12025 public Twitter TwitterInstance
12030 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12032 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
12034 _mySpDis3 = SplitContainer3.SplitterDistance;
12035 _modifySettingLocal = true;
12039 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12041 if (_statuses.RemovedTab.Count == 0)
12043 UndoRemoveTabMenuItem.Enabled = false;
12047 UndoRemoveTabMenuItem.Enabled = true;
12049 if (ListTab.SelectedTab != null)
12051 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12052 PublicSearchQueryMenuItem.Enabled = true;
12054 PublicSearchQueryMenuItem.Enabled = false;
12058 PublicSearchQueryMenuItem.Enabled = false;
12060 if (!this.ExistCurrentPost)
12062 this.CopySTOTMenuItem.Enabled = false;
12063 this.CopyURLMenuItem.Enabled = false;
12064 this.CopyUserIdStripMenuItem.Enabled = false;
12068 this.CopySTOTMenuItem.Enabled = true;
12069 this.CopyURLMenuItem.Enabled = true;
12070 this.CopyUserIdStripMenuItem.Enabled = true;
12071 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12072 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12076 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12078 SetNotifyIconText();
12081 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12084 if (_curPost != null)
12086 id = _curPost.ScreenName;
12088 ShowUserStatus(id);
12091 private class GetUserInfoArgs
12095 public TwitterUser user;
12098 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
12100 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
12101 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
12104 private void doShowUserStatus(string id, bool ShowInputDialog)
12106 TwitterUser user = null;
12107 GetUserInfoArgs args = new GetUserInfoArgs();
12108 if (ShowInputDialog)
12110 using (InputTabName inputName = new InputTabName())
12112 inputName.FormTitle = "Show UserStatus";
12113 inputName.FormDescription = Properties.Resources.FRMessage1;
12114 inputName.TabName = id;
12115 if (inputName.ShowDialog() == DialogResult.OK &&
12116 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12118 id = inputName.TabName.Trim();
12122 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12123 GetUserInfo_DoWork,
12127 _info.ShowDialog();
12128 string ret = (string)_info.Result;
12129 if (string.IsNullOrEmpty(ret))
12130 doShowUserStatus(args.user);
12132 MessageBox.Show(ret);
12142 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12143 GetUserInfo_DoWork,
12147 _info.ShowDialog();
12148 string ret = (string)_info.Result;
12149 if (string.IsNullOrEmpty(ret))
12151 doShowUserStatus(args.user);
12155 MessageBox.Show(ret);
12161 private async void doShowUserStatus(TwitterUser user)
12163 using (var userDialog = new UserInfoDialog(this, this.tw))
12165 var showUserTask = userDialog.ShowUserAsync(user);
12166 userDialog.ShowDialog(this);
12169 this.BringToFront();
12171 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12172 await showUserTask;
12176 private void ShowUserStatus(string id, bool ShowInputDialog)
12178 doShowUserStatus(id, ShowInputDialog);
12181 private void ShowUserStatus(string id)
12183 doShowUserStatus(id, true);
12186 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12188 if (NameLabel.Tag != null)
12190 string id = (string)NameLabel.Tag;
12191 if (id != tw.Username)
12198 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12200 if (NameLabel.Tag != null)
12202 string id = (string)NameLabel.Tag;
12203 if (id != tw.Username)
12205 RemoveCommand(id, false);
12210 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12212 if (NameLabel.Tag != null)
12214 string id = (string)NameLabel.Tag;
12215 if (id != tw.Username)
12217 ShowFriendship(id);
12222 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12224 if (NameLabel.Tag != null)
12226 string id = (string)NameLabel.Tag;
12227 ShowUserStatus(id, false);
12231 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12233 if (NameLabel.Tag != null)
12235 string id = (string)NameLabel.Tag;
12236 AddNewTabForUserTimeline(id);
12240 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12242 if (NameLabel.Tag != null)
12244 string id = (string)NameLabel.Tag;
12245 AddNewTabForSearch("@" + id);
12249 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12251 if (_curPost != null)
12253 ShowUserStatus(_curPost.ScreenName, false);
12257 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12262 if (_curPost.RetweetedId != null)
12264 statusid = _curPost.RetweetedId.Value;
12268 statusid = _curPost.StatusId;
12270 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12272 e.Result = counter;
12275 private void RtCountMenuItem_Click(object sender, EventArgs e)
12277 if (this.ExistCurrentPost)
12279 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12280 GetRetweet_DoWork))
12282 int retweet_count = 0;
12285 _info.ShowDialog();
12286 retweet_count = (int)_info.Result;
12287 if (retweet_count < 0)
12289 MessageBox.Show(Properties.Resources.RtCountText2);
12293 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12299 private HookGlobalHotkey _hookGlobalHotkey;
12302 this.http = MyCommon.CreateHttpClient();
12303 _hookGlobalHotkey = new HookGlobalHotkey(this);
12305 // この呼び出しは、Windows フォーム デザイナで必要です。
12306 InitializeComponent();
12308 // InitializeComponent() 呼び出しの後で初期化を追加します。
12310 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12311 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12312 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12313 this.gh.NotifyClicked += GrowlHelper_Callback;
12315 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12316 this.ListTab.HandleCreated += (s, e) => Win32Api.SetMinTabWidth((TabControl)s, 40);
12318 this._apiGauge = new ToolStripAPIGauge();
12319 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12320 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12322 this.ImageSelector.Visible = false;
12323 this.ImageSelector.Enabled = false;
12324 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12326 this.ReplaceAppName();
12329 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12331 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12334 this.Visible = false;
12336 else if (Form.ActiveForm == null)
12338 this.Visible = true;
12339 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12341 this.BringToFront();
12342 this.StatusText.Focus();
12346 private void UserPicture_MouseEnter(object sender, EventArgs e)
12348 this.UserPicture.Cursor = Cursors.Hand;
12351 private void UserPicture_MouseLeave(object sender, EventArgs e)
12353 this.UserPicture.Cursor = Cursors.Default;
12356 private void UserPicture_DoubleClick(object sender, EventArgs e)
12358 if (NameLabel.Tag != null)
12360 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12364 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12366 this.MultiLineMenuItem.PerformClick();
12369 public PostClass CurPost
12371 get { return _curPost; }
12374 public bool IsPreviewEnable
12376 get { return SettingDialog.PreviewEnable; }
12380 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12382 if (ImageSelector.Visible)
12383 ImageSelector.EndSelection();
12385 ImageSelector.BeginSelection();
12388 private void SelectMedia_DragEnter(DragEventArgs e)
12390 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0]))
12392 e.Effect = DragDropEffects.Copy;
12395 e.Effect = DragDropEffects.None;
12398 private void SelectMedia_DragOver(DragEventArgs e)
12403 private void SelectMedia_DragDrop(DragEventArgs e)
12406 this.BringToFront();
12407 ImageSelector.BeginSelection(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0]);
12408 StatusText.Focus();
12411 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12413 TimelinePanel.Visible = false;
12414 TimelinePanel.Enabled = false;
12417 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12419 TimelinePanel.Visible = true;
12420 TimelinePanel.Enabled = true;
12421 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12424 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12426 this.AllowDrop = false;
12429 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12431 this.AllowDrop = true;
12434 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12436 if (ImageSelector.Visible)
12438 _modifySettingCommon = true;
12439 SaveConfigsAll(true);
12441 if (ImageSelector.ServiceName.Equals("Twitter"))
12442 this.StatusText_TextChanged(null, null);
12446 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12448 this.StatusText_TextChanged(null, null);
12452 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12454 using (ListManage form = new ListManage(tw))
12456 form.ShowDialog(this);
12460 public bool ModifySettingCommon
12462 set { _modifySettingCommon = value; }
12465 public bool ModifySettingLocal
12467 set { _modifySettingLocal = value; }
12470 public bool ModifySettingAtId
12472 set { _modifySettingAtId = value; }
12475 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12477 string link = (string)SourceLinkLabel.Tag;
12478 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12480 OpenUriAsync(link);
12484 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12486 string link = (string)SourceLinkLabel.Tag;
12487 if (!string.IsNullOrEmpty(link))
12489 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12493 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12495 SetStatusLabelUrl();
12498 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12500 if (this.ExistCurrentPost && !_curPost.IsDm)
12501 RtCountMenuItem.Enabled = true;
12503 RtCountMenuItem.Enabled = false;
12505 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12506 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12508 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12511 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12516 private void CopyUserId()
12518 if (_curPost == null) return;
12519 string clstr = _curPost.ScreenName;
12522 Clipboard.SetDataObject(clstr, false, 5, 100);
12524 catch (Exception ex)
12526 MessageBox.Show(ex.Message);
12530 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12532 if (this.ExistCurrentPost && !_curPost.IsDm)
12536 this.OpenRelatedTab(this._curPost);
12538 catch (TabException ex)
12540 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12546 /// 指定されたツイートに対する関連発言タブを開きます
12548 /// <param name="post">表示する対象となるツイート</param>
12549 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12550 private void OpenRelatedTab(PostClass post)
12552 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12555 if (tabRelated == null)
12557 tabName = this._statuses.MakeTabName("Related Tweets");
12559 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12560 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12562 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12563 tabRelated.UnreadManage = false;
12564 tabRelated.Notify = false;
12568 tabName = tabRelated.TabName;
12571 tabRelated.RelationTargetPost = post;
12572 this.ClearTab(tabName, false);
12574 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12576 var tabPage = this.ListTab.TabPages[i];
12577 if (tabName == tabPage.Text)
12579 this.ListTab.SelectedIndex = i;
12580 this.ListTabSelect(tabPage);
12585 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, 1, tabName);
12588 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12590 StringBuilder buf = new StringBuilder();
12591 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12592 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12593 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12594 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12595 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12598 private void tw_UserIdChanged()
12600 this._modifySettingCommon = true;
12603 #region "Userstream"
12604 private bool _isActiveUserstream = false;
12606 private void tw_PostDeleted(long id)
12610 if (InvokeRequired && !IsDisposed)
12612 Invoke((Action) (() =>
12614 _statuses.RemovePostReserve(id);
12615 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(id))
12617 this.PurgeListViewItemCache();
12618 ((DetailsListView)_curTab.Tag).Update();
12619 if (_curPost != null && _curPost.StatusId == id) DispSelectedPost(true);
12625 catch (ObjectDisposedException)
12629 catch (InvalidOperationException)
12635 private void tw_NewPostFromStream()
12637 if (SettingDialog.ReadOldPosts)
12639 _statuses.SetRead(); //新着時未読クリア
12642 int rsltAddCount = _statuses.DistributePosts();
12645 DateTime tm = DateTime.Now;
12646 if (_tlTimestamps.ContainsKey(tm))
12648 _tlTimestamps[tm] += rsltAddCount;
12652 _tlTimestamps.Add(tm, rsltAddCount);
12654 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12655 List<DateTime> keys = new List<DateTime>();
12657 foreach (DateTime key in _tlTimestamps.Keys)
12659 if (key.CompareTo(oneHour) < 0)
12662 _tlCount += _tlTimestamps[key];
12664 foreach (DateTime key in keys)
12666 _tlTimestamps.Remove(key);
12670 //Static DateTime before = Now;
12671 //if (before.Subtract(Now).Seconds > -5) return;
12675 if (SettingDialog.UserstreamPeriodInt > 0) return;
12679 if (InvokeRequired && !IsDisposed)
12681 Invoke(new Action<bool>(RefreshTimeline), true);
12685 catch (ObjectDisposedException)
12689 catch (InvalidOperationException)
12695 private void tw_UserStreamStarted()
12697 this._isActiveUserstream = true;
12700 if (InvokeRequired && !IsDisposed)
12702 Invoke(new MethodInvoker(tw_UserStreamStarted));
12706 catch (ObjectDisposedException)
12710 catch (InvalidOperationException)
12715 MenuItemUserStream.Text = "&UserStream ▶";
12716 MenuItemUserStream.Enabled = true;
12717 StopToolStripMenuItem.Text = "&Stop";
12718 StopToolStripMenuItem.Enabled = true;
12720 StatusLabel.Text = "UserStream Started.";
12723 private void tw_UserStreamStopped()
12725 this._isActiveUserstream = false;
12728 if (InvokeRequired && !IsDisposed)
12730 Invoke(new MethodInvoker(tw_UserStreamStopped));
12734 catch (ObjectDisposedException)
12738 catch (InvalidOperationException)
12743 MenuItemUserStream.Text = "&UserStream ■";
12744 MenuItemUserStream.Enabled = true;
12745 StopToolStripMenuItem.Text = "&Start";
12746 StopToolStripMenuItem.Enabled = true;
12748 StatusLabel.Text = "UserStream Stopped.";
12751 private void tw_UserStreamEventArrived(Twitter.FormattedEvent ev)
12755 if (InvokeRequired && !IsDisposed)
12757 Invoke(new Action<Twitter.FormattedEvent>(tw_UserStreamEventArrived), ev);
12761 catch (ObjectDisposedException)
12765 catch (InvalidOperationException)
12769 StatusLabel.Text = "Event: " + ev.Event;
12770 //if (ev.Event == "favorite")
12772 // NotifyFavorite(ev);
12775 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12777 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12779 this.PurgeListViewItemCache();
12780 ((DetailsListView)_curTab.Tag).Update();
12782 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12784 RemovePostFromFavTab(new long[] {ev.Id});
12789 private void NotifyEvent(Twitter.FormattedEvent ev)
12792 if (BalloonRequired(ev))
12794 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12795 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12796 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12797 StringBuilder title = new StringBuilder();
12798 if (SettingDialog.DispUsername)
12800 title.Append(tw.Username);
12801 title.Append(" - ");
12807 title.Append(Application.ProductName);
12808 title.Append(" [");
12809 title.Append(ev.Event.ToUpper());
12810 title.Append("] by ");
12811 if (!string.IsNullOrEmpty(ev.Username))
12813 title.Append(ev.Username.ToString());
12817 //title.Append("");
12820 if (!string.IsNullOrEmpty(ev.Target))
12822 //NotifyIcon1.BalloonTipText = ev.Target;
12827 //NotifyIcon1.BalloonTipText = " ";
12830 //NotifyIcon1.ShowBalloonTip(500);
12831 if (SettingDialog.IsNotifyUseGrowl)
12833 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
12834 ev.Id.ToString(), title.ToString(), text);
12838 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12839 NotifyIcon1.BalloonTipTitle = title.ToString();
12840 NotifyIcon1.BalloonTipText = text;
12841 NotifyIcon1.ShowBalloonTip(500);
12846 string snd = SettingDialog.EventSoundFile;
12847 if (!_initial && SettingDialog.PlaySound && !string.IsNullOrEmpty(snd))
12849 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
12853 string dir = Application.StartupPath;
12854 if (Directory.Exists(Path.Combine(dir, "Sounds")))
12856 dir = Path.Combine(dir, "Sounds");
12858 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
12870 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
12872 MenuItemUserStream.Enabled = false;
12873 if (StopRefreshAllMenuItem.Checked)
12875 StopRefreshAllMenuItem.Checked = false;
12878 if (this._isActiveUserstream)
12880 tw.StopUserStream();
12884 tw.StartUserStream();
12888 private static string inputTrack = "";
12890 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
12892 if (TrackToolStripMenuItem.Checked)
12894 using (InputTabName inputForm = new InputTabName())
12896 inputForm.TabName = inputTrack;
12897 inputForm.FormTitle = "Input track word";
12898 inputForm.FormDescription = "Track word";
12899 if (inputForm.ShowDialog() != DialogResult.OK)
12901 TrackToolStripMenuItem.Checked = false;
12904 inputTrack = inputForm.TabName.Trim();
12906 if (!inputTrack.Equals(tw.TrackWord))
12908 tw.TrackWord = inputTrack;
12909 this._modifySettingCommon = true;
12910 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
12911 tw.ReconnectUserStream();
12917 tw.ReconnectUserStream();
12919 this._modifySettingCommon = true;
12922 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
12924 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
12925 this._modifySettingCommon = true;
12926 tw.ReconnectUserStream();
12929 private void EventViewerMenuItem_Click(object sender, EventArgs e)
12931 if (evtDialog == null || evtDialog.IsDisposed)
12934 evtDialog = new EventViewerDialog();
12935 evtDialog.Owner = this;
12937 Point pos = evtDialog.Location;
12938 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
12939 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
12940 evtDialog.Location = pos;
12942 evtDialog.EventSource = tw.StoredEvent;
12943 if (!evtDialog.Visible)
12945 evtDialog.Show(this);
12949 evtDialog.Activate();
12951 this.TopMost = this.SettingDialog.AlwaysTop;
12955 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12957 MyCommon._endingFlag = true;
12961 Application.Restart();
12965 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12969 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12971 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12974 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12976 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
12979 private async Task doTranslation(string str)
12981 if (string.IsNullOrEmpty(str))
12984 var bing = new Bing(this.http);
12987 var translatedText = await bing.TranslateAsync(str,
12989 langTo: this.SettingDialog.TranslateLanguage);
12991 this.PostBrowser.DocumentText = translatedText;
12993 catch (HttpRequestException e)
12995 this.StatusLabel.Text = "Err:" + e.Message;
12999 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13001 if (!this.ExistCurrentPost)
13004 await this.doTranslation(this._curPost.TextFromApi);
13007 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13009 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
13010 await this.doTranslation(text);
13013 private bool ExistCurrentPost
13017 if (_curPost == null) return false;
13018 if (_curPost.IsDeleted) return false;
13023 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13025 ShowUserTimeline();
13028 public bool FavEventChangeUnread
13030 get { return SettingDialog.FavEventUnread; }
13033 private string GetUserIdFromCurPostOrInput(string caption)
13036 if (_curPost != null)
13038 id = _curPost.ScreenName;
13040 using (InputTabName inputName = new InputTabName())
13042 inputName.FormTitle = caption;
13043 inputName.FormDescription = Properties.Resources.FRMessage1;
13044 inputName.TabName = id;
13045 if (inputName.ShowDialog() == DialogResult.OK &&
13046 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13048 id = inputName.TabName.Trim();
13058 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13060 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13061 if (!string.IsNullOrEmpty(id))
13063 AddNewTabForUserTimeline(id);
13067 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13069 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13070 if (!string.IsNullOrEmpty(id))
13072 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13076 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13078 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13081 private void TimelineRefreshEnableChange(bool isEnable)
13085 tw.StartUserStream();
13089 tw.StopUserStream();
13091 TimerTimeline.Enabled = isEnable;
13094 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13096 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13099 private void OpenUserAppointUrl()
13101 if (SettingDialog.UserAppointUrl != null)
13103 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
13105 if (_curPost != null)
13107 string xUrl = SettingDialog.UserAppointUrl;
13108 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13109 if (_curPost.RetweetedId != null)
13111 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
13115 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
13117 OpenUriAsync(xUrl);
13122 OpenUriAsync(SettingDialog.UserAppointUrl);
13127 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13129 OpenUserAppointUrl();
13132 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13134 string selText = SourceLinkLabel.Text;
13137 Clipboard.SetDataObject(selText, false, 5, 100);
13139 catch (Exception ex)
13141 MessageBox.Show(ex.Message);
13145 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13147 string selText = (string)SourceLinkLabel.Tag;
13150 Clipboard.SetDataObject(selText, false, 5, 100);
13152 catch (Exception ex)
13154 MessageBox.Show(ex.Message);
13158 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13160 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13162 SourceCopyMenuItem.Enabled = false;
13163 SourceUrlCopyMenuItem.Enabled = false;
13167 SourceCopyMenuItem.Enabled = true;
13168 SourceUrlCopyMenuItem.Enabled = true;
13172 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13174 if (Form.ActiveForm == null)
13176 this.BeginInvoke((Action) (() =>
13178 this.Visible = true;
13179 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13181 this.BringToFront();
13182 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13184 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13188 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13194 private void ReplaceAppName()
13196 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13197 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13200 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13202 this.SplitContainer3.Panel2Collapsed = false;
13204 // PreviewDistance が起動のたびに広がっていく問題の回避策
13205 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13206 // None で開いた後に設定するようにする
13207 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13208 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13211 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13213 this.OpenThumbnailPicture(e.Thumbnail);
13216 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13218 this.OpenUriAsync(e.ImageUrl);
13221 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13223 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13226 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13228 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13231 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13233 if (e.KeyCode == Keys.Space)
13235 this.JumpUnreadMenuItem_Click(null, null);
13237 e.SuppressKeyPress = true;
13241 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13243 this.IconSizeNoneToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.IconNone;
13244 this.IconSize16ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon16;
13245 this.IconSize24ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon24;
13246 this.IconSize48ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48;
13247 this.IconSize48_2ToolStripMenuItem.Checked = SettingDialog.IconSz == MyCommon.IconSizes.Icon48_2;
13249 this.LockListSortOrderToolStripMenuItem.Checked = SettingDialog.SortOrderLock;
13252 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13254 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13257 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13259 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13262 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13264 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13267 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13269 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13272 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13274 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13277 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13279 if (SettingDialog.IconSz == iconSize) return;
13281 var oldIconCol = _iconCol;
13283 SettingDialog.IconSz = iconSize;
13284 ApplyListViewIconSize(iconSize);
13286 if (_iconCol != oldIconCol)
13288 foreach (TabPage tp in ListTab.TabPages)
13290 ResetColumns((DetailsListView)tp.Tag);
13294 if (_curList != null) _curList.Refresh();
13296 _modifySettingCommon = true;
13299 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13301 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13302 if (SettingDialog.SortOrderLock == state) return;
13304 SettingDialog.SortOrderLock = state;
13306 _modifySettingCommon = true;