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
57 private Size _mySize; //画面サイズ
58 private Point _myLoc; //画面位置
59 private int _mySpDis; //区切り位置
60 private int _mySpDis2; //発言欄区切り位置
61 private int _mySpDis3; //プレビュー区切り位置
62 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
63 private bool _iconCol; //1列表示の時true(48サイズのとき)
66 private bool _initial; //true:起動時処理中
67 private bool _initialLayout = true;
68 private bool _ignoreConfigSave; //true:起動時処理中
69 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
70 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
71 private Point _tabMouseDownPoint;
72 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
73 private readonly object _syncObject = new object(); //ロック用
74 private const string detailHtmlFormatMono1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- pre {font-family: \"";
75 private const string detailHtmlFormat2 = "\", sans-serif; font-size: ";
76 private const string detailHtmlFormat3 = "pt; margin: 0; word-wrap: break-word; white-space: pre-wrap; color:rgb(";
77 private const string detailHtmlFormat4 = ");} a:link, a:visited, a:active, a:hover {color:rgb(";
78 private const string detailHtmlFormat5 = "); } --></style></head><body style=\"margin:0px; background-color:rgb(";
79 private const string detailHtmlFormatMono6 = ");\"><pre>";
80 private const string detailHtmlFormatMono7 = "</pre></body></html>";
81 private const string detailHtmlFormat1 = "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\"><style type=\"text/css\"><!-- p {font-family: \"";
82 private const string detailHtmlFormat6 = ");\"><p><span style=\"vertical-align:text-bottom\">";
83 private const string detailHtmlFormat7 = "</span></p></body></html>";
84 private string detailHtmlFormatHeader;
85 private string detailHtmlFormatFooter;
86 private bool _myStatusError = false;
87 private bool _myStatusOnline = false;
88 private bool soundfileListup = false;
89 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
92 //private SettingToConfig _cfg; //旧
93 private SettingLocal _cfgLocal;
94 private SettingCommon _cfgCommon;
95 private bool _modifySettingLocal = false;
96 private bool _modifySettingCommon = false;
97 private bool _modifySettingAtId = false;
100 private Twitter tw = new Twitter();
103 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
106 private AppendSettingDialog SettingDialog = AppendSettingDialog.Instance; //設定画面インスタンス
107 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
108 private FilterDialog fltDialog = new FilterDialog(); //フィルター編集画面
109 private OpenURL UrlDialog = new OpenURL();
110 public AtIdSupplement AtIdSupl; //@id補助
111 public AtIdSupplement HashSupl; //Hashtag補助
112 public HashtagManage HashMgr;
113 private EventViewerDialog evtDialog;
116 private Font _fntUnread; //未読用フォント
117 private Color _clUnread; //未読用文字色
118 private Font _fntReaded; //既読用フォント
119 private Color _clReaded; //既読用文字色
120 private Color _clFav; //Fav用文字色
121 private Color _clOWL; //片思い用文字色
122 private Color _clRetweet; //Retweet用文字色
123 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
124 private Font _fntDetail; //発言詳細部用フォント
125 private Color _clDetail; //発言詳細部用色
126 private Color _clDetailLink; //発言詳細部用リンク文字色
127 private Color _clDetailBackcolor; //発言詳細部用背景色
128 private Color _clSelf; //自分の発言用背景色
129 private Color _clAtSelf; //自分宛返信用背景色
130 private Color _clTarget; //選択発言者の他の発言用背景色
131 private Color _clAtTarget; //選択発言中の返信先用背景色
132 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
133 private Color _clAtTo; //選択発言の唯一@先
134 private Color _clListBackcolor; //リスト部通常発言背景色
135 private Color _clInputBackcolor; //入力欄背景色
136 private Color _clInputFont; //入力欄文字色
137 private Font _fntInputFont; //入力欄フォント
138 private ImageCache IconCache; //アイコン画像リスト
139 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
140 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
141 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
142 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
143 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
144 private Icon MainIcon; //Main.ico 画面左上のアイコン
145 private Icon ReplyIcon; //5g
146 private Icon ReplyIconBlink; //6g
148 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
150 private PostClass _anchorPost;
151 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
153 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
154 private int _hisIdx; //発言履歴カレントインデックス
156 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
157 private long? _reply_to_id; // リプライ先のステータスID 0の場合はリプライではない 注:複数あてのものはリプライではない
158 private string _reply_to_name; // リプライ先ステータスの書き込み者の名前
161 private List<DateTime> _postTimestamps = new List<DateTime>();
162 private List<DateTime> _favTimestamps = new List<DateTime>();
163 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
164 private int _tlCount;
167 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
168 private SolidBrush _brsBackColorMine;
169 private SolidBrush _brsBackColorAt;
170 private SolidBrush _brsBackColorYou;
171 private SolidBrush _brsBackColorAtYou;
172 private SolidBrush _brsBackColorAtFromTarget;
173 private SolidBrush _brsBackColorAtTo;
174 private SolidBrush _brsBackColorNone;
175 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
176 private StringFormat sfTab = new StringFormat();
178 //////////////////////////////////////////////////////////////////////////////////////////////////////////
179 private ToolStripAPIGauge _apiGauge;
180 private TabInformations _statuses;
182 // ListViewItem のキャッシュ関連
183 private int _itemCacheIndex;
184 private ListViewItem[] _itemCache;
185 private PostClass[] _postCache;
186 private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
188 private TabPage _curTab;
189 private int _curItemIndex;
190 private DetailsListView _curList;
191 private PostClass _curPost;
192 private bool _isColumnChanged = false;
193 private bool _waitTimeline = false;
194 private bool _waitReply = false;
195 private bool _waitDm = false;
196 private bool _waitFav = false;
197 private bool _waitPubSearch = false;
198 private bool _waitUserTimeline = false;
199 private bool _waitLists = false;
200 private BackgroundWorker[] _bw = new BackgroundWorker[20];
201 private BackgroundWorker _bwFollower;
203 private int UnreadCounter = -1;
204 private int UnreadAtCounter = -1;
206 private string[] ColumnOrgText = new string[9];
207 private string[] ColumnText = new string[9];
209 private bool _DoFavRetweetFlags = false;
210 private bool osResumed = false;
212 //////////////////////////////////////////////////////////////////////////////////////////////////////////
213 private string _postBrowserStatusText = "";
215 private bool _colorize = false;
217 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
219 private ImageListViewItem displayItem;
222 /// デザイン時の DPI (96dpi) と実際の表示時の DPI との比を表します
224 protected SizeF currentScaleFactor = new SizeF();
227 private struct urlUndo
229 public string Before;
233 private List<urlUndo> urlUndoBuffer = null;
235 private struct ReplyChain
237 public long OriginalId;
238 public long InReplyToId;
239 public TabPage OriginalTab;
241 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
243 this.OriginalId = originalId;
244 this.InReplyToId = inReplyToId;
245 this.OriginalTab = originalTab;
249 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
250 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
252 //Backgroundworkerの処理結果通知用引数構造体
253 private class GetWorkerResult
255 public string retMsg = ""; //処理結果詳細メッセージ。エラー時に値がセットされる
256 public MyCommon.WORKERTYPE type; //処理種別
257 public string tName = ""; //Fav追加・削除時のタブ名
258 public List<long> sIds = null; //Fav追加・削除成功分のID
259 public bool newDM = false;
261 public PostingStatus status;
264 //Backgroundworkerへ処理内容を通知するための引数用構造体
265 private class GetWorkerArg
267 public int page; //処理対象ページ番号
268 public MyCommon.WORKERTYPE type; //処理種別
269 public PostingStatus status = new PostingStatus(); //発言POST時の発言内容
270 public List<long> ids; //Fav追加・削除時のItemIndex
271 public List<long> sIds; //Fav追加・削除成功分のItemIndex
272 public string tName = ""; //Fav追加・削除時のタブ名
276 private enum SEARCHTYPE
283 private class PostingStatus
285 public string status = "";
286 public long? inReplyToId = null;
287 public string inReplyToName = null;
288 public string imageService = ""; //画像投稿サービス名
289 public string[] imagePath = null;
290 public PostingStatus()
293 public PostingStatus(string status, long? replyToId, string replyToName)
295 this.status = status;
296 this.inReplyToId = replyToId;
297 this.inReplyToName = replyToName;
301 private void TweenMain_Activated(object sender, EventArgs e)
303 //画面がアクティブになったら、発言欄の背景色戻す
304 if (StatusText.Focused)
306 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
310 private bool disposed = false;
313 /// 使用中のリソースをすべてクリーンアップします。
315 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
316 protected override void Dispose(bool disposing)
318 base.Dispose(disposing);
325 if (this.components != null)
326 this.components.Dispose();
329 SettingDialog.Dispose();
330 SearchDialog.Dispose();
333 if (NIconAt != null) NIconAt.Dispose();
334 if (NIconAtRed != null) NIconAtRed.Dispose();
335 if (NIconAtSmoke != null) NIconAtSmoke.Dispose();
336 if (NIconRefresh[0] != null) NIconRefresh[0].Dispose();
337 if (NIconRefresh[1] != null) NIconRefresh[1].Dispose();
338 if (NIconRefresh[2] != null) NIconRefresh[2].Dispose();
339 if (NIconRefresh[3] != null) NIconRefresh[3].Dispose();
340 if (TabIcon != null) TabIcon.Dispose();
341 if (MainIcon != null) MainIcon.Dispose();
342 if (ReplyIcon != null) ReplyIcon.Dispose();
343 if (ReplyIconBlink != null) ReplyIconBlink.Dispose();
344 _listViewImageList.Dispose();
345 _brsHighLight.Dispose();
346 if (_brsBackColorMine != null) _brsBackColorMine.Dispose();
347 if (_brsBackColorAt != null) _brsBackColorAt.Dispose();
348 if (_brsBackColorYou != null) _brsBackColorYou.Dispose();
349 if (_brsBackColorAtYou != null) _brsBackColorAtYou.Dispose();
350 if (_brsBackColorAtFromTarget != null) _brsBackColorAtFromTarget.Dispose();
351 if (_brsBackColorAtTo != null) _brsBackColorAtTo.Dispose();
352 if (_brsBackColorNone != null) _brsBackColorNone.Dispose();
353 if (_brsDeactiveSelection != null) _brsDeactiveSelection.Dispose();
356 foreach (BackgroundWorker bw in _bw)
361 if (_bwFollower != null)
363 _bwFollower.Dispose();
365 this._apiGauge.Dispose();
366 if (IconCache != null)
368 this.IconCache.CancelAsync();
369 this.IconCache.Dispose();
372 if (this.thumbnailTokenSource != null)
373 this.thumbnailTokenSource.Dispose();
375 this.itemCacheLock.Dispose();
377 this._hookGlobalHotkey.Dispose();
380 // 終了時にRemoveHandlerしておかないとメモリリークする
381 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
382 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
384 this.disposed = true;
387 private void LoadIcon(ref Icon IconInstance, string FileName)
389 string dir = Application.StartupPath;
390 if (File.Exists(Path.Combine(dir, FileName)))
394 IconInstance = new Icon(Path.Combine(dir, FileName));
402 private void LoadIcons()
406 string dir = Application.StartupPath;
408 NIconAt = Properties.Resources.At;
409 NIconAtRed = Properties.Resources.AtRed;
410 NIconAtSmoke = Properties.Resources.AtSmoke;
411 NIconRefresh[0] = Properties.Resources.Refresh;
412 NIconRefresh[1] = Properties.Resources.Refresh2;
413 NIconRefresh[2] = Properties.Resources.Refresh3;
414 NIconRefresh[3] = Properties.Resources.Refresh4;
415 TabIcon = Properties.Resources.TabIcon;
416 MainIcon = Properties.Resources.MIcon;
417 ReplyIcon = Properties.Resources.Reply;
418 ReplyIconBlink = Properties.Resources.ReplyBlink;
420 if (!Directory.Exists(Path.Combine(dir, "Icons")))
423 LoadIcon(ref NIconAt, "Icons\\At.ico");
426 LoadIcon(ref NIconAtRed, "Icons\\AtRed.ico");
429 LoadIcon(ref NIconAtSmoke, "Icons\\AtSmoke.ico");
432 //アニメーション対応により4種類読み込み
433 LoadIcon(ref NIconRefresh[0], "Icons\\Refresh.ico");
434 LoadIcon(ref NIconRefresh[1], "Icons\\Refresh2.ico");
435 LoadIcon(ref NIconRefresh[2], "Icons\\Refresh3.ico");
436 LoadIcon(ref NIconRefresh[3], "Icons\\Refresh4.ico");
439 LoadIcon(ref TabIcon, "Icons\\Tab.ico");
442 LoadIcon(ref MainIcon, "Icons\\MIcon.ico");
445 LoadIcon(ref ReplyIcon, "Icons\\Reply.ico");
448 LoadIcon(ref ReplyIconBlink, "Icons\\ReplyBlink.ico");
451 private void InitColumns(ListView list, bool startup)
453 ColumnHeader _colHd1 = new ColumnHeader(); //アイコン
454 ColumnHeader _colHd2 = new ColumnHeader(); //ニックネーム
455 ColumnHeader _colHd3 = new ColumnHeader(); //本文
456 ColumnHeader _colHd4 = new ColumnHeader(); //日付
457 ColumnHeader _colHd5 = new ColumnHeader(); //ユーザID
458 ColumnHeader _colHd6 = new ColumnHeader(); //未読
459 ColumnHeader _colHd7 = new ColumnHeader(); //マーク&プロテクト
460 ColumnHeader _colHd8 = new ColumnHeader(); //ソース
464 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
468 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
472 _colHd1.Text = ColumnText[0];
474 _colHd2.Text = ColumnText[1];
476 _colHd3.Text = ColumnText[2];
478 _colHd4.Text = ColumnText[3];
480 _colHd5.Text = ColumnText[4];
482 _colHd6.Text = ColumnText[5];
484 _colHd7.Text = ColumnText[6];
486 _colHd8.Text = ColumnText[7];
489 int[] dispOrder = new int[8];
492 for (int i = 0; i < _curList.Columns.Count; i++)
494 for (int j = 0; j < _curList.Columns.Count; j++)
496 if (_curList.Columns[j].DisplayIndex == i)
503 for (int i = 0; i < _curList.Columns.Count; i++)
505 list.Columns[i].Width = _curList.Columns[i].Width;
506 list.Columns[dispOrder[i]].DisplayIndex = i;
513 list.Columns[0].Width = _cfgLocal.Width1;
514 list.Columns[1].Width = _cfgLocal.Width3;
515 list.Columns[0].DisplayIndex = 0;
516 list.Columns[1].DisplayIndex = 1;
520 for (int i = 0; i <= 7; i++)
522 if (_cfgLocal.DisplayIndex1 == i)
524 else if (_cfgLocal.DisplayIndex2 == i)
526 else if (_cfgLocal.DisplayIndex3 == i)
528 else if (_cfgLocal.DisplayIndex4 == i)
530 else if (_cfgLocal.DisplayIndex5 == i)
532 else if (_cfgLocal.DisplayIndex6 == i)
534 else if (_cfgLocal.DisplayIndex7 == i)
536 else if (_cfgLocal.DisplayIndex8 == i)
539 list.Columns[0].Width = _cfgLocal.Width1;
540 list.Columns[1].Width = _cfgLocal.Width2;
541 list.Columns[2].Width = _cfgLocal.Width3;
542 list.Columns[3].Width = _cfgLocal.Width4;
543 list.Columns[4].Width = _cfgLocal.Width5;
544 list.Columns[5].Width = _cfgLocal.Width6;
545 list.Columns[6].Width = _cfgLocal.Width7;
546 list.Columns[7].Width = _cfgLocal.Width8;
547 for (int i = 0; i <= 7; i++)
549 list.Columns[dispOrder[i]].DisplayIndex = i;
555 private void InitColumnText()
558 ColumnText[1] = Properties.Resources.AddNewTabText2;
559 ColumnText[2] = Properties.Resources.AddNewTabText3;
560 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
561 ColumnText[4] = Properties.Resources.AddNewTabText5;
564 ColumnText[7] = "Source";
566 ColumnOrgText[0] = "";
567 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
568 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
569 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
570 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
571 ColumnOrgText[5] = "";
572 ColumnOrgText[6] = "";
573 ColumnOrgText[7] = "Source";
576 switch (_statuses.SortMode)
578 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
581 case IdComparerClass.ComparerMode.Data: //本文
584 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
587 case IdComparerClass.ComparerMode.Name: //名前
590 case IdComparerClass.ComparerMode.Source: //Source
597 if (_statuses.SortOrder == SortOrder.Descending)
599 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
600 ColumnText[2] = ColumnOrgText[2] + "▾";
604 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
605 ColumnText[2] = ColumnOrgText[2] + "▴";
610 if (_statuses.SortOrder == SortOrder.Descending)
612 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
613 ColumnText[c] = ColumnOrgText[c] + "▾";
617 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
618 ColumnText[c] = ColumnOrgText[c] + "▴";
623 private void InitializeTraceFrag()
626 TraceOutToolStripMenuItem.Checked = true;
627 MyCommon.TraceFlag = true;
629 if (!MyCommon.FileVersion.EndsWith("0"))
631 TraceOutToolStripMenuItem.Checked = true;
632 MyCommon.TraceFlag = true;
636 private void TweenMain_Load(object sender, EventArgs e)
638 _ignoreConfigSave = true;
639 this.Visible = false;
641 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
643 new InternetSecurityManager(PostBrowser);
644 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
646 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
647 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
649 if (MyApplication.StartupOptions.ContainsKey("d"))
650 MyCommon.TraceFlag = true;
652 Regex.CacheSize = 100;
654 InitializeTraceFrag();
655 LoadIcons(); // アイコン読み込み
658 _statuses = TabInformations.GetInstance();
661 this.Icon = MainIcon; //メインフォーム(TweenMain)
662 NotifyIcon1.Icon = NIconAt; //タスクトレイ
663 TabImage.Images.Add(TabIcon); //タブ見出し
665 SettingDialog.Owner = this;;
666 SearchDialog.Owner = this;
667 fltDialog.Owner = this;
668 UrlDialog.Owner = this;
670 _history.Add(new PostingStatus());
673 _reply_to_name = null;
675 //<<<<<<<<<設定関連>>>>>>>>>
682 ThumbnailGenerator.InitializeGenerator();
684 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
685 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
686 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
688 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
689 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
690 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
693 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
694 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
697 _fntUnread = _cfgLocal.FontUnread;
698 _clUnread = _cfgLocal.ColorUnread;
699 _fntReaded = _cfgLocal.FontRead;
700 _clReaded = _cfgLocal.ColorRead;
701 _clFav = _cfgLocal.ColorFav;
702 _clOWL = _cfgLocal.ColorOWL;
703 _clRetweet = _cfgLocal.ColorRetweet;
704 _fntDetail = _cfgLocal.FontDetail;
705 _clDetail = _cfgLocal.ColorDetail;
706 _clDetailLink = _cfgLocal.ColorDetailLink;
707 _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
708 _clSelf = _cfgLocal.ColorSelf;
709 _clAtSelf = _cfgLocal.ColorAtSelf;
710 _clTarget = _cfgLocal.ColorTarget;
711 _clAtTarget = _cfgLocal.ColorAtTarget;
712 _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
713 _clAtTo = _cfgLocal.ColorAtTo;
714 _clListBackcolor = _cfgLocal.ColorListBackcolor;
715 _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
716 _clInputFont = _cfgLocal.ColorInputFont;
717 _fntInputFont = _cfgLocal.FontInputFont;
719 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
720 if (fontUIGlobal != null)
722 OTBaseForm.GlobalFont = fontUIGlobal;
723 this.Font = fontUIGlobal;
726 // StringFormatオブジェクトへの事前設定
727 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
728 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
729 //sf.FormatFlags = StringFormatFlags.LineLimit; //
730 sfTab.Alignment = StringAlignment.Center;
731 sfTab.LineAlignment = StringAlignment.Center;
734 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
736 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
737 this._cfgCommon.TimelinePeriod = 15;
739 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
740 this._cfgCommon.ReplyPeriod = 15;
742 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
743 this._cfgCommon.DMPeriod = 15;
745 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
746 this._cfgCommon.PubSearchPeriod = 30;
748 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
749 this._cfgCommon.UserTimelinePeriod = 15;
751 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
752 this._cfgCommon.ListsPeriod = 15;
756 this.SettingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
757 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
758 SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
761 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
762 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
764 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
766 //新着取得時のリストスクロールをするか。trueならスクロールしない
767 ListLockMenuItem.Checked = _cfgCommon.ListLock;
768 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
770 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
771 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
773 SettingDialog.NameBalloon = _cfgCommon.NameBalloon;
775 SettingDialog.CountApi = _cfgCommon.CountApi;
776 SettingDialog.CountApiReply = _cfgCommon.CountApiReply;
777 if (SettingDialog.CountApi < 20 || SettingDialog.CountApi > 200) SettingDialog.CountApi = 60;
778 if (SettingDialog.CountApiReply < 20 || SettingDialog.CountApiReply > 200) SettingDialog.CountApiReply = 40;
780 SettingDialog.PostAndGet = _cfgCommon.PostAndGet;
781 SettingDialog.DispUsername = _cfgCommon.DispUsername;
782 SettingDialog.DispLatestPost = _cfgCommon.DispLatestPost;
783 SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
785 SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
786 SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
787 SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
788 SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
789 SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
791 SettingDialog.AlwaysTop = _cfgCommon.AlwaysTop;
792 SettingDialog.UrlConvertAuto = false;
793 //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
795 SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
796 SettingDialog.LimitBalloon = _cfgCommon.LimitBalloon;
797 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
798 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
799 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
800 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
801 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
802 SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
803 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
805 //廃止サービスが選択されていた場合bit.lyへ読み替え
806 if (_cfgCommon.AutoShortUrlFirst < 0)
807 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
809 SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
810 SettingDialog.TabIconDisp = _cfgCommon.TabIconDisp;
811 SettingDialog.ReplyIconState = _cfgCommon.ReplyIconState;
812 SettingDialog.BitlyUser = _cfgCommon.BilyUser;
813 SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
814 SettingDialog.Language = _cfgCommon.Language;
815 SettingDialog.PreviewEnable = _cfgCommon.PreviewEnable;
816 SettingDialog.StatusAreaAtBottom = _cfgCommon.StatusAreaAtBottom;
817 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
819 SettingDialog.IsMonospace = _cfgCommon.IsMonospace;
821 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
822 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
824 //Regex statregex = new Regex("^0*");
825 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
827 SettingDialog.Nicoms = _cfgCommon.Nicoms;
829 SettingDialog.BlinkNewMentions = _cfgCommon.BlinkNewMentions;
831 SettingDialog.UseAdditionalCount = _cfgCommon.UseAdditionalCount;
832 SettingDialog.MoreCountApi = _cfgCommon.MoreCountApi;
833 SettingDialog.FirstCountApi = _cfgCommon.FirstCountApi;
834 SettingDialog.SearchCountApi = _cfgCommon.SearchCountApi;
835 SettingDialog.FavoritesCountApi = _cfgCommon.FavoritesCountApi;
836 SettingDialog.UserTimelineCountApi = _cfgCommon.UserTimelineCountApi;
837 SettingDialog.ListCountApi = _cfgCommon.ListCountApi;
839 SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
841 SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
842 SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
843 SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
844 SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
845 SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
846 SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
847 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
848 SettingDialog.IsNotifyUseGrowl = _cfgCommon.IsUseNotifyGrowl;
851 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
852 HashMgr = new HashtagManage(HashSupl,
853 _cfgCommon.HashTags.ToArray(),
854 _cfgCommon.HashSelected,
855 _cfgCommon.HashIsPermanent,
856 _cfgCommon.HashIsHead,
857 _cfgCommon.HashIsNotAddToAtReply);
858 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
862 Networking.Initialize();
865 this.IconCache = new ImageCache();
867 bool saveRequired = false;
868 bool firstRun = false;
870 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
871 if (string.IsNullOrEmpty(tw.Username))
875 SettingDialog.ShowInTaskbar = true;
877 //設定せずにキャンセルされた場合はプログラム終了
878 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
880 Application.Exit(); //強制終了
883 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
884 if (string.IsNullOrEmpty(tw.Username))
886 Application.Exit(); //強制終了
889 SettingDialog.ShowInTaskbar = false;
893 _fntUnread = this._cfgLocal.FontUnread;
894 _clUnread = this._cfgLocal.ColorUnread;
895 _fntReaded = this._cfgLocal.FontRead;
896 _clReaded = this._cfgLocal.ColorRead;
897 _clFav = this._cfgLocal.ColorFav;
898 _clOWL = this._cfgLocal.ColorOWL;
899 _clRetweet = this._cfgLocal.ColorRetweet;
900 _fntDetail = this._cfgLocal.FontDetail;
901 _clDetail = this._cfgLocal.ColorDetail;
902 _clDetailLink = this._cfgLocal.ColorDetailLink;
903 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
904 _clSelf = this._cfgLocal.ColorSelf;
905 _clAtSelf = this._cfgLocal.ColorAtSelf;
906 _clTarget = this._cfgLocal.ColorTarget;
907 _clAtTarget = this._cfgLocal.ColorAtTarget;
908 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
909 _clAtTo = this._cfgLocal.ColorAtTo;
910 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
911 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
912 _clInputFont = this._cfgLocal.ColorInputFont;
913 _fntInputFont = this._cfgLocal.FontInputFont;
915 //他の設定項目は、随時設定画面で保持している値を読み出して使用
918 _brsBackColorMine = new SolidBrush(_clSelf);
919 _brsBackColorAt = new SolidBrush(_clAtSelf);
920 _brsBackColorYou = new SolidBrush(_clTarget);
921 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
922 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
923 _brsBackColorAtTo = new SolidBrush(_clAtTo);
924 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
925 _brsBackColorNone = new SolidBrush(_clListBackcolor);
927 InitDetailHtmlFormat();
929 if (this._cfgCommon.HotkeyEnabled)
932 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
933 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
934 modKey |= HookGlobalHotkey.ModKeys.Alt;
935 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
936 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
937 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
938 modKey |= HookGlobalHotkey.ModKeys.Shift;
939 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
940 modKey |= HookGlobalHotkey.ModKeys.Win;
942 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
946 Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut);
947 Networking.SetWebProxy(this.SettingDialog.SelectedProxyType,
948 this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort,
949 this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword);
951 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
952 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
953 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
954 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
955 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
956 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
957 tw.TrackWord = _cfgCommon.TrackWord;
958 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
959 tw.AllAtReply = _cfgCommon.AllAtReply;
960 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
963 ImageSelector.Initialize(tw, SettingDialog.TwitterConfiguration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
966 this.ClientSize = _cfgLocal.FormSize;
967 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
968 _myLoc = _cfgLocal.FormLocation;
970 if (this.WindowState != FormWindowState.Minimized)
972 this.DesktopLocation = _cfgLocal.FormLocation;
973 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
974 bool outOfScreen = true;
975 if (Screen.AllScreens.Length == 1) //ハングするとの報告
977 foreach (Screen scr in Screen.AllScreens)
979 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
987 this.DesktopLocation = new Point(0, 0);
988 _myLoc = this.DesktopLocation;
992 this.TopMost = SettingDialog.AlwaysTop;
993 _mySpDis = _cfgLocal.SplitterDistance;
994 _mySpDis2 = _cfgLocal.StatusTextHeight;
995 _mySpDis3 = _cfgLocal.PreviewDistance;
998 _mySpDis3 = _mySize.Width - 150;
999 if (_mySpDis3 < 1) _mySpDis3 = 50;
1000 _cfgLocal.PreviewDistance = _mySpDis3;
1002 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
1003 //this.Tween_ClientSizeChanged(this, null);
1004 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
1005 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
1007 StatusText.Font = _fntInputFont;
1008 StatusText.ForeColor = _clInputFont;
1010 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
1011 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
1013 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1014 SplitContainer1.IsPanelInverted = !SettingDialog.StatusAreaAtBottom;
1016 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1017 if (this._cfgCommon.UnreadManage == false)
1019 ReadedStripMenuItem.Enabled = false;
1020 UnreadStripMenuItem.Enabled = false;
1023 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
1026 TimerTimeline.AutoReset = true;
1027 TimerTimeline.SynchronizingObject = this;
1029 TimerTimeline.Interval = 1000;
1030 TimerTimeline.Enabled = true;
1033 TimerRefreshIcon.Interval = 200;
1034 TimerRefreshIcon.Enabled = true;
1037 StatusLabel.Text = "";
1038 StatusLabel.AutoToolTip = false;
1039 StatusLabel.ToolTipText = "";
1041 lblLen.Text = GetRestStatusCount(true, false).ToString();
1043 ////////////////////////////////////////////////////////////////////////////////
1044 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1045 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1046 switch (_cfgCommon.SortColumn)
1048 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1052 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1055 mode = IdComparerClass.ComparerMode.Nickname;
1058 mode = IdComparerClass.ComparerMode.Data;
1061 mode = IdComparerClass.ComparerMode.Id;
1064 mode = IdComparerClass.ComparerMode.Name;
1067 mode = IdComparerClass.ComparerMode.Source;
1070 _statuses.SortMode = mode;
1071 ////////////////////////////////////////////////////////////////////////////////
1073 ApplyListViewIconSize(this._cfgCommon.IconSize);
1075 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1076 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1077 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1078 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1079 SourceLinkLabel.Text = ""; //Source部分初期化
1081 //<<<<<<<<タブ関連>>>>>>>
1082 //デフォルトタブの存在チェック、ない場合には追加
1083 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1086 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1088 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1092 tab.TabType = MyCommon.TabUsageType.Home;
1095 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1098 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1100 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1104 tab.TabType = MyCommon.TabUsageType.Mentions;
1107 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1110 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1112 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1116 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1119 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1122 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1124 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1128 tab.TabType = MyCommon.TabUsageType.Favorites;
1131 foreach (var tab in _statuses.Tabs.Values)
1133 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1135 tab.TabType = MyCommon.TabUsageType.UserDefined;
1137 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1138 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1141 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1142 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1143 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1144 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1146 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1148 this.Visible = true;
1150 _curTab = ListTab.SelectedTab;
1152 _curList = (DetailsListView)_curTab.Tag;
1153 SetMainWindowTitle();
1154 SetNotifyIconText();
1156 if (SettingDialog.TabIconDisp)
1158 ListTab.DrawMode = TabDrawMode.Normal;
1162 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1163 ListTab.DrawItem += ListTab_DrawItem;
1164 ListTab.ImageList = null;
1167 _ignoreConfigSave = false;
1168 this.TweenMain_Resize(null, null);
1169 if (saveRequired) SaveConfigsAll(false);
1173 tw.VerifyCredentials();
1174 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1176 if (ua.Username.ToLower() == tw.Username.ToLower())
1178 ua.UserId = tw.UserId;
1183 foreach (UserAccount ua in SettingDialog.UserAccounts)
1185 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1187 ua.UserId = tw.UserId;
1194 // 初回起動時だけ右下のメニューを目立たせる
1195 HashStripSplitButton.ShowDropDown();
1202 private void InitDetailHtmlFormat()
1204 if (SettingDialog.IsMonospace)
1206 detailHtmlFormatHeader = detailHtmlFormatMono1;
1207 detailHtmlFormatFooter = detailHtmlFormatMono7;
1211 detailHtmlFormatHeader = detailHtmlFormat1;
1212 detailHtmlFormatFooter = detailHtmlFormat7;
1214 detailHtmlFormatHeader += _fntDetail.Name + detailHtmlFormat2 + _fntDetail.Size.ToString() + detailHtmlFormat3 + _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString() + detailHtmlFormat4 + _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString() + detailHtmlFormat5 + _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString();
1215 if (SettingDialog.IsMonospace)
1217 detailHtmlFormatHeader += detailHtmlFormatMono6;
1221 detailHtmlFormatHeader += detailHtmlFormat6;
1225 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1230 txt = ListTab.TabPages[e.Index].Text;
1237 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1238 if (e.State == DrawItemState.Selected)
1240 e.DrawFocusRectangle();
1245 if (_statuses.Tabs[txt].UnreadCount > 0)
1248 fore = System.Drawing.SystemBrushes.ControlText;
1252 fore = System.Drawing.SystemBrushes.ControlText;
1254 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1257 private void LoadConfig()
1259 _cfgCommon = SettingCommon.Load();
1260 SettingCommon.Instance = this._cfgCommon;
1261 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1263 _cfgCommon.UserAccounts = new List<UserAccount>();
1264 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1266 UserAccount account = new UserAccount();
1267 account.Username = _cfgCommon.UserName;
1268 account.UserId = _cfgCommon.UserId;
1269 account.Token = _cfgCommon.Token;
1270 account.TokenSecret = _cfgCommon.TokenSecret;
1272 _cfgCommon.UserAccounts.Add(account);
1275 _cfgLocal = SettingLocal.Load();
1276 List<TabClass> tabs = SettingTabs.Load().Tabs;
1277 foreach (TabClass tb in tabs)
1281 _statuses.Tabs.Add(tb.TabName, tb);
1285 tb.TabName = _statuses.GetUniqueTabName();
1286 _statuses.Tabs.Add(tb.TabName, tb);
1289 if (_statuses.Tabs.Count == 0)
1291 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1292 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1293 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1294 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1298 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1300 if (!TimerTimeline.Enabled) return;
1304 private IntervalChangedEventArgs ResetTimers = new IntervalChangedEventArgs();
1306 private static int homeCounter = 0;
1307 private static int mentionCounter = 0;
1308 private static int dmCounter = 0;
1309 private static int pubSearchCounter = 0;
1310 private static int userTimelineCounter = 0;
1311 private static int listsCounter = 0;
1312 private static int usCounter = 0;
1313 private static int ResumeWait = 0;
1314 private static int refreshFollowers = 0;
1316 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1318 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1319 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1320 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1321 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1322 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1323 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1324 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1325 Interlocked.Increment(ref refreshFollowers);
1328 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1330 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1331 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1332 ResetTimers.Timeline = false;
1334 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1336 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1337 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1338 ResetTimers.Reply = false;
1340 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1342 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1343 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1344 ResetTimers.DirectMessage = false;
1346 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1348 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1349 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1350 ResetTimers.PublicSearch = false;
1352 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1354 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1355 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1356 ResetTimers.UserTimeline = false;
1358 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1360 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1361 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1362 ResetTimers.Lists = false;
1364 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1366 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1367 if (this._isActiveUserstream) RefreshTimeline(true);
1368 ResetTimers.UserStream = false;
1370 if (refreshFollowers > 6 * 3600)
1372 Interlocked.Exchange(ref refreshFollowers, 0);
1373 doGetFollowersMenu();
1374 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
1375 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1379 Interlocked.Increment(ref ResumeWait);
1380 if (ResumeWait > 30)
1383 Interlocked.Exchange(ref ResumeWait, 0);
1384 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1385 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1386 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1387 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1388 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1389 GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1390 doGetFollowersMenu();
1391 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1396 private void RefreshTimeline(bool isUserStream)
1398 if (isUserStream) this.RefreshTasktrayIcon(true);
1400 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1401 long topId = GetScrollPos(ref smode);
1402 int befCnt = _curList.VirtualListSize;
1405 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1406 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1407 SaveSelectedStatus(selId, focusedId);
1410 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1413 PostClass[] notifyPosts = null;
1414 string soundFile = "";
1416 bool isMention = false;
1417 bool isDelete = false;
1418 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1420 if (MyCommon._endingFlag) return;
1425 foreach (TabPage tab in ListTab.TabPages)
1427 DetailsListView lst = (DetailsListView)tab.Tag;
1428 TabClass tabInfo = _statuses.Tabs[tab.Text];
1429 using (ControlTransaction.Update(lst))
1431 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1433 if (lst.Equals(_curList))
1435 this.PurgeListViewItemCache();
1439 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1445 this.SelectListItem(lst,
1446 tabInfo.IndexOf(selId[tab.Text]),
1447 tabInfo.IndexOf(focusedId[tab.Text]));
1450 if (tabInfo.UnreadCount > 0)
1451 if (SettingDialog.TabIconDisp)
1452 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1454 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
1458 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1467 if (befCnt != _curList.VirtualListSize)
1473 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1477 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1484 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1486 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1487 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1493 catch (Exception ex)
1495 ex.Data["Msg"] = "Ref2";
1501 NotifyNewPosts(notifyPosts,
1504 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1506 SetMainWindowTitle();
1507 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1509 HashSupl.AddRangeItem(tw.GetHashList());
1513 private long GetScrollPos(ref int smode)
1516 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1518 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1520 if (_statuses.SortOrder == SortOrder.Ascending)
1523 if (ListLockMenuItem.Checked)
1528 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1533 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1535 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1536 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1537 if (_item.Index == _curList.VirtualListSize - 1)
1544 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1552 if (ListLockMenuItem.Checked)
1555 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1560 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1563 _item = _curList.GetItemAt(0, 10); //一番上
1564 if (_item == null) _item = _curList.Items[0];
1565 if (_item.Index == 0)
1571 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1580 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1591 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1593 if (MyCommon._endingFlag) return;
1594 foreach (TabPage tab in ListTab.TabPages)
1596 var lst = (DetailsListView)tab.Tag;
1597 var tabInfo = _statuses.Tabs[tab.Text];
1598 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1600 selId.Add(tab.Text, tabInfo.GetId(lst.SelectedIndices));
1604 selId.Add(tab.Text, new long[1] {-2});
1607 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1608 var item = lst.FocusedItem;
1609 fIds[0] = (item != null) ? tabInfo.GetId(item.Index) : -2;
1610 var mIdx = lst.SelectionMark;
1611 fIds[1] = (mIdx > -1) ? tabInfo.GetId(mIdx) : -2;
1612 focusedId.Add(tab.Text, fIds);
1617 private bool BalloonRequired()
1619 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1620 ev.Eventtype = MyCommon.EVENTTYPE.None;
1622 return BalloonRequired(ev);
1625 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1627 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1630 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1632 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1635 private bool BalloonRequired(Twitter.FormattedEvent ev)
1638 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1639 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1643 SettingDialog.LimitBalloon &&
1645 this.WindowState == FormWindowState.Minimized ||
1647 Form.ActiveForm == null
1650 !SettingDialog.LimitBalloon
1653 !NativeMethods.IsScreenSaverRunning())
1663 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1665 if (notifyPosts != null &&
1666 notifyPosts.Length > 0 &&
1667 this._cfgCommon.ReadOwnPost &&
1668 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1674 if (BalloonRequired())
1676 if (notifyPosts != null && notifyPosts.Length > 0)
1678 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1679 if (SettingDialog.IsNotifyUseGrowl)
1681 StringBuilder sb = new StringBuilder();
1685 foreach (PostClass post in notifyPosts)
1687 if (!(notifyPosts.Length > 3))
1693 if (post.IsReply && !post.IsExcludeReply) reply = true;
1694 if (post.IsDm) dm = true;
1695 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1696 switch (SettingDialog.NameBalloon)
1698 case MyCommon.NameBalloonEnum.UserID:
1699 sb.Append(post.ScreenName).Append(" : ");
1701 case MyCommon.NameBalloonEnum.NickName:
1702 sb.Append(post.Nickname).Append(" : ");
1705 sb.Append(post.TextFromApi);
1706 if (notifyPosts.Length > 3)
1708 if (notifyPosts.Last() != post) continue;
1711 StringBuilder title = new StringBuilder();
1712 GrowlHelper.NotifyType nt;
1713 if (SettingDialog.DispUsername)
1715 title.Append(tw.Username);
1716 title.Append(" - ");
1724 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1725 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1726 title.Append(Application.ProductName);
1727 title.Append(" [DM] ");
1728 title.Append(Properties.Resources.RefreshDirectMessageText1);
1730 title.Append(addCount);
1731 title.Append(Properties.Resources.RefreshDirectMessageText2);
1732 nt = GrowlHelper.NotifyType.DirectMessage;
1736 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1737 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1738 title.Append(Application.ProductName);
1739 title.Append(" [Reply!] ");
1740 title.Append(Properties.Resources.RefreshTimelineText1);
1742 title.Append(addCount);
1743 title.Append(Properties.Resources.RefreshTimelineText2);
1744 nt = GrowlHelper.NotifyType.Reply;
1748 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1749 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1750 title.Append(Application.ProductName);
1752 title.Append(Properties.Resources.RefreshTimelineText1);
1754 title.Append(addCount);
1755 title.Append(Properties.Resources.RefreshTimelineText2);
1756 nt = GrowlHelper.NotifyType.Notify;
1758 string bText = sb.ToString();
1759 if (string.IsNullOrEmpty(bText)) return;
1761 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1762 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1767 StringBuilder sb = new StringBuilder();
1770 foreach (PostClass post in notifyPosts)
1772 if (post.IsReply && !post.IsExcludeReply) reply = true;
1773 if (post.IsDm) dm = true;
1774 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1775 switch (SettingDialog.NameBalloon)
1777 case MyCommon.NameBalloonEnum.UserID:
1778 sb.Append(post.ScreenName).Append(" : ");
1780 case MyCommon.NameBalloonEnum.NickName:
1781 sb.Append(post.Nickname).Append(" : ");
1784 sb.Append(post.TextFromApi);
1787 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1788 StringBuilder title = new StringBuilder();
1790 if (SettingDialog.DispUsername)
1792 title.Append(tw.Username);
1793 title.Append(" - ");
1801 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1802 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1803 ntIcon = ToolTipIcon.Warning;
1804 title.Append(Application.ProductName);
1805 title.Append(" [DM] ");
1806 title.Append(Properties.Resources.RefreshDirectMessageText1);
1808 title.Append(addCount);
1809 title.Append(Properties.Resources.RefreshDirectMessageText2);
1813 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1814 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1815 ntIcon = ToolTipIcon.Warning;
1816 title.Append(Application.ProductName);
1817 title.Append(" [Reply!] ");
1818 title.Append(Properties.Resources.RefreshTimelineText1);
1820 title.Append(addCount);
1821 title.Append(Properties.Resources.RefreshTimelineText2);
1825 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1826 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1827 ntIcon = ToolTipIcon.Info;
1828 title.Append(Application.ProductName);
1830 title.Append(Properties.Resources.RefreshTimelineText1);
1832 title.Append(addCount);
1833 title.Append(Properties.Resources.RefreshTimelineText2);
1835 string bText = sb.ToString();
1836 if (string.IsNullOrEmpty(bText)) return;
1837 //NotifyIcon1.BalloonTipText = sb.ToString();
1838 //NotifyIcon1.ShowBalloonTip(500);
1839 NotifyIcon1.BalloonTipTitle = title.ToString();
1840 NotifyIcon1.BalloonTipText = bText;
1841 NotifyIcon1.BalloonTipIcon = ntIcon;
1842 NotifyIcon1.ShowBalloonTip(500);
1848 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1852 string dir = Application.StartupPath;
1853 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1855 dir = Path.Combine(dir, "Sounds");
1857 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1867 //mentions新着時に画面ブリンク
1868 if (!_initial && SettingDialog.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1870 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1874 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1876 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1878 _curItemIndex = _curList.SelectedIndices[0];
1879 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1883 _curPost = GetCurTabPost(_curItemIndex);
1885 catch (ArgumentException)
1890 this.PushSelectPostChain();
1892 if (this._cfgCommon.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1894 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1900 private void ChangeCacheStyleRead(bool Read, int Index)
1902 var tabInfo = _statuses.Tabs[_curTab.Text];
1903 //Read:true=既読 false=未読
1904 //未読管理していなかったら既読として扱う
1905 if (!tabInfo.UnreadManage ||
1906 !this._cfgCommon.UnreadManage) Read = true;
1909 ListViewItem itm = null;
1910 PostClass post = null;
1912 this.TryGetListViewItemCache(Index, out itm, out post);
1914 if (itm == null || post == null)
1916 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1917 post = tabInfo[Index];
1920 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1923 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1930 Item.SubItems[5].Text = "";
1935 Item.SubItems[5].Text = "★";
1941 else if (Post.RetweetedId != null)
1943 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1945 else if (Read || !this._cfgCommon.UseUnreadStyle)
1950 if (DList == null || Item.Index == -1)
1952 Item.ForeColor = cl;
1953 if (this._cfgCommon.UseUnreadStyle)
1959 if (this._cfgCommon.UseUnreadStyle)
1960 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1962 DList.ChangeItemForeColor(Item.Index, cl);
1963 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1967 private void ColorizeList()
1969 //Index:更新対象のListviewItem.Index。Colorを返す。
1970 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1973 _post = _anchorPost;
1977 if (_post == null) return;
1979 var itemColors = new Color[] { };
1982 this.itemCacheLock.EnterReadLock();
1985 if (this._itemCache == null) return;
1988 from i in Enumerable.Range(0, this._itemCache.Length)
1989 select this.JudgeColor(_post, this._postCache[i]);
1991 itemColors = query.ToArray();
1992 itemIndex = _itemCacheIndex;
1994 finally { this.itemCacheLock.ExitReadLock(); }
1996 if (itemIndex < 0) return;
1998 foreach (var backColor in itemColors)
2000 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
2001 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
2002 _curList.ChangeItemBackColor(itemIndex++, backColor);
2006 private void ColorizeList(ListViewItem Item, int Index)
2008 //Index:更新対象のListviewItem.Index。Colorを返す。
2009 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2012 _post = _anchorPost;
2016 PostClass tPost = GetCurTabPost(Index);
2018 if (_post == null) return;
2020 if (Item.Index == -1)
2021 Item.BackColor = JudgeColor(_post, tPost);
2023 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2026 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2029 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2032 else if (TargetPost.IsMe)
2035 else if (TargetPost.IsReply)
2038 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2040 cl = _clAtFromTarget;
2041 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2044 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2049 cl = _clListBackcolor;
2054 private async void PostButton_Click(object sender, EventArgs e)
2056 if (StatusText.Text.Trim().Length == 0)
2058 if (!ImageSelector.Enabled)
2065 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2067 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2069 MessageBoxButtons.YesNoCancel,
2070 MessageBoxIcon.Question);
2073 case DialogResult.Yes:
2074 doReTweetOfficial(false);
2075 StatusText.Text = "";
2077 case DialogResult.Cancel:
2082 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2084 if (SettingDialog.Nicoms)
2086 StatusText.SelectionStart = StatusText.Text.Length;
2087 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2089 //if (SettingDialog.UrlConvertAuto)
2091 // StatusText.SelectionStart = StatusText.Text.Length;
2092 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2094 //else if (SettingDialog.Nicoms)
2096 // StatusText.SelectionStart = StatusText.Text.Length;
2097 // UrlConvert(UrlConverter.Nicoms);
2099 StatusText.SelectionStart = StatusText.Text.Length;
2100 GetWorkerArg args = new GetWorkerArg();
2102 args.type = MyCommon.WORKERTYPE.PostMessage;
2103 CheckReplyTo(StatusText.Text);
2106 int adjustCount = 0;
2107 string tmpStatus = StatusText.Text.Trim();
2108 if (ToolStripMenuItemApiCommandEvasion.Checked)
2111 if (Regex.IsMatch(tmpStatus,
2112 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2113 RegexOptions.IgnoreCase)
2114 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2117 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2120 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2123 bool isCutOff = false;
2124 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2125 if (StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
2127 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2128 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2130 if (this._cfgCommon.PostShiftEnter)
2132 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2134 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2136 isRemoveFooter = true;
2138 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2140 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2143 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2144 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2146 isRemoveFooter = true;
2157 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2165 if (HashMgr.IsNotAddToAtReply)
2167 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2170 header = HashMgr.UseHash + " ";
2172 footer = " " + HashMgr.UseHash;
2177 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2180 header = HashMgr.UseHash + " ";
2182 footer = " " + HashMgr.UseHash;
2185 if (!isRemoveFooter)
2187 if (this._cfgLocal.UseRecommendStatus)
2189 footer += SettingDialog.RecommendStatusText;
2191 // テキストボックスに入力されている文字列を使用する
2192 footer += " " + this._cfgLocal.StatusText.Trim();
2195 args.status.status = header + StatusText.Text + footer;
2197 if (ToolStripMenuItemApiCommandEvasion.Checked)
2200 if (Regex.IsMatch(args.status.status,
2201 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2202 RegexOptions.IgnoreCase)
2203 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2206 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2209 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2210 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2213 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2215 // 文中の全角スペースを半角スペース1個にする
2216 args.status.status = args.status.status.Replace(" ", " ");
2219 if (isCutOff && args.status.status.Length > 140)
2221 args.status.status = args.status.status.Substring(0, 140);
2222 string AtId = @"(@|@)[a-z0-9_/]+$";
2223 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2224 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2225 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2226 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2229 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2230 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2232 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2235 args.status.inReplyToId = _reply_to_id;
2236 args.status.inReplyToName = _reply_to_name;
2237 if (ImageSelector.Visible)
2240 if (!ImageSelector.TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2246 _reply_to_id = null;
2247 _reply_to_name = null;
2248 StatusText.Text = "";
2249 _history.Add(new PostingStatus());
2250 _hisIdx = _history.Count - 1;
2251 if (!ToolStripFocusLockMenuItem.Checked)
2252 ((Control)ListTab.SelectedTab.Tag).Focus();
2253 urlUndoBuffer = null;
2254 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2257 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2259 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2260 await this.OpenUriAsync(tmp);
2264 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2266 MyCommon._endingFlag = true;
2270 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2272 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2274 //_endingFlag=false:フォームの×ボタン
2276 this.Visible = false;
2280 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2281 _ignoreConfigSave = true;
2282 MyCommon._endingFlag = true;
2283 TimerTimeline.Enabled = false;
2284 TimerRefreshIcon.Enabled = false;
2288 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2290 this.Visible = true;
2291 if (this.WindowState == FormWindowState.Minimized)
2293 this.WindowState = FormWindowState.Normal;
2296 this.BringToFront();
2299 private static int errorCount = 0;
2301 private static bool CheckAccountValid()
2303 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2309 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2318 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2320 BackgroundWorker bw = (BackgroundWorker)sender;
2321 if (bw.CancellationPending || MyCommon._endingFlag)
2327 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2329 MyApplication.InitCulture();
2332 GetWorkerResult rslt = new GetWorkerResult();
2334 bool read = !this._cfgCommon.UnreadManage;
2335 if (_initial && this._cfgCommon.UnreadManage) read = this._cfgCommon.Read;
2337 GetWorkerArg args = (GetWorkerArg)e.Argument;
2339 if (!CheckAccountValid())
2341 rslt.retMsg = "Auth error. Check your account";
2342 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2343 rslt.tName = args.tName;
2348 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2352 case MyCommon.WORKERTYPE.Timeline:
2353 case MyCommon.WORKERTYPE.Reply:
2354 bw.ReportProgress(50, MakeStatusMessage(args, false));
2355 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2357 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && this._cfgCommon.ReadOldPosts)
2358 _statuses.SetRead();
2360 rslt.addCount = _statuses.DistributePosts();
2362 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2363 bw.ReportProgress(50, MakeStatusMessage(args, false));
2364 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2365 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2366 rslt.addCount = _statuses.DistributePosts();
2369 case MyCommon.WORKERTYPE.FavAdd:
2373 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2375 for (int i = 0; i <= args.ids.Count - 1; i++)
2377 var post = tab.Posts[args.ids[i]];
2380 bw.ReportProgress(50, MakeStatusMessage(args, false));
2383 if (post.RetweetedId == null)
2384 ret = tw.PostFavAdd(post.StatusId);
2386 ret = tw.PostFavAdd(post.RetweetedId.Value);
2388 if (ret.Length == 0)
2390 args.sIds.Add(post.StatusId);
2391 post.IsFav = true; //リスト再描画必要
2392 _favTimestamps.Add(DateTime.Now);
2393 if (string.IsNullOrEmpty(post.RelTabName))
2395 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2396 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2400 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2401 if (_statuses.ContainsKey(post.StatusId))
2403 PostClass postTl = _statuses[post.StatusId];
2404 postTl.IsFav = true;
2405 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2408 //検索,リスト,UserTimeline,Relatedの各タブに反映
2409 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2411 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2417 rslt.sIds = args.sIds;
2421 case MyCommon.WORKERTYPE.FavRemove:
2425 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2427 for (int i = 0; i <= args.ids.Count - 1; i++)
2429 var post = tab.Posts[args.ids[i]];
2432 bw.ReportProgress(50, MakeStatusMessage(args, false));
2435 if (post.RetweetedId == null)
2436 ret = tw.PostFavRemove(post.StatusId);
2438 ret = tw.PostFavRemove(post.RetweetedId.Value);
2440 if (ret.Length == 0)
2442 args.sIds.Add(post.StatusId);
2443 post.IsFav = false; //リスト再描画必要
2444 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2445 //検索,リスト,UserTimeline,Relatedの各タブに反映
2446 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2448 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2454 rslt.sIds = args.sIds;
2458 case MyCommon.WORKERTYPE.PostMessage:
2459 bw.ReportProgress(200);
2460 if (args.status.imagePath == null || args.status.imagePath.Length == 0 || string.IsNullOrEmpty(args.status.imagePath[0]))
2462 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2466 var service = ImageSelector.GetService(args.status.imageService);
2469 service.PostStatusAsync(args.status.status, args.status.inReplyToId, args.status.imagePath)
2472 catch (AggregateException ex)
2474 ret = ex.InnerException.Message;
2477 bw.ReportProgress(300);
2478 rslt.status = args.status;
2480 case MyCommon.WORKERTYPE.Retweet:
2481 bw.ReportProgress(200);
2482 for (int i = 0; i <= args.ids.Count - 1; i++)
2484 ret = tw.PostRetweet(args.ids[i], read);
2486 bw.ReportProgress(300);
2488 case MyCommon.WORKERTYPE.Follower:
2489 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2492 tw.RefreshFollowerIds();
2494 catch (WebApiException ex) { ret = ex.Message; }
2496 case MyCommon.WORKERTYPE.NoRetweetIds:
2499 tw.RefreshNoRetweetIds();
2501 catch (WebApiException ex) { ret = ex.Message; }
2503 case MyCommon.WORKERTYPE.Configuration:
2506 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2508 catch (WebApiException ex) { ret = ex.Message; }
2510 case MyCommon.WORKERTYPE.Favorites:
2511 bw.ReportProgress(50, MakeStatusMessage(args, false));
2512 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2513 rslt.addCount = _statuses.DistributePosts();
2515 case MyCommon.WORKERTYPE.PublicSearch:
2516 bw.ReportProgress(50, MakeStatusMessage(args, false));
2517 if (string.IsNullOrEmpty(args.tName))
2519 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2521 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2522 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2527 TabClass tb = _statuses.GetTabByName(args.tName);
2530 //ret = tw.GetPhoenixSearch(read, tb, false);
2531 ret = tw.GetSearch(read, tb, false);
2532 if (string.IsNullOrEmpty(ret) && args.page == -1)
2534 //ret = tw.GetPhoenixSearch(read, tb, true)
2535 ret = tw.GetSearch(read, tb, true);
2540 rslt.addCount = _statuses.DistributePosts();
2542 case MyCommon.WORKERTYPE.UserTimeline:
2543 bw.ReportProgress(50, MakeStatusMessage(args, false));
2545 if (SettingDialog.UseAdditionalCount) count = SettingDialog.UserTimelineCountApi;
2546 if (string.IsNullOrEmpty(args.tName))
2548 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2550 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2555 TabClass tb = _statuses.GetTabByName(args.tName);
2558 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2562 rslt.addCount = _statuses.DistributePosts();
2564 case MyCommon.WORKERTYPE.List:
2565 bw.ReportProgress(50, MakeStatusMessage(args, false));
2566 if (string.IsNullOrEmpty(args.tName))
2569 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2571 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2577 TabClass tb = _statuses.GetTabByName(args.tName);
2580 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2584 rslt.addCount = _statuses.DistributePosts();
2587 case MyCommon.WORKERTYPE.Related:
2589 bw.ReportProgress(50, MakeStatusMessage(args, false));
2590 TabClass tab = _statuses.GetTabByName(args.tName);
2591 ret = tw.GetRelatedResult(read, tab);
2592 rslt.addCount = _statuses.DistributePosts();
2596 case MyCommon.WORKERTYPE.BlockIds:
2597 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2600 tw.RefreshBlockIds();
2602 catch (WebApiException ex) { ret = ex.Message; }
2606 if (bw.CancellationPending)
2613 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2615 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2616 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2618 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2620 _favTimestamps.RemoveAt(i);
2624 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2628 DateTime tm = DateTime.Now;
2629 if (_tlTimestamps.ContainsKey(tm))
2630 _tlTimestamps[tm] += rslt.addCount;
2632 _tlTimestamps.Add(tm, rslt.addCount);
2634 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2635 List<DateTime> keys = new List<DateTime>();
2637 foreach (DateTime key in _tlTimestamps.Keys)
2639 if (key.CompareTo(oneHour) < 0)
2645 _tlCount += _tlTimestamps[key];
2648 foreach (DateTime key in keys)
2650 _tlTimestamps.Remove(key);
2657 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2660 rslt.type = args.type;
2661 rslt.tName = args.tName;
2666 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2672 switch (AsyncArg.type)
2674 case MyCommon.WORKERTYPE.Timeline:
2675 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2677 case MyCommon.WORKERTYPE.Reply:
2678 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2680 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2681 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2683 case MyCommon.WORKERTYPE.FavAdd:
2684 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2685 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2687 case MyCommon.WORKERTYPE.FavRemove:
2688 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2689 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2691 case MyCommon.WORKERTYPE.Favorites:
2692 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2694 case MyCommon.WORKERTYPE.PublicSearch:
2695 smsg = "Search refreshing...";
2697 case MyCommon.WORKERTYPE.List:
2698 smsg = "List refreshing...";
2700 case MyCommon.WORKERTYPE.Related:
2701 smsg = "Related refreshing...";
2703 case MyCommon.WORKERTYPE.UserTimeline:
2704 smsg = "UserTimeline refreshing...";
2711 switch (AsyncArg.type)
2713 case MyCommon.WORKERTYPE.Timeline:
2714 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2716 case MyCommon.WORKERTYPE.Reply:
2717 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2719 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2720 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2722 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2723 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2725 case MyCommon.WORKERTYPE.FavAdd:
2728 case MyCommon.WORKERTYPE.FavRemove:
2731 case MyCommon.WORKERTYPE.Favorites:
2732 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2734 case MyCommon.WORKERTYPE.Follower:
2735 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2737 case MyCommon.WORKERTYPE.NoRetweetIds:
2738 smsg = "NoRetweetIds refreshed";
2740 case MyCommon.WORKERTYPE.Configuration:
2743 case MyCommon.WORKERTYPE.PublicSearch:
2744 smsg = "Search refreshed";
2746 case MyCommon.WORKERTYPE.List:
2747 smsg = "List refreshed";
2749 case MyCommon.WORKERTYPE.Related:
2750 smsg = "Related refreshed";
2752 case MyCommon.WORKERTYPE.UserTimeline:
2753 smsg = "UserTimeline refreshed";
2755 case MyCommon.WORKERTYPE.BlockIds:
2756 smsg = Properties.Resources.UpdateBlockUserText3;
2763 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2765 if (MyCommon._endingFlag) return;
2766 if (e.ProgressPercentage > 100)
2769 if (e.ProgressPercentage == 200) //開始
2770 StatusLabel.Text = "Posting...";
2771 if (e.ProgressPercentage == 300) //終了
2772 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2776 string smsg = (string)e.UserState;
2777 if (smsg.Length > 0) StatusLabel.Text = smsg;
2781 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2783 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2785 if (e.Error != null)
2787 _myStatusError = true;
2788 _waitTimeline = false;
2792 _waitPubSearch = false;
2793 _waitUserTimeline = false;
2795 throw new Exception("BackgroundWorker Exception", e.Error);
2798 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2801 if (rslt.retMsg.Length > 0)
2803 _myStatusError = true;
2804 StatusLabel.Text = rslt.retMsg;
2807 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2809 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2811 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2815 //bool busy = false;
2816 //foreach (BackgroundWorker bw in _bw)
2818 // if (bw != null && bw.IsBusy)
2824 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2825 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2826 rslt.type == MyCommon.WORKERTYPE.Reply ||
2827 rslt.type == MyCommon.WORKERTYPE.List ||
2828 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2829 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2830 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2831 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2832 rslt.type == MyCommon.WORKERTYPE.Follower ||
2833 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2834 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2835 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2836 rslt.type == MyCommon.WORKERTYPE.Related ||
2837 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2838 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2839 rslt.type == MyCommon.WORKERTYPE.Configuration)
2841 RefreshTimeline(false); //リスト反映
2846 case MyCommon.WORKERTYPE.Timeline:
2847 _waitTimeline = false;
2850 // //API使用時の取得調整は別途考える(カウント調整?)
2853 case MyCommon.WORKERTYPE.Reply:
2855 if (rslt.newDM && !_initial)
2857 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
2860 case MyCommon.WORKERTYPE.Favorites:
2863 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2866 case MyCommon.WORKERTYPE.FavAdd:
2867 case MyCommon.WORKERTYPE.FavRemove:
2868 if (_curList != null && _curTab != null)
2870 using (ControlTransaction.Update(this._curList))
2872 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2878 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2880 if (_curTab.Text.Equals(rslt.tName))
2882 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2885 PostClass post = null;
2886 TabClass tb = _statuses.Tabs[rslt.tName];
2889 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2891 post = tb.Posts[rslt.sIds[i]];
2895 post = _statuses[rslt.sIds[i]];
2897 ChangeCacheStyleRead(post.IsRead, idx);
2899 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2907 case MyCommon.WORKERTYPE.PostMessage:
2908 if (string.IsNullOrEmpty(rslt.retMsg) ||
2909 rslt.retMsg.StartsWith("OK:") ||
2910 rslt.retMsg == "Warn:Status is a duplicate.")
2912 _postTimestamps.Add(DateTime.Now);
2913 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2914 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2916 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2918 _postTimestamps.RemoveAt(i);
2922 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2924 HashMgr.ClearHashtag();
2925 this.HashStripSplitButton.Text = "#[-]";
2926 this.HashToggleMenuItem.Checked = false;
2927 this.HashToggleToolStripMenuItem.Checked = false;
2929 SetMainWindowTitle();
2937 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
2938 Properties.Resources.StatusUpdateFailed1,
2939 Properties.Resources.StatusUpdateFailed2),
2940 "Failed to update status",
2941 MessageBoxButtons.RetryCancel,
2942 MessageBoxIcon.Question);
2946 retry = DialogResult.Abort;
2948 if (retry == DialogResult.Retry)
2950 GetWorkerArg args = new GetWorkerArg();
2952 args.type = MyCommon.WORKERTYPE.PostMessage;
2953 args.status = rslt.status;
2958 if (ToolStripFocusLockMenuItem.Checked)
2960 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2961 StatusText_Enter(StatusText, new EventArgs());
2965 if (rslt.retMsg.Length == 0 && this._cfgCommon.PostAndGet)
2967 if (_isActiveUserstream)
2969 RefreshTimeline(true);
2973 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2977 case MyCommon.WORKERTYPE.Retweet:
2978 if (rslt.retMsg.Length == 0)
2980 _postTimestamps.Add(DateTime.Now);
2981 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2982 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2984 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2986 _postTimestamps.RemoveAt(i);
2989 if (!_isActiveUserstream && this._cfgCommon.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2992 case MyCommon.WORKERTYPE.Follower:
2993 //_waitFollower = false;
2994 this.PurgeListViewItemCache();
2995 if (_curList != null) _curList.Refresh();
2997 case MyCommon.WORKERTYPE.NoRetweetIds:
2999 case MyCommon.WORKERTYPE.Configuration:
3000 //_waitFollower = false
3001 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
3003 foreach (var service in this.ImageSelector.GetServices())
3005 service.UpdateTwitterConfiguration(this.SettingDialog.TwitterConfiguration);
3008 this.PurgeListViewItemCache();
3009 if (_curList != null) _curList.Refresh();
3011 case MyCommon.WORKERTYPE.PublicSearch:
3012 _waitPubSearch = false;
3014 case MyCommon.WORKERTYPE.UserTimeline:
3015 _waitUserTimeline = false;
3017 case MyCommon.WORKERTYPE.List:
3020 case MyCommon.WORKERTYPE.Related:
3021 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
3022 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3024 foreach (TabPage tp in ListTab.TabPages)
3026 if (tp.Text == tab.TabName)
3028 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3029 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3038 private async Task RefreshMuteUserIdsAsync()
3040 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3044 await tw.RefreshMuteUserIdsAsync();
3046 catch (WebApiException ex)
3048 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3052 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3055 private void RemovePostFromFavTab(Int64[] ids)
3057 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3059 if (_curTab.Text.Equals(favTabName))
3061 if (_curList.FocusedItem != null)
3062 fidx = _curList.FocusedItem.Index;
3063 else if (_curList.TopItem != null)
3064 fidx = _curList.TopItem.Index;
3069 foreach (long i in ids)
3073 _statuses.RemoveFavPost(i);
3080 if (_curTab != null && _curTab.Text.Equals(favTabName))
3082 this.PurgeListViewItemCache();
3084 //_curItemIndex = -1;
3086 foreach (TabPage tp in ListTab.TabPages)
3088 if (tp.Text == favTabName)
3090 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3094 if (_curTab.Text.Equals(favTabName))
3098 _curList.SelectedIndices.Clear();
3100 while (_curList.SelectedIndices.Count > 0);
3102 if (_statuses.Tabs[favTabName].AllCount > 0)
3104 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3106 _curList.SelectedIndices.Add(fidx);
3110 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3112 if (_curList.SelectedIndices.Count > 0)
3114 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3115 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3121 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3123 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, string tabName)
3125 if (!this.IsNetworkAvailable()) return;
3128 GetWorkerArg args = new GetWorkerArg();
3129 args.page = fromPage;
3131 args.tName = tabName;
3133 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3134 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3135 if (period > 1 || period < -1)
3137 lastTime[WkType] = DateTime.Now;
3141 //Timeline取得モードの場合はReplyも同時に取得
3142 //if (!SettingDialog.UseAPI &&
3144 // WkType == MyCommon.WORKERTYPE.Timeline &&
3145 // SettingDialog.CheckReply)
3147 // //TimerReply.Enabled = false;
3148 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3149 // GetWorkerArg _args = new GetWorkerArg();
3150 // _args.page = fromPage;
3151 // _args.endPage = toPage;
3152 // _args.type = MyCommon.WORKERTYPE.Reply;
3157 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3159 if (e.Button == MouseButtons.Left)
3161 this.Visible = true;
3162 if (this.WindowState == FormWindowState.Minimized)
3164 this.WindowState = _formWindowState;
3167 this.BringToFront();
3171 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3173 switch (this._cfgCommon.ListDoubleClickAction)
3176 MakeReplyOrDirectStatus();
3179 FavoriteChange(true);
3182 if (_curPost != null)
3183 ShowUserStatus(_curPost.ScreenName, false);
3189 ShowRelatedStatusesMenuItem_Click(null, null);
3192 MoveToHomeToolStripMenuItem_Click(null, null);
3195 StatusOpenMenuItem_Click(null, null);
3203 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3205 FavoriteChange(true);
3208 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3210 FavoriteChange(false);
3214 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3216 FavoritesRetweetOriginal();
3219 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3221 FavoritesRetweetUnofficial();
3224 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3226 //trueでFavAdd,falseでFavRemove
3227 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3228 || !this.ExistCurrentPost) return;
3231 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3233 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3234 _DoFavRetweetFlags = false;
3237 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3241 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3242 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3243 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3244 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3246 _DoFavRetweetFlags = false;
3252 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3253 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3260 GetWorkerArg args = new GetWorkerArg();
3261 args.ids = new List<long>();
3262 args.sIds = new List<long>();
3263 args.tName = _curTab.Text;
3266 args.type = MyCommon.WORKERTYPE.FavAdd;
3270 args.type = MyCommon.WORKERTYPE.FavRemove;
3272 foreach (int idx in _curList.SelectedIndices)
3274 PostClass post = GetCurTabPost(idx);
3277 if (!post.IsFav) args.ids.Add(post.StatusId);
3281 if (post.IsFav) args.ids.Add(post.StatusId);
3284 if (args.ids.Count == 0)
3287 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3289 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3297 private PostClass GetCurTabPost(int Index)
3299 this.itemCacheLock.EnterReadLock();
3302 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3303 return _postCache[Index - _itemCacheIndex];
3305 finally { this.itemCacheLock.ExitReadLock(); }
3307 return _statuses[_curTab.Text, Index];
3311 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3313 if (_curList.SelectedIndices.Count > 0)
3314 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3315 else if (_curList.SelectedIndices.Count == 0)
3316 OpenUriAsync(MyCommon.TwitterUrl);
3319 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3321 if (_curList.SelectedIndices.Count > 0)
3322 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3325 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3327 if ((!_initialLayout) && this.Visible)
3329 if (this.WindowState == FormWindowState.Normal)
3331 _mySize = this.ClientSize;
3332 _mySpDis = this.SplitContainer1.SplitterDistance;
3333 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3334 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3335 _modifySettingLocal = true;
3340 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3342 if (this._cfgCommon.SortOrderLock) return;
3343 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3346 mode = IdComparerClass.ComparerMode.Id;
3354 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3358 mode = IdComparerClass.ComparerMode.Nickname;
3361 mode = IdComparerClass.ComparerMode.Data;
3364 mode = IdComparerClass.ComparerMode.Id;
3367 mode = IdComparerClass.ComparerMode.Name;
3370 mode = IdComparerClass.ComparerMode.Source;
3374 _statuses.ToggleSortOrder(mode);
3377 DetailsListView list = (DetailsListView)sender;
3380 list.Columns[0].Text = ColumnOrgText[0];
3381 list.Columns[1].Text = ColumnText[2];
3385 for (int i = 0; i <= 7; i++)
3387 list.Columns[i].Text = ColumnOrgText[i];
3389 list.Columns[e.Column].Text = ColumnText[e.Column];
3392 this.PurgeListViewItemCache();
3394 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3396 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3399 SelectListItem(_curList, idx);
3400 _curList.EnsureVisible(idx);
3404 _modifySettingCommon = true;
3407 private void TweenMain_LocationChanged(object sender, EventArgs e)
3409 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3411 _myLoc = this.DesktopLocation;
3412 _modifySettingLocal = true;
3416 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3418 if (ListTab.SelectedTab == null) return;
3419 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3420 if (!this.ExistCurrentPost)
3422 ReplyStripMenuItem.Enabled = false;
3423 ReplyAllStripMenuItem.Enabled = false;
3424 DMStripMenuItem.Enabled = false;
3425 ShowProfileMenuItem.Enabled = false;
3426 ShowUserTimelineContextMenuItem.Enabled = false;
3427 ListManageUserContextToolStripMenuItem2.Enabled = false;
3428 MoveToFavToolStripMenuItem.Enabled = false;
3429 TabMenuItem.Enabled = false;
3430 IDRuleMenuItem.Enabled = false;
3431 ReadedStripMenuItem.Enabled = false;
3432 UnreadStripMenuItem.Enabled = false;
3436 ShowProfileMenuItem.Enabled = true;
3437 ListManageUserContextToolStripMenuItem2.Enabled = true;
3438 ReplyStripMenuItem.Enabled = true;
3439 ReplyAllStripMenuItem.Enabled = true;
3440 DMStripMenuItem.Enabled = true;
3441 ShowUserTimelineContextMenuItem.Enabled = true;
3442 MoveToFavToolStripMenuItem.Enabled = true;
3443 TabMenuItem.Enabled = true;
3444 IDRuleMenuItem.Enabled = true;
3445 ReadedStripMenuItem.Enabled = true;
3446 UnreadStripMenuItem.Enabled = true;
3448 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3449 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3451 FavAddToolStripMenuItem.Enabled = false;
3452 FavRemoveToolStripMenuItem.Enabled = false;
3453 StatusOpenMenuItem.Enabled = false;
3454 FavorareMenuItem.Enabled = false;
3455 ShowRelatedStatusesMenuItem.Enabled = false;
3457 ReTweetStripMenuItem.Enabled = false;
3458 ReTweetOriginalStripMenuItem.Enabled = false;
3459 QuoteStripMenuItem.Enabled = false;
3460 FavoriteRetweetContextMenu.Enabled = false;
3461 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3462 if (this.ExistCurrentPost && _curPost.IsDm)
3463 DeleteStripMenuItem.Enabled = true;
3465 DeleteStripMenuItem.Enabled = false;
3469 FavAddToolStripMenuItem.Enabled = true;
3470 FavRemoveToolStripMenuItem.Enabled = true;
3471 StatusOpenMenuItem.Enabled = true;
3472 FavorareMenuItem.Enabled = true;
3473 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3477 ReTweetOriginalStripMenuItem.Enabled = false;
3478 FavoriteRetweetContextMenu.Enabled = false;
3479 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3481 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3485 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3487 DeleteStripMenuItem.Enabled = true;
3491 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3493 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3497 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3499 DeleteStripMenuItem.Enabled = false;
3500 if (_curPost.IsProtect)
3502 ReTweetOriginalStripMenuItem.Enabled = false;
3503 ReTweetStripMenuItem.Enabled = false;
3504 QuoteStripMenuItem.Enabled = false;
3505 FavoriteRetweetContextMenu.Enabled = false;
3506 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3510 ReTweetOriginalStripMenuItem.Enabled = true;
3511 ReTweetStripMenuItem.Enabled = true;
3512 QuoteStripMenuItem.Enabled = true;
3513 FavoriteRetweetContextMenu.Enabled = true;
3514 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3518 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3520 // RefreshMoreStripMenuItem.Enabled = true;
3524 // RefreshMoreStripMenuItem.Enabled = false;
3526 if (!this.ExistCurrentPost
3527 || _curPost.InReplyToStatusId == null)
3529 RepliedStatusOpenMenuItem.Enabled = false;
3533 RepliedStatusOpenMenuItem.Enabled = true;
3535 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3537 MoveToRTHomeMenuItem.Enabled = false;
3541 MoveToRTHomeMenuItem.Enabled = true;
3545 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3547 MakeReplyOrDirectStatus(false, true);
3550 private void DMStripMenuItem_Click(object sender, EventArgs e)
3552 MakeReplyOrDirectStatus(false, false);
3555 private void doStatusDelete()
3557 if (_curTab == null || _curList == null) return;
3558 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3560 bool myPost = false;
3561 foreach (int idx in _curList.SelectedIndices)
3563 if (GetCurTabPost(idx).IsMe ||
3564 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3570 if (!myPost) return;
3574 if (_curList.SelectedIndices.Count == 0)
3578 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3580 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3581 MessageBoxButtons.OKCancel,
3582 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3585 if (_curList.FocusedItem != null)
3586 fidx = _curList.FocusedItem.Index;
3587 else if (_curList.TopItem != null)
3588 fidx = _curList.TopItem.Index;
3594 this.Cursor = Cursors.WaitCursor;
3597 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3600 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3602 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3606 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3607 rtn = tw.RemoveStatus(Id);
3618 _statuses.RemovePost(Id);
3623 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3625 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3627 this.PurgeListViewItemCache();
3630 foreach (TabPage tb in ListTab.TabPages)
3632 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3633 if (_curTab.Equals(tb))
3637 _curList.SelectedIndices.Clear();
3639 while (_curList.SelectedIndices.Count > 0);
3641 if (_statuses.Tabs[tb.Text].AllCount > 0)
3643 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3644 _curList.SelectedIndices.Add(fidx);
3646 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3648 if (_curList.SelectedIndices.Count > 0)
3650 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3651 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3655 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3657 if (SettingDialog.TabIconDisp)
3659 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3663 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3667 this.Cursor = Cursors.Default;
3671 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3676 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3678 using (ControlTransaction.Update(this._curList))
3680 if (this._cfgCommon.UnreadManage)
3682 foreach (int idx in _curList.SelectedIndices)
3684 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3687 foreach (int idx in _curList.SelectedIndices)
3689 ChangeCacheStyleRead(true, idx);
3693 foreach (TabPage tb in ListTab.TabPages)
3695 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3697 if (SettingDialog.TabIconDisp)
3699 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3703 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3706 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3708 using (ControlTransaction.Update(this._curList))
3710 if (this._cfgCommon.UnreadManage)
3712 foreach (int idx in _curList.SelectedIndices)
3714 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3717 foreach (int idx in _curList.SelectedIndices)
3719 ChangeCacheStyleRead(false, idx);
3723 foreach (TabPage tb in ListTab.TabPages)
3725 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3727 if (SettingDialog.TabIconDisp)
3729 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3733 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
3736 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3741 private void DoRefresh()
3743 if (_curTab != null)
3745 switch (_statuses.Tabs[_curTab.Text].TabType)
3747 case MyCommon.TabUsageType.Mentions:
3748 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
3750 case MyCommon.TabUsageType.DirectMessage:
3751 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
3753 case MyCommon.TabUsageType.Favorites:
3754 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
3756 //case MyCommon.TabUsageType.Profile:
3758 case MyCommon.TabUsageType.PublicSearch:
3760 TabClass tb = _statuses.Tabs[_curTab.Text];
3761 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3762 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, _curTab.Text);
3764 case MyCommon.TabUsageType.UserTimeline:
3765 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, _curTab.Text);
3767 case MyCommon.TabUsageType.Lists:
3769 TabClass tab = _statuses.Tabs[_curTab.Text];
3770 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3771 GetTimeline(MyCommon.WORKERTYPE.List, 1, _curTab.Text);
3774 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3780 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3784 private void DoRefreshMore()
3787 if (_curTab != null)
3789 switch (_statuses.Tabs[_curTab.Text].TabType)
3791 case MyCommon.TabUsageType.Mentions:
3792 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
3794 case MyCommon.TabUsageType.DirectMessage:
3795 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
3797 case MyCommon.TabUsageType.Favorites:
3798 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, "");
3800 case MyCommon.TabUsageType.Profile:
3803 case MyCommon.TabUsageType.PublicSearch:
3805 TabClass tb = _statuses.Tabs[_curTab.Text];
3806 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3807 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, _curTab.Text);
3809 case MyCommon.TabUsageType.UserTimeline:
3810 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, _curTab.Text);
3812 case MyCommon.TabUsageType.Lists:
3814 TabClass tab = _statuses.Tabs[_curTab.Text];
3815 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3816 GetTimeline(MyCommon.WORKERTYPE.List, -1, _curTab.Text);
3819 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3825 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3829 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3831 DialogResult result;
3832 string uid = tw.Username.ToLower();
3836 result = SettingDialog.ShowDialog(this);
3843 if (result == DialogResult.OK)
3847 var oldIconSz = this._cfgCommon.IconSize;
3849 this.SettingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3851 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3852 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3853 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3854 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3855 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3856 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3858 Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut);
3859 Networking.SetWebProxy(this.SettingDialog.SelectedProxyType,
3860 this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort,
3861 this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword);
3863 ImageSelector.Reset(tw, SettingDialog.TwitterConfiguration);
3867 if (SettingDialog.TabIconDisp)
3869 ListTab.DrawItem -= ListTab_DrawItem;
3870 ListTab.DrawMode = TabDrawMode.Normal;
3871 ListTab.ImageList = this.TabImage;
3875 ListTab.DrawItem -= ListTab_DrawItem;
3876 ListTab.DrawItem += ListTab_DrawItem;
3877 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3878 ListTab.ImageList = null;
3881 catch (Exception ex)
3883 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3884 ex.Data["IsTerminatePermission"] = false;
3890 if (!this._cfgCommon.UnreadManage)
3892 ReadedStripMenuItem.Enabled = false;
3893 UnreadStripMenuItem.Enabled = false;
3894 if (SettingDialog.TabIconDisp)
3896 foreach (TabPage myTab in ListTab.TabPages)
3898 myTab.ImageIndex = -1;
3904 ReadedStripMenuItem.Enabled = true;
3905 UnreadStripMenuItem.Enabled = true;
3908 catch (Exception ex)
3910 ex.Data["Instance"] = "ListTab(UnreadManage)";
3911 ex.Data["IsTerminatePermission"] = false;
3918 SplitContainer1.IsPanelInverted = !SettingDialog.StatusAreaAtBottom;
3920 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3921 imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3922 imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3924 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3925 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3926 _fntUnread = this._cfgLocal.FontUnread;
3927 _clUnread = this._cfgLocal.ColorUnread;
3928 _fntReaded = this._cfgLocal.FontRead;
3929 _clReaded = this._cfgLocal.ColorRead;
3930 _clFav = this._cfgLocal.ColorFav;
3931 _clOWL = this._cfgLocal.ColorOWL;
3932 _clRetweet = this._cfgLocal.ColorRetweet;
3933 _fntDetail = this._cfgLocal.FontDetail;
3934 _clDetail = this._cfgLocal.ColorDetail;
3935 _clDetailLink = this._cfgLocal.ColorDetailLink;
3936 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3937 _clSelf = this._cfgLocal.ColorSelf;
3938 _clAtSelf = this._cfgLocal.ColorAtSelf;
3939 _clTarget = this._cfgLocal.ColorTarget;
3940 _clAtTarget = this._cfgLocal.ColorAtTarget;
3941 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3942 _clAtTo = this._cfgLocal.ColorAtTo;
3943 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3944 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3945 _clInputFont = this._cfgLocal.ColorInputFont;
3946 _fntInputFont = this._cfgLocal.FontInputFont;
3947 _brsBackColorMine.Dispose();
3948 _brsBackColorAt.Dispose();
3949 _brsBackColorYou.Dispose();
3950 _brsBackColorAtYou.Dispose();
3951 _brsBackColorAtFromTarget.Dispose();
3952 _brsBackColorAtTo.Dispose();
3953 _brsBackColorNone.Dispose();
3954 _brsBackColorMine = new SolidBrush(_clSelf);
3955 _brsBackColorAt = new SolidBrush(_clAtSelf);
3956 _brsBackColorYou = new SolidBrush(_clTarget);
3957 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3958 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3959 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3960 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3964 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3965 StatusText.Font = _fntInputFont;
3966 StatusText.ForeColor = _clInputFont;
3968 catch (Exception ex)
3970 MessageBox.Show(ex.Message);
3975 InitDetailHtmlFormat();
3977 catch (Exception ex)
3979 ex.Data["Instance"] = "Font";
3980 ex.Data["IsTerminatePermission"] = false;
3986 _statuses.SetUnreadManage(this._cfgCommon.UnreadManage);
3988 catch (Exception ex)
3990 ex.Data["Instance"] = "_statuses";
3991 ex.Data["IsTerminatePermission"] = false;
3997 foreach (TabPage tb in ListTab.TabPages)
3999 if (SettingDialog.TabIconDisp)
4001 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4008 catch (Exception ex)
4010 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4011 ex.Data["IsTerminatePermission"] = false;
4017 var oldIconCol = _iconCol;
4019 if (this._cfgCommon.IconSize != oldIconSz)
4020 ApplyListViewIconSize(this._cfgCommon.IconSize);
4022 foreach (TabPage tp in ListTab.TabPages)
4024 DetailsListView lst = (DetailsListView)tp.Tag;
4026 using (ControlTransaction.Update(lst))
4028 lst.GridLines = this._cfgCommon.ShowGrid;
4029 lst.Font = _fntReaded;
4030 lst.BackColor = _clListBackcolor;
4032 if (_iconCol != oldIconCol)
4037 catch (Exception ex)
4039 ex.Data["Instance"] = "ListView(IconSize)";
4040 ex.Data["IsTerminatePermission"] = false;
4044 SetMainWindowTitle();
4045 SetNotifyIconText();
4047 this.PurgeListViewItemCache();
4048 if (_curList != null) _curList.Refresh();
4051 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4052 if (this._cfgCommon.HotkeyEnabled)
4054 ///グローバルホットキーの登録。設定で変更可能にするかも
4055 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4056 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4057 modKey |= HookGlobalHotkey.ModKeys.Alt;
4058 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4059 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4060 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4061 modKey |= HookGlobalHotkey.ModKeys.Shift;
4062 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4063 modKey |= HookGlobalHotkey.ModKeys.Win;
4065 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4068 if (uid != tw.Username) this.doGetFollowersMenu();
4070 if (SettingDialog.IsNotifyUseGrowl) gh.RegisterGrowl();
4073 StatusText_TextChanged(null, null);
4081 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4083 this.TopMost = SettingDialog.AlwaysTop;
4084 SaveConfigsAll(false);
4090 private void SetTabAlignment()
4092 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4093 if (ListTab.Alignment == newAlignment) return;
4096 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
4097 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
4098 SaveSelectedStatus(selId, focusedId);
4100 ListTab.Alignment = newAlignment;
4103 foreach (TabPage tab in ListTab.TabPages)
4105 DetailsListView lst = (DetailsListView)tab.Tag;
4106 TabClass tabInfo = _statuses.Tabs[tab.Text];
4107 using (ControlTransaction.Update(lst))
4109 this.SelectListItem(lst,
4110 tabInfo.IndexOf(selId[tab.Text]),
4111 tabInfo.IndexOf(focusedId[tab.Text]));
4116 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4122 case MyCommon.IconSizes.IconNone:
4125 case MyCommon.IconSizes.Icon16:
4128 case MyCommon.IconSizes.Icon24:
4131 case MyCommon.IconSizes.Icon48:
4134 case MyCommon.IconSizes.Icon48_2:
4142 // ディスプレイの DPI 設定を考慮したサイズを設定する
4143 _listViewImageList.ImageSize = new Size(
4145 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4149 _listViewImageList.ImageSize = new Size(1, 1);
4153 private void ResetColumns(DetailsListView list)
4155 using (ControlTransaction.Update(list))
4156 using (ControlTransaction.Layout(list, false))
4159 list.ColumnClick -= MyList_ColumnClick;
4160 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4161 list.ColumnReordered -= MyList_ColumnReordered;
4162 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4164 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4165 list.Columns.Clear();
4166 cols.ForEach(col => col.Dispose());
4169 InitColumns(list, true);
4171 list.ColumnClick += MyList_ColumnClick;
4172 list.DrawColumnHeader += MyList_DrawColumnHeader;
4173 list.ColumnReordered += MyList_ColumnReordered;
4174 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4178 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4180 if (e.Url.AbsoluteUri != "about:blank")
4183 OpenUriAsync(e.Url.OriginalString);
4187 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4189 if (e.Url.Scheme == "data")
4191 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4193 else if (e.Url.AbsoluteUri != "about:blank")
4197 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4198 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4201 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4202 int i = urlStr.IndexOf('#');
4203 if (i == -1) return;
4205 string hash = urlStr.Substring(i);
4206 HashSupl.AddItem(hash);
4207 HashMgr.AddHashToHistory(hash.Trim(), false);
4208 AddNewTabForSearch(hash);
4213 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4214 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4216 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4217 if (this._cfgCommon.OpenUserTimeline)
4219 if (MyCommon.IsKeyDown(Keys.Control))
4220 OpenUriAsync(e.Url.OriginalString);
4222 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4226 if (MyCommon.IsKeyDown(Keys.Control))
4227 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4229 OpenUriAsync(e.Url.OriginalString);
4234 OpenUriAsync(e.Url.OriginalString);
4240 public void AddNewTabForSearch(string searchWord)
4242 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4243 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4245 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4247 foreach (TabPage tp in ListTab.TabPages)
4249 if (tb.TabName == tp.Text)
4251 ListTab.SelectedTab = tp;
4258 string tabName = searchWord;
4259 for (int i = 0; i <= 100; i++)
4261 if (_statuses.ContainsTab(tabName))
4267 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4268 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4270 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4272 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4273 cmb.Items.Add(searchWord);
4274 cmb.Text = searchWord;
4277 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4280 private void ShowUserTimeline()
4282 if (!this.ExistCurrentPost) return;
4283 AddNewTabForUserTimeline(_curPost.ScreenName);
4286 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4288 if (e.KeyCode == Keys.Escape)
4290 TabPage relTp = ListTab.SelectedTab;
4291 RemoveSpecifiedTab(relTp.Text, false);
4293 e.SuppressKeyPress = true;
4297 public void AddNewTabForUserTimeline(string user)
4299 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4300 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4302 if (tb.User == user)
4304 foreach (TabPage tp in ListTab.TabPages)
4306 if (tb.TabName == tp.Text)
4308 ListTab.SelectedTab = tp;
4315 string tabName = "user:" + user;
4316 while (_statuses.ContainsTab(tabName))
4321 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4322 _statuses.Tabs[tabName].User = user;
4323 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4325 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4329 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, tabName);
4332 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4335 foreach (TabPage tb in ListTab.TabPages)
4337 if (tb.Text == tabName) return false;
4341 if (tabName == Properties.Resources.AddNewTabText1) return false;
4346 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4347 tabType == MyCommon.TabUsageType.Favorites ||
4348 tabType == MyCommon.TabUsageType.Home ||
4349 tabType == MyCommon.TabUsageType.Mentions ||
4350 tabType == MyCommon.TabUsageType.Related)
4352 if (_statuses.GetTabByType(tabType) != null) return false;
4356 TabPage _tabPage = new TabPage();
4357 DetailsListView _listCustom = new DetailsListView();
4359 int cnt = ListTab.TabPages.Count;
4361 ///ToDo:Create and set controls follow tabtypes
4363 using (ControlTransaction.Update(_listCustom))
4364 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4365 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4366 using (ControlTransaction.Layout(this.SplitContainer1, false))
4367 using (ControlTransaction.Layout(this.ListTab, false))
4368 using (ControlTransaction.Layout(this))
4369 using (ControlTransaction.Layout(_tabPage, false))
4373 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4375 label = new Label();
4376 label.Dock = DockStyle.Top;
4377 label.Name = "labelUser";
4378 if (tabType == MyCommon.TabUsageType.Lists)
4380 label.Text = listInfo.ToString();
4384 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4386 label.TextAlign = ContentAlignment.MiddleLeft;
4387 using (ComboBox tmpComboBox = new ComboBox())
4389 label.Height = tmpComboBox.Height;
4391 _tabPage.Controls.Add(label);
4396 if (tabType == MyCommon.TabUsageType.PublicSearch)
4400 Label lbl = new Label();
4401 ComboBox cmb = new ComboBox();
4402 Button btn = new Button();
4403 ComboBox cmbLang = new ComboBox();
4405 pnl.SuspendLayout();
4407 pnl.Controls.Add(cmb);
4408 pnl.Controls.Add(cmbLang);
4409 pnl.Controls.Add(btn);
4410 pnl.Controls.Add(lbl);
4411 pnl.Name = "panelSearch";
4412 pnl.Dock = DockStyle.Top;
4413 pnl.Height = cmb.Height;
4414 pnl.Enter += SearchControls_Enter;
4415 pnl.Leave += SearchControls_Leave;
4418 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4419 cmb.Dock = DockStyle.Fill;
4420 cmb.Name = "comboSearch";
4421 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4422 cmb.ImeMode = ImeMode.NoControl;
4423 cmb.TabStop = false;
4424 cmb.AutoCompleteMode = AutoCompleteMode.None;
4425 cmb.KeyDown += SearchComboBox_KeyDown;
4427 if (_statuses.ContainsTab(tabName))
4429 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4430 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4434 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4435 cmbLang.Dock = DockStyle.Right;
4437 cmbLang.Name = "comboLang";
4438 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4439 cmbLang.TabStop = false;
4440 cmbLang.Items.Add("");
4441 cmbLang.Items.Add("ja");
4442 cmbLang.Items.Add("en");
4443 cmbLang.Items.Add("ar");
4444 cmbLang.Items.Add("da");
4445 cmbLang.Items.Add("nl");
4446 cmbLang.Items.Add("fa");
4447 cmbLang.Items.Add("fi");
4448 cmbLang.Items.Add("fr");
4449 cmbLang.Items.Add("de");
4450 cmbLang.Items.Add("hu");
4451 cmbLang.Items.Add("is");
4452 cmbLang.Items.Add("it");
4453 cmbLang.Items.Add("no");
4454 cmbLang.Items.Add("pl");
4455 cmbLang.Items.Add("pt");
4456 cmbLang.Items.Add("ru");
4457 cmbLang.Items.Add("es");
4458 cmbLang.Items.Add("sv");
4459 cmbLang.Items.Add("th");
4460 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4462 lbl.Text = "Search(C-S-f)";
4463 lbl.Name = "label1";
4464 lbl.Dock = DockStyle.Left;
4466 lbl.Height = cmb.Height;
4467 lbl.TextAlign = ContentAlignment.MiddleLeft;
4469 btn.Text = "Search";
4470 btn.Name = "buttonSearch";
4471 btn.UseVisualStyleBackColor = true;
4472 btn.Dock = DockStyle.Right;
4473 btn.TabStop = false;
4474 btn.Click += SearchButton_Click;
4477 this.ListTab.Controls.Add(_tabPage);
4478 _tabPage.Controls.Add(_listCustom);
4480 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4481 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4483 _tabPage.Location = new Point(4, 4);
4484 _tabPage.Name = "CTab" + cnt.ToString();
4485 _tabPage.Size = new Size(380, 260);
4486 _tabPage.TabIndex = 2 + cnt;
4487 _tabPage.Text = tabName;
4488 _tabPage.UseVisualStyleBackColor = true;
4490 _listCustom.AllowColumnReorder = true;
4491 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4492 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4493 _listCustom.Dock = DockStyle.Fill;
4494 _listCustom.FullRowSelect = true;
4495 _listCustom.HideSelection = false;
4496 _listCustom.Location = new Point(0, 0);
4497 _listCustom.Margin = new Padding(0);
4498 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4499 _listCustom.ShowItemToolTips = true;
4500 _listCustom.Size = new Size(380, 260);
4501 _listCustom.UseCompatibleStateImageBehavior = false;
4502 _listCustom.View = View.Details;
4503 _listCustom.OwnerDraw = true;
4504 _listCustom.VirtualMode = true;
4505 _listCustom.Font = _fntReaded;
4506 _listCustom.BackColor = _clListBackcolor;
4508 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4509 _listCustom.AllowDrop = true;
4511 _listCustom.SmallImageList = _listViewImageList;
4513 InitColumns(_listCustom, startup);
4515 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4516 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4517 _listCustom.ColumnClick += MyList_ColumnClick;
4518 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4519 _listCustom.DragDrop += TweenMain_DragDrop;
4520 _listCustom.DragEnter += TweenMain_DragEnter;
4521 _listCustom.DragOver += TweenMain_DragOver;
4522 _listCustom.DrawItem += MyList_DrawItem;
4523 _listCustom.MouseClick += MyList_MouseClick;
4524 _listCustom.ColumnReordered += MyList_ColumnReordered;
4525 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4526 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4527 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4528 _listCustom.DrawSubItem += MyList_DrawSubItem;
4529 _listCustom.HScrolled += MyList_HScrolled;
4531 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4534 _tabPage.Tag = _listCustom;
4538 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4540 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4544 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4545 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4546 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4552 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4553 if (_tabPage == null) return false;
4555 SetListProperty(); //他のタブに列幅等を反映
4557 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4560 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4561 _tabPage.Tag = null;
4563 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4564 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4565 using (ControlTransaction.Layout(this.SplitContainer1, false))
4566 using (ControlTransaction.Layout(this.ListTab, false))
4567 using (ControlTransaction.Layout(this))
4568 using (ControlTransaction.Layout(_tabPage, false))
4570 if (this.ListTab.SelectedTab == _tabPage)
4572 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4573 this._beforeSelectedTab = null;
4575 this.ListTab.Controls.Remove(_tabPage);
4578 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4580 using (Control label = _tabPage.Controls["labelUser"])
4582 _tabPage.Controls.Remove(label);
4585 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4587 using (Control pnl = _tabPage.Controls["panelSearch"])
4589 pnl.Enter -= SearchControls_Enter;
4590 pnl.Leave -= SearchControls_Leave;
4591 _tabPage.Controls.Remove(pnl);
4593 foreach (Control ctrl in pnl.Controls)
4595 if (ctrl.Name == "buttonSearch")
4597 ctrl.Click -= SearchButton_Click;
4599 else if (ctrl.Name == "comboSearch")
4601 ctrl.KeyDown -= SearchComboBox_KeyDown;
4603 pnl.Controls.Remove(ctrl);
4609 _tabPage.Controls.Remove(_listCustom);
4611 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4612 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4613 _listCustom.ColumnClick -= MyList_ColumnClick;
4614 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4615 _listCustom.DragDrop -= TweenMain_DragDrop;
4616 _listCustom.DragEnter -= TweenMain_DragEnter;
4617 _listCustom.DragOver -= TweenMain_DragOver;
4618 _listCustom.DrawItem -= MyList_DrawItem;
4619 _listCustom.MouseClick -= MyList_MouseClick;
4620 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4621 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4622 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4623 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4624 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4625 _listCustom.HScrolled -= MyList_HScrolled;
4627 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4628 _listCustom.Columns.Clear();
4629 cols.ForEach(col => col.Dispose());
4632 _listCustom.ContextMenuStrip = null;
4633 _listCustom.ColumnHeaderContextMenuStrip = null;
4634 _listCustom.Font = null;
4636 _listCustom.SmallImageList = null;
4637 _listCustom.ListViewItemSorter = null;
4640 if (_curTab.Equals(_tabPage))
4647 this.PurgeListViewItemCache();
4651 _listCustom.Dispose();
4652 _statuses.RemoveTab(TabName);
4654 foreach (TabPage tp in ListTab.TabPages)
4656 DetailsListView lst = (DetailsListView)tp.Tag;
4657 var count = _statuses.Tabs[tp.Text].AllCount;
4658 if (lst.VirtualListSize != count)
4660 lst.VirtualListSize = count;
4667 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4669 this.PurgeListViewItemCache();
4670 _beforeSelectedTab = e.TabPage;
4673 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4677 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4680 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4681 if (!dragEnableRectangle.Contains(e.Location))
4683 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4684 tn = ListTab.SelectedTab.Text;
4687 if (string.IsNullOrEmpty(tn)) return;
4689 foreach (TabPage tb in ListTab.TabPages)
4693 ListTab.DoDragDrop(tb, DragDropEffects.All);
4703 Point cpos = new Point(e.X, e.Y);
4704 for (int i = 0; i < ListTab.TabPages.Count; i++)
4706 Rectangle rect = ListTab.GetTabRect(i);
4707 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4708 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4710 _rclickTabName = ListTab.TabPages[i].Text;
4716 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4718 //_curList.Refresh();
4720 SetMainWindowTitle();
4721 SetStatusLabelUrl();
4722 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4723 TabMenuControl(ListTab.SelectedTab.Text);
4724 this.PushSelectPostChain();
4727 private void SetListProperty()
4729 //削除などで見つからない場合は処理せず
4730 if (_curList == null) return;
4731 if (!_isColumnChanged) return;
4733 int[] dispOrder = new int[_curList.Columns.Count];
4734 for (int i = 0; i < _curList.Columns.Count; i++)
4736 for (int j = 0; j < _curList.Columns.Count; j++)
4738 if (_curList.Columns[j].DisplayIndex == i)
4747 foreach (TabPage tb in ListTab.TabPages)
4749 if (!tb.Equals(_curTab))
4751 if (tb.Tag != null && tb.Controls.Count > 0)
4753 DetailsListView lst = (DetailsListView)tb.Tag;
4754 for (int i = 0; i < lst.Columns.Count; i++)
4756 lst.Columns[dispOrder[i]].DisplayIndex = i;
4757 lst.Columns[i].Width = _curList.Columns[i].Width;
4763 _isColumnChanged = false;
4766 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4770 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4771 || PostBrowser.StatusText.StartsWith("data"))
4773 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4775 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4777 SetStatusLabelUrl();
4785 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4787 if (e.KeyChar == '@')
4789 if (!this._cfgCommon.UseAtIdSupplement) return;
4791 int cnt = AtIdSupl.ItemCount;
4792 ShowSuplDialog(StatusText, AtIdSupl);
4793 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4796 else if (e.KeyChar == '#')
4798 if (!this._cfgCommon.UseHashSupplement) return;
4799 ShowSuplDialog(StatusText, HashSupl);
4804 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4806 ShowSuplDialog(owner, dialog, 0, "");
4809 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4811 ShowSuplDialog(owner, dialog, offset, "");
4814 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4816 dialog.StartsWith = startswith;
4823 dialog.ShowDialog();
4825 this.TopMost = SettingDialog.AlwaysTop;
4826 int selStart = owner.SelectionStart;
4829 if (dialog.DialogResult == DialogResult.OK)
4831 if (!string.IsNullOrEmpty(dialog.inputText))
4835 fHalf = owner.Text.Substring(0, selStart - offset);
4837 if (selStart < owner.Text.Length)
4839 eHalf = owner.Text.Substring(selStart);
4841 owner.Text = fHalf + dialog.inputText + eHalf;
4842 owner.SelectionStart = selStart + dialog.inputText.Length;
4849 fHalf = owner.Text.Substring(0, selStart);
4851 if (selStart < owner.Text.Length)
4853 eHalf = owner.Text.Substring(selStart);
4855 owner.Text = fHalf + eHalf;
4858 owner.SelectionStart = selStart;
4864 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4867 if (!e.Alt && !e.Control && !e.Shift)
4869 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4871 bool isSpace = false;
4872 foreach (char c in StatusText.Text.ToCharArray())
4874 if (c == ' ' || c == ' ')
4887 StatusText.Text = "";
4888 JumpUnreadMenuItem_Click(null, null);
4892 this.StatusText_TextChanged(null, null);
4895 private void StatusText_TextChanged(object sender, EventArgs e)
4898 int pLen = GetRestStatusCount(true, false);
4899 lblLen.Text = pLen.ToString();
4902 StatusText.ForeColor = Color.Red;
4906 StatusText.ForeColor = _clInputFont;
4908 if (string.IsNullOrEmpty(StatusText.Text))
4910 _reply_to_id = null;
4911 _reply_to_name = null;
4915 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4918 var statusText = this.StatusText.Text;
4919 statusText = statusText.Replace("\r\n", "\n");
4921 int pLen = 140 - statusText.Length;
4922 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4923 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && this._cfgCommon.PostShiftEnter) ||
4924 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !this._cfgCommon.PostShiftEnter) ||
4925 (!isAuto && isAddFooter))
4927 if (this._cfgLocal.UseRecommendStatus)
4928 pLen -= SettingDialog.RecommendStatusText.Length;
4929 else if (this._cfgLocal.StatusText.Length > 0)
4930 pLen -= this._cfgLocal.StatusText.Length + 1;
4932 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4934 pLen -= HashMgr.UseHash.Length + 1;
4936 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4938 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4940 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4942 string before = m.Result("${before}");
4943 string url = m.Result("${url}");
4944 string protocol = m.Result("${protocol}");
4945 string domain = m.Result("${domain}");
4946 string path = m.Result("${path}");
4947 if (protocol.Length == 0)
4949 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4954 bool last_url_invalid_match = false;
4955 string lasturl = null;
4956 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4958 lasturl = mm.ToString();
4959 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4960 if (!last_url_invalid_match)
4962 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4966 if (path.Length != 0)
4968 if (last_url_invalid_match)
4970 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4972 pLen += path.Length;
4977 int shortUrlLength = protocol == "https://"
4978 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
4979 : SettingDialog.TwitterConfiguration.ShortUrlLength;
4981 pLen += url.Length - shortUrlLength;
4984 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
4986 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4989 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
4991 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
4996 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4998 this.itemCacheLock.EnterUpgradeableReadLock();
5001 if (_curList.Equals(sender))
5003 if (_itemCache != null &&
5004 e.StartIndex >= _itemCacheIndex &&
5005 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5007 //If the newly requested cache is a subset of the old cache,
5008 //no need to rebuild everything, so do nothing.
5012 //Now we need to rebuild the cache.
5013 CreateCache(e.StartIndex, e.EndIndex);
5016 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5019 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5021 ListViewItem item = null;
5022 PostClass cacheItemPost = null;
5024 if (_curList.Equals(sender))
5025 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5029 //A cache miss, so create a new ListViewItem and pass it back.
5030 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5033 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5038 string[] sitem = {"", "", "", "", "", "", "", ""};
5039 item = new ImageListViewItem(sitem);
5043 // e.Item に値をセットする前に await しないこと
5046 await ((ImageListViewItem)item).GetImageAsync();
5049 private void CreateCache(int StartIndex, int EndIndex)
5051 this.itemCacheLock.EnterWriteLock();
5054 var tabInfo = _statuses.Tabs[_curTab.Text];
5056 //キャッシュ要求(要求範囲±30を作成)
5058 if (StartIndex < 0) StartIndex = 0;
5060 if (EndIndex >= tabInfo.AllCount) EndIndex = tabInfo.AllCount - 1;
5061 _postCache = tabInfo[StartIndex, EndIndex]; //配列で取得
5062 _itemCacheIndex = StartIndex;
5064 _itemCache = new ListViewItem[0] {};
5065 Array.Resize(ref _itemCache, _postCache.Length);
5067 for (int i = 0; i < _postCache.Length; i++)
5069 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5074 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5076 _itemCacheIndex = -1;
5079 finally { this.itemCacheLock.ExitWriteLock(); }
5083 /// DetailsListView のための ListViewItem のキャッシュを消去する
5085 private void PurgeListViewItemCache()
5087 this.itemCacheLock.EnterWriteLock();
5090 this._itemCache = null;
5091 this._itemCacheIndex = -1;
5092 this._postCache = null;
5094 finally { this.itemCacheLock.ExitWriteLock(); }
5097 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5099 this.itemCacheLock.EnterReadLock();
5102 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5104 item = this._itemCache[index - _itemCacheIndex];
5105 post = this._postCache[index - _itemCacheIndex];
5109 finally { this.itemCacheLock.ExitReadLock(); }
5116 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5118 StringBuilder mk = new StringBuilder();
5119 //if (Post.IsDeleted) mk.Append("×");
5120 //if (Post.IsMark) mk.Append("♪");
5121 //if (Post.IsProtect) mk.Append("Ю");
5122 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5123 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5124 ImageListViewItem itm;
5125 if (Post.RetweetedId == null)
5127 string[] sitem= {"",
5129 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5130 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5135 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5139 string[] sitem = {"",
5141 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5142 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5143 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5147 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5149 itm.StateIndex = Post.StateIndex;
5151 bool read = Post.IsRead;
5152 //未読管理していなかったら既読として扱う
5153 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5154 ChangeItemStyleRead(read, itm, Post, null);
5155 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5160 /// 全てのタブの振り分けルールを反映し直します
5162 private void ApplyPostFilters()
5166 this.Cursor = Cursors.WaitCursor;
5168 this.PurgeListViewItemCache();
5169 this._curPost = null;
5170 this._curItemIndex = -1;
5171 this._statuses.FilterAll();
5173 foreach (TabPage tabPage in this.ListTab.TabPages)
5175 var tab = this._statuses.Tabs[tabPage.Text];
5177 var listview = (DetailsListView)tabPage.Tag;
5178 listview.VirtualListSize = tab.AllCount;
5180 if (this.SettingDialog.TabIconDisp)
5182 if (tab.UnreadCount > 0)
5183 tabPage.ImageIndex = 0;
5185 tabPage.ImageIndex = -1;
5189 if (!this.SettingDialog.TabIconDisp)
5190 this.ListTab.Refresh();
5194 this.Cursor = Cursors.Default;
5198 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5200 e.DrawDefault = true;
5203 private void MyList_HScrolled(object sender, EventArgs e)
5205 DetailsListView listView = (DetailsListView)sender;
5209 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5211 if (e.State == 0) return;
5212 e.DrawDefault = false;
5214 SolidBrush brs2 = null;
5215 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5217 if (e.Item.BackColor == _clSelf)
5218 brs2 = _brsBackColorMine;
5219 else if (e.Item.BackColor == _clAtSelf)
5220 brs2 = _brsBackColorAt;
5221 else if (e.Item.BackColor == _clTarget)
5222 brs2 = _brsBackColorYou;
5223 else if (e.Item.BackColor == _clAtTarget)
5224 brs2 = _brsBackColorAtYou;
5225 else if (e.Item.BackColor == _clAtFromTarget)
5226 brs2 = _brsBackColorAtFromTarget;
5227 else if (e.Item.BackColor == _clAtTo)
5228 brs2 = _brsBackColorAtTo;
5230 brs2 = _brsBackColorNone;
5235 if (((Control)sender).Focused)
5236 brs2 = _brsHighLight;
5238 brs2 = _brsDeactiveSelection;
5240 e.Graphics.FillRectangle(brs2, e.Bounds);
5241 e.DrawFocusRectangle();
5242 this.DrawListViewItemIcon(e);
5245 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5247 if (e.ItemState == 0) return;
5249 if (e.ColumnIndex > 0)
5252 RectangleF rct = e.Bounds;
5253 rct.Width = e.Header.Width;
5254 int fontHeight = e.Item.Font.Height;
5257 rct.Y += fontHeight;
5258 rct.Height -= fontHeight;
5262 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5264 //if (heightDiff > fontHeight * 0.7)
5266 // rct.Height += fontHeight;
5267 // drawLineCount += 1;
5270 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5271 if (!_iconCol && drawLineCount <= 1)
5273 //rct.Inflate(0, heightDiff / -2);
5274 //rct.Height += fontHeight / 2;
5276 else if (heightDiff < fontHeight * 0.7)
5278 //最終行が70%以上欠けていたら、最終行は表示しない
5279 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5280 rct.Height = (fontHeight * drawLineCount) - 1;
5287 //if (!_iconCol && drawLineCount > 1)
5289 // rct.Y += fontHeight * 0.2;
5290 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5295 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5296 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5301 Rectangle rctB = e.Bounds;
5302 rctB.Width = e.Header.Width;
5303 rctB.Height = fontHeight;
5305 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5307 TextRenderer.DrawText(e.Graphics,
5308 e.Item.SubItems[2].Text,
5310 Rectangle.Round(rct),
5312 TextFormatFlags.WordBreak |
5313 TextFormatFlags.EndEllipsis |
5314 TextFormatFlags.GlyphOverhangPadding |
5315 TextFormatFlags.NoPrefix);
5316 TextRenderer.DrawText(e.Graphics,
5317 e.Item.SubItems[4].Text + " / " + e.Item.SubItems[1].Text + " (" + e.Item.SubItems[3].Text + ") " + e.Item.SubItems[5].Text + e.Item.SubItems[6].Text + " [" + e.Item.SubItems[7].Text + "]",
5321 TextFormatFlags.SingleLine |
5322 TextFormatFlags.EndEllipsis |
5323 TextFormatFlags.GlyphOverhangPadding |
5324 TextFormatFlags.NoPrefix);
5327 else if (drawLineCount == 1)
5329 TextRenderer.DrawText(e.Graphics,
5332 Rectangle.Round(rct),
5334 TextFormatFlags.SingleLine |
5335 TextFormatFlags.EndEllipsis |
5336 TextFormatFlags.GlyphOverhangPadding |
5337 TextFormatFlags.NoPrefix |
5338 TextFormatFlags.VerticalCenter);
5342 TextRenderer.DrawText(e.Graphics,
5345 Rectangle.Round(rct),
5347 TextFormatFlags.WordBreak |
5348 TextFormatFlags.EndEllipsis |
5349 TextFormatFlags.GlyphOverhangPadding |
5350 TextFormatFlags.NoPrefix);
5352 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5357 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5359 if (_iconSz == 0) return;
5361 ImageListViewItem item = (ImageListViewItem)e.Item;
5363 //e.Bounds.Leftが常に0を指すから自前で計算
5364 Rectangle itemRect = item.Bounds;
5365 var col0 = e.Item.ListView.Columns[0];
5366 itemRect.Width = col0.Width;
5368 if (col0.DisplayIndex > 0)
5370 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5372 if (clm.DisplayIndex < col0.DisplayIndex)
5373 itemRect.X += clm.Width;
5377 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5378 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5379 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5382 var img = item.Image;
5385 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5386 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5388 if (iconRect.Width > 0)
5390 e.Graphics.FillRectangle(Brushes.White, iconRect);
5391 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5394 e.Graphics.DrawImage(img.Image, iconRect);
5396 catch (ArgumentException)
5398 item.RefreshImageAsync();
5404 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5405 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5408 if (item.StateIndex > -1)
5410 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5411 if (stateRect.Width > 0)
5413 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5414 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5415 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5420 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5422 base.ScaleControl(factor, specified);
5424 const int baseDpi = 96;
5426 // デザイン時の DPI (96dpi) との比を更新する
5427 this.currentScaleFactor = new SizeF(
5428 this.CurrentAutoScaleDimensions.Width / baseDpi,
5429 this.CurrentAutoScaleDimensions.Height / baseDpi);
5432 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5434 // ImageListViewItem item = (ImageListViewItem)e.Item;
5435 // if (item.StateImageIndex > -1)
5437 // ////e.Bounds.Leftが常に0を指すから自前で計算
5438 // //Rectangle itemRect = item.Bounds;
5439 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5441 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5443 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5445 // // itemRect.X += clm.Width;
5449 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5450 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5452 // if (rct.Width > 0)
5454 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5455 // //e.Graphics.FillRectangle(Brushes.White, rct);
5456 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5457 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5462 private void DoTabSearch(string _word,
5472 if (_curList.VirtualListSize == 0)
5474 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5477 if (_curList.SelectedIndices.Count > 0)
5479 cidx = _curList.SelectedIndices[0];
5481 toIdx = _curList.VirtualListSize;
5485 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5486 if (_curList.SelectedIndices.Count > 0)
5487 cidx = _curList.SelectedIndices[0];
5491 case SEARCHTYPE.NextSearch: //次を検索
5492 if (_curList.SelectedIndices.Count > 0)
5494 cidx = _curList.SelectedIndices[0] + 1;
5495 if (cidx > toIdx) cidx = toIdx;
5502 case SEARCHTYPE.PrevSearch: //前を検索
5503 if (_curList.SelectedIndices.Count > 0)
5505 cidx = _curList.SelectedIndices[0] - 1;
5506 if (cidx < 0) cidx = 0;
5517 RegexOptions regOpt = RegexOptions.None;
5518 StringComparison fndOpt = StringComparison.Ordinal;
5521 regOpt = RegexOptions.IgnoreCase;
5522 fndOpt = StringComparison.OrdinalIgnoreCase;
5533 _search = new Regex(_word, regOpt);
5534 for (int idx = cidx; idx != toIdx; idx += stp)
5539 post = _statuses[_curTab.Text, idx];
5545 if (_search.IsMatch(post.Nickname)
5546 || _search.IsMatch(post.TextFromApi)
5547 || _search.IsMatch(post.ScreenName))
5549 SelectListItem(_curList, idx);
5550 _curList.EnsureVisible(idx);
5555 catch (ArgumentException)
5557 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5564 for (int idx = cidx; idx != toIdx; idx += stp)
5569 post = _statuses[_curTab.Text, idx];
5575 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5576 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5577 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5579 SelectListItem(_curList, idx);
5580 _curList.EnsureVisible(idx);
5590 case SEARCHTYPE.DialogSearch:
5591 case SEARCHTYPE.NextSearch:
5595 case SEARCHTYPE.PrevSearch:
5597 cidx = _curList.VirtualListSize - 1;
5604 catch (ArgumentOutOfRangeException)
5607 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5610 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5613 this.ShowSearchDialog();
5616 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5618 var previousSearch = this.SearchDialog.ResultOptions;
5619 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5621 this.SearchDialog.Reset();
5622 this.ShowSearchDialog();
5628 previousSearch.Query,
5629 previousSearch.CaseSensitive,
5630 previousSearch.UseRegex,
5631 SEARCHTYPE.NextSearch);
5634 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5636 var previousSearch = this.SearchDialog.ResultOptions;
5637 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5639 this.SearchDialog.Reset();
5640 this.ShowSearchDialog();
5646 previousSearch.Query,
5647 previousSearch.CaseSensitive,
5648 previousSearch.UseRegex,
5649 SEARCHTYPE.PrevSearch);
5653 /// 検索ダイアログを表示し、検索を実行します
5655 private void ShowSearchDialog()
5657 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5658 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5659 this.SearchDialog.DisableNewTabButton = false;
5661 this.SearchDialog.DisableNewTabButton = true;
5663 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5665 this.TopMost = this.SettingDialog.AlwaysTop;
5668 this.TopMost = this.SettingDialog.AlwaysTop;
5670 var searchOptions = this.SearchDialog.ResultOptions;
5671 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5673 if (searchOptions.NewTab)
5675 var tabName = searchOptions.Query;
5679 tabName = this._statuses.MakeTabName(tabName);
5681 catch (TabException ex)
5683 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5686 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5687 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5689 var filter = new PostFilterRule
5691 FilterBody = new[] { searchOptions.Query },
5692 UseRegex = searchOptions.UseRegex,
5693 CaseSensitive = searchOptions.CaseSensitive,
5695 this._statuses.Tabs[tabName].AddFilter(filter);
5697 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5698 .First(x => x.Text == tabName);
5700 this.ListTab.SelectedTab = tabPage;
5701 this.ListTabSelect(tabPage);
5703 this.ApplyPostFilters();
5704 this.SaveConfigsTabs();
5709 searchOptions.Query,
5710 searchOptions.CaseSensitive,
5711 searchOptions.UseRegex,
5712 SEARCHTYPE.DialogSearch);
5715 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5717 this.AddNewTabForSearch(searchOptions.Query);
5721 private void AboutMenuItem_Click(object sender, EventArgs e)
5723 using (TweenAboutBox about = new TweenAboutBox())
5725 about.ShowDialog(this);
5727 this.TopMost = SettingDialog.AlwaysTop;
5730 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5732 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5734 DetailsListView lst = null;
5736 if (ImageSelector.Enabled)
5740 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5743 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5746 ListTab.SelectedIndex = i;
5747 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5748 //_curTab = ListTab.TabPages[i];
5753 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5754 if (idx == -1 && bgnIdx > 0)
5756 for (int i = 0; i < bgnIdx; i++)
5758 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5761 ListTab.SelectedIndex = i;
5762 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5763 //_curTab = ListTab.TabPages[i];
5769 //全部調べたが未読見つからず→先頭タブの最新発言へ
5772 ListTab.SelectedIndex = 0;
5773 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5774 //_curTab = ListTab.TabPages[0];
5775 if (_statuses.SortOrder == SortOrder.Ascending)
5776 idx = lst.VirtualListSize - 1;
5781 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5783 SelectListItem(lst, idx);
5784 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5786 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5787 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5793 lst.EnsureVisible(idx);
5798 lst.EnsureVisible(idx);
5804 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5806 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5808 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5809 OpenUriAsync(MyCommon.GetStatusUrl(post));
5813 private void FavorareMenuItem_Click(object sender, EventArgs e)
5815 if (_curList.SelectedIndices.Count > 0)
5817 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5818 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5822 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5824 await this.CheckNewVersion(false);
5827 private void RunTweenUp()
5829 ProcessStartInfo pinfo = new ProcessStartInfo();
5830 pinfo.UseShellExecute = true;
5831 pinfo.WorkingDirectory = MyCommon.settingPath;
5832 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5833 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5836 Process.Start(pinfo);
5840 MessageBox.Show("Failed to execute TweenUp3.exe.");
5844 public class VersionInfo
5846 public Version Version { get; set; }
5847 public Uri DownloadUri { get; set; }
5848 public string ReleaseNote { get; set; }
5852 /// OpenTween の最新バージョンの情報を取得します
5854 public async Task<VersionInfo> GetVersionInfoAsync()
5856 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5857 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5859 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5860 .ConfigureAwait(false);
5862 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5863 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5865 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5866 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5868 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5870 return new VersionInfo
5872 Version = Version.Parse(msgHeader[0]),
5873 DownloadUri = new Uri(msgHeader[1]),
5874 ReleaseNote = msgBody,
5878 private async Task CheckNewVersion(bool startup = false)
5880 if (ApplicationSettings.VersionInfoUrl == null)
5881 return; // 更新チェック無効化
5885 var versionInfo = await this.GetVersionInfoAsync();
5887 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5892 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5893 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5894 msgtext = MyCommon.ReplaceAppName(msgtext);
5896 MessageBox.Show(msgtext,
5897 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5898 MessageBoxButtons.OK, MessageBoxIcon.Information);
5903 using (var dialog = new UpdateDialog())
5905 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5906 MyCommon.GetReadableVersion(versionInfo.Version));
5907 dialog.DetailsText = versionInfo.ReleaseNote;
5909 if (dialog.ShowDialog(this) == DialogResult.Yes)
5911 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5917 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5920 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5921 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5922 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5927 private void Colorize()
5931 //件数関連の場合、タイトル即時書き換え
5932 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
5933 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5934 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5935 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5937 SetMainWindowTitle();
5939 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5940 foreach (TabPage tb in ListTab.TabPages)
5942 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5944 if (SettingDialog.TabIconDisp)
5946 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5950 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
5953 public string createDetailHtml(string orgdata)
5955 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5958 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5960 if (sender.Equals(displayItem))
5962 this.ClearUserPicture();
5964 var img = displayItem.Image;
5968 img = await img.CloneAsync();
5970 UserPicture.Image = img;
5974 UserPicture.ShowErrorImage();
5979 private void DispSelectedPost()
5981 DispSelectedPost(false);
5984 private PostClass displayPost = new PostClass();
5987 /// サムネイルの表示処理を表すタスク
5989 private Task thumbnailTask = null;
5992 /// サムネイル表示に使用する CancellationToken の生成元
5994 private CancellationTokenSource thumbnailTokenSource = null;
5996 private void DispSelectedPost(bool forceupdate)
5998 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6001 var oldDisplayPost = this.displayPost;
6002 this.displayPost = this._curPost;
6004 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6007 if (displayItem != null)
6009 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6012 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6013 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6015 using (ControlTransaction.Update(this.TableLayoutPanel1))
6017 var sourceText = "";
6018 string sourceUrl = null;
6021 var mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6024 var src = mc.Groups["sourceurl"].Value;
6025 if (Regex.IsMatch(src, "^https?://"))
6028 sourceUrl = "https://twitter.com/" + src;
6031 if (_curPost.Source != null)
6032 sourceText = _curPost.Source;
6034 SourceLinkLabel.Text = sourceText;
6035 SourceLinkLabel.Tag = sourceUrl;
6036 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6042 nameText = "DM FROM <- ";
6044 nameText = "DM TO -> ";
6050 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6051 if (_curPost.RetweetedId != null)
6052 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6054 NameLabel.Text = nameText;
6055 NameLabel.Tag = _curPost.ScreenName;
6057 var nameForeColor = SystemColors.ControlText;
6058 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6059 nameForeColor = this._clOWL;
6060 if (_curPost.RetweetedId != null)
6061 nameForeColor = this._clRetweet;
6063 nameForeColor = this._clFav;
6064 NameLabel.ForeColor = nameForeColor;
6066 this.ClearUserPicture();
6068 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6070 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6073 UserPicture.Image = image != null ? image.Clone() : null;
6077 UserPicture.ShowErrorImage();
6081 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6083 if (DumpPostClassToolStripMenuItem.Checked)
6085 StringBuilder sb = new StringBuilder(512);
6087 sb.Append("-----Start PostClass Dump<br>");
6088 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6089 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6090 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6091 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6092 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6093 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6094 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6095 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6096 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6097 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6098 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6099 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6100 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6101 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6102 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6104 foreach (string nm in _curPost.ReplyToList)
6106 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6109 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6110 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6111 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6112 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6113 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6114 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6115 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6116 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6117 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6118 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6119 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6120 sb.Append("-----End PostClass Dump<br>");
6122 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6126 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6127 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6128 if (_curPost.StatusId != oldDisplayPost.StatusId)
6130 this.PostBrowser.DocumentText =
6131 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6133 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6135 this.SplitContainer3.Panel2Collapsed = true;
6137 if (this.IsPreviewEnable)
6139 if (this.thumbnailTokenSource != null)
6141 var oldTokenSource = this.thumbnailTokenSource;
6143 var cancelTask = Task.Run(() => oldTokenSource.Cancel());
6145 Task.WhenAll(this.thumbnailTask, cancelTask)
6146 .ContinueWith(_ => oldTokenSource.Dispose(), TaskScheduler.Default);
6149 this.thumbnailTokenSource = new CancellationTokenSource();
6151 var token = this.thumbnailTokenSource.Token;
6152 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6159 private void MatomeMenuItem_Click(object sender, EventArgs e)
6161 OpenApplicationWebsite();
6164 private void OpenApplicationWebsite()
6166 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6169 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6171 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6174 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6176 if (ListTab.SelectedTab != null)
6178 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6180 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6181 if (pnl.Controls["comboSearch"].Focused ||
6182 pnl.Controls["comboLang"].Focused ||
6183 pnl.Controls["buttonSearch"].Focused) return;
6185 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6186 if (State == ModifierState.NotFlags) return;
6187 if (State != ModifierState.None) _anchorFlag = false;
6188 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6191 e.SuppressKeyPress = true;
6196 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6198 ModifierState state = ModifierState.None;
6199 if (sControl) state = state | ModifierState.Ctrl;
6200 if (sShift) state = state | ModifierState.Shift;
6201 if (sAlt) state = state | ModifierState.Alt;
6206 private enum ModifierState
6218 //PostBrowser = 102,
6222 private enum FocusedControl : int
6230 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6232 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6233 if (Focused == FocusedControl.ListTab)
6235 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6236 Modifier == ModifierState.Ctrl ||
6237 Modifier == ModifierState.None ||
6238 Modifier == ModifierState.Shift)
6240 if (KeyCode == Keys.J)
6242 SendKeys.Send("{DOWN}");
6245 else if (KeyCode == Keys.K)
6247 SendKeys.Send("{UP}");
6251 if (Modifier == ModifierState.Shift ||
6252 Modifier == ModifierState.None)
6254 if (KeyCode == Keys.F)
6256 SendKeys.Send("{PGDN}");
6259 else if (KeyCode == Keys.B)
6261 SendKeys.Send("{PGUP}");
6270 case ModifierState.None:
6275 OpenApplicationWebsite();
6278 MenuItemSearchNext_Click(null, null);
6284 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
6287 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
6290 if (Focused != FocusedControl.StatusText)
6296 case Keys.ProcessKey:
6297 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6298 JumpUnreadMenuItem_Click(null, null);
6301 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6302 ShowRelatedStatusesMenuItem_Click(null, null);
6306 if (Focused == FocusedControl.ListTab)
6319 case Keys.OemPeriod:
6323 if (this.StatusText.Enabled) this.StatusText.Focus();
6326 MakeReplyOrDirectStatus();
6333 _anchorFlag = false;
6353 // ] in_reply_to参照元へ戻る
6354 GoInReplyToPostTree();
6357 // [ in_reply_toへジャンプ
6358 GoBackInReplyToPostTree();
6361 if (ListTab.SelectedTab != null)
6363 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6364 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6366 TabPage relTp = ListTab.SelectedTab;
6367 RemoveSpecifiedTab(relTp.Text, false);
6375 else if (Focused == FocusedControl.PostBrowser)
6382 //スクロールを発生させるため、true を返す
6387 case ModifierState.Ctrl:
6392 MakeReplyOrDirectStatus(false, true);
6398 MakeReplyOrDirectStatus(false, false);
6401 FavoriteChange(true);
6404 doRepliedStatusOpen();
6410 ReadedStripMenuItem_Click(null, null);
6413 HashManageMenuItem_Click(null, null);
6416 UrlConvertAutoToolStripMenuItem_Click(null, null);
6419 if (Focused != FocusedControl.PostBrowser)
6421 MultiLineMenuItem_Click(null, null);
6426 MenuItemSubSearch_Click(null, null);
6433 MoveToHomeToolStripMenuItem_Click(null, null);
6437 MoveToFavToolStripMenuItem_Click(null, null);
6441 StatusOpenMenuItem_Click(null, null);
6445 OpenURLMenuItem_Click(null, null);
6449 if (Focused == FocusedControl.ListTab)
6456 return false; //スルーする
6474 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6475 int tabNo = KeyCode - Keys.D1;
6476 if (ListTab.TabPages.Count < tabNo)
6478 ListTab.SelectedIndex = tabNo;
6479 ListTabSelect(ListTab.TabPages[tabNo]);
6482 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6483 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6487 else if (Focused == FocusedControl.StatusText)
6493 StatusText.SelectAll();
6497 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6499 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6501 if (KeyCode == Keys.Up)
6504 if (_hisIdx < 0) _hisIdx = 0;
6509 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6511 StatusText.Text = _history[_hisIdx].status;
6512 _reply_to_id = _history[_hisIdx].inReplyToId;
6513 _reply_to_name = _history[_hisIdx].inReplyToName;
6514 StatusText.SelectionStart = StatusText.Text.Length;
6518 if (ListTab.SelectedIndex == 0)
6520 ListTab.SelectedIndex = ListTab.TabCount - 1;
6524 ListTab.SelectedIndex -= 1;
6530 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6532 ListTab.SelectedIndex = 0;
6536 ListTab.SelectedIndex += 1;
6544 //フォーカスPostBrowserもしくは関係なし
6548 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6552 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6553 if (!string.IsNullOrEmpty(_selText))
6557 Clipboard.SetDataObject(_selText, false, 5, 100);
6559 catch (Exception ex)
6561 MessageBox.Show(ex.Message);
6566 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6567 MultiLineMenuItem_Click(null, null);
6572 case ModifierState.Shift:
6577 MenuItemSearchPrev_Click(null, null);
6583 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
6586 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
6590 if (Focused != FocusedControl.StatusText)
6592 if (KeyCode == Keys.R)
6599 if (Focused == FocusedControl.ListTab)
6619 GoBackInReplyToPostTree(true, false);
6622 GoBackInReplyToPostTree(true, true);
6626 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6631 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6635 this.GoBackSelectPostChain();
6640 case ModifierState.Alt:
6644 doReTweetOfficial(true);
6647 if (_curPost != null)
6649 doShowUserStatus(_curPost.ScreenName, false);
6654 ScrollDownPostBrowser(false);
6657 ScrollDownPostBrowser(true);
6660 PageDownPostBrowser(false);
6663 PageDownPostBrowser(true);
6666 if (Focused == FocusedControl.ListTab)
6668 // 別タブの同じ書き込みへ(ALT+←/→)
6669 if (KeyCode == Keys.Right)
6671 GoSamePostToAnotherTab(false);
6674 else if (KeyCode == Keys.Left)
6676 GoSamePostToAnotherTab(true);
6681 case ModifierState.Ctrl | ModifierState.Shift:
6685 MakeReplyOrDirectStatus(false, true, true);
6691 if (ListTab.SelectedTab != null)
6693 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6695 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6701 FavoriteChange(false);
6704 UnreadStripMenuItem_Click(null, null);
6707 HashToggleMenuItem_Click(null, null);
6710 ImageSelectMenuItem_Click(null, null);
6716 FavorareMenuItem_Click(null, null);
6719 if (Focused == FocusedControl.StatusText)
6725 if (_curList != null && _curList.VirtualListSize != 0 &&
6726 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6728 idx = _curList.SelectedIndices[0] - 1;
6729 SelectListItem(_curList, idx);
6730 _curList.EnsureVisible(idx);
6735 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6736 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6738 idx = _curList.SelectedIndices[0] + 1;
6739 SelectListItem(_curList, idx);
6740 _curList.EnsureVisible(idx);
6745 if (StatusText.SelectionStart > 0)
6747 int endidx = StatusText.SelectionStart - 1;
6748 string startstr = "";
6749 bool pressed = false;
6750 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6752 char c = StatusText.Text[i];
6753 if (Char.IsLetterOrDigit(c) || c == '_')
6760 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6761 int cnt = AtIdSupl.ItemCount;
6762 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6763 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6768 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6769 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6781 else if (Focused == FocusedControl.ListTab)
6783 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6795 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6796 int colNo = KeyCode - Keys.D1;
6797 if (lst.Columns.Count < colNo) return false;
6798 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6799 if (col == null) return false;
6800 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6803 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6804 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6809 case ModifierState.Ctrl | ModifierState.Alt:
6810 if (KeyCode == Keys.S)
6812 FavoritesRetweetOriginal();
6815 else if (KeyCode == Keys.R)
6817 FavoritesRetweetUnofficial();
6820 else if (KeyCode == Keys.H)
6822 OpenUserAppointUrl();
6826 case ModifierState.Alt | ModifierState.Shift:
6827 if (Focused == FocusedControl.PostBrowser)
6829 if (KeyCode == Keys.R)
6830 doReTweetUnofficial();
6831 else if (KeyCode == Keys.C)
6838 if (!this.ExistCurrentPost) return false;
6839 doTranslation(_curPost.TextFromApi);
6842 doReTweetUnofficial();
6848 this.tweetThumbnail1.ScrollUp();
6851 this.tweetThumbnail1.ScrollDown();
6854 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6856 if (!this.SplitContainer3.Panel2Collapsed)
6858 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6868 private void ScrollDownPostBrowser(bool forward)
6870 var doc = PostBrowser.Document;
6871 if (doc == null) return;
6873 var tags = doc.GetElementsByTagName("html");
6877 tags[0].ScrollTop += this._fntDetail.Height;
6879 tags[0].ScrollTop -= this._fntDetail.Height;
6883 private void PageDownPostBrowser(bool forward)
6885 var doc = PostBrowser.Document;
6886 if (doc == null) return;
6888 var tags = doc.GetElementsByTagName("html");
6892 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6894 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6898 private void GoNextTab(bool forward)
6900 int idx = ListTab.SelectedIndex;
6904 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6909 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6911 ListTab.SelectedIndex = idx;
6912 ListTabSelect(ListTab.TabPages[idx]);
6915 private void CopyStot()
6918 StringBuilder sb = new StringBuilder();
6919 bool IsProtected = false;
6921 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6922 foreach (int idx in _curList.SelectedIndices)
6924 PostClass post = _statuses[_curTab.Text, idx];
6930 if (post.IsDeleted) continue;
6933 if (post.RetweetedId != null)
6934 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6936 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6940 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6945 MessageBox.Show(Properties.Resources.CopyStotText1);
6949 clstr = sb.ToString();
6952 Clipboard.SetDataObject(clstr, false, 5, 100);
6954 catch (Exception ex)
6956 MessageBox.Show(ex.Message);
6961 private void CopyIdUri()
6964 StringBuilder sb = new StringBuilder();
6965 if (this._curTab == null) return;
6966 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
6967 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
6968 foreach (int idx in _curList.SelectedIndices)
6970 var post = _statuses[_curTab.Text, idx];
6971 sb.Append(MyCommon.GetStatusUrl(post));
6972 sb.Append(Environment.NewLine);
6976 clstr = sb.ToString();
6979 Clipboard.SetDataObject(clstr, false, 5, 100);
6981 catch (Exception ex)
6983 MessageBox.Show(ex.Message);
6988 private void GoFav(bool forward)
6990 if (_curList.VirtualListSize == 0) return;
6997 if (_curList.SelectedIndices.Count == 0)
7003 fIdx = _curList.SelectedIndices[0] + 1;
7004 if (fIdx > _curList.VirtualListSize - 1) return;
7006 toIdx = _curList.VirtualListSize;
7011 if (_curList.SelectedIndices.Count == 0)
7013 fIdx = _curList.VirtualListSize - 1;
7017 fIdx = _curList.SelectedIndices[0] - 1;
7018 if (fIdx < 0) return;
7024 for (int idx = fIdx; idx != toIdx; idx += stp)
7026 if (_statuses[_curTab.Text, idx].IsFav)
7028 SelectListItem(_curList, idx);
7029 _curList.EnsureVisible(idx);
7035 private void GoSamePostToAnotherTab(bool left)
7037 if (_curList.VirtualListSize == 0) return;
7043 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7044 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7046 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7051 if (ListTab.SelectedIndex == 0)
7057 fIdx = ListTab.SelectedIndex - 1;
7065 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7071 fIdx = ListTab.SelectedIndex + 1;
7073 toIdx = ListTab.TabCount;
7078 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7080 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7081 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7083 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7085 ListTab.SelectedIndex = tabidx;
7086 ListTabSelect(ListTab.TabPages[tabidx]);
7087 SelectListItem(_curList, idx);
7088 _curList.EnsureVisible(idx);
7097 private void GoPost(bool forward)
7099 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7106 fIdx = _curList.SelectedIndices[0] + 1;
7107 if (fIdx > _curList.VirtualListSize - 1) return;
7108 toIdx = _curList.VirtualListSize;
7113 fIdx = _curList.SelectedIndices[0] - 1;
7114 if (fIdx < 0) return;
7120 if (_curPost.RetweetedId == null)
7122 name = _curPost.ScreenName;
7126 name = _curPost.RetweetedBy;
7128 for (int idx = fIdx; idx != toIdx; idx += stp)
7130 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7132 if (_statuses[_curTab.Text, idx].ScreenName == name)
7134 SelectListItem(_curList, idx);
7135 _curList.EnsureVisible(idx);
7141 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7143 SelectListItem(_curList, idx);
7144 _curList.EnsureVisible(idx);
7151 private void GoRelPost(bool forward)
7153 if (_curList.SelectedIndices.Count == 0) return;
7160 fIdx = _curList.SelectedIndices[0] + 1;
7161 if (fIdx > _curList.VirtualListSize - 1) return;
7162 toIdx = _curList.VirtualListSize;
7167 fIdx = _curList.SelectedIndices[0] - 1;
7168 if (fIdx < 0) return;
7175 if (_curPost == null) return;
7176 _anchorPost = _curPost;
7181 if (_anchorPost == null) return;
7184 for (int idx = fIdx; idx != toIdx; idx += stp)
7186 PostClass post = _statuses[_curTab.Text, idx];
7187 if (post.ScreenName == _anchorPost.ScreenName ||
7188 post.RetweetedBy == _anchorPost.ScreenName ||
7189 post.ScreenName == _anchorPost.RetweetedBy ||
7190 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7191 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7192 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7193 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7194 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7196 SelectListItem(_curList, idx);
7197 _curList.EnsureVisible(idx);
7203 private void GoAnchor()
7205 if (_anchorPost == null) return;
7206 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7207 if (idx == -1) return;
7209 SelectListItem(_curList, idx);
7210 _curList.EnsureVisible(idx);
7213 private void GoTopEnd(bool GoTop)
7220 _item = _curList.GetItemAt(0, 25);
7228 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7230 idx = _curList.VirtualListSize - 1;
7234 SelectListItem(_curList, idx);
7237 private void GoMiddle()
7244 _item = _curList.GetItemAt(0, 0);
7254 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7257 idx2 = _curList.VirtualListSize - 1;
7263 idx3 = (idx1 + idx2) / 2;
7265 SelectListItem(_curList, idx3);
7268 private void GoLast()
7270 if (_curList.VirtualListSize == 0) return;
7272 if (_statuses.SortOrder == SortOrder.Ascending)
7274 SelectListItem(_curList, _curList.VirtualListSize - 1);
7275 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7279 SelectListItem(_curList, 0);
7280 _curList.EnsureVisible(0);
7284 private void MoveTop()
7286 if (_curList.SelectedIndices.Count == 0) return;
7287 int idx = _curList.SelectedIndices[0];
7288 if (_statuses.SortOrder == SortOrder.Ascending)
7290 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7294 _curList.EnsureVisible(0);
7296 _curList.EnsureVisible(idx);
7299 private void GoInReplyToPostTree()
7301 if (_curPost == null) return;
7303 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7305 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7307 PostClass post = null;
7308 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7309 if (string.IsNullOrEmpty(r) && post != null)
7311 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7312 _curPost.InReplyToUser = post.InReplyToUser;
7313 _curPost.IsReply = post.IsReply;
7314 this.PurgeListViewItemCache();
7315 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7319 this.StatusLabel.Text = r;
7323 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7325 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7327 replyChains = new Stack<ReplyChain>();
7329 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7332 string inReplyToTabName;
7333 long inReplyToId = _curPost.InReplyToStatusId.Value;
7334 string inReplyToUser = _curPost.InReplyToUser;
7335 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7337 var inReplyToPosts = from tab in _statuses.Tabs.Values
7338 orderby tab != curTabClass
7339 from post in tab.Posts.Values
7340 where post.StatusId == inReplyToId
7341 let index = tab.IndexOf(post.StatusId)
7343 select new {Tab = tab, Index = index};
7347 var inReplyPost = inReplyToPosts.First();
7348 inReplyToTabName = inReplyPost.Tab.TabName;
7349 inReplyToIndex = inReplyPost.Index;
7351 catch (InvalidOperationException)
7353 PostClass post = null;
7354 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7355 if (string.IsNullOrEmpty(r) && post != null)
7358 _statuses.AddPost(post);
7359 _statuses.DistributePosts();
7360 //_statuses.SubmitUpdate(null, null, null, false);
7361 this.RefreshTimeline(false);
7364 var inReplyPost = inReplyToPosts.First();
7365 inReplyToTabName = inReplyPost.Tab.TabName;
7366 inReplyToIndex = inReplyPost.Index;
7368 catch (InvalidOperationException)
7370 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7376 this.StatusLabel.Text = r;
7377 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7382 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7383 DetailsListView listView = (DetailsListView)tabPage.Tag;
7385 if (_curTab != tabPage)
7387 this.ListTab.SelectTab(tabPage);
7390 this.SelectListItem(listView, inReplyToIndex);
7391 listView.EnsureVisible(inReplyToIndex);
7394 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7396 if (_curPost == null) return;
7398 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7399 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7403 if (_curPost.InReplyToStatusId != null)
7405 var posts = from t in _statuses.Tabs
7406 from p in t.Value.Posts
7407 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7408 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7410 orderby isForward ? indexOf : indexOf * -1
7411 orderby t.Value != curTabClass
7412 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7415 var postList = posts.ToList();
7416 for (int i = postList.Count - 1; i >= 0; i--)
7419 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7421 postList.RemoveAt(index);
7424 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7425 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7426 if (post == null) post = postList.First();
7427 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7428 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7429 SelectListItem(listView, post.Index);
7430 listView.EnsureVisible(post.Index);
7432 catch (InvalidOperationException)
7440 if (replyChains == null || replyChains.Count < 1)
7442 var posts = from t in _statuses.Tabs
7443 from p in t.Value.Posts
7444 where p.Value.InReplyToStatusId == _curPost.StatusId
7445 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7448 orderby t.Value != curTabClass
7449 select new {Tab = t.Value, Index = indexOf};
7452 var post = posts.First();
7453 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7454 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7455 SelectListItem(listView, post.Index);
7456 listView.EnsureVisible(post.Index);
7458 catch (InvalidOperationException)
7465 ReplyChain chainHead = replyChains.Pop();
7466 if (chainHead.InReplyToId == _curPost.StatusId)
7468 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7477 ListTab.SelectTab(chainHead.OriginalTab);
7483 SelectListItem(_curList, idx);
7484 _curList.EnsureVisible(idx);
7490 this.GoBackInReplyToPostTree(parallel);
7496 private void GoBackSelectPostChain()
7498 if (this.selectPostChains.Count > 1)
7507 this.selectPostChains.Pop();
7508 var tabPostPair = this.selectPostChains.Peek();
7510 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7512 if (tabPostPair.Item2 != null)
7514 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7515 if (idx == -1) continue; //該当ポストが存在しないので無視
7518 tp = tabPostPair.Item1;
7520 this.selectPostChains.Pop();
7522 catch (InvalidOperationException)
7528 while (this.selectPostChains.Count > 1);
7533 //履歴が残り1つであればクリアしておく
7534 if (this.selectPostChains.Count == 1)
7535 this.selectPostChains.Clear();
7539 DetailsListView lst = (DetailsListView)tp.Tag;
7540 this.ListTab.SelectedTab = tp;
7543 SelectListItem(lst, idx);
7544 lst.EnsureVisible(idx);
7550 private void PushSelectPostChain()
7552 int count = this.selectPostChains.Count;
7555 var p = this.selectPostChains.Peek();
7556 if (p.Item1 == this._curTab)
7558 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7559 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7562 if (count >= 2500) TrimPostChain();
7563 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7566 private void TrimPostChain()
7568 if (this.selectPostChains.Count <= 2000) return;
7569 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7570 for (int i = 0; i < 2000; i++)
7572 p.Push(this.selectPostChains.Pop());
7574 this.selectPostChains.Clear();
7575 for (int i = 0; i < 2000; i++)
7577 this.selectPostChains.Push(p.Pop());
7581 private bool GoStatus(long statusId)
7583 if (statusId == 0) return false;
7584 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7586 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7588 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7589 ListTab.SelectedIndex = tabidx;
7590 ListTabSelect(ListTab.TabPages[tabidx]);
7591 SelectListItem(_curList, idx);
7592 _curList.EnsureVisible(idx);
7599 private bool GoDirectMessage(long statusId)
7601 if (statusId == 0) return false;
7602 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7604 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7606 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7607 ListTab.SelectedIndex = tabidx;
7608 ListTabSelect(ListTab.TabPages[tabidx]);
7609 SelectListItem(_curList, idx);
7610 _curList.EnsureVisible(idx);
7617 private void MyList_MouseClick(object sender, MouseEventArgs e)
7619 _anchorFlag = false;
7622 private void StatusText_Enter(object sender, EventArgs e)
7624 // フォーカスの戻り先を StatusText に設定
7625 this.Tag = StatusText;
7626 StatusText.BackColor = _clInputBackcolor;
7629 public Color InputBackColor
7631 get { return _clInputBackcolor; }
7632 set { _clInputBackcolor = value; }
7635 private void StatusText_Leave(object sender, EventArgs e)
7637 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7638 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7639 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7642 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7644 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7645 if (State == ModifierState.NotFlags) return;
7646 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7649 e.SuppressKeyPress = true;
7652 this.StatusText_TextChanged(null, null);
7655 private void SaveConfigsAll(bool ifModified)
7659 SaveConfigsCommon();
7666 if (_modifySettingCommon) SaveConfigsCommon();
7667 if (_modifySettingLocal) SaveConfigsLocal();
7668 if (_modifySettingAtId) SaveConfigsAtId();
7672 private void SaveConfigsAtId()
7674 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7676 _modifySettingAtId = false;
7677 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7681 private void SaveConfigsCommon()
7683 if (_ignoreConfigSave) return;
7685 _modifySettingCommon = false;
7688 _cfgCommon.UserName = tw.Username;
7689 _cfgCommon.UserId = tw.UserId;
7690 _cfgCommon.Password = tw.Password;
7691 _cfgCommon.Token = tw.AccessToken;
7692 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7693 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7695 _cfgCommon.NameBalloon = SettingDialog.NameBalloon;
7696 _cfgCommon.CountApi = SettingDialog.CountApi;
7697 _cfgCommon.CountApiReply = SettingDialog.CountApiReply;
7698 _cfgCommon.DispUsername = SettingDialog.DispUsername;
7699 _cfgCommon.DispLatestPost = SettingDialog.DispLatestPost;
7700 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7701 _cfgCommon.AlwaysTop = SettingDialog.AlwaysTop;
7702 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7703 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7704 _cfgCommon.LimitBalloon = SettingDialog.LimitBalloon;
7705 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7706 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7707 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7708 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7709 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7710 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7711 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7712 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7713 _cfgCommon.TabIconDisp = SettingDialog.TabIconDisp;
7714 _cfgCommon.ReplyIconState = SettingDialog.ReplyIconState;
7715 _cfgCommon.IsMonospace = SettingDialog.IsMonospace;
7716 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7717 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7719 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7721 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7722 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7723 _cfgCommon.PreviewEnable = SettingDialog.PreviewEnable;
7724 _cfgCommon.StatusAreaAtBottom = SettingDialog.StatusAreaAtBottom;
7725 _cfgCommon.Language = SettingDialog.Language;
7727 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7728 switch (_statuses.SortMode)
7730 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7731 _cfgCommon.SortColumn = 1;
7733 case IdComparerClass.ComparerMode.Data: //本文
7734 _cfgCommon.SortColumn = 2;
7736 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7737 _cfgCommon.SortColumn = 3;
7739 case IdComparerClass.ComparerMode.Name: //名前
7740 _cfgCommon.SortColumn = 4;
7742 case IdComparerClass.ComparerMode.Source: //Source
7743 _cfgCommon.SortColumn = 7;
7747 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7748 _cfgCommon.HashTags = HashMgr.HashHistories;
7749 if (HashMgr.IsPermanent)
7751 _cfgCommon.HashSelected = HashMgr.UseHash;
7755 _cfgCommon.HashSelected = "";
7757 _cfgCommon.HashIsHead = HashMgr.IsHead;
7758 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7759 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7760 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7761 _cfgCommon.BlinkNewMentions = SettingDialog.BlinkNewMentions;
7762 if (ToolStripFocusLockMenuItem != null &&
7763 ToolStripFocusLockMenuItem.IsDisposed == false)
7765 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7767 _cfgCommon.UseAdditionalCount = SettingDialog.UseAdditionalCount;
7768 _cfgCommon.MoreCountApi = SettingDialog.MoreCountApi;
7769 _cfgCommon.FirstCountApi = SettingDialog.FirstCountApi;
7770 _cfgCommon.SearchCountApi = SettingDialog.SearchCountApi;
7771 _cfgCommon.FavoritesCountApi = SettingDialog.FavoritesCountApi;
7772 _cfgCommon.UserTimelineCountApi = SettingDialog.UserTimelineCountApi;
7773 _cfgCommon.TrackWord = tw.TrackWord;
7774 _cfgCommon.AllAtReply = tw.AllAtReply;
7775 _cfgCommon.ListCountApi = SettingDialog.ListCountApi;
7776 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7777 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7778 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7779 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7780 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7781 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7782 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7783 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7784 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7785 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7786 _cfgCommon.IsUseNotifyGrowl = SettingDialog.IsNotifyUseGrowl;
7792 private void SaveConfigsLocal()
7794 if (_ignoreConfigSave) return;
7797 _modifySettingLocal = false;
7798 _cfgLocal.FormSize = _mySize;
7799 _cfgLocal.FormLocation = _myLoc;
7800 _cfgLocal.SplitterDistance = _mySpDis;
7801 _cfgLocal.PreviewDistance = _mySpDis3;
7802 _cfgLocal.StatusMultiline = StatusText.Multiline;
7803 _cfgLocal.StatusTextHeight = _mySpDis2;
7805 _cfgLocal.FontUnread = _fntUnread;
7806 _cfgLocal.ColorUnread = _clUnread;
7807 _cfgLocal.FontRead = _fntReaded;
7808 _cfgLocal.ColorRead = _clReaded;
7809 _cfgLocal.FontDetail = _fntDetail;
7810 _cfgLocal.ColorDetail = _clDetail;
7811 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7812 _cfgLocal.ColorDetailLink = _clDetailLink;
7813 _cfgLocal.ColorFav = _clFav;
7814 _cfgLocal.ColorOWL = _clOWL;
7815 _cfgLocal.ColorRetweet = _clRetweet;
7816 _cfgLocal.ColorSelf = _clSelf;
7817 _cfgLocal.ColorAtSelf = _clAtSelf;
7818 _cfgLocal.ColorTarget = _clTarget;
7819 _cfgLocal.ColorAtTarget = _clAtTarget;
7820 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7821 _cfgLocal.ColorAtTo = _clAtTo;
7822 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7823 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7824 _cfgLocal.ColorInputFont = _clInputFont;
7825 _cfgLocal.FontInputFont = _fntInputFont;
7827 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7828 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7829 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7830 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7831 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7832 if (_ignoreConfigSave) return;
7837 private void SaveConfigsTabs()
7839 SettingTabs tabSetting = new SettingTabs();
7840 for (int i = 0; i < ListTab.TabPages.Count; i++)
7842 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7847 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7850 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7851 if (ret != DialogResult.OK)
7854 var match = Twitter.StatusUrlRegex.Match(inputText);
7857 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7858 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7862 var statusId = long.Parse(match.Groups["StatusId"].Value);
7864 var post = this._statuses[statusId];
7869 post = await Task.Run(() =>
7871 PostClass newPost = null;
7873 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7874 if (!string.IsNullOrEmpty(err))
7875 throw new WebApiException(err);
7880 catch (WebApiException ex)
7882 var message = ex.Message;
7883 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7884 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7891 this.OpenRelatedTab(post);
7893 catch (TabException ex)
7895 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7899 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7901 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7902 Properties.Resources.SaveLogMenuItem_ClickText2,
7903 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7904 if (rslt == DialogResult.Cancel) return;
7906 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7907 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7908 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7909 SaveFileDialog1.FilterIndex = 0;
7910 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7911 SaveFileDialog1.RestoreDirectory = true;
7913 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7915 if (!SaveFileDialog1.ValidateNames) return;
7916 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7918 if (rslt == DialogResult.Yes)
7921 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7923 PostClass post = _statuses[_curTab.Text, idx];
7924 string protect = "";
7925 if (post.IsProtect) protect = "Protect";
7926 sw.WriteLine(post.Nickname + "\t" +
7927 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7928 post.CreatedAt.ToString() + "\t" +
7929 post.ScreenName + "\t" +
7930 post.StatusId.ToString() + "\t" +
7931 post.ImageUrl + "\t" +
7932 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7938 foreach (int idx in _curList.SelectedIndices)
7940 PostClass post = _statuses[_curTab.Text, idx];
7941 string protect = "";
7942 if (post.IsProtect) protect = "Protect";
7943 sw.WriteLine(post.Nickname + "\t" +
7944 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7945 post.CreatedAt.ToString() + "\t" +
7946 post.ScreenName + "\t" +
7947 post.StatusId.ToString() + "\t" +
7948 post.ImageUrl + "\t" +
7949 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7955 this.TopMost = SettingDialog.AlwaysTop;
7958 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
7960 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7961 if (State == ModifierState.NotFlags) return;
7962 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
7965 e.IsInputKey = true;
7968 public bool TabRename(ref string tabName)
7971 string newTabText = null;
7972 using (InputTabName inputName = new InputTabName())
7974 inputName.TabName = tabName;
7975 inputName.ShowDialog();
7976 if (inputName.DialogResult == DialogResult.Cancel) return false;
7977 newTabText = inputName.TabName;
7979 this.TopMost = SettingDialog.AlwaysTop;
7980 if (!string.IsNullOrEmpty(newTabText))
7983 for (int i = 0; i < ListTab.TabCount; i++)
7985 if (ListTab.TabPages[i].Text == newTabText)
7987 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
7988 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7992 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
7993 for (int i = 0; i < ListTab.TabCount; i++)
7995 if (ListTab.TabPages[i].Text == tabName)
7997 ListTab.TabPages[i].Text = newTabText;
8000 _statuses.RenameTab(tabName, newTabText);
8002 for (int i = 0; i < ListTab.TabCount; i++)
8004 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
8006 if (ListTab.TabPages[i].Text == tabName)
8008 ListTab.TabPages[i].Text = newTabText;
8012 SaveConfigsCommon();
8014 _rclickTabName = newTabText;
8015 tabName = newTabText;
8024 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8026 if (e.Button == MouseButtons.Middle)
8028 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8030 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8032 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8033 this.SaveConfigsTabs();
8040 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8042 string tn = ListTab.SelectedTab.Text;
8046 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8048 if (this._cfgCommon.TabMouseLock) return;
8049 Point cpos = new Point(e.X, e.Y);
8050 if (e.Button == MouseButtons.Left)
8052 for (int i = 0; i < ListTab.TabPages.Count; i++)
8054 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8057 _tabMouseDownPoint = e.Location;
8068 private void ListTab_DragEnter(object sender, DragEventArgs e)
8070 if (e.Data.GetDataPresent(typeof(TabPage)))
8071 e.Effect = DragDropEffects.Move;
8073 e.Effect = DragDropEffects.None;
8076 private void ListTab_DragDrop(object sender, DragEventArgs e)
8078 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8083 Point cpos = new Point(e.X, e.Y);
8084 Point spos = ListTab.PointToClient(cpos);
8086 for (i = 0; i < ListTab.TabPages.Count; i++)
8088 Rectangle rect = ListTab.GetTabRect(i);
8089 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8090 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8092 tn = ListTab.TabPages[i].Text;
8093 if (spos.X <= (rect.Left + rect.Right) / 2)
8102 //タブのないところにドロップ->最後尾へ移動
8103 if (string.IsNullOrEmpty(tn))
8105 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8107 i = ListTab.TabPages.Count - 1;
8110 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8111 if (tp.Text == tn) return;
8113 ReOrderTab(tp.Text, tn, bef);
8116 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8119 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8121 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8124 using (ControlTransaction.Layout(this.ListTab))
8127 for (int j = 0; j < ListTab.TabPages.Count; j++)
8129 if (ListTab.TabPages[j].Text == targetTabText)
8131 mTp = ListTab.TabPages[j];
8132 ListTab.TabPages.Remove(mTp);
8133 if (j < baseIndex) baseIndex -= 1;
8137 if (isBeforeBaseTab)
8138 ListTab.TabPages.Insert(baseIndex, mTp);
8140 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8146 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8148 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8149 //isReply:true=@,false=DM
8150 if (!StatusText.Enabled) return;
8151 if (_curList == null) return;
8152 if (_curTab == null) return;
8153 if (!this.ExistCurrentPost) return;
8155 // 複数あてリプライはReplyではなく通常ポスト
8156 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8157 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8158 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8160 if (_curList.SelectedIndices.Count > 0)
8163 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8166 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8169 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8170 StatusText.SelectionStart = StatusText.Text.Length;
8172 _reply_to_id = null;
8173 _reply_to_name = null;
8176 if (string.IsNullOrEmpty(StatusText.Text))
8180 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8181 StatusText.Text = "@" + _curPost.ScreenName + " ";
8182 if (_curPost.RetweetedId != null)
8184 _reply_to_id = _curPost.RetweetedId.Value;
8188 _reply_to_id = _curPost.StatusId;
8190 _reply_to_name = _curPost.ScreenName;
8198 //1件選んでEnter or DoubleClick
8199 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8201 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8204 if (_curPost.RetweetedId != null)
8206 _reply_to_id = _curPost.RetweetedId.Value;
8210 _reply_to_id = _curPost.StatusId;
8212 _reply_to_name = _curPost.ScreenName;
8216 if (!StatusText.Text.StartsWith("@"))
8219 if (StatusText.Text.StartsWith(". "))
8222 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8223 _reply_to_id = null;
8224 _reply_to_name = null;
8229 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8230 if (_curPost.RetweetedId != null)
8232 _reply_to_id = _curPost.RetweetedId.Value;
8236 _reply_to_id = _curPost.StatusId;
8238 _reply_to_name = _curPost.ScreenName;
8245 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8246 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8247 _reply_to_id = null;
8248 _reply_to_name = null;
8253 //1件選んでCtrl-Rの場合(返信先操作せず)
8254 int sidx = StatusText.SelectionStart;
8255 string id = "@" + _curPost.ScreenName + " ";
8258 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8263 StatusText.Text = StatusText.Text.Insert(sidx, id);
8265 //if (StatusText.Text.StartsWith("@"))
8268 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8269 // sidx += 5 + _curPost.ScreenName.Length;
8274 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8275 // sidx += 3 + _curPost.ScreenName.Length;
8277 StatusText.SelectionStart = sidx;
8280 //_reply_to_name = null;
8288 if (!isAuto && !isReply) return;
8290 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8294 //Enter or DoubleClick
8296 string sTxt = StatusText.Text;
8297 if (!sTxt.StartsWith(". "))
8300 _reply_to_id = null;
8301 _reply_to_name = null;
8303 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8305 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8306 if (!sTxt.Contains("@" + post.ScreenName + " "))
8308 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8309 //sTxt = "@" + post.ScreenName + " " + sTxt;
8312 StatusText.Text = sTxt;
8317 if (_curList.SelectedIndices.Count > 1)
8322 int sidx = StatusText.SelectionStart;
8323 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8325 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8326 if (!ids.Contains("@" + post.ScreenName + " ") &&
8327 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8329 ids += "@" + post.ScreenName + " ";
8333 foreach (string nm in post.ReplyToList)
8335 if (!ids.Contains("@" + nm + " ") &&
8336 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8338 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8340 ids += "@" + m.Result("${id}") + " ";
8342 ids += "@" + nm + " ";
8347 if (ids.Length == 0) return;
8348 if (!StatusText.Text.StartsWith(". "))
8350 StatusText.Text = ". " + StatusText.Text;
8352 _reply_to_id = null;
8353 _reply_to_name = null;
8357 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8362 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8364 //if (StatusText.Text.StartsWith("@"))
8366 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8367 // sidx += 2 + ids.Length;
8371 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8372 // sidx += 1 + ids.Length;
8374 StatusText.SelectionStart = sidx;
8380 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8383 int sidx = StatusText.SelectionStart;
8384 PostClass post = _curPost;
8385 if (!ids.Contains("@" + post.ScreenName + " ") &&
8386 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8388 ids += "@" + post.ScreenName + " ";
8390 foreach (string nm in post.ReplyToList)
8392 if (!ids.Contains("@" + nm + " ") &&
8393 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8395 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8397 ids += "@" + m.Result("${id}") + " ";
8399 ids += "@" + nm + " ";
8402 if (!string.IsNullOrEmpty(post.RetweetedBy))
8404 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8405 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8407 ids += "@" + post.RetweetedBy + " ";
8410 if (ids.Length == 0) return;
8411 if (string.IsNullOrEmpty(StatusText.Text))
8414 StatusText.Text = ids;
8415 StatusText.SelectionStart = ids.Length;
8417 if (post.RetweetedId != null)
8419 _reply_to_id = post.RetweetedId.Value;
8423 _reply_to_id = post.StatusId;
8425 _reply_to_name = post.ScreenName;
8431 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8436 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8438 StatusText.SelectionStart = sidx;
8444 StatusText.SelectionStart = StatusText.Text.Length;
8449 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8454 private static int iconCnt = 0;
8455 private static int blinkCnt = 0;
8456 private static bool blink = false;
8457 private static bool idle = false;
8459 private void RefreshTasktrayIcon(bool forceRefresh)
8461 if (_colorize) Colorize();
8462 if (!TimerRefreshIcon.Enabled) return;
8463 //Static usCheckCnt As int = 0
8465 //Static iconDlListTopItem As ListViewItem = null
8467 if (forceRefresh) idle = false;
8469 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8470 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8472 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8474 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8480 //if (usCheckCnt > 300) //1min
8483 // if (!this.IsReceivedUserStream)
8485 // TraceOut("ReconnectUserStream");
8486 // tw.ReconnectUserStream();
8491 foreach (BackgroundWorker bw in this._bw)
8493 if (bw != null && bw.IsBusy)
8508 SaveConfigsAll(true);
8513 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8515 _myStatusError = false;
8519 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8520 if (SettingDialog.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8522 if (blinkCnt > 0) return;
8524 if (blink || SettingDialog.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8526 NotifyIcon1.Icon = ReplyIcon;
8530 NotifyIcon1.Icon = ReplyIconBlink;
8538 //優先度:エラー→オフライン→アイドル
8542 NotifyIcon1.Icon = NIconAtRed;
8545 if (_myStatusOnline)
8547 NotifyIcon1.Icon = NIconAt;
8551 NotifyIcon1.Icon = NIconAtSmoke;
8555 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8558 this.RefreshTasktrayIcon(false);
8561 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8563 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8564 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8566 if (ListTab != null && ListTab.SelectedTab != null)
8567 _rclickTabName = ListTab.SelectedTab.Text;
8572 if (_statuses == null) return;
8573 if (_statuses.Tabs == null) return;
8575 TabClass tb = _statuses.Tabs[_rclickTabName];
8576 if (tb == null) return;
8578 NotifyDispMenuItem.Checked = tb.Notify;
8579 this.NotifyTbMenuItem.Checked = tb.Notify;
8581 soundfileListup = true;
8582 SoundFileComboBox.Items.Clear();
8583 this.SoundFileTbComboBox.Items.Clear();
8584 SoundFileComboBox.Items.Add("");
8585 this.SoundFileTbComboBox.Items.Add("");
8586 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8587 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8589 oDir = oDir.GetDirectories("Sounds")[0];
8591 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8593 SoundFileComboBox.Items.Add(oFile.Name);
8594 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8596 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8597 if (idx == -1) idx = 0;
8598 SoundFileComboBox.SelectedIndex = idx;
8599 this.SoundFileTbComboBox.SelectedIndex = idx;
8600 soundfileListup = false;
8601 UreadManageMenuItem.Checked = tb.UnreadManage;
8602 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8604 TabMenuControl(_rclickTabName);
8607 private void TabMenuControl(string tabName)
8609 this.FilterEditMenuItem.Enabled = true;
8610 this.EditRuleTbMenuItem.Enabled = true;
8612 if (_statuses.IsDefaultTab(tabName))
8614 this.ProtectTabMenuItem.Enabled = false;
8615 this.ProtectTbMenuItem.Enabled = false;
8619 this.ProtectTabMenuItem.Enabled = true;
8620 this.ProtectTbMenuItem.Enabled = true;
8623 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8625 this.ProtectTabMenuItem.Checked = true;
8626 this.ProtectTbMenuItem.Checked = true;
8627 this.DeleteTabMenuItem.Enabled = false;
8628 this.DeleteTbMenuItem.Enabled = false;
8632 this.ProtectTabMenuItem.Checked = false;
8633 this.ProtectTbMenuItem.Checked = false;
8634 this.DeleteTabMenuItem.Enabled = true;
8635 this.DeleteTbMenuItem.Enabled = true;
8639 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8641 var checkState = ((ToolStripMenuItem)sender).Checked;
8644 this.ProtectTbMenuItem.Checked = checkState;
8645 this.ProtectTabMenuItem.Checked = checkState;
8648 this.DeleteTabMenuItem.Enabled = !checkState;
8649 this.DeleteTbMenuItem.Enabled = !checkState;
8651 if (string.IsNullOrEmpty(_rclickTabName)) return;
8652 _statuses.Tabs[_rclickTabName].Protected = checkState;
8657 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8659 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8660 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8662 if (string.IsNullOrEmpty(_rclickTabName)) return;
8663 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8668 public void ChangeTabUnreadManage(string tabName, bool isManage)
8671 for (idx = 0; idx < ListTab.TabCount; idx++)
8673 if (ListTab.TabPages[idx].Text == tabName) break;
8676 _statuses.SetTabUnreadManage(tabName, isManage);
8677 if (SettingDialog.TabIconDisp)
8679 if (_statuses.Tabs[tabName].UnreadCount > 0)
8680 ListTab.TabPages[idx].ImageIndex = 0;
8682 ListTab.TabPages[idx].ImageIndex = -1;
8685 if (_curTab.Text == tabName)
8687 this.PurgeListViewItemCache();
8691 SetMainWindowTitle();
8692 SetStatusLabelUrl();
8693 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
8696 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8698 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8699 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8701 if (string.IsNullOrEmpty(_rclickTabName)) return;
8703 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8708 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8710 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8712 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8717 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8719 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8721 RemoveSpecifiedTab(_rclickTabName, true);
8725 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8727 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8728 fltDialog.SetCurrent(_rclickTabName);
8729 fltDialog.ShowDialog(this);
8730 this.TopMost = SettingDialog.AlwaysTop;
8732 this.ApplyPostFilters();
8736 private void AddTabMenuItem_Click(object sender, EventArgs e)
8738 string tabName = null;
8739 MyCommon.TabUsageType tabUsage;
8740 using (InputTabName inputName = new InputTabName())
8742 inputName.TabName = _statuses.GetUniqueTabName();
8743 inputName.IsShowUsage = true;
8744 inputName.ShowDialog();
8745 if (inputName.DialogResult == DialogResult.Cancel) return;
8746 tabName = inputName.TabName;
8747 tabUsage = inputName.Usage;
8749 this.TopMost = SettingDialog.AlwaysTop;
8750 if (!string.IsNullOrEmpty(tabName))
8753 ListElement list = null;
8754 if (tabUsage == MyCommon.TabUsageType.Lists)
8756 using (ListAvailable listAvail = new ListAvailable())
8758 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8759 if (listAvail.SelectedList == null) return;
8760 list = listAvail.SelectedList;
8763 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8765 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8766 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8772 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8774 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8775 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8776 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8778 if (tabUsage == MyCommon.TabUsageType.Lists)
8780 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8781 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8782 GetTimeline(MyCommon.WORKERTYPE.List, 1, tabName);
8788 private void TabMenuItem_Click(object sender, EventArgs e)
8791 foreach (int idx in _curList.SelectedIndices)
8795 if (!SelectTab(out tabName)) return;
8797 fltDialog.SetCurrent(tabName);
8798 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8800 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8804 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8806 fltDialog.ShowDialog(this);
8807 this.TopMost = SettingDialog.AlwaysTop;
8810 this.ApplyPostFilters();
8812 if (this.ListTab.SelectedTab != null &&
8813 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8815 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8819 protected override bool ProcessDialogKey(Keys keyData)
8821 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8822 if ((keyData & Keys.KeyCode) == Keys.Enter)
8824 if (StatusText.Focused)
8826 bool _NewLine = false;
8829 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8831 if (StatusText.Multiline)
8833 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8835 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8839 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8843 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8845 if (StatusText.Multiline)
8847 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8849 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8853 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8859 if (StatusText.Multiline)
8861 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8863 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8864 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8868 if (((keyData & Keys.Shift) == Keys.Shift) ||
8869 (((keyData & Keys.Control) != Keys.Control) &&
8870 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8876 int pos1 = StatusText.SelectionStart;
8877 if (StatusText.SelectionLength > 0)
8879 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8881 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8882 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8887 PostButton_Click(null, null);
8891 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8892 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8893 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8895 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8900 return base.ProcessDialogKey(keyData);
8903 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8905 MakeReplyOrDirectStatus(false, true, true);
8908 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8913 if (_curList.SelectedIndices.Count == 0) return;
8916 if (!SelectTab(out tabName)) return;
8920 MoveOrCopy(ref mv, ref mk);
8922 List<string> ids = new List<string>();
8923 foreach (int idx in _curList.SelectedIndices)
8925 PostClass post = _statuses[_curTab.Text, idx];
8926 if (!ids.Contains(post.ScreenName))
8928 PostFilterRule fc = new PostFilterRule();
8929 ids.Add(post.ScreenName);
8930 if (post.RetweetedId == null)
8932 fc.FilterName = post.ScreenName;
8936 fc.FilterName = post.RetweetedBy;
8938 fc.UseNameField = true;
8939 fc.MoveMatches = mv;
8940 fc.MarkMatches = mk;
8941 fc.UseRegex = false;
8942 fc.FilterByUrl = false;
8943 _statuses.Tabs[tabName].AddFilter(fc);
8948 List<string> atids = new List<string>();
8949 foreach (string id in ids)
8951 atids.Add("@" + id);
8953 int cnt = AtIdSupl.ItemCount;
8954 AtIdSupl.AddRangeItem(atids.ToArray());
8955 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
8958 this.ApplyPostFilters();
8962 private bool SelectTab(out string tabName)
8969 using (var dialog = new TabsDialog(_statuses))
8971 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8973 var selectedTab = dialog.SelectedTab;
8974 tabName = selectedTab == null ? null : selectedTab.TabName;
8977 ListTab.SelectedTab.Focus();
8979 if (tabName == null)
8981 using (InputTabName inputName = new InputTabName())
8983 inputName.TabName = _statuses.GetUniqueTabName();
8984 inputName.ShowDialog();
8985 if (inputName.DialogResult == DialogResult.Cancel) return false;
8986 tabName = inputName.TabName;
8988 this.TopMost = SettingDialog.AlwaysTop;
8989 if (!string.IsNullOrEmpty(tabName))
8991 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
8993 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8994 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9012 private void MoveOrCopy(ref bool move, ref bool mark)
9016 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9017 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9025 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9026 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9032 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9037 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9042 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9044 if (StatusText.Focused)
9047 StatusText.SelectAll();
9051 // ListView上でのCtrl+A
9052 for (int i = 0; i < _curList.VirtualListSize; i++)
9054 _curList.SelectedIndices.Add(i);
9059 private void MoveMiddle()
9065 if (_curList.SelectedIndices.Count == 0) return;
9067 int idx = _curList.SelectedIndices[0];
9069 _item = _curList.GetItemAt(0, 25);
9075 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9077 idx2 = _curList.VirtualListSize - 1;
9081 idx -= Math.Abs(idx1 - idx2) / 2;
9082 if (idx < 0) idx = 0;
9084 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9085 _curList.EnsureVisible(idx);
9088 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9090 if (PostBrowser.Document.Links.Count > 0)
9092 UrlDialog.ClearUrl();
9094 string openUrlStr = "";
9096 if (PostBrowser.Document.Links.Count == 1)
9101 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9103 catch (ArgumentException)
9112 if (string.IsNullOrEmpty(urlStr)) return;
9113 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9117 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9120 string linkText = "";
9124 urlStr = linkElm.GetAttribute("title");
9125 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9126 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9127 linkText = linkElm.InnerText;
9128 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9130 linkText = "@" + linkText;
9133 catch (ArgumentException)
9142 if (string.IsNullOrEmpty(urlStr)) continue;
9143 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9147 if (UrlDialog.ShowDialog() == DialogResult.OK)
9149 openUrlStr = UrlDialog.SelectedUrl;
9156 this.TopMost = SettingDialog.AlwaysTop;
9158 if (string.IsNullOrEmpty(openUrlStr)) return;
9160 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9161 openUrlStr.StartsWith("https://twitter.com/search?q="))
9164 string urlStr = Uri.UnescapeDataString(openUrlStr);
9165 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9166 HashSupl.AddItem(hash);
9167 HashMgr.AddHashToHistory(hash.Trim(), false);
9168 AddNewTabForSearch(hash);
9173 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9174 if (this._cfgCommon.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9175 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9177 OpenUriAsync(openUrlStr);
9183 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9185 if (string.IsNullOrEmpty(_rclickTabName)) return;
9186 ClearTab(_rclickTabName, true);
9189 private void ClearTab(string tabName, bool showWarning)
9193 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9194 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9200 _statuses.ClearTabIds(tabName);
9201 if (ListTab.SelectedTab.Text == tabName)
9204 _anchorFlag = false;
9205 this.PurgeListViewItemCache();
9209 foreach (TabPage tb in ListTab.TabPages)
9211 if (tb.Text == tabName)
9214 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9218 if (!SettingDialog.TabIconDisp) ListTab.Refresh();
9220 SetMainWindowTitle();
9221 SetStatusLabelUrl();
9224 private static long followers = 0;
9226 private void SetMainWindowTitle()
9229 StringBuilder ttl = new StringBuilder(256);
9232 if (SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.None &&
9233 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9234 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9235 SettingDialog.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9237 foreach (var tab in _statuses.Tabs.Values)
9239 ur += tab.UnreadCount;
9244 if (SettingDialog.DispUsername) ttl.Append(tw.Username).Append(" - ");
9245 ttl.Append(Application.ProductName);
9247 switch (SettingDialog.DispLatestPost)
9249 case MyCommon.DispTitleEnum.Ver:
9250 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9252 case MyCommon.DispTitleEnum.Post:
9253 if (_history != null && _history.Count > 1)
9254 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9256 case MyCommon.DispTitleEnum.UnreadRepCount:
9257 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9259 case MyCommon.DispTitleEnum.UnreadAllCount:
9260 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9262 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9263 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9265 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9266 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9268 case MyCommon.DispTitleEnum.OwnStatus:
9269 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9270 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9276 this.Text = ttl.ToString();
9278 catch (AccessViolationException)
9280 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9284 private string GetStatusLabelText()
9287 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9288 if (_statuses == null) return "";
9289 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9290 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9291 if (tbRep == null || tbDm == null) return "";
9292 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9297 StringBuilder slbl = new StringBuilder(256);
9300 foreach (var tab in _statuses.Tabs.Values)
9302 ur += tab.UnreadCount;
9304 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9306 tur = tab.UnreadCount;
9317 UnreadAtCounter = urat;
9319 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9320 if (this._cfgCommon.TimelinePeriod == 0)
9322 slbl.Append(Properties.Resources.SetStatusLabelText2);
9326 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9328 return slbl.ToString();
9331 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9335 if (this.InvokeRequired && !this.IsDisposed)
9337 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9341 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9342 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9344 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9348 catch (ObjectDisposedException)
9352 catch (InvalidOperationException)
9358 private void SetStatusLabelUrl()
9360 StatusLabelUrl.Text = GetStatusLabelText();
9363 public void SetStatusLabel(string text)
9365 StatusLabel.Text = text;
9368 private static StringBuilder ur = new StringBuilder(64);
9370 private void SetNotifyIconText()
9372 // タスクトレイアイコンのツールチップテキスト書き換え
9374 ur.Remove(0, ur.Length);
9375 if (SettingDialog.DispUsername)
9377 ur.Append(tw.Username);
9380 ur.Append(Application.ProductName);
9382 ur.Append("(Debug Build)");
9384 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9387 ur.Append(UnreadCounter);
9389 ur.Append(UnreadAtCounter);
9392 NotifyIcon1.Text = ur.ToString();
9395 internal void CheckReplyTo(string StatusText)
9399 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9401 foreach (Match hm in m)
9403 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9405 hstr += "#" + hm.Result("$3") + " ";
9406 HashSupl.AddItem("#" + hm.Result("$3"));
9409 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9411 hstr += HashMgr.UseHash;
9413 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9415 // 本当にリプライ先指定すべきかどうかの判定
9416 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9418 if (this._cfgCommon.UseAtIdSupplement)
9420 int bCnt = AtIdSupl.ItemCount;
9421 foreach (Match mid in m)
9423 AtIdSupl.AddItem(mid.Result("${id}"));
9425 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9428 // リプライ先ステータスIDの指定がない場合は指定しない
9429 if (_reply_to_id == null) return;
9431 // リプライ先ユーザー名がない場合も指定しない
9432 if (string.IsNullOrEmpty(_reply_to_name))
9434 _reply_to_id = null;
9439 // 次の条件を満たす場合に in_reply_to_status_id 指定
9440 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9441 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9442 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9446 if (StatusText.StartsWith("@"))
9448 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9452 foreach (Match mid in m)
9454 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9459 _reply_to_id = null;
9460 _reply_to_name = null;
9464 private void TweenMain_Resize(object sender, EventArgs e)
9466 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9468 this.Visible = false;
9470 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9472 this.ClientSize = _cfgLocal.FormSize;
9473 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9474 this.DesktopLocation = _cfgLocal.FormLocation;
9475 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9476 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9477 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9479 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9482 StatusText.Multiline = _cfgLocal.StatusMultiline;
9483 if (StatusText.Multiline)
9485 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9486 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9488 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9490 StatusText.Height = _cfgLocal.StatusTextHeight;
9494 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9496 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9499 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9501 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9503 _initialLayout = false;
9505 if (this.WindowState != FormWindowState.Minimized)
9507 _formWindowState = this.WindowState;
9511 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9513 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9514 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9515 if (PlaySoundMenuItem.Checked)
9517 this._cfgCommon.PlaySound = true;
9521 this._cfgCommon.PlaySound = false;
9523 _modifySettingCommon = true;
9526 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9528 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9530 _mySpDis = SplitContainer1.SplitterDistance;
9531 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9532 _modifySettingLocal = true;
9536 private void doRepliedStatusOpen()
9538 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9540 if (MyCommon.IsKeyDown(Keys.Shift))
9542 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9545 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9547 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9548 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9552 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9554 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9555 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9556 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9559 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9564 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9566 doRepliedStatusOpen();
9570 /// UserPicture.Image に設定されている画像を破棄します。
9572 private void ClearUserPicture()
9574 if (this.UserPicture.Image != null)
9576 var oldImage = this.UserPicture.Image;
9577 this.UserPicture.Image = null;
9582 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9584 //発言詳細のアイコン右クリック時のメニュー制御
9585 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9587 string name = _curPost.ImageUrl;
9588 if (name != null && name.Length > 0)
9590 int idx = name.LastIndexOf('/');
9593 name = Path.GetFileName(name.Substring(idx));
9594 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9596 name = name.Replace("_normal", "");
9597 this.IconNameToolStripMenuItem.Text = name;
9598 this.IconNameToolStripMenuItem.Enabled = true;
9602 this.IconNameToolStripMenuItem.Enabled = false;
9603 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9608 this.IconNameToolStripMenuItem.Enabled = false;
9609 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9612 this.ReloadIconToolStripMenuItem.Enabled = true;
9614 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9616 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9620 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9625 this.IconNameToolStripMenuItem.Enabled = false;
9626 this.ReloadIconToolStripMenuItem.Enabled = false;
9627 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9628 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9633 this.IconNameToolStripMenuItem.Enabled = false;
9634 this.ReloadIconToolStripMenuItem.Enabled = false;
9635 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9636 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9638 if (NameLabel.Tag != null)
9640 string id = (string)NameLabel.Tag;
9641 if (id == tw.Username)
9643 FollowToolStripMenuItem.Enabled = false;
9644 UnFollowToolStripMenuItem.Enabled = false;
9645 ShowFriendShipToolStripMenuItem.Enabled = false;
9646 ShowUserStatusToolStripMenuItem.Enabled = true;
9647 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9648 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9649 ListManageUserContextToolStripMenuItem3.Enabled = true;
9653 FollowToolStripMenuItem.Enabled = true;
9654 UnFollowToolStripMenuItem.Enabled = true;
9655 ShowFriendShipToolStripMenuItem.Enabled = true;
9656 ShowUserStatusToolStripMenuItem.Enabled = true;
9657 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9658 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9659 ListManageUserContextToolStripMenuItem3.Enabled = true;
9664 FollowToolStripMenuItem.Enabled = false;
9665 UnFollowToolStripMenuItem.Enabled = false;
9666 ShowFriendShipToolStripMenuItem.Enabled = false;
9667 ShowUserStatusToolStripMenuItem.Enabled = false;
9668 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9669 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9670 ListManageUserContextToolStripMenuItem3.Enabled = false;
9674 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9676 if (_curPost == null) return;
9677 string name = _curPost.ImageUrl;
9678 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9681 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9683 if (this._curPost == null) return;
9685 await this.UserPicture.SetImageFromTask(async () =>
9687 var imageUrl = this._curPost.ImageUrl;
9689 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9690 .ConfigureAwait(false);
9692 return await image.CloneAsync()
9693 .ConfigureAwait(false);
9697 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9699 if (_curPost == null) return;
9700 string name = _curPost.ImageUrl;
9701 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9703 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9705 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9711 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9713 if (_curPost == null) return;
9714 string name = _curPost.ImageUrl;
9716 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9718 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9722 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9724 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9726 using (Graphics g = Graphics.FromImage(bmp2))
9728 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9729 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9731 bmp2.Save(this.SaveFileDialog1.FileName);
9737 //処理中にキャッシュアウトする可能性あり
9742 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9744 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9745 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9746 _modifySettingLocal = true;
9749 private void StatusText_MultilineChanged(object sender, EventArgs e)
9751 if (this.StatusText.Multiline)
9752 this.StatusText.ScrollBars = ScrollBars.Vertical;
9754 this.StatusText.ScrollBars = ScrollBars.None;
9756 _modifySettingLocal = true;
9759 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9762 StatusText.Multiline = MultiLineMenuItem.Checked;
9763 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9764 if (MultiLineMenuItem.Checked)
9766 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9767 SplitContainer2.SplitterDistance = 0;
9769 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9773 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9775 _modifySettingLocal = true;
9778 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9780 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9781 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9783 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9784 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9785 //Appendix A. Collected ABNF for URI
9786 //http://www.ietf.org/rfc/rfc3986.txt
9790 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9792 if (StatusText.SelectionLength > 0)
9794 string tmp = StatusText.SelectedText;
9795 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9796 if (tmp.StartsWith("http"))
9798 // 文字列が選択されている場合はその文字列について処理
9800 //nico.ms使用、nicovideoにマッチしたら変換
9801 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9803 result = nicoms.Shorten(tmp);
9805 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9807 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9810 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9811 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9812 result = resultUri.ToString();
9814 catch (WebApiException e)
9816 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9819 catch (UriFormatException e)
9821 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9830 if (!string.IsNullOrEmpty(result))
9832 urlUndo undotmp = new urlUndo();
9834 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9835 StatusText.SelectedText = result;
9838 undotmp.Before = tmp;
9839 undotmp.After = result;
9841 if (urlUndoBuffer == null)
9843 urlUndoBuffer = new List<urlUndo>();
9844 UrlUndoToolStripMenuItem.Enabled = true;
9847 urlUndoBuffer.Add(undotmp);
9853 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9854 @"(?<url>(?<protocol>https?://)" +
9855 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9856 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9857 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9858 // 正規表現にマッチしたURL文字列をtinyurl化
9859 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9861 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9862 string tmp = mt.Result("${url}");
9863 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9864 urlUndo undotmp = new urlUndo();
9867 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9869 //nico.ms使用、nicovideoにマッチしたら変換
9870 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9872 result = nicoms.Shorten(tmp);
9874 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9876 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9879 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9880 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9881 result = resultUri.ToString();
9883 catch (HttpRequestException e)
9885 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9886 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9887 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9889 this.StatusLabel.Text = Converter_Type + ":" + message;
9892 catch (WebApiException e)
9894 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9897 catch (UriFormatException e)
9899 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9908 if (!string.IsNullOrEmpty(result))
9910 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9911 StatusText.SelectedText = result;
9913 undotmp.Before = mt.Result("${url}");
9914 undotmp.After = result;
9916 if (urlUndoBuffer == null)
9918 urlUndoBuffer = new List<urlUndo>();
9919 UrlUndoToolStripMenuItem.Enabled = true;
9922 urlUndoBuffer.Add(undotmp);
9930 private void doUrlUndo()
9932 if (urlUndoBuffer != null)
9934 string tmp = StatusText.Text;
9935 foreach (urlUndo data in urlUndoBuffer)
9937 tmp = tmp.Replace(data.After, data.Before);
9939 StatusText.Text = tmp;
9940 urlUndoBuffer = null;
9941 UrlUndoToolStripMenuItem.Enabled = false;
9942 StatusText.SelectionStart = 0;
9943 StatusText.SelectionLength = 0;
9947 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9949 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9952 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9954 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9957 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9959 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9962 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9964 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9967 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9969 if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
9971 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
9972 Random rnd = new Random();
9973 // 前回使用した短縮URLサービス以外を選択する
9976 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9978 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9979 await UrlConvertAsync(svc);
9983 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9988 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9990 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9991 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9992 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9993 _modifySettingCommon = true;
9996 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9998 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9999 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10000 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10001 _modifySettingCommon = true;
10004 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10006 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10007 MenuStrip1.Tag = new Object();
10008 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10011 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10013 if (this.Tag != null) // 設定された戻り先へ遷移
10015 if (this.Tag == this.ListTab.SelectedTab)
10016 ((Control)this.ListTab.SelectedTab.Tag).Select();
10018 ((Control)this.Tag).Select();
10020 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10022 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10024 this.Tag = ListTab.SelectedTab.Tag;
10025 ((Control)this.Tag).Select();
10028 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10029 MenuStrip1.Tag = null;
10032 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10034 DetailsListView lst = (DetailsListView)sender;
10035 if (_cfgLocal == null) return;
10039 _cfgLocal.Width1 = lst.Columns[0].Width;
10040 _cfgLocal.Width3 = lst.Columns[1].Width;
10044 int[] darr = new int[lst.Columns.Count];
10045 for (int i = 0; i < lst.Columns.Count; i++)
10047 darr[lst.Columns[i].DisplayIndex] = i;
10049 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10051 for (int i = 0; i < lst.Columns.Count; i++)
10056 _cfgLocal.DisplayIndex1 = i;
10059 _cfgLocal.DisplayIndex2 = i;
10062 _cfgLocal.DisplayIndex3 = i;
10065 _cfgLocal.DisplayIndex4 = i;
10068 _cfgLocal.DisplayIndex5 = i;
10071 _cfgLocal.DisplayIndex6 = i;
10074 _cfgLocal.DisplayIndex7 = i;
10077 _cfgLocal.DisplayIndex8 = i;
10081 _cfgLocal.Width1 = lst.Columns[0].Width;
10082 _cfgLocal.Width2 = lst.Columns[1].Width;
10083 _cfgLocal.Width3 = lst.Columns[2].Width;
10084 _cfgLocal.Width4 = lst.Columns[3].Width;
10085 _cfgLocal.Width5 = lst.Columns[4].Width;
10086 _cfgLocal.Width6 = lst.Columns[5].Width;
10087 _cfgLocal.Width7 = lst.Columns[6].Width;
10088 _cfgLocal.Width8 = lst.Columns[7].Width;
10090 _modifySettingLocal = true;
10091 _isColumnChanged = true;
10094 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10096 DetailsListView lst = (DetailsListView)sender;
10097 if (_cfgLocal == null) return;
10100 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10102 _cfgLocal.Width1 = lst.Columns[0].Width;
10103 _modifySettingLocal = true;
10104 _isColumnChanged = true;
10106 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10108 _cfgLocal.Width3 = lst.Columns[1].Width;
10109 _modifySettingLocal = true;
10110 _isColumnChanged = true;
10115 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10117 _cfgLocal.Width1 = lst.Columns[0].Width;
10118 _modifySettingLocal = true;
10119 _isColumnChanged = true;
10121 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10123 _cfgLocal.Width2 = lst.Columns[1].Width;
10124 _modifySettingLocal = true;
10125 _isColumnChanged = true;
10127 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10129 _cfgLocal.Width3 = lst.Columns[2].Width;
10130 _modifySettingLocal = true;
10131 _isColumnChanged = true;
10133 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10135 _cfgLocal.Width4 = lst.Columns[3].Width;
10136 _modifySettingLocal = true;
10137 _isColumnChanged = true;
10139 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10141 _cfgLocal.Width5 = lst.Columns[4].Width;
10142 _modifySettingLocal = true;
10143 _isColumnChanged = true;
10145 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10147 _cfgLocal.Width6 = lst.Columns[5].Width;
10148 _modifySettingLocal = true;
10149 _isColumnChanged = true;
10151 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10153 _cfgLocal.Width7 = lst.Columns[6].Width;
10154 _modifySettingLocal = true;
10155 _isColumnChanged = true;
10157 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10159 _cfgLocal.Width8 = lst.Columns[7].Width;
10160 _modifySettingLocal = true;
10161 _isColumnChanged = true;
10164 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10167 // SaveConfigsLocal();
10171 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10173 //発言詳細で「選択文字列をコピー」を行う
10174 //WebBrowserコンポーネントのインスタンスを渡す
10175 Type typ = ComponentInstance.ActiveXInstance.GetType();
10176 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10177 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10178 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10181 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10184 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10187 Clipboard.SetDataObject(_selText, false, 5, 100);
10189 catch (Exception ex)
10191 MessageBox.Show(ex.Message);
10195 private void doSearchToolStrip(string url)
10197 //発言詳細で「選択文字列で検索」(選択文字列取得)
10198 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10200 if (_selText != null)
10202 if (url == Properties.Resources.SearchItem4Url)
10205 AddNewTabForSearch(_selText);
10209 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10214 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10217 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10220 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10222 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10225 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10227 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10230 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10232 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10235 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10239 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10240 foreach (Match m in mc)
10242 if (m.Groups["url"].Value == this._postBrowserStatusText)
10244 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10250 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10252 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10254 catch (Exception ex)
10256 MessageBox.Show(ex.Message);
10260 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10262 // URLコピーの項目の表示/非表示
10263 if (PostBrowser.StatusText.StartsWith("http"))
10265 this._postBrowserStatusText = PostBrowser.StatusText;
10266 string name = GetUserId();
10267 UrlCopyContextMenuItem.Enabled = true;
10270 FollowContextMenuItem.Enabled = true;
10271 RemoveContextMenuItem.Enabled = true;
10272 FriendshipContextMenuItem.Enabled = true;
10273 ShowUserStatusContextMenuItem.Enabled = true;
10274 SearchPostsDetailToolStripMenuItem.Enabled = true;
10275 IdFilterAddMenuItem.Enabled = true;
10276 ListManageUserContextToolStripMenuItem.Enabled = true;
10277 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10281 FollowContextMenuItem.Enabled = false;
10282 RemoveContextMenuItem.Enabled = false;
10283 FriendshipContextMenuItem.Enabled = false;
10284 ShowUserStatusContextMenuItem.Enabled = false;
10285 SearchPostsDetailToolStripMenuItem.Enabled = false;
10286 IdFilterAddMenuItem.Enabled = false;
10287 ListManageUserContextToolStripMenuItem.Enabled = false;
10288 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10291 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10292 UseHashtagMenuItem.Enabled = true;
10294 UseHashtagMenuItem.Enabled = false;
10298 this._postBrowserStatusText = "";
10299 UrlCopyContextMenuItem.Enabled = false;
10300 FollowContextMenuItem.Enabled = false;
10301 RemoveContextMenuItem.Enabled = false;
10302 FriendshipContextMenuItem.Enabled = false;
10303 ShowUserStatusContextMenuItem.Enabled = false;
10304 SearchPostsDetailToolStripMenuItem.Enabled = false;
10305 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10306 UseHashtagMenuItem.Enabled = false;
10307 IdFilterAddMenuItem.Enabled = false;
10308 ListManageUserContextToolStripMenuItem.Enabled = false;
10310 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10311 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10312 if (_selText == null)
10314 SelectionSearchContextMenuItem.Enabled = false;
10315 SelectionCopyContextMenuItem.Enabled = false;
10316 SelectionTranslationToolStripMenuItem.Enabled = false;
10320 SelectionSearchContextMenuItem.Enabled = true;
10321 SelectionCopyContextMenuItem.Enabled = true;
10322 SelectionTranslationToolStripMenuItem.Enabled = true;
10324 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10325 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10326 bool fAllFlag = false;
10327 foreach (Match mu in ma)
10329 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10335 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10337 if (_curPost == null)
10338 TranslationToolStripMenuItem.Enabled = false;
10340 TranslationToolStripMenuItem.Enabled = true;
10345 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10347 //発言詳細の選択文字列で現在のタブを検索
10348 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10350 if (_selText != null)
10352 var searchOptions = new SearchWordDialog.SearchOptions(
10353 SearchWordDialog.SearchType.Timeline,
10356 caseSensitive: false,
10359 this.SearchDialog.ResultOptions = searchOptions;
10362 searchOptions.Query,
10363 searchOptions.CaseSensitive,
10364 searchOptions.UseRegex,
10365 SEARCHTYPE.NextSearch);
10369 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10371 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10372 _modifySettingLocal = true;
10375 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10377 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10379 SelectMedia_DragDrop(e);
10381 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10383 var url = GetUrlFromDataObject(e.Data);
10386 if (url.Item2 == null)
10387 appendText = url.Item1;
10389 appendText = url.Item2 + " " + url.Item1;
10391 if (this.StatusText.TextLength == 0)
10392 this.StatusText.Text = appendText;
10394 this.StatusText.Text += " " + appendText;
10396 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10398 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10399 if (data != null) StatusText.Text += data;
10404 /// IDataObject から URL とタイトルの対を取得します
10407 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10409 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10410 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10411 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10413 if (data.GetDataPresent("text/x-moz-url"))
10415 // Firefox, Google Chrome で利用可能
10416 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10418 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10420 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10421 if (lines.Length < 2)
10422 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10424 return new Tuple<string, string>(lines[0], lines[1]);
10427 else if (data.GetDataPresent("IESiteModeToUrl"))
10429 // Internet Exproler 用
10430 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10432 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10434 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10435 if (lines.Length < 2)
10436 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10438 return new Tuple<string, string>(lines[0], lines[1]);
10441 else if (data.GetDataPresent("UniformResourceLocatorW"))
10445 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10447 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10448 return new Tuple<string, string>(url, null);
10452 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10455 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10457 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10459 SelectMedia_DragEnter(e);
10463 private void TweenMain_DragOver(object sender, DragEventArgs e)
10465 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10467 SelectMedia_DragOver(e);
10469 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10471 e.Effect = DragDropEffects.Copy;
10473 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10475 e.Effect = DragDropEffects.Copy;
10479 e.Effect = DragDropEffects.None;
10483 public bool IsNetworkAvailable()
10486 nw = MyCommon.IsNetworkAvailable();
10487 _myStatusOnline = nw;
10491 public Task OpenUriAsync(string UriString)
10493 return Task.Run(() =>
10495 string myPath = UriString;
10499 var configBrowserPath = this._cfgLocal.BrowserPath;
10500 if (!string.IsNullOrEmpty(configBrowserPath))
10502 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10504 int sep = configBrowserPath.IndexOf("\"", 2);
10505 string browserPath = configBrowserPath.Substring(1, sep - 1);
10507 if (sep < configBrowserPath.Length - 1)
10509 arg = configBrowserPath.Substring(sep + 1);
10511 myPath = arg + " " + myPath;
10512 System.Diagnostics.Process.Start(browserPath, myPath);
10516 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10521 System.Diagnostics.Process.Start(myPath);
10526 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10531 private void ListTabSelect(TabPage _tab)
10535 this.PurgeListViewItemCache();
10538 _curList = (DetailsListView)_tab.Tag;
10539 if (_curList.SelectedIndices.Count > 0)
10541 _curItemIndex = _curList.SelectedIndices[0];
10542 _curPost = GetCurTabPost(_curItemIndex);
10546 _curItemIndex = -1;
10550 _anchorPost = null;
10551 _anchorFlag = false;
10555 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10559 for (int i = 0; i < _curList.Columns.Count; i++)
10561 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10566 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10568 ListTabSelect(e.TabPage);
10571 private void SelectListItem(DetailsListView LView, int Index)
10574 Rectangle bnd = new Rectangle();
10576 var item = LView.FocusedItem;
10585 LView.SelectedIndices.Clear();
10587 while (LView.SelectedIndices.Count > 0);
10588 item = LView.Items[Index];
10589 item.Selected = true;
10590 item.Focused = true;
10592 if (flg) LView.Invalidate(bnd);
10595 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10598 Rectangle bnd = new Rectangle();
10600 var item = LView.FocusedItem;
10608 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10612 LView.SelectedIndices.Clear();
10614 while (LView.SelectedIndices.Count > 0);
10615 foreach (int idx in Index)
10617 if (idx > -1 && LView.VirtualListSize > idx)
10619 LView.SelectedIndices.Add(idx);
10620 if (fIdx == -1) fIdx = idx;
10624 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10626 LView.SelectionMark = FocusedIndex[1];
10628 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10630 LView.Items[FocusedIndex[0]].Focused = true;
10632 else if (fIdx > -1)
10634 LView.Items[fIdx].Focused = true;
10637 if (flg) LView.Invalidate(bnd);
10640 private void RunAsync(GetWorkerArg args)
10642 BackgroundWorker bw = null;
10643 if (args.type != MyCommon.WORKERTYPE.Follower)
10645 for (int i = 0; i < _bw.Length; i++)
10647 if (_bw[i] != null && !_bw[i].IsBusy)
10655 for (int i = 0; i < _bw.Length; i++)
10657 if (_bw[i] == null)
10659 _bw[i] = new BackgroundWorker();
10661 bw.WorkerReportsProgress = true;
10662 bw.WorkerSupportsCancellation = true;
10663 bw.DoWork += GetTimelineWorker_DoWork;
10664 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10665 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10673 if (_bwFollower == null)
10675 _bwFollower = new BackgroundWorker();
10677 bw.WorkerReportsProgress = true;
10678 bw.WorkerSupportsCancellation = true;
10679 bw.DoWork += GetTimelineWorker_DoWork;
10680 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10681 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10685 if (_bwFollower.IsBusy == false)
10689 if (bw == null) return;
10691 bw.RunWorkerAsync(args);
10694 private void StartUserStream()
10696 tw.NewPostFromStream += tw_NewPostFromStream;
10697 tw.UserStreamStarted += tw_UserStreamStarted;
10698 tw.UserStreamStopped += tw_UserStreamStopped;
10699 tw.PostDeleted += tw_PostDeleted;
10700 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10702 MenuItemUserStream.Text = "&UserStream ■";
10703 MenuItemUserStream.Enabled = true;
10704 StopToolStripMenuItem.Text = "&Start";
10705 StopToolStripMenuItem.Enabled = true;
10706 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
10709 private async void TweenMain_Shown(object sender, EventArgs e)
10713 PostBrowser.Url = new Uri("about:blank");
10714 PostBrowser.DocumentText = ""; //発言詳細部初期化
10720 NotifyIcon1.Visible = true;
10722 if (this.IsNetworkAvailable())
10724 this.RefreshMuteUserIdsAsync();
10725 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, "");
10726 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10727 if (this._cfgCommon.StartupFollowers)
10729 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10731 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10733 _waitTimeline = true;
10734 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
10736 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
10738 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
10739 if (this._cfgCommon.GetFav)
10742 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
10744 _waitPubSearch = true;
10745 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, ""); //tabname="":全タブ
10746 _waitUserTimeline = true;
10747 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, ""); //tabname="":全タブ
10749 GetTimeline(MyCommon.WORKERTYPE.List, 1, ""); //tabname="":全タブ
10752 while (this.IsInitialRead())
10754 await Task.Delay(5000);
10757 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10759 if (MyCommon._endingFlag)
10763 if (MyCommon._endingFlag) return;
10765 if (ApplicationSettings.VersionInfoUrl != null)
10767 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10768 if (this._cfgCommon.StartupVersion)
10769 await this.CheckNewVersion(true);
10773 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10774 this.VerUpMenuItem.Enabled = false;
10775 this.VerUpMenuItem.Available = false;
10776 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10780 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10781 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10784 if (!tw.GetNoRetweetSuccess)
10785 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10788 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10789 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10791 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10792 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10794 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10795 SettingStripMenuItem_Click(null, null);
10802 TimerTimeline.Enabled = true;
10805 private bool IsInitialRead()
10807 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10810 private void doGetFollowersMenu()
10812 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, "");
10813 DispSelectedPost(true);
10816 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10818 doGetFollowersMenu();
10821 private void doReTweetUnofficial()
10824 if (this.ExistCurrentPost)
10826 if (_curPost.IsDm ||
10827 !StatusText.Enabled) return;
10829 if (_curPost.IsProtect)
10831 MessageBox.Show("Protected.");
10834 string rtdata = _curPost.Text;
10835 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10837 this._reply_to_id = null;
10838 this._reply_to_name = null;
10840 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10842 StatusText.SelectionStart = 0;
10843 StatusText.Focus();
10847 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10849 doReTweetUnofficial();
10852 private void doReTweetOfficial(bool isConfirm)
10855 if (this.ExistCurrentPost)
10857 if (_curPost.IsProtect)
10859 MessageBox.Show("Protected.");
10860 _DoFavRetweetFlags = false;
10863 if (_curList.SelectedIndices.Count > 15)
10865 MessageBox.Show(Properties.Resources.RetweetLimitText);
10866 _DoFavRetweetFlags = false;
10869 else if (_curList.SelectedIndices.Count > 1)
10871 string QuestionText = Properties.Resources.RetweetQuestion2;
10872 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10873 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10875 case DialogResult.Cancel:
10876 case DialogResult.No:
10877 _DoFavRetweetFlags = false;
10883 if (_curPost.IsDm || _curPost.IsMe)
10885 _DoFavRetweetFlags = false;
10888 if (!this._cfgCommon.RetweetNoConfirm)
10890 string Questiontext = Properties.Resources.RetweetQuestion1;
10891 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10892 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10894 _DoFavRetweetFlags = false;
10899 GetWorkerArg args = new GetWorkerArg();
10900 args.ids = new List<long>();
10901 args.sIds = new List<long>();
10902 args.tName = _curTab.Text;
10903 args.type = MyCommon.WORKERTYPE.Retweet;
10904 foreach (int idx in _curList.SelectedIndices)
10906 PostClass post = GetCurTabPost(idx);
10907 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10913 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10915 doReTweetOfficial(true);
10918 private void FavoritesRetweetOriginal()
10920 if (!this.ExistCurrentPost) return;
10921 _DoFavRetweetFlags = true;
10922 doReTweetOfficial(true);
10923 if (_DoFavRetweetFlags)
10925 _DoFavRetweetFlags = false;
10926 FavoriteChange(true, false);
10930 private void FavoritesRetweetUnofficial()
10932 if (this.ExistCurrentPost && !_curPost.IsDm)
10934 _DoFavRetweetFlags = true;
10935 FavoriteChange(true);
10936 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10938 _DoFavRetweetFlags = false;
10939 doReTweetUnofficial();
10945 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10947 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10948 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10949 /// <returns>復元されたツイート本文</returns>
10950 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10952 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10955 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10957 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10959 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10963 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10965 statusHtml = statusHtml.Replace("<br>", " ");
10967 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10968 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10969 statusHtml = statusHtml.Replace(" ", " ");
10971 return WebUtility.HtmlDecode(statusHtml);
10974 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10976 if (_curPost != null)
10977 DispSelectedPost(true);
10980 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10982 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10983 DebugModeToolStripMenuItem.Visible = true;
10985 DebugModeToolStripMenuItem.Visible = false;
10988 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10990 SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10993 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10995 ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
10998 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11000 if (TraceOutToolStripMenuItem.Checked)
11001 MyCommon.TraceFlag = true;
11003 MyCommon.TraceFlag = false;
11006 private void TweenMain_Deactivate(object sender, EventArgs e)
11008 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11009 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11012 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11014 if (string.IsNullOrEmpty(_rclickTabName)) return;
11015 TabRename(ref _rclickTabName);
11018 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11020 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11023 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11025 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11029 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11031 e.Result = tw.GetInfoApi();
11034 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11036 StringBuilder tmp = new StringBuilder();
11038 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11042 var result = (TwitterApiStatus)dlg.Result;
11044 if (result == null)
11046 var accessLevel = result.AccessLevel;
11047 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11048 var mediaLimit = result.MediaUploadLimit;
11050 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11051 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11052 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11053 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11056 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11057 SetStatusLabelUrl();
11060 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11061 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11062 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11066 tmp.Append(Properties.Resources.ApiInfo5);
11070 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11073 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11076 if (_curPost != null) id = _curPost.ScreenName;
11080 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11082 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11083 e.Result = arg.tw.PostFollowCommand(arg.id);
11086 private void FollowCommand(string id)
11088 using (InputTabName inputName = new InputTabName())
11090 inputName.FormTitle = "Follow";
11091 inputName.FormDescription = Properties.Resources.FRMessage1;
11092 inputName.TabName = id;
11093 if (inputName.ShowDialog() == DialogResult.OK &&
11094 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11096 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11098 arg.id = inputName.TabName.Trim();
11099 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11100 FollowCommand_DoWork,
11104 _info.ShowDialog();
11105 string ret = (string)_info.Result;
11106 if (!string.IsNullOrEmpty(ret))
11107 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11109 MessageBox.Show(Properties.Resources.FRMessage3);
11115 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11118 if (_curPost != null) id = _curPost.ScreenName;
11119 RemoveCommand(id, false);
11122 private class FollowRemoveCommandArgs
11128 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11130 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11131 e.Result = arg.tw.PostRemoveCommand(arg.id);
11134 private void RemoveCommand(string id, bool skipInput)
11136 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11141 using (InputTabName inputName = new InputTabName())
11143 inputName.FormTitle = "Unfollow";
11144 inputName.FormDescription = Properties.Resources.FRMessage1;
11145 inputName.TabName = id;
11146 if (inputName.ShowDialog() == DialogResult.OK &&
11147 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11150 arg.id = inputName.TabName.Trim();
11159 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11160 RemoveCommand_DoWork,
11164 _info.ShowDialog();
11165 string ret = (string)_info.Result;
11166 if (!string.IsNullOrEmpty(ret))
11167 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11169 MessageBox.Show(Properties.Resources.FRMessage3);
11173 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11176 if (_curPost != null)
11177 id = _curPost.ScreenName;
11179 ShowFriendship(id);
11182 private class ShowFriendshipArgs
11185 public class FriendshipInfo
11187 public string id = "";
11188 public bool isFollowing = false;
11189 public bool isFollowed = false;
11190 public FriendshipInfo(string id)
11195 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11198 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11200 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11201 string result = "";
11202 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11204 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11205 if (!string.IsNullOrEmpty(rt))
11207 if (string.IsNullOrEmpty(result)) result = rt;
11213 private void ShowFriendship(string id)
11215 ShowFriendshipArgs args = new ShowFriendshipArgs();
11217 using (InputTabName inputName = new InputTabName())
11219 inputName.FormTitle = "Show Friendships";
11220 inputName.FormDescription = Properties.Resources.FRMessage1;
11221 inputName.TabName = id;
11222 if (inputName.ShowDialog() == DialogResult.OK &&
11223 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11226 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11227 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11228 ShowFriendship_DoWork,
11232 _info.ShowDialog();
11233 ret = (string)_info.Result;
11235 string result = "";
11236 if (string.IsNullOrEmpty(ret))
11238 if (args.ids[0].isFollowing)
11240 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11244 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11246 if (args.ids[0].isFollowed)
11248 result += Properties.Resources.GetFriendshipInfo3;
11252 result += Properties.Resources.GetFriendshipInfo4;
11254 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11260 MessageBox.Show(result);
11265 private void ShowFriendship(string[] ids)
11267 foreach (string id in ids)
11270 ShowFriendshipArgs args = new ShowFriendshipArgs();
11272 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11273 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11274 ShowFriendship_DoWork,
11278 _info.ShowDialog();
11279 ret = (string)_info.Result;
11281 string result = "";
11282 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11284 if (string.IsNullOrEmpty(ret))
11287 if (fInfo.isFollowing)
11289 ff += Properties.Resources.GetFriendshipInfo1;
11293 ff += Properties.Resources.GetFriendshipInfo2;
11296 ff += System.Environment.NewLine + " ";
11297 if (fInfo.isFollowed)
11299 ff += Properties.Resources.GetFriendshipInfo3;
11303 ff += Properties.Resources.GetFriendshipInfo4;
11305 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11306 if (fInfo.isFollowing)
11308 if (MessageBox.Show(
11309 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11310 MessageBoxButtons.YesNo,
11311 MessageBoxIcon.Question,
11312 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11314 RemoveCommand(fInfo.id, true);
11319 MessageBox.Show(result);
11324 MessageBox.Show(ret);
11329 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11331 doShowUserStatus(tw.Username, false);
11332 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11334 // doShowUserStatus(tw.Username, false);
11338 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11343 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11344 // URLから切り出した文字列を渡す
11346 public bool IsTwitterId(string name)
11348 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11349 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11351 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11354 private string GetUserId()
11356 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11357 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11358 return m.Result("${ScreenName}");
11363 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11365 string name = GetUserId();
11366 if (name != null) FollowCommand(name);
11369 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11371 string name = GetUserId();
11372 if (name != null) RemoveCommand(name, false);
11375 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11377 string name = GetUserId();
11378 if (name != null) ShowFriendship(name);
11381 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11383 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11384 List<string> ids = new List<string>();
11385 foreach (Match mu in ma)
11387 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11389 ids.Add(mu.Result("${ScreenName}"));
11392 ShowFriendship(ids.ToArray());
11395 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11397 string name = GetUserId();
11398 if (name != null) ShowUserStatus(name);
11401 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11403 string name = GetUserId();
11404 if (name != null) AddNewTabForUserTimeline(name);
11407 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11409 string name = GetUserId();
11410 if (name != null) AddNewTabForSearch("@" + name);
11413 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11415 _modifySettingCommon = true;
11418 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11420 _modifySettingCommon = true;
11423 private void doQuote()
11427 if (this.ExistCurrentPost)
11429 if (_curPost.IsDm ||
11430 !StatusText.Enabled) return;
11432 if (_curPost.IsProtect)
11434 MessageBox.Show("Protected.");
11437 string rtdata = _curPost.Text;
11438 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11440 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11441 if (_curPost.RetweetedId == null)
11443 _reply_to_id = _curPost.StatusId;
11447 _reply_to_id = _curPost.RetweetedId.Value;
11449 _reply_to_name = _curPost.ScreenName;
11451 StatusText.SelectionStart = 0;
11452 StatusText.Focus();
11456 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11461 private void SearchButton_Click(object sender, EventArgs e)
11464 Control pnl = ((Control)sender).Parent;
11465 if (pnl == null) return;
11466 string tbName = pnl.Parent.Text;
11467 TabClass tb = _statuses.Tabs[tbName];
11468 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11469 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11470 cmb.Text = cmb.Text.Trim();
11471 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11472 bool Quote = false;
11473 StringBuilder buf = new StringBuilder();
11474 char[] c = cmb.Text.ToCharArray();
11475 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11477 if (cnt > cmb.Text.Length - 4)
11479 buf.Append(cmb.Text.Substring(cnt));
11488 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11490 buf.Append(" OR ");
11495 buf.Append(c[cnt]);
11497 cmb.Text = buf.ToString();
11499 tb.SearchWords = cmb.Text;
11500 tb.SearchLang = cmbLang.Text;
11501 if (string.IsNullOrEmpty(cmb.Text))
11503 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11507 if (tb.IsQueryChanged())
11509 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11510 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11511 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11512 cmb.Text = tb.SearchWords;
11514 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11515 this.PurgeListViewItemCache();
11516 lst.VirtualListSize = 0;
11517 _statuses.ClearTabIds(tbName);
11518 SaveConfigsTabs(); //検索条件の保存
11521 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, tbName);
11522 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11525 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11531 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11533 if (_statuses.RemovedTab.Count == 0)
11535 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11540 TabClass tb = _statuses.RemovedTab.Pop();
11541 if (tb.TabType == MyCommon.TabUsageType.Related)
11543 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11544 if (relatedTab != null)
11546 // 関連発言なら既存のタブを置き換える
11547 tb.TabName = relatedTab.TabName;
11548 this.ClearTab(tb.TabName, false);
11549 _statuses.Tabs[tb.TabName] = tb;
11550 for (int i = 0; i < ListTab.TabPages.Count; i++)
11552 if (tb.TabName == ListTab.TabPages[i].Text)
11554 ListTab.SelectedIndex = i;
11555 ListTabSelect(ListTab.TabPages[i]);
11562 const string TabName = "Related Tweets";
11563 string renamed = TabName;
11564 for (int i = 2; i <= 100; i++)
11566 if (!_statuses.ContainsTab(renamed)) break;
11567 renamed = TabName + i.ToString();
11569 tb.TabName = renamed;
11570 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11571 _statuses.Tabs.Add(renamed, tb); // 後に
11572 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11573 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11578 string renamed = tb.TabName;
11579 for (int i = 1; i < int.MaxValue; i++)
11581 if (!_statuses.ContainsTab(renamed)) break;
11582 renamed = tb.TabName + "(" + i.ToString() + ")";
11584 tb.TabName = renamed;
11585 _statuses.Tabs.Add(renamed, tb); // 先に
11586 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11587 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11588 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11594 private void doMoveToRTHome()
11596 if (_curList.SelectedIndices.Count > 0)
11598 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11599 if (post.RetweetedId != null)
11601 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11606 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11611 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11613 string name = GetUserId();
11619 if (_curList.SelectedIndices.Count == 0) return;
11622 if (!SelectTab(out tabName)) return;
11626 MoveOrCopy(ref mv, ref mk);
11628 PostFilterRule fc = new PostFilterRule();
11629 fc.FilterName = name;
11630 fc.UseNameField = true;
11631 fc.MoveMatches = mv;
11632 fc.MarkMatches = mk;
11633 fc.UseRegex = false;
11634 fc.FilterByUrl = false;
11635 _statuses.Tabs[tabName].AddFilter(fc);
11637 this.ApplyPostFilters();
11642 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11646 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11648 if (menuItem.Owner == this.ContextMenuPostBrowser)
11650 user = GetUserId();
11651 if (user == null) return;
11653 else if (this._curPost != null)
11655 user = this._curPost.ScreenName;
11662 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11664 string res = this.tw.GetListsApi();
11666 if (!string.IsNullOrEmpty(res))
11668 MessageBox.Show("Failed to get lists. (" + res + ")");
11673 using (MyLists listSelectForm = new MyLists(user, this.tw))
11675 listSelectForm.ShowDialog(this);
11679 private void SearchControls_Enter(object sender, EventArgs e)
11681 Control pnl = (Control)sender;
11682 foreach (Control ctl in pnl.Controls)
11684 ctl.TabStop = true;
11688 private void SearchControls_Leave(object sender, EventArgs e)
11690 Control pnl = (Control)sender;
11691 foreach (Control ctl in pnl.Controls)
11693 ctl.TabStop = false;
11697 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11699 if (ListTab.SelectedTab != null)
11701 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11702 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11706 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11708 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11711 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
11712 HashStripSplitButton.Text = HashMgr.UseHash;
11713 HashToggleMenuItem.Checked = true;
11714 HashToggleToolStripMenuItem.Checked = true;
11716 _modifySettingCommon = true;
11720 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11722 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11725 private void HashManageMenuItem_Click(object sender, EventArgs e)
11727 DialogResult rslt = DialogResult.Cancel;
11730 rslt = HashMgr.ShowDialog();
11736 this.TopMost = SettingDialog.AlwaysTop;
11737 if (rslt == DialogResult.Cancel) return;
11738 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11740 HashStripSplitButton.Text = HashMgr.UseHash;
11741 HashToggleMenuItem.Checked = true;
11742 HashToggleToolStripMenuItem.Checked = true;
11746 HashStripSplitButton.Text = "#[-]";
11747 HashToggleMenuItem.Checked = false;
11748 HashToggleToolStripMenuItem.Checked = false;
11750 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11752 // int sidx = StatusText.SelectionStart;
11753 // string hash = HashMgr.UseHash + " ";
11756 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11757 // hash = " " + hash;
11759 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11760 // sidx += hash.Length;
11761 // StatusText.SelectionStart = sidx;
11762 // StatusText.Focus();
11764 _modifySettingCommon = true;
11765 this.StatusText_TextChanged(null, null);
11768 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11770 HashMgr.ToggleHash();
11771 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11773 HashStripSplitButton.Text = HashMgr.UseHash;
11774 HashToggleMenuItem.Checked = true;
11775 HashToggleToolStripMenuItem.Checked = true;
11779 HashStripSplitButton.Text = "#[-]";
11780 HashToggleMenuItem.Checked = false;
11781 HashToggleToolStripMenuItem.Checked = false;
11783 _modifySettingCommon = true;
11784 this.StatusText_TextChanged(null, null);
11787 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11789 HashToggleMenuItem_Click(null, null);
11792 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11794 if (ListTab.SelectedTab == null) return;
11795 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11796 if (!this.ExistCurrentPost)
11798 this.ReplyOpMenuItem.Enabled = false;
11799 this.ReplyAllOpMenuItem.Enabled = false;
11800 this.DmOpMenuItem.Enabled = false;
11801 this.ShowProfMenuItem.Enabled = false;
11802 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11803 this.ListManageMenuItem.Enabled = false;
11804 this.OpenFavOpMenuItem.Enabled = false;
11805 this.CreateTabRuleOpMenuItem.Enabled = false;
11806 this.CreateIdRuleOpMenuItem.Enabled = false;
11807 this.ReadOpMenuItem.Enabled = false;
11808 this.UnreadOpMenuItem.Enabled = false;
11812 this.ReplyOpMenuItem.Enabled = true;
11813 this.ReplyAllOpMenuItem.Enabled = true;
11814 this.DmOpMenuItem.Enabled = true;
11815 this.ShowProfMenuItem.Enabled = true;
11816 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11817 this.ListManageMenuItem.Enabled = true;
11818 this.OpenFavOpMenuItem.Enabled = true;
11819 this.CreateTabRuleOpMenuItem.Enabled = true;
11820 this.CreateIdRuleOpMenuItem.Enabled = true;
11821 this.ReadOpMenuItem.Enabled = true;
11822 this.UnreadOpMenuItem.Enabled = true;
11825 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11827 this.FavOpMenuItem.Enabled = false;
11828 this.UnFavOpMenuItem.Enabled = false;
11829 this.OpenStatusOpMenuItem.Enabled = false;
11830 this.OpenFavotterOpMenuItem.Enabled = false;
11831 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11832 this.RtOpMenuItem.Enabled = false;
11833 this.RtUnOpMenuItem.Enabled = false;
11834 this.QtOpMenuItem.Enabled = false;
11835 this.FavoriteRetweetMenuItem.Enabled = false;
11836 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11837 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11841 this.FavOpMenuItem.Enabled = true;
11842 this.UnFavOpMenuItem.Enabled = true;
11843 this.OpenStatusOpMenuItem.Enabled = true;
11844 this.OpenFavotterOpMenuItem.Enabled = true;
11845 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11849 this.RtOpMenuItem.Enabled = false;
11850 this.FavoriteRetweetMenuItem.Enabled = false;
11851 this.DelOpMenuItem.Enabled = true;
11855 this.DelOpMenuItem.Enabled = false;
11856 if (_curPost.IsProtect)
11858 this.RtOpMenuItem.Enabled = false;
11859 this.RtUnOpMenuItem.Enabled = false;
11860 this.QtOpMenuItem.Enabled = false;
11861 this.FavoriteRetweetMenuItem.Enabled = false;
11862 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11866 this.RtOpMenuItem.Enabled = true;
11867 this.RtUnOpMenuItem.Enabled = true;
11868 this.QtOpMenuItem.Enabled = true;
11869 this.FavoriteRetweetMenuItem.Enabled = true;
11870 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11875 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11877 this.RefreshPrevOpMenuItem.Enabled = true;
11881 this.RefreshPrevOpMenuItem.Enabled = false;
11883 if (!this.ExistCurrentPost
11884 || _curPost.InReplyToStatusId == null)
11886 OpenRepSourceOpMenuItem.Enabled = false;
11890 OpenRepSourceOpMenuItem.Enabled = true;
11892 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11894 OpenRterHomeMenuItem.Enabled = false;
11898 OpenRterHomeMenuItem.Enabled = true;
11902 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11904 ContextMenuTabProperty_Opening(sender, null);
11907 public Twitter TwitterInstance
11912 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11914 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
11916 _mySpDis3 = SplitContainer3.SplitterDistance;
11917 _modifySettingLocal = true;
11921 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11923 if (_statuses.RemovedTab.Count == 0)
11925 UndoRemoveTabMenuItem.Enabled = false;
11929 UndoRemoveTabMenuItem.Enabled = true;
11931 if (ListTab.SelectedTab != null)
11933 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11934 PublicSearchQueryMenuItem.Enabled = true;
11936 PublicSearchQueryMenuItem.Enabled = false;
11940 PublicSearchQueryMenuItem.Enabled = false;
11942 if (!this.ExistCurrentPost)
11944 this.CopySTOTMenuItem.Enabled = false;
11945 this.CopyURLMenuItem.Enabled = false;
11946 this.CopyUserIdStripMenuItem.Enabled = false;
11950 this.CopySTOTMenuItem.Enabled = true;
11951 this.CopyURLMenuItem.Enabled = true;
11952 this.CopyUserIdStripMenuItem.Enabled = true;
11953 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11954 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11958 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11960 SetNotifyIconText();
11963 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11966 if (_curPost != null)
11968 id = _curPost.ScreenName;
11970 ShowUserStatus(id);
11973 private class GetUserInfoArgs
11977 public TwitterUser user;
11980 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
11982 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
11983 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
11986 private void doShowUserStatus(string id, bool ShowInputDialog)
11988 TwitterUser user = null;
11989 GetUserInfoArgs args = new GetUserInfoArgs();
11990 if (ShowInputDialog)
11992 using (InputTabName inputName = new InputTabName())
11994 inputName.FormTitle = "Show UserStatus";
11995 inputName.FormDescription = Properties.Resources.FRMessage1;
11996 inputName.TabName = id;
11997 if (inputName.ShowDialog() == DialogResult.OK &&
11998 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12000 id = inputName.TabName.Trim();
12004 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12005 GetUserInfo_DoWork,
12009 _info.ShowDialog();
12010 string ret = (string)_info.Result;
12011 if (string.IsNullOrEmpty(ret))
12012 doShowUserStatus(args.user);
12014 MessageBox.Show(ret);
12024 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12025 GetUserInfo_DoWork,
12029 _info.ShowDialog();
12030 string ret = (string)_info.Result;
12031 if (string.IsNullOrEmpty(ret))
12033 doShowUserStatus(args.user);
12037 MessageBox.Show(ret);
12043 private async void doShowUserStatus(TwitterUser user)
12045 using (var userDialog = new UserInfoDialog(this, this.tw))
12047 var showUserTask = userDialog.ShowUserAsync(user);
12048 userDialog.ShowDialog(this);
12051 this.BringToFront();
12053 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12054 await showUserTask;
12058 private void ShowUserStatus(string id, bool ShowInputDialog)
12060 doShowUserStatus(id, ShowInputDialog);
12063 private void ShowUserStatus(string id)
12065 doShowUserStatus(id, true);
12068 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12070 if (NameLabel.Tag != null)
12072 string id = (string)NameLabel.Tag;
12073 if (id != tw.Username)
12080 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12082 if (NameLabel.Tag != null)
12084 string id = (string)NameLabel.Tag;
12085 if (id != tw.Username)
12087 RemoveCommand(id, false);
12092 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12094 if (NameLabel.Tag != null)
12096 string id = (string)NameLabel.Tag;
12097 if (id != tw.Username)
12099 ShowFriendship(id);
12104 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12106 if (NameLabel.Tag != null)
12108 string id = (string)NameLabel.Tag;
12109 ShowUserStatus(id, false);
12113 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12115 if (NameLabel.Tag != null)
12117 string id = (string)NameLabel.Tag;
12118 AddNewTabForUserTimeline(id);
12122 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12124 if (NameLabel.Tag != null)
12126 string id = (string)NameLabel.Tag;
12127 AddNewTabForSearch("@" + id);
12131 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12133 if (_curPost != null)
12135 ShowUserStatus(_curPost.ScreenName, false);
12139 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12144 if (_curPost.RetweetedId != null)
12146 statusid = _curPost.RetweetedId.Value;
12150 statusid = _curPost.StatusId;
12152 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12154 e.Result = counter;
12157 private void RtCountMenuItem_Click(object sender, EventArgs e)
12159 if (this.ExistCurrentPost)
12161 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12162 GetRetweet_DoWork))
12164 int retweet_count = 0;
12167 _info.ShowDialog();
12168 retweet_count = (int)_info.Result;
12169 if (retweet_count < 0)
12171 MessageBox.Show(Properties.Resources.RtCountText2);
12175 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12181 private HookGlobalHotkey _hookGlobalHotkey;
12184 _hookGlobalHotkey = new HookGlobalHotkey(this);
12186 // この呼び出しは、Windows フォーム デザイナで必要です。
12187 InitializeComponent();
12189 // InitializeComponent() 呼び出しの後で初期化を追加します。
12191 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12192 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12193 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12194 this.gh.NotifyClicked += GrowlHelper_Callback;
12196 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12197 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12199 this._apiGauge = new ToolStripAPIGauge();
12200 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12201 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12203 this.ImageSelector.Visible = false;
12204 this.ImageSelector.Enabled = false;
12205 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12207 this.ReplaceAppName();
12210 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12212 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12215 this.Visible = false;
12217 else if (Form.ActiveForm == null)
12219 this.Visible = true;
12220 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12222 this.BringToFront();
12223 this.StatusText.Focus();
12227 private void UserPicture_MouseEnter(object sender, EventArgs e)
12229 this.UserPicture.Cursor = Cursors.Hand;
12232 private void UserPicture_MouseLeave(object sender, EventArgs e)
12234 this.UserPicture.Cursor = Cursors.Default;
12237 private void UserPicture_DoubleClick(object sender, EventArgs e)
12239 if (NameLabel.Tag != null)
12241 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12245 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12247 this.MultiLineMenuItem.PerformClick();
12250 public PostClass CurPost
12252 get { return _curPost; }
12255 public bool IsPreviewEnable
12257 get { return SettingDialog.PreviewEnable; }
12261 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12263 if (ImageSelector.Visible)
12264 ImageSelector.EndSelection();
12266 ImageSelector.BeginSelection();
12269 private void SelectMedia_DragEnter(DragEventArgs e)
12271 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12273 e.Effect = DragDropEffects.Copy;
12276 e.Effect = DragDropEffects.None;
12279 private void SelectMedia_DragOver(DragEventArgs e)
12284 private void SelectMedia_DragDrop(DragEventArgs e)
12287 this.BringToFront();
12288 ImageSelector.BeginSelection(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0]);
12289 StatusText.Focus();
12292 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12294 TimelinePanel.Visible = false;
12295 TimelinePanel.Enabled = false;
12298 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12300 TimelinePanel.Visible = true;
12301 TimelinePanel.Enabled = true;
12302 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12305 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12307 this.AllowDrop = false;
12310 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12312 this.AllowDrop = true;
12315 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12317 if (ImageSelector.Visible)
12319 _modifySettingCommon = true;
12320 SaveConfigsAll(true);
12322 if (ImageSelector.ServiceName.Equals("Twitter"))
12323 this.StatusText_TextChanged(null, null);
12327 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12329 this.StatusText_TextChanged(null, null);
12333 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12335 using (ListManage form = new ListManage(tw))
12337 form.ShowDialog(this);
12341 public bool ModifySettingCommon
12343 set { _modifySettingCommon = value; }
12346 public bool ModifySettingLocal
12348 set { _modifySettingLocal = value; }
12351 public bool ModifySettingAtId
12353 set { _modifySettingAtId = value; }
12356 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12358 string link = (string)SourceLinkLabel.Tag;
12359 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12361 OpenUriAsync(link);
12365 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12367 string link = (string)SourceLinkLabel.Tag;
12368 if (!string.IsNullOrEmpty(link))
12370 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12374 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12376 SetStatusLabelUrl();
12379 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12381 if (this.ExistCurrentPost && !_curPost.IsDm)
12382 RtCountMenuItem.Enabled = true;
12384 RtCountMenuItem.Enabled = false;
12386 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12387 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12389 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12392 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12397 private void CopyUserId()
12399 if (_curPost == null) return;
12400 string clstr = _curPost.ScreenName;
12403 Clipboard.SetDataObject(clstr, false, 5, 100);
12405 catch (Exception ex)
12407 MessageBox.Show(ex.Message);
12411 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12413 if (this.ExistCurrentPost && !_curPost.IsDm)
12417 this.OpenRelatedTab(this._curPost);
12419 catch (TabException ex)
12421 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12427 /// 指定されたツイートに対する関連発言タブを開きます
12429 /// <param name="post">表示する対象となるツイート</param>
12430 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12431 private void OpenRelatedTab(PostClass post)
12433 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12436 if (tabRelated == null)
12438 tabName = this._statuses.MakeTabName("Related Tweets");
12440 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12441 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12443 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12444 tabRelated.UnreadManage = false;
12445 tabRelated.Notify = false;
12449 tabName = tabRelated.TabName;
12452 tabRelated.RelationTargetPost = post;
12453 this.ClearTab(tabName, false);
12455 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12457 var tabPage = this.ListTab.TabPages[i];
12458 if (tabName == tabPage.Text)
12460 this.ListTab.SelectedIndex = i;
12461 this.ListTabSelect(tabPage);
12466 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, tabName);
12469 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12471 StringBuilder buf = new StringBuilder();
12472 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12473 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12474 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12475 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12476 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12479 private void tw_UserIdChanged()
12481 this._modifySettingCommon = true;
12484 #region "Userstream"
12485 private bool _isActiveUserstream = false;
12487 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12491 if (InvokeRequired && !IsDisposed)
12493 Invoke((Action) (() =>
12495 _statuses.RemovePostReserve(e.StatusId);
12496 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12498 this.PurgeListViewItemCache();
12499 ((DetailsListView)_curTab.Tag).Update();
12500 if (_curPost != null && _curPost.StatusId == e.StatusId) DispSelectedPost(true);
12506 catch (ObjectDisposedException)
12510 catch (InvalidOperationException)
12516 private void tw_NewPostFromStream(object sender, EventArgs e)
12518 if (this._cfgCommon.ReadOldPosts)
12520 _statuses.SetRead(); //新着時未読クリア
12523 int rsltAddCount = _statuses.DistributePosts();
12526 DateTime tm = DateTime.Now;
12527 if (_tlTimestamps.ContainsKey(tm))
12529 _tlTimestamps[tm] += rsltAddCount;
12533 _tlTimestamps.Add(tm, rsltAddCount);
12535 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12536 List<DateTime> keys = new List<DateTime>();
12538 foreach (DateTime key in _tlTimestamps.Keys)
12540 if (key.CompareTo(oneHour) < 0)
12543 _tlCount += _tlTimestamps[key];
12545 foreach (DateTime key in keys)
12547 _tlTimestamps.Remove(key);
12551 //Static DateTime before = Now;
12552 //if (before.Subtract(Now).Seconds > -5) return;
12556 if (this._cfgCommon.UserstreamPeriod > 0) return;
12560 if (InvokeRequired && !IsDisposed)
12562 Invoke(new Action<bool>(RefreshTimeline), true);
12566 catch (ObjectDisposedException)
12570 catch (InvalidOperationException)
12576 private void tw_UserStreamStarted(object sender, EventArgs e)
12578 this._isActiveUserstream = true;
12581 if (InvokeRequired && !IsDisposed)
12583 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12587 catch (ObjectDisposedException)
12591 catch (InvalidOperationException)
12596 MenuItemUserStream.Text = "&UserStream ▶";
12597 MenuItemUserStream.Enabled = true;
12598 StopToolStripMenuItem.Text = "&Stop";
12599 StopToolStripMenuItem.Enabled = true;
12601 StatusLabel.Text = "UserStream Started.";
12604 private void tw_UserStreamStopped(object sender, EventArgs e)
12606 this._isActiveUserstream = false;
12609 if (InvokeRequired && !IsDisposed)
12611 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12615 catch (ObjectDisposedException)
12619 catch (InvalidOperationException)
12624 MenuItemUserStream.Text = "&UserStream ■";
12625 MenuItemUserStream.Enabled = true;
12626 StopToolStripMenuItem.Text = "&Start";
12627 StopToolStripMenuItem.Enabled = true;
12629 StatusLabel.Text = "UserStream Stopped.";
12632 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12636 if (InvokeRequired && !IsDisposed)
12638 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12642 catch (ObjectDisposedException)
12646 catch (InvalidOperationException)
12650 var ev = e.EventData;
12651 StatusLabel.Text = "Event: " + ev.Event;
12652 //if (ev.Event == "favorite")
12654 // NotifyFavorite(ev);
12657 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12659 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12661 this.PurgeListViewItemCache();
12662 ((DetailsListView)_curTab.Tag).Update();
12664 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12666 RemovePostFromFavTab(new long[] {ev.Id});
12671 private void NotifyEvent(Twitter.FormattedEvent ev)
12674 if (BalloonRequired(ev))
12676 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12677 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12678 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12679 StringBuilder title = new StringBuilder();
12680 if (SettingDialog.DispUsername)
12682 title.Append(tw.Username);
12683 title.Append(" - ");
12689 title.Append(Application.ProductName);
12690 title.Append(" [");
12691 title.Append(ev.Event.ToUpper());
12692 title.Append("] by ");
12693 if (!string.IsNullOrEmpty(ev.Username))
12695 title.Append(ev.Username.ToString());
12699 //title.Append("");
12702 if (!string.IsNullOrEmpty(ev.Target))
12704 //NotifyIcon1.BalloonTipText = ev.Target;
12709 //NotifyIcon1.BalloonTipText = " ";
12712 //NotifyIcon1.ShowBalloonTip(500);
12713 if (SettingDialog.IsNotifyUseGrowl)
12715 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
12716 ev.Id.ToString(), title.ToString(), text);
12720 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12721 NotifyIcon1.BalloonTipTitle = title.ToString();
12722 NotifyIcon1.BalloonTipText = text;
12723 NotifyIcon1.ShowBalloonTip(500);
12728 string snd = SettingDialog.EventSoundFile;
12729 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
12731 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
12735 string dir = Application.StartupPath;
12736 if (Directory.Exists(Path.Combine(dir, "Sounds")))
12738 dir = Path.Combine(dir, "Sounds");
12740 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
12752 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
12754 MenuItemUserStream.Enabled = false;
12755 if (StopRefreshAllMenuItem.Checked)
12757 StopRefreshAllMenuItem.Checked = false;
12760 if (this._isActiveUserstream)
12762 tw.StopUserStream();
12766 tw.StartUserStream();
12770 private static string inputTrack = "";
12772 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
12774 if (TrackToolStripMenuItem.Checked)
12776 using (InputTabName inputForm = new InputTabName())
12778 inputForm.TabName = inputTrack;
12779 inputForm.FormTitle = "Input track word";
12780 inputForm.FormDescription = "Track word";
12781 if (inputForm.ShowDialog() != DialogResult.OK)
12783 TrackToolStripMenuItem.Checked = false;
12786 inputTrack = inputForm.TabName.Trim();
12788 if (!inputTrack.Equals(tw.TrackWord))
12790 tw.TrackWord = inputTrack;
12791 this._modifySettingCommon = true;
12792 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
12793 tw.ReconnectUserStream();
12799 tw.ReconnectUserStream();
12801 this._modifySettingCommon = true;
12804 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
12806 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
12807 this._modifySettingCommon = true;
12808 tw.ReconnectUserStream();
12811 private void EventViewerMenuItem_Click(object sender, EventArgs e)
12813 if (evtDialog == null || evtDialog.IsDisposed)
12816 evtDialog = new EventViewerDialog();
12817 evtDialog.Owner = this;
12819 Point pos = evtDialog.Location;
12820 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
12821 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
12822 evtDialog.Location = pos;
12824 evtDialog.EventSource = tw.StoredEvent;
12825 if (!evtDialog.Visible)
12827 evtDialog.Show(this);
12831 evtDialog.Activate();
12833 this.TopMost = this.SettingDialog.AlwaysTop;
12837 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12839 MyCommon._endingFlag = true;
12843 Application.Restart();
12847 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12851 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12853 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12856 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12858 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
12861 private async Task doTranslation(string str)
12863 if (string.IsNullOrEmpty(str))
12866 var bing = new Bing();
12869 var translatedText = await bing.TranslateAsync(str,
12871 langTo: this.SettingDialog.TranslateLanguage);
12873 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
12875 catch (HttpRequestException e)
12877 this.StatusLabel.Text = "Err:" + e.Message;
12881 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
12883 if (!this.ExistCurrentPost)
12886 await this.doTranslation(this._curPost.TextFromApi);
12889 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
12891 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
12892 await this.doTranslation(text);
12895 private bool ExistCurrentPost
12899 if (_curPost == null) return false;
12900 if (_curPost.IsDeleted) return false;
12905 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12907 ShowUserTimeline();
12910 public bool FavEventChangeUnread
12912 get { return SettingDialog.FavEventUnread; }
12915 private string GetUserIdFromCurPostOrInput(string caption)
12918 if (_curPost != null)
12920 id = _curPost.ScreenName;
12922 using (InputTabName inputName = new InputTabName())
12924 inputName.FormTitle = caption;
12925 inputName.FormDescription = Properties.Resources.FRMessage1;
12926 inputName.TabName = id;
12927 if (inputName.ShowDialog() == DialogResult.OK &&
12928 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12930 id = inputName.TabName.Trim();
12940 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12942 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12943 if (!string.IsNullOrEmpty(id))
12945 AddNewTabForUserTimeline(id);
12949 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12951 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12952 if (!string.IsNullOrEmpty(id))
12954 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12958 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12960 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12963 private void TimelineRefreshEnableChange(bool isEnable)
12967 tw.StartUserStream();
12971 tw.StopUserStream();
12973 TimerTimeline.Enabled = isEnable;
12976 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12978 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12981 private void OpenUserAppointUrl()
12983 if (SettingDialog.UserAppointUrl != null)
12985 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
12987 if (_curPost != null)
12989 string xUrl = SettingDialog.UserAppointUrl;
12990 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12991 if (_curPost.RetweetedId != null)
12993 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
12997 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
12999 OpenUriAsync(xUrl);
13004 OpenUriAsync(SettingDialog.UserAppointUrl);
13009 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13011 OpenUserAppointUrl();
13014 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13016 string selText = SourceLinkLabel.Text;
13019 Clipboard.SetDataObject(selText, false, 5, 100);
13021 catch (Exception ex)
13023 MessageBox.Show(ex.Message);
13027 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13029 string selText = (string)SourceLinkLabel.Tag;
13032 Clipboard.SetDataObject(selText, false, 5, 100);
13034 catch (Exception ex)
13036 MessageBox.Show(ex.Message);
13040 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13042 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13044 SourceCopyMenuItem.Enabled = false;
13045 SourceUrlCopyMenuItem.Enabled = false;
13049 SourceCopyMenuItem.Enabled = true;
13050 SourceUrlCopyMenuItem.Enabled = true;
13054 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13056 if (Form.ActiveForm == null)
13058 this.BeginInvoke((Action) (() =>
13060 this.Visible = true;
13061 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13063 this.BringToFront();
13064 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13066 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13070 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13076 private void ReplaceAppName()
13078 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13079 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13082 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13084 this.SplitContainer3.Panel2Collapsed = false;
13086 // PreviewDistance が起動のたびに広がっていく問題の回避策
13087 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13088 // None で開いた後に設定するようにする
13089 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13090 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13093 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13095 this.OpenThumbnailPicture(e.Thumbnail);
13098 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13100 this.OpenUriAsync(e.ImageUrl);
13103 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13105 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13108 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13110 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13113 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13115 if (e.KeyCode == Keys.Space)
13117 this.JumpUnreadMenuItem_Click(null, null);
13119 e.SuppressKeyPress = true;
13123 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13125 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13126 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13127 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13128 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13129 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13131 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13134 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13136 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13139 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13141 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13144 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13146 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13149 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13151 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13154 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13156 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13159 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13161 if (this._cfgCommon.IconSize == iconSize) return;
13163 var oldIconCol = _iconCol;
13165 this._cfgCommon.IconSize = iconSize;
13166 ApplyListViewIconSize(iconSize);
13168 if (_iconCol != oldIconCol)
13170 foreach (TabPage tp in ListTab.TabPages)
13172 ResetColumns((DetailsListView)tp.Tag);
13176 if (_curList != null) _curList.Refresh();
13178 _modifySettingCommon = true;
13181 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13183 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13184 if (this._cfgCommon.SortOrderLock == state) return;
13186 this._cfgCommon.SortOrderLock = state;
13188 _modifySettingCommon = true;