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;
755 if (this._cfgCommon.CountApi < 20 || this._cfgCommon.CountApi > 200)
756 this._cfgCommon.CountApi = 60;
757 if (this._cfgCommon.CountApiReply < 20 || this._cfgCommon.CountApiReply > 200)
758 this._cfgCommon.CountApiReply = 40;
761 this.SettingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
762 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
765 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
766 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
768 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
770 //新着取得時のリストスクロールをするか。trueならスクロールしない
771 ListLockMenuItem.Checked = _cfgCommon.ListLock;
772 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
774 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
775 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
777 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
778 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
779 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
780 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
781 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
782 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
784 //廃止サービスが選択されていた場合bit.lyへ読み替え
785 if (_cfgCommon.AutoShortUrlFirst < 0)
786 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
788 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
790 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
791 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
793 //Regex statregex = new Regex("^0*");
794 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
796 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
799 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
800 HashMgr = new HashtagManage(HashSupl,
801 _cfgCommon.HashTags.ToArray(),
802 _cfgCommon.HashSelected,
803 _cfgCommon.HashIsPermanent,
804 _cfgCommon.HashIsHead,
805 _cfgCommon.HashIsNotAddToAtReply);
806 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
810 Networking.Initialize();
813 this.IconCache = new ImageCache();
815 bool saveRequired = false;
816 bool firstRun = false;
818 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
819 if (string.IsNullOrEmpty(tw.Username))
823 SettingDialog.ShowInTaskbar = true;
825 //設定せずにキャンセルされた場合はプログラム終了
826 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
828 Application.Exit(); //強制終了
831 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
832 if (string.IsNullOrEmpty(tw.Username))
834 Application.Exit(); //強制終了
837 SettingDialog.ShowInTaskbar = false;
841 _fntUnread = this._cfgLocal.FontUnread;
842 _clUnread = this._cfgLocal.ColorUnread;
843 _fntReaded = this._cfgLocal.FontRead;
844 _clReaded = this._cfgLocal.ColorRead;
845 _clFav = this._cfgLocal.ColorFav;
846 _clOWL = this._cfgLocal.ColorOWL;
847 _clRetweet = this._cfgLocal.ColorRetweet;
848 _fntDetail = this._cfgLocal.FontDetail;
849 _clDetail = this._cfgLocal.ColorDetail;
850 _clDetailLink = this._cfgLocal.ColorDetailLink;
851 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
852 _clSelf = this._cfgLocal.ColorSelf;
853 _clAtSelf = this._cfgLocal.ColorAtSelf;
854 _clTarget = this._cfgLocal.ColorTarget;
855 _clAtTarget = this._cfgLocal.ColorAtTarget;
856 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
857 _clAtTo = this._cfgLocal.ColorAtTo;
858 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
859 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
860 _clInputFont = this._cfgLocal.ColorInputFont;
861 _fntInputFont = this._cfgLocal.FontInputFont;
863 //他の設定項目は、随時設定画面で保持している値を読み出して使用
866 _brsBackColorMine = new SolidBrush(_clSelf);
867 _brsBackColorAt = new SolidBrush(_clAtSelf);
868 _brsBackColorYou = new SolidBrush(_clTarget);
869 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
870 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
871 _brsBackColorAtTo = new SolidBrush(_clAtTo);
872 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
873 _brsBackColorNone = new SolidBrush(_clListBackcolor);
875 InitDetailHtmlFormat();
877 if (this._cfgCommon.HotkeyEnabled)
880 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
881 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
882 modKey |= HookGlobalHotkey.ModKeys.Alt;
883 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
884 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
885 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
886 modKey |= HookGlobalHotkey.ModKeys.Shift;
887 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
888 modKey |= HookGlobalHotkey.ModKeys.Win;
890 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
894 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
895 Networking.SetWebProxy(this._cfgLocal.ProxyType,
896 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
897 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
899 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
900 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
901 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
902 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
903 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
904 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
905 tw.TrackWord = _cfgCommon.TrackWord;
906 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
907 tw.AllAtReply = _cfgCommon.AllAtReply;
908 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
911 ImageSelector.Initialize(tw, SettingDialog.TwitterConfiguration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
914 this.ClientSize = _cfgLocal.FormSize;
915 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
916 _myLoc = _cfgLocal.FormLocation;
918 if (this.WindowState != FormWindowState.Minimized)
920 this.DesktopLocation = _cfgLocal.FormLocation;
921 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
922 bool outOfScreen = true;
923 if (Screen.AllScreens.Length == 1) //ハングするとの報告
925 foreach (Screen scr in Screen.AllScreens)
927 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
935 this.DesktopLocation = new Point(0, 0);
936 _myLoc = this.DesktopLocation;
940 this.TopMost = this._cfgCommon.AlwaysTop;
941 _mySpDis = _cfgLocal.SplitterDistance;
942 _mySpDis2 = _cfgLocal.StatusTextHeight;
943 _mySpDis3 = _cfgLocal.PreviewDistance;
946 _mySpDis3 = _mySize.Width - 150;
947 if (_mySpDis3 < 1) _mySpDis3 = 50;
948 _cfgLocal.PreviewDistance = _mySpDis3;
950 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
951 //this.Tween_ClientSizeChanged(this, null);
952 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
953 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
955 StatusText.Font = _fntInputFont;
956 StatusText.ForeColor = _clInputFont;
958 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
959 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
961 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
962 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
964 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
965 if (this._cfgCommon.UnreadManage == false)
967 ReadedStripMenuItem.Enabled = false;
968 UnreadStripMenuItem.Enabled = false;
971 if (this._cfgCommon.IsUseNotifyGrowl)
975 TimerTimeline.AutoReset = true;
976 TimerTimeline.SynchronizingObject = this;
978 TimerTimeline.Interval = 1000;
979 TimerTimeline.Enabled = true;
982 TimerRefreshIcon.Interval = 200;
983 TimerRefreshIcon.Enabled = true;
986 StatusLabel.Text = "";
987 StatusLabel.AutoToolTip = false;
988 StatusLabel.ToolTipText = "";
990 lblLen.Text = GetRestStatusCount(true, false).ToString();
992 ////////////////////////////////////////////////////////////////////////////////
993 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
994 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
995 switch (_cfgCommon.SortColumn)
997 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1001 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1004 mode = IdComparerClass.ComparerMode.Nickname;
1007 mode = IdComparerClass.ComparerMode.Data;
1010 mode = IdComparerClass.ComparerMode.Id;
1013 mode = IdComparerClass.ComparerMode.Name;
1016 mode = IdComparerClass.ComparerMode.Source;
1019 _statuses.SortMode = mode;
1020 ////////////////////////////////////////////////////////////////////////////////
1022 ApplyListViewIconSize(this._cfgCommon.IconSize);
1024 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1025 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1026 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1027 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1028 SourceLinkLabel.Text = ""; //Source部分初期化
1030 //<<<<<<<<タブ関連>>>>>>>
1031 //デフォルトタブの存在チェック、ない場合には追加
1032 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1035 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1037 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1041 tab.TabType = MyCommon.TabUsageType.Home;
1044 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1047 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1049 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1053 tab.TabType = MyCommon.TabUsageType.Mentions;
1056 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1059 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1061 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1065 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1068 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1071 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1073 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1077 tab.TabType = MyCommon.TabUsageType.Favorites;
1080 foreach (var tab in _statuses.Tabs.Values)
1082 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1084 tab.TabType = MyCommon.TabUsageType.UserDefined;
1086 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1087 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1090 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1091 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1092 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1093 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1095 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1097 this.Visible = true;
1099 _curTab = ListTab.SelectedTab;
1101 _curList = (DetailsListView)_curTab.Tag;
1102 SetMainWindowTitle();
1103 SetNotifyIconText();
1105 if (this._cfgCommon.TabIconDisp)
1107 ListTab.DrawMode = TabDrawMode.Normal;
1111 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1112 ListTab.DrawItem += ListTab_DrawItem;
1113 ListTab.ImageList = null;
1116 _ignoreConfigSave = false;
1117 this.TweenMain_Resize(null, null);
1118 if (saveRequired) SaveConfigsAll(false);
1122 tw.VerifyCredentials();
1123 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1125 if (ua.Username.ToLower() == tw.Username.ToLower())
1127 ua.UserId = tw.UserId;
1132 foreach (UserAccount ua in SettingDialog.UserAccounts)
1134 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1136 ua.UserId = tw.UserId;
1143 // 初回起動時だけ右下のメニューを目立たせる
1144 HashStripSplitButton.ShowDropDown();
1151 private void InitDetailHtmlFormat()
1153 if (this._cfgCommon.IsMonospace)
1155 detailHtmlFormatHeader = detailHtmlFormatMono1;
1156 detailHtmlFormatFooter = detailHtmlFormatMono7;
1160 detailHtmlFormatHeader = detailHtmlFormat1;
1161 detailHtmlFormatFooter = detailHtmlFormat7;
1163 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();
1164 if (this._cfgCommon.IsMonospace)
1166 detailHtmlFormatHeader += detailHtmlFormatMono6;
1170 detailHtmlFormatHeader += detailHtmlFormat6;
1174 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1179 txt = ListTab.TabPages[e.Index].Text;
1186 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1187 if (e.State == DrawItemState.Selected)
1189 e.DrawFocusRectangle();
1194 if (_statuses.Tabs[txt].UnreadCount > 0)
1197 fore = System.Drawing.SystemBrushes.ControlText;
1201 fore = System.Drawing.SystemBrushes.ControlText;
1203 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1206 private void LoadConfig()
1208 _cfgCommon = SettingCommon.Load();
1209 SettingCommon.Instance = this._cfgCommon;
1210 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1212 _cfgCommon.UserAccounts = new List<UserAccount>();
1213 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1215 UserAccount account = new UserAccount();
1216 account.Username = _cfgCommon.UserName;
1217 account.UserId = _cfgCommon.UserId;
1218 account.Token = _cfgCommon.Token;
1219 account.TokenSecret = _cfgCommon.TokenSecret;
1221 _cfgCommon.UserAccounts.Add(account);
1224 _cfgLocal = SettingLocal.Load();
1225 List<TabClass> tabs = SettingTabs.Load().Tabs;
1226 foreach (TabClass tb in tabs)
1230 _statuses.Tabs.Add(tb.TabName, tb);
1234 tb.TabName = _statuses.GetUniqueTabName();
1235 _statuses.Tabs.Add(tb.TabName, tb);
1238 if (_statuses.Tabs.Count == 0)
1240 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1241 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1242 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1243 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1247 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1249 if (!TimerTimeline.Enabled) return;
1253 private IntervalChangedEventArgs ResetTimers = new IntervalChangedEventArgs();
1255 private static int homeCounter = 0;
1256 private static int mentionCounter = 0;
1257 private static int dmCounter = 0;
1258 private static int pubSearchCounter = 0;
1259 private static int userTimelineCounter = 0;
1260 private static int listsCounter = 0;
1261 private static int usCounter = 0;
1262 private static int ResumeWait = 0;
1263 private static int refreshFollowers = 0;
1265 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1267 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1268 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1269 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1270 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1271 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1272 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1273 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1274 Interlocked.Increment(ref refreshFollowers);
1277 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1279 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1280 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1281 ResetTimers.Timeline = false;
1283 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1285 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1286 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1287 ResetTimers.Reply = false;
1289 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1291 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1292 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1293 ResetTimers.DirectMessage = false;
1295 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1297 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1298 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1299 ResetTimers.PublicSearch = false;
1301 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1303 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1304 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1305 ResetTimers.UserTimeline = false;
1307 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1309 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1310 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1311 ResetTimers.Lists = false;
1313 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1315 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1316 if (this._isActiveUserstream) RefreshTimeline(true);
1317 ResetTimers.UserStream = false;
1319 if (refreshFollowers > 6 * 3600)
1321 Interlocked.Exchange(ref refreshFollowers, 0);
1322 doGetFollowersMenu();
1323 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
1324 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1328 Interlocked.Increment(ref ResumeWait);
1329 if (ResumeWait > 30)
1332 Interlocked.Exchange(ref ResumeWait, 0);
1333 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1334 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1335 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1336 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1337 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1338 GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1339 doGetFollowersMenu();
1340 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1345 private void RefreshTimeline(bool isUserStream)
1347 if (isUserStream) this.RefreshTasktrayIcon(true);
1349 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1350 long topId = GetScrollPos(ref smode);
1351 int befCnt = _curList.VirtualListSize;
1354 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1355 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1356 SaveSelectedStatus(selId, focusedId);
1359 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1362 PostClass[] notifyPosts = null;
1363 string soundFile = "";
1365 bool isMention = false;
1366 bool isDelete = false;
1367 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1369 if (MyCommon._endingFlag) return;
1374 foreach (TabPage tab in ListTab.TabPages)
1376 DetailsListView lst = (DetailsListView)tab.Tag;
1377 TabClass tabInfo = _statuses.Tabs[tab.Text];
1378 using (ControlTransaction.Update(lst))
1380 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1382 if (lst.Equals(_curList))
1384 this.PurgeListViewItemCache();
1388 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1394 this.SelectListItem(lst,
1395 tabInfo.IndexOf(selId[tab.Text]),
1396 tabInfo.IndexOf(focusedId[tab.Text]));
1399 if (tabInfo.UnreadCount > 0)
1400 if (this._cfgCommon.TabIconDisp)
1401 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1403 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1407 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1416 if (befCnt != _curList.VirtualListSize)
1422 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1426 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1433 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1435 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1436 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1442 catch (Exception ex)
1444 ex.Data["Msg"] = "Ref2";
1450 NotifyNewPosts(notifyPosts,
1453 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1455 SetMainWindowTitle();
1456 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1458 HashSupl.AddRangeItem(tw.GetHashList());
1462 private long GetScrollPos(ref int smode)
1465 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1467 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1469 if (_statuses.SortOrder == SortOrder.Ascending)
1472 if (ListLockMenuItem.Checked)
1477 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1482 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1484 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1485 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1486 if (_item.Index == _curList.VirtualListSize - 1)
1493 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1501 if (ListLockMenuItem.Checked)
1504 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1509 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1512 _item = _curList.GetItemAt(0, 10); //一番上
1513 if (_item == null) _item = _curList.Items[0];
1514 if (_item.Index == 0)
1520 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1529 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1540 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1542 if (MyCommon._endingFlag) return;
1543 foreach (TabPage tab in ListTab.TabPages)
1545 var lst = (DetailsListView)tab.Tag;
1546 var tabInfo = _statuses.Tabs[tab.Text];
1547 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1549 selId.Add(tab.Text, tabInfo.GetId(lst.SelectedIndices));
1553 selId.Add(tab.Text, new long[1] {-2});
1556 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1557 var item = lst.FocusedItem;
1558 fIds[0] = (item != null) ? tabInfo.GetId(item.Index) : -2;
1559 var mIdx = lst.SelectionMark;
1560 fIds[1] = (mIdx > -1) ? tabInfo.GetId(mIdx) : -2;
1561 focusedId.Add(tab.Text, fIds);
1566 private bool BalloonRequired()
1568 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1569 ev.Eventtype = MyCommon.EVENTTYPE.None;
1571 return BalloonRequired(ev);
1574 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1576 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1579 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1581 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1584 private bool BalloonRequired(Twitter.FormattedEvent ev)
1587 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1588 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1592 this._cfgCommon.LimitBalloon &&
1594 this.WindowState == FormWindowState.Minimized ||
1596 Form.ActiveForm == null
1599 !this._cfgCommon.LimitBalloon
1602 !NativeMethods.IsScreenSaverRunning())
1612 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1614 if (notifyPosts != null &&
1615 notifyPosts.Length > 0 &&
1616 this._cfgCommon.ReadOwnPost &&
1617 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1623 if (BalloonRequired())
1625 if (notifyPosts != null && notifyPosts.Length > 0)
1627 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1628 if (this._cfgCommon.IsUseNotifyGrowl)
1630 StringBuilder sb = new StringBuilder();
1634 foreach (PostClass post in notifyPosts)
1636 if (!(notifyPosts.Length > 3))
1642 if (post.IsReply && !post.IsExcludeReply) reply = true;
1643 if (post.IsDm) dm = true;
1644 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1645 switch (this._cfgCommon.NameBalloon)
1647 case MyCommon.NameBalloonEnum.UserID:
1648 sb.Append(post.ScreenName).Append(" : ");
1650 case MyCommon.NameBalloonEnum.NickName:
1651 sb.Append(post.Nickname).Append(" : ");
1654 sb.Append(post.TextFromApi);
1655 if (notifyPosts.Length > 3)
1657 if (notifyPosts.Last() != post) continue;
1660 StringBuilder title = new StringBuilder();
1661 GrowlHelper.NotifyType nt;
1662 if (this._cfgCommon.DispUsername)
1664 title.Append(tw.Username);
1665 title.Append(" - ");
1673 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1674 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1675 title.Append(Application.ProductName);
1676 title.Append(" [DM] ");
1677 title.Append(Properties.Resources.RefreshDirectMessageText1);
1679 title.Append(addCount);
1680 title.Append(Properties.Resources.RefreshDirectMessageText2);
1681 nt = GrowlHelper.NotifyType.DirectMessage;
1685 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1686 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1687 title.Append(Application.ProductName);
1688 title.Append(" [Reply!] ");
1689 title.Append(Properties.Resources.RefreshTimelineText1);
1691 title.Append(addCount);
1692 title.Append(Properties.Resources.RefreshTimelineText2);
1693 nt = GrowlHelper.NotifyType.Reply;
1697 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1698 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1699 title.Append(Application.ProductName);
1701 title.Append(Properties.Resources.RefreshTimelineText1);
1703 title.Append(addCount);
1704 title.Append(Properties.Resources.RefreshTimelineText2);
1705 nt = GrowlHelper.NotifyType.Notify;
1707 string bText = sb.ToString();
1708 if (string.IsNullOrEmpty(bText)) return;
1710 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1711 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1716 StringBuilder sb = new StringBuilder();
1719 foreach (PostClass post in notifyPosts)
1721 if (post.IsReply && !post.IsExcludeReply) reply = true;
1722 if (post.IsDm) dm = true;
1723 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1724 switch (this._cfgCommon.NameBalloon)
1726 case MyCommon.NameBalloonEnum.UserID:
1727 sb.Append(post.ScreenName).Append(" : ");
1729 case MyCommon.NameBalloonEnum.NickName:
1730 sb.Append(post.Nickname).Append(" : ");
1733 sb.Append(post.TextFromApi);
1736 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1737 StringBuilder title = new StringBuilder();
1739 if (this._cfgCommon.DispUsername)
1741 title.Append(tw.Username);
1742 title.Append(" - ");
1750 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1751 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1752 ntIcon = ToolTipIcon.Warning;
1753 title.Append(Application.ProductName);
1754 title.Append(" [DM] ");
1755 title.Append(Properties.Resources.RefreshDirectMessageText1);
1757 title.Append(addCount);
1758 title.Append(Properties.Resources.RefreshDirectMessageText2);
1762 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1763 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1764 ntIcon = ToolTipIcon.Warning;
1765 title.Append(Application.ProductName);
1766 title.Append(" [Reply!] ");
1767 title.Append(Properties.Resources.RefreshTimelineText1);
1769 title.Append(addCount);
1770 title.Append(Properties.Resources.RefreshTimelineText2);
1774 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1775 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1776 ntIcon = ToolTipIcon.Info;
1777 title.Append(Application.ProductName);
1779 title.Append(Properties.Resources.RefreshTimelineText1);
1781 title.Append(addCount);
1782 title.Append(Properties.Resources.RefreshTimelineText2);
1784 string bText = sb.ToString();
1785 if (string.IsNullOrEmpty(bText)) return;
1786 //NotifyIcon1.BalloonTipText = sb.ToString();
1787 //NotifyIcon1.ShowBalloonTip(500);
1788 NotifyIcon1.BalloonTipTitle = title.ToString();
1789 NotifyIcon1.BalloonTipText = bText;
1790 NotifyIcon1.BalloonTipIcon = ntIcon;
1791 NotifyIcon1.ShowBalloonTip(500);
1797 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1801 string dir = Application.StartupPath;
1802 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1804 dir = Path.Combine(dir, "Sounds");
1806 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1816 //mentions新着時に画面ブリンク
1817 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1819 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1823 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1825 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1827 _curItemIndex = _curList.SelectedIndices[0];
1828 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1832 _curPost = GetCurTabPost(_curItemIndex);
1834 catch (ArgumentException)
1839 this.PushSelectPostChain();
1841 if (this._cfgCommon.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1843 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1849 private void ChangeCacheStyleRead(bool Read, int Index)
1851 var tabInfo = _statuses.Tabs[_curTab.Text];
1852 //Read:true=既読 false=未読
1853 //未読管理していなかったら既読として扱う
1854 if (!tabInfo.UnreadManage ||
1855 !this._cfgCommon.UnreadManage) Read = true;
1858 ListViewItem itm = null;
1859 PostClass post = null;
1861 this.TryGetListViewItemCache(Index, out itm, out post);
1863 if (itm == null || post == null)
1865 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1866 post = tabInfo[Index];
1869 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1872 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1879 Item.SubItems[5].Text = "";
1884 Item.SubItems[5].Text = "★";
1890 else if (Post.RetweetedId != null)
1892 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1894 else if (Read || !this._cfgCommon.UseUnreadStyle)
1899 if (DList == null || Item.Index == -1)
1901 Item.ForeColor = cl;
1902 if (this._cfgCommon.UseUnreadStyle)
1908 if (this._cfgCommon.UseUnreadStyle)
1909 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1911 DList.ChangeItemForeColor(Item.Index, cl);
1912 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1916 private void ColorizeList()
1918 //Index:更新対象のListviewItem.Index。Colorを返す。
1919 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1922 _post = _anchorPost;
1926 if (_post == null) return;
1928 var itemColors = new Color[] { };
1931 this.itemCacheLock.EnterReadLock();
1934 if (this._itemCache == null) return;
1937 from i in Enumerable.Range(0, this._itemCache.Length)
1938 select this.JudgeColor(_post, this._postCache[i]);
1940 itemColors = query.ToArray();
1941 itemIndex = _itemCacheIndex;
1943 finally { this.itemCacheLock.ExitReadLock(); }
1945 if (itemIndex < 0) return;
1947 foreach (var backColor in itemColors)
1949 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
1950 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
1951 _curList.ChangeItemBackColor(itemIndex++, backColor);
1955 private void ColorizeList(ListViewItem Item, int Index)
1957 //Index:更新対象のListviewItem.Index。Colorを返す。
1958 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1961 _post = _anchorPost;
1965 PostClass tPost = GetCurTabPost(Index);
1967 if (_post == null) return;
1969 if (Item.Index == -1)
1970 Item.BackColor = JudgeColor(_post, tPost);
1972 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
1975 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
1978 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
1981 else if (TargetPost.IsMe)
1984 else if (TargetPost.IsReply)
1987 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
1989 cl = _clAtFromTarget;
1990 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
1993 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
1998 cl = _clListBackcolor;
2003 private async void PostButton_Click(object sender, EventArgs e)
2005 if (StatusText.Text.Trim().Length == 0)
2007 if (!ImageSelector.Enabled)
2014 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2016 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2018 MessageBoxButtons.YesNoCancel,
2019 MessageBoxIcon.Question);
2022 case DialogResult.Yes:
2023 doReTweetOfficial(false);
2024 StatusText.Text = "";
2026 case DialogResult.Cancel:
2031 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2033 if (this._cfgCommon.Nicoms)
2035 StatusText.SelectionStart = StatusText.Text.Length;
2036 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2038 //if (SettingDialog.UrlConvertAuto)
2040 // StatusText.SelectionStart = StatusText.Text.Length;
2041 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2043 //else if (SettingDialog.Nicoms)
2045 // StatusText.SelectionStart = StatusText.Text.Length;
2046 // UrlConvert(UrlConverter.Nicoms);
2048 StatusText.SelectionStart = StatusText.Text.Length;
2049 GetWorkerArg args = new GetWorkerArg();
2051 args.type = MyCommon.WORKERTYPE.PostMessage;
2052 CheckReplyTo(StatusText.Text);
2055 int adjustCount = 0;
2056 string tmpStatus = StatusText.Text.Trim();
2057 if (ToolStripMenuItemApiCommandEvasion.Checked)
2060 if (Regex.IsMatch(tmpStatus,
2061 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2062 RegexOptions.IgnoreCase)
2063 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2066 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2069 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2072 bool isCutOff = false;
2073 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2074 if (StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
2076 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2077 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2079 if (this._cfgCommon.PostShiftEnter)
2081 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2083 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2085 isRemoveFooter = true;
2087 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2089 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2092 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2093 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2095 isRemoveFooter = true;
2106 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2114 if (HashMgr.IsNotAddToAtReply)
2116 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2119 header = HashMgr.UseHash + " ";
2121 footer = " " + HashMgr.UseHash;
2126 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2129 header = HashMgr.UseHash + " ";
2131 footer = " " + HashMgr.UseHash;
2134 if (!isRemoveFooter)
2136 if (this._cfgLocal.UseRecommendStatus)
2138 footer += SettingDialog.RecommendStatusText;
2140 // テキストボックスに入力されている文字列を使用する
2141 footer += " " + this._cfgLocal.StatusText.Trim();
2144 args.status.status = header + StatusText.Text + footer;
2146 if (ToolStripMenuItemApiCommandEvasion.Checked)
2149 if (Regex.IsMatch(args.status.status,
2150 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2151 RegexOptions.IgnoreCase)
2152 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2155 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2158 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2159 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2162 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2164 // 文中の全角スペースを半角スペース1個にする
2165 args.status.status = args.status.status.Replace(" ", " ");
2168 if (isCutOff && args.status.status.Length > 140)
2170 args.status.status = args.status.status.Substring(0, 140);
2171 string AtId = @"(@|@)[a-z0-9_/]+$";
2172 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2173 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2174 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2175 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2178 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2179 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2181 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2184 args.status.inReplyToId = _reply_to_id;
2185 args.status.inReplyToName = _reply_to_name;
2186 if (ImageSelector.Visible)
2189 if (!ImageSelector.TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2195 _reply_to_id = null;
2196 _reply_to_name = null;
2197 StatusText.Text = "";
2198 _history.Add(new PostingStatus());
2199 _hisIdx = _history.Count - 1;
2200 if (!ToolStripFocusLockMenuItem.Checked)
2201 ((Control)ListTab.SelectedTab.Tag).Focus();
2202 urlUndoBuffer = null;
2203 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2206 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2208 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2209 await this.OpenUriAsync(tmp);
2213 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2215 MyCommon._endingFlag = true;
2219 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2221 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2223 //_endingFlag=false:フォームの×ボタン
2225 this.Visible = false;
2229 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2230 _ignoreConfigSave = true;
2231 MyCommon._endingFlag = true;
2232 TimerTimeline.Enabled = false;
2233 TimerRefreshIcon.Enabled = false;
2237 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2239 this.Visible = true;
2240 if (this.WindowState == FormWindowState.Minimized)
2242 this.WindowState = FormWindowState.Normal;
2245 this.BringToFront();
2248 private static int errorCount = 0;
2250 private static bool CheckAccountValid()
2252 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2258 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2267 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2269 BackgroundWorker bw = (BackgroundWorker)sender;
2270 if (bw.CancellationPending || MyCommon._endingFlag)
2276 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2278 MyApplication.InitCulture();
2281 GetWorkerResult rslt = new GetWorkerResult();
2283 bool read = !this._cfgCommon.UnreadManage;
2284 if (_initial && this._cfgCommon.UnreadManage) read = this._cfgCommon.Read;
2286 GetWorkerArg args = (GetWorkerArg)e.Argument;
2288 if (!CheckAccountValid())
2290 rslt.retMsg = "Auth error. Check your account";
2291 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2292 rslt.tName = args.tName;
2297 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2301 case MyCommon.WORKERTYPE.Timeline:
2302 case MyCommon.WORKERTYPE.Reply:
2303 bw.ReportProgress(50, MakeStatusMessage(args, false));
2304 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2306 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && this._cfgCommon.ReadOldPosts)
2307 _statuses.SetRead();
2309 rslt.addCount = _statuses.DistributePosts();
2311 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2312 bw.ReportProgress(50, MakeStatusMessage(args, false));
2313 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2314 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2315 rslt.addCount = _statuses.DistributePosts();
2318 case MyCommon.WORKERTYPE.FavAdd:
2322 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2324 for (int i = 0; i <= args.ids.Count - 1; i++)
2326 var post = tab.Posts[args.ids[i]];
2329 bw.ReportProgress(50, MakeStatusMessage(args, false));
2332 if (post.RetweetedId == null)
2333 ret = tw.PostFavAdd(post.StatusId);
2335 ret = tw.PostFavAdd(post.RetweetedId.Value);
2337 if (ret.Length == 0)
2339 args.sIds.Add(post.StatusId);
2340 post.IsFav = true; //リスト再描画必要
2341 _favTimestamps.Add(DateTime.Now);
2342 if (string.IsNullOrEmpty(post.RelTabName))
2344 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2345 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2349 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2350 if (_statuses.ContainsKey(post.StatusId))
2352 PostClass postTl = _statuses[post.StatusId];
2353 postTl.IsFav = true;
2354 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2357 //検索,リスト,UserTimeline,Relatedの各タブに反映
2358 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2360 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2366 rslt.sIds = args.sIds;
2370 case MyCommon.WORKERTYPE.FavRemove:
2374 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2376 for (int i = 0; i <= args.ids.Count - 1; i++)
2378 var post = tab.Posts[args.ids[i]];
2381 bw.ReportProgress(50, MakeStatusMessage(args, false));
2384 if (post.RetweetedId == null)
2385 ret = tw.PostFavRemove(post.StatusId);
2387 ret = tw.PostFavRemove(post.RetweetedId.Value);
2389 if (ret.Length == 0)
2391 args.sIds.Add(post.StatusId);
2392 post.IsFav = false; //リスト再描画必要
2393 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2394 //検索,リスト,UserTimeline,Relatedの各タブに反映
2395 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2397 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2403 rslt.sIds = args.sIds;
2407 case MyCommon.WORKERTYPE.PostMessage:
2408 bw.ReportProgress(200);
2409 if (args.status.imagePath == null || args.status.imagePath.Length == 0 || string.IsNullOrEmpty(args.status.imagePath[0]))
2411 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2415 var service = ImageSelector.GetService(args.status.imageService);
2418 service.PostStatusAsync(args.status.status, args.status.inReplyToId, args.status.imagePath)
2421 catch (AggregateException ex)
2423 ret = ex.InnerException.Message;
2426 bw.ReportProgress(300);
2427 rslt.status = args.status;
2429 case MyCommon.WORKERTYPE.Retweet:
2430 bw.ReportProgress(200);
2431 for (int i = 0; i <= args.ids.Count - 1; i++)
2433 ret = tw.PostRetweet(args.ids[i], read);
2435 bw.ReportProgress(300);
2437 case MyCommon.WORKERTYPE.Follower:
2438 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2441 tw.RefreshFollowerIds();
2443 catch (WebApiException ex) { ret = ex.Message; }
2445 case MyCommon.WORKERTYPE.NoRetweetIds:
2448 tw.RefreshNoRetweetIds();
2450 catch (WebApiException ex) { ret = ex.Message; }
2452 case MyCommon.WORKERTYPE.Configuration:
2455 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2457 catch (WebApiException ex) { ret = ex.Message; }
2459 case MyCommon.WORKERTYPE.Favorites:
2460 bw.ReportProgress(50, MakeStatusMessage(args, false));
2461 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2462 rslt.addCount = _statuses.DistributePosts();
2464 case MyCommon.WORKERTYPE.PublicSearch:
2465 bw.ReportProgress(50, MakeStatusMessage(args, false));
2466 if (string.IsNullOrEmpty(args.tName))
2468 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2470 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2471 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2476 TabClass tb = _statuses.GetTabByName(args.tName);
2479 //ret = tw.GetPhoenixSearch(read, tb, false);
2480 ret = tw.GetSearch(read, tb, false);
2481 if (string.IsNullOrEmpty(ret) && args.page == -1)
2483 //ret = tw.GetPhoenixSearch(read, tb, true)
2484 ret = tw.GetSearch(read, tb, true);
2489 rslt.addCount = _statuses.DistributePosts();
2491 case MyCommon.WORKERTYPE.UserTimeline:
2492 bw.ReportProgress(50, MakeStatusMessage(args, false));
2494 if (this._cfgCommon.UseAdditionalCount) count = this._cfgCommon.UserTimelineCountApi;
2495 if (string.IsNullOrEmpty(args.tName))
2497 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2499 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2504 TabClass tb = _statuses.GetTabByName(args.tName);
2507 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2511 rslt.addCount = _statuses.DistributePosts();
2513 case MyCommon.WORKERTYPE.List:
2514 bw.ReportProgress(50, MakeStatusMessage(args, false));
2515 if (string.IsNullOrEmpty(args.tName))
2518 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2520 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2526 TabClass tb = _statuses.GetTabByName(args.tName);
2529 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2533 rslt.addCount = _statuses.DistributePosts();
2536 case MyCommon.WORKERTYPE.Related:
2538 bw.ReportProgress(50, MakeStatusMessage(args, false));
2539 TabClass tab = _statuses.GetTabByName(args.tName);
2540 ret = tw.GetRelatedResult(read, tab);
2541 rslt.addCount = _statuses.DistributePosts();
2545 case MyCommon.WORKERTYPE.BlockIds:
2546 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2549 tw.RefreshBlockIds();
2551 catch (WebApiException ex) { ret = ex.Message; }
2555 if (bw.CancellationPending)
2562 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2564 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2565 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2567 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2569 _favTimestamps.RemoveAt(i);
2573 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2577 DateTime tm = DateTime.Now;
2578 if (_tlTimestamps.ContainsKey(tm))
2579 _tlTimestamps[tm] += rslt.addCount;
2581 _tlTimestamps.Add(tm, rslt.addCount);
2583 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2584 List<DateTime> keys = new List<DateTime>();
2586 foreach (DateTime key in _tlTimestamps.Keys)
2588 if (key.CompareTo(oneHour) < 0)
2594 _tlCount += _tlTimestamps[key];
2597 foreach (DateTime key in keys)
2599 _tlTimestamps.Remove(key);
2606 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2609 rslt.type = args.type;
2610 rslt.tName = args.tName;
2615 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2621 switch (AsyncArg.type)
2623 case MyCommon.WORKERTYPE.Timeline:
2624 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2626 case MyCommon.WORKERTYPE.Reply:
2627 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2629 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2630 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2632 case MyCommon.WORKERTYPE.FavAdd:
2633 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2634 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2636 case MyCommon.WORKERTYPE.FavRemove:
2637 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2638 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2640 case MyCommon.WORKERTYPE.Favorites:
2641 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2643 case MyCommon.WORKERTYPE.PublicSearch:
2644 smsg = "Search refreshing...";
2646 case MyCommon.WORKERTYPE.List:
2647 smsg = "List refreshing...";
2649 case MyCommon.WORKERTYPE.Related:
2650 smsg = "Related refreshing...";
2652 case MyCommon.WORKERTYPE.UserTimeline:
2653 smsg = "UserTimeline refreshing...";
2660 switch (AsyncArg.type)
2662 case MyCommon.WORKERTYPE.Timeline:
2663 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2665 case MyCommon.WORKERTYPE.Reply:
2666 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2668 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2669 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2671 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2672 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2674 case MyCommon.WORKERTYPE.FavAdd:
2677 case MyCommon.WORKERTYPE.FavRemove:
2680 case MyCommon.WORKERTYPE.Favorites:
2681 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2683 case MyCommon.WORKERTYPE.Follower:
2684 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2686 case MyCommon.WORKERTYPE.NoRetweetIds:
2687 smsg = "NoRetweetIds refreshed";
2689 case MyCommon.WORKERTYPE.Configuration:
2692 case MyCommon.WORKERTYPE.PublicSearch:
2693 smsg = "Search refreshed";
2695 case MyCommon.WORKERTYPE.List:
2696 smsg = "List refreshed";
2698 case MyCommon.WORKERTYPE.Related:
2699 smsg = "Related refreshed";
2701 case MyCommon.WORKERTYPE.UserTimeline:
2702 smsg = "UserTimeline refreshed";
2704 case MyCommon.WORKERTYPE.BlockIds:
2705 smsg = Properties.Resources.UpdateBlockUserText3;
2712 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2714 if (MyCommon._endingFlag) return;
2715 if (e.ProgressPercentage > 100)
2718 if (e.ProgressPercentage == 200) //開始
2719 StatusLabel.Text = "Posting...";
2720 if (e.ProgressPercentage == 300) //終了
2721 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2725 string smsg = (string)e.UserState;
2726 if (smsg.Length > 0) StatusLabel.Text = smsg;
2730 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2732 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2734 if (e.Error != null)
2736 _myStatusError = true;
2737 _waitTimeline = false;
2741 _waitPubSearch = false;
2742 _waitUserTimeline = false;
2744 throw new Exception("BackgroundWorker Exception", e.Error);
2747 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2750 if (rslt.retMsg.Length > 0)
2752 _myStatusError = true;
2753 StatusLabel.Text = rslt.retMsg;
2756 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2758 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2760 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2764 //bool busy = false;
2765 //foreach (BackgroundWorker bw in _bw)
2767 // if (bw != null && bw.IsBusy)
2773 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2774 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2775 rslt.type == MyCommon.WORKERTYPE.Reply ||
2776 rslt.type == MyCommon.WORKERTYPE.List ||
2777 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2778 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2779 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2780 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2781 rslt.type == MyCommon.WORKERTYPE.Follower ||
2782 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2783 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2784 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2785 rslt.type == MyCommon.WORKERTYPE.Related ||
2786 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2787 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2788 rslt.type == MyCommon.WORKERTYPE.Configuration)
2790 RefreshTimeline(false); //リスト反映
2795 case MyCommon.WORKERTYPE.Timeline:
2796 _waitTimeline = false;
2799 // //API使用時の取得調整は別途考える(カウント調整?)
2802 case MyCommon.WORKERTYPE.Reply:
2804 if (rslt.newDM && !_initial)
2806 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
2809 case MyCommon.WORKERTYPE.Favorites:
2812 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2815 case MyCommon.WORKERTYPE.FavAdd:
2816 case MyCommon.WORKERTYPE.FavRemove:
2817 if (_curList != null && _curTab != null)
2819 using (ControlTransaction.Update(this._curList))
2821 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2827 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2829 if (_curTab.Text.Equals(rslt.tName))
2831 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2834 PostClass post = null;
2835 TabClass tb = _statuses.Tabs[rslt.tName];
2838 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2840 post = tb.Posts[rslt.sIds[i]];
2844 post = _statuses[rslt.sIds[i]];
2846 ChangeCacheStyleRead(post.IsRead, idx);
2848 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2856 case MyCommon.WORKERTYPE.PostMessage:
2857 if (string.IsNullOrEmpty(rslt.retMsg) ||
2858 rslt.retMsg.StartsWith("OK:") ||
2859 rslt.retMsg == "Warn:Status is a duplicate.")
2861 _postTimestamps.Add(DateTime.Now);
2862 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2863 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2865 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2867 _postTimestamps.RemoveAt(i);
2871 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2873 HashMgr.ClearHashtag();
2874 this.HashStripSplitButton.Text = "#[-]";
2875 this.HashToggleMenuItem.Checked = false;
2876 this.HashToggleToolStripMenuItem.Checked = false;
2878 SetMainWindowTitle();
2886 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
2887 Properties.Resources.StatusUpdateFailed1,
2888 Properties.Resources.StatusUpdateFailed2),
2889 "Failed to update status",
2890 MessageBoxButtons.RetryCancel,
2891 MessageBoxIcon.Question);
2895 retry = DialogResult.Abort;
2897 if (retry == DialogResult.Retry)
2899 GetWorkerArg args = new GetWorkerArg();
2901 args.type = MyCommon.WORKERTYPE.PostMessage;
2902 args.status = rslt.status;
2907 if (ToolStripFocusLockMenuItem.Checked)
2909 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2910 StatusText_Enter(StatusText, new EventArgs());
2914 if (rslt.retMsg.Length == 0 && this._cfgCommon.PostAndGet)
2916 if (_isActiveUserstream)
2918 RefreshTimeline(true);
2922 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2926 case MyCommon.WORKERTYPE.Retweet:
2927 if (rslt.retMsg.Length == 0)
2929 _postTimestamps.Add(DateTime.Now);
2930 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2931 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2933 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2935 _postTimestamps.RemoveAt(i);
2938 if (!_isActiveUserstream && this._cfgCommon.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2941 case MyCommon.WORKERTYPE.Follower:
2942 //_waitFollower = false;
2943 this.PurgeListViewItemCache();
2944 if (_curList != null) _curList.Refresh();
2946 case MyCommon.WORKERTYPE.NoRetweetIds:
2948 case MyCommon.WORKERTYPE.Configuration:
2949 //_waitFollower = false
2950 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
2952 foreach (var service in this.ImageSelector.GetServices())
2954 service.UpdateTwitterConfiguration(this.SettingDialog.TwitterConfiguration);
2957 this.PurgeListViewItemCache();
2958 if (_curList != null) _curList.Refresh();
2960 case MyCommon.WORKERTYPE.PublicSearch:
2961 _waitPubSearch = false;
2963 case MyCommon.WORKERTYPE.UserTimeline:
2964 _waitUserTimeline = false;
2966 case MyCommon.WORKERTYPE.List:
2969 case MyCommon.WORKERTYPE.Related:
2970 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
2971 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
2973 foreach (TabPage tp in ListTab.TabPages)
2975 if (tp.Text == tab.TabName)
2977 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
2978 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
2987 private async Task RefreshMuteUserIdsAsync()
2989 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2993 await tw.RefreshMuteUserIdsAsync();
2995 catch (WebApiException ex)
2997 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3001 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3004 private void RemovePostFromFavTab(Int64[] ids)
3006 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3008 if (_curTab.Text.Equals(favTabName))
3010 if (_curList.FocusedItem != null)
3011 fidx = _curList.FocusedItem.Index;
3012 else if (_curList.TopItem != null)
3013 fidx = _curList.TopItem.Index;
3018 foreach (long i in ids)
3022 _statuses.RemoveFavPost(i);
3029 if (_curTab != null && _curTab.Text.Equals(favTabName))
3031 this.PurgeListViewItemCache();
3033 //_curItemIndex = -1;
3035 foreach (TabPage tp in ListTab.TabPages)
3037 if (tp.Text == favTabName)
3039 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3043 if (_curTab.Text.Equals(favTabName))
3047 _curList.SelectedIndices.Clear();
3049 while (_curList.SelectedIndices.Count > 0);
3051 if (_statuses.Tabs[favTabName].AllCount > 0)
3053 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3055 _curList.SelectedIndices.Add(fidx);
3059 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3061 if (_curList.SelectedIndices.Count > 0)
3063 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3064 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3070 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3072 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, string tabName)
3074 if (!this.IsNetworkAvailable()) return;
3077 GetWorkerArg args = new GetWorkerArg();
3078 args.page = fromPage;
3080 args.tName = tabName;
3082 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3083 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3084 if (period > 1 || period < -1)
3086 lastTime[WkType] = DateTime.Now;
3090 //Timeline取得モードの場合はReplyも同時に取得
3091 //if (!SettingDialog.UseAPI &&
3093 // WkType == MyCommon.WORKERTYPE.Timeline &&
3094 // SettingDialog.CheckReply)
3096 // //TimerReply.Enabled = false;
3097 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3098 // GetWorkerArg _args = new GetWorkerArg();
3099 // _args.page = fromPage;
3100 // _args.endPage = toPage;
3101 // _args.type = MyCommon.WORKERTYPE.Reply;
3106 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3108 if (e.Button == MouseButtons.Left)
3110 this.Visible = true;
3111 if (this.WindowState == FormWindowState.Minimized)
3113 this.WindowState = _formWindowState;
3116 this.BringToFront();
3120 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3122 switch (this._cfgCommon.ListDoubleClickAction)
3125 MakeReplyOrDirectStatus();
3128 FavoriteChange(true);
3131 if (_curPost != null)
3132 ShowUserStatus(_curPost.ScreenName, false);
3138 ShowRelatedStatusesMenuItem_Click(null, null);
3141 MoveToHomeToolStripMenuItem_Click(null, null);
3144 StatusOpenMenuItem_Click(null, null);
3152 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3154 FavoriteChange(true);
3157 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3159 FavoriteChange(false);
3163 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3165 FavoritesRetweetOriginal();
3168 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3170 FavoritesRetweetUnofficial();
3173 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3175 //trueでFavAdd,falseでFavRemove
3176 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3177 || !this.ExistCurrentPost) return;
3180 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3182 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3183 _DoFavRetweetFlags = false;
3186 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3190 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3191 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3192 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3193 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3195 _DoFavRetweetFlags = false;
3201 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3202 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3209 GetWorkerArg args = new GetWorkerArg();
3210 args.ids = new List<long>();
3211 args.sIds = new List<long>();
3212 args.tName = _curTab.Text;
3215 args.type = MyCommon.WORKERTYPE.FavAdd;
3219 args.type = MyCommon.WORKERTYPE.FavRemove;
3221 foreach (int idx in _curList.SelectedIndices)
3223 PostClass post = GetCurTabPost(idx);
3226 if (!post.IsFav) args.ids.Add(post.StatusId);
3230 if (post.IsFav) args.ids.Add(post.StatusId);
3233 if (args.ids.Count == 0)
3236 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3238 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3246 private PostClass GetCurTabPost(int Index)
3248 this.itemCacheLock.EnterReadLock();
3251 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3252 return _postCache[Index - _itemCacheIndex];
3254 finally { this.itemCacheLock.ExitReadLock(); }
3256 return _statuses[_curTab.Text, Index];
3260 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3262 if (_curList.SelectedIndices.Count > 0)
3263 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3264 else if (_curList.SelectedIndices.Count == 0)
3265 OpenUriAsync(MyCommon.TwitterUrl);
3268 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3270 if (_curList.SelectedIndices.Count > 0)
3271 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3274 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3276 if ((!_initialLayout) && this.Visible)
3278 if (this.WindowState == FormWindowState.Normal)
3280 _mySize = this.ClientSize;
3281 _mySpDis = this.SplitContainer1.SplitterDistance;
3282 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3283 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3284 _modifySettingLocal = true;
3289 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3291 if (this._cfgCommon.SortOrderLock) return;
3292 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3295 mode = IdComparerClass.ComparerMode.Id;
3303 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3307 mode = IdComparerClass.ComparerMode.Nickname;
3310 mode = IdComparerClass.ComparerMode.Data;
3313 mode = IdComparerClass.ComparerMode.Id;
3316 mode = IdComparerClass.ComparerMode.Name;
3319 mode = IdComparerClass.ComparerMode.Source;
3323 _statuses.ToggleSortOrder(mode);
3326 DetailsListView list = (DetailsListView)sender;
3329 list.Columns[0].Text = ColumnOrgText[0];
3330 list.Columns[1].Text = ColumnText[2];
3334 for (int i = 0; i <= 7; i++)
3336 list.Columns[i].Text = ColumnOrgText[i];
3338 list.Columns[e.Column].Text = ColumnText[e.Column];
3341 this.PurgeListViewItemCache();
3343 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3345 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3348 SelectListItem(_curList, idx);
3349 _curList.EnsureVisible(idx);
3353 _modifySettingCommon = true;
3356 private void TweenMain_LocationChanged(object sender, EventArgs e)
3358 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3360 _myLoc = this.DesktopLocation;
3361 _modifySettingLocal = true;
3365 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3367 if (ListTab.SelectedTab == null) return;
3368 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3369 if (!this.ExistCurrentPost)
3371 ReplyStripMenuItem.Enabled = false;
3372 ReplyAllStripMenuItem.Enabled = false;
3373 DMStripMenuItem.Enabled = false;
3374 ShowProfileMenuItem.Enabled = false;
3375 ShowUserTimelineContextMenuItem.Enabled = false;
3376 ListManageUserContextToolStripMenuItem2.Enabled = false;
3377 MoveToFavToolStripMenuItem.Enabled = false;
3378 TabMenuItem.Enabled = false;
3379 IDRuleMenuItem.Enabled = false;
3380 ReadedStripMenuItem.Enabled = false;
3381 UnreadStripMenuItem.Enabled = false;
3385 ShowProfileMenuItem.Enabled = true;
3386 ListManageUserContextToolStripMenuItem2.Enabled = true;
3387 ReplyStripMenuItem.Enabled = true;
3388 ReplyAllStripMenuItem.Enabled = true;
3389 DMStripMenuItem.Enabled = true;
3390 ShowUserTimelineContextMenuItem.Enabled = true;
3391 MoveToFavToolStripMenuItem.Enabled = true;
3392 TabMenuItem.Enabled = true;
3393 IDRuleMenuItem.Enabled = true;
3394 ReadedStripMenuItem.Enabled = true;
3395 UnreadStripMenuItem.Enabled = true;
3397 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3398 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3400 FavAddToolStripMenuItem.Enabled = false;
3401 FavRemoveToolStripMenuItem.Enabled = false;
3402 StatusOpenMenuItem.Enabled = false;
3403 FavorareMenuItem.Enabled = false;
3404 ShowRelatedStatusesMenuItem.Enabled = false;
3406 ReTweetStripMenuItem.Enabled = false;
3407 ReTweetOriginalStripMenuItem.Enabled = false;
3408 QuoteStripMenuItem.Enabled = false;
3409 FavoriteRetweetContextMenu.Enabled = false;
3410 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3411 if (this.ExistCurrentPost && _curPost.IsDm)
3412 DeleteStripMenuItem.Enabled = true;
3414 DeleteStripMenuItem.Enabled = false;
3418 FavAddToolStripMenuItem.Enabled = true;
3419 FavRemoveToolStripMenuItem.Enabled = true;
3420 StatusOpenMenuItem.Enabled = true;
3421 FavorareMenuItem.Enabled = true;
3422 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3426 ReTweetOriginalStripMenuItem.Enabled = false;
3427 FavoriteRetweetContextMenu.Enabled = false;
3428 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3430 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3434 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3436 DeleteStripMenuItem.Enabled = true;
3440 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3442 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3446 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3448 DeleteStripMenuItem.Enabled = false;
3449 if (_curPost.IsProtect)
3451 ReTweetOriginalStripMenuItem.Enabled = false;
3452 ReTweetStripMenuItem.Enabled = false;
3453 QuoteStripMenuItem.Enabled = false;
3454 FavoriteRetweetContextMenu.Enabled = false;
3455 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3459 ReTweetOriginalStripMenuItem.Enabled = true;
3460 ReTweetStripMenuItem.Enabled = true;
3461 QuoteStripMenuItem.Enabled = true;
3462 FavoriteRetweetContextMenu.Enabled = true;
3463 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3467 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3469 // RefreshMoreStripMenuItem.Enabled = true;
3473 // RefreshMoreStripMenuItem.Enabled = false;
3475 if (!this.ExistCurrentPost
3476 || _curPost.InReplyToStatusId == null)
3478 RepliedStatusOpenMenuItem.Enabled = false;
3482 RepliedStatusOpenMenuItem.Enabled = true;
3484 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3486 MoveToRTHomeMenuItem.Enabled = false;
3490 MoveToRTHomeMenuItem.Enabled = true;
3494 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3496 MakeReplyOrDirectStatus(false, true);
3499 private void DMStripMenuItem_Click(object sender, EventArgs e)
3501 MakeReplyOrDirectStatus(false, false);
3504 private void doStatusDelete()
3506 if (_curTab == null || _curList == null) return;
3507 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3509 bool myPost = false;
3510 foreach (int idx in _curList.SelectedIndices)
3512 if (GetCurTabPost(idx).IsMe ||
3513 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3519 if (!myPost) return;
3523 if (_curList.SelectedIndices.Count == 0)
3527 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3529 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3530 MessageBoxButtons.OKCancel,
3531 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3534 if (_curList.FocusedItem != null)
3535 fidx = _curList.FocusedItem.Index;
3536 else if (_curList.TopItem != null)
3537 fidx = _curList.TopItem.Index;
3543 this.Cursor = Cursors.WaitCursor;
3546 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3549 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3551 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3555 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3556 rtn = tw.RemoveStatus(Id);
3567 _statuses.RemovePost(Id);
3572 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3574 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3576 this.PurgeListViewItemCache();
3579 foreach (TabPage tb in ListTab.TabPages)
3581 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3582 if (_curTab.Equals(tb))
3586 _curList.SelectedIndices.Clear();
3588 while (_curList.SelectedIndices.Count > 0);
3590 if (_statuses.Tabs[tb.Text].AllCount > 0)
3592 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3593 _curList.SelectedIndices.Add(fidx);
3595 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3597 if (_curList.SelectedIndices.Count > 0)
3599 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3600 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3604 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3606 if (this._cfgCommon.TabIconDisp)
3608 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3612 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3616 this.Cursor = Cursors.Default;
3620 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3625 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3627 using (ControlTransaction.Update(this._curList))
3629 if (this._cfgCommon.UnreadManage)
3631 foreach (int idx in _curList.SelectedIndices)
3633 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3636 foreach (int idx in _curList.SelectedIndices)
3638 ChangeCacheStyleRead(true, idx);
3642 foreach (TabPage tb in ListTab.TabPages)
3644 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3646 if (this._cfgCommon.TabIconDisp)
3648 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3652 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3655 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3657 using (ControlTransaction.Update(this._curList))
3659 if (this._cfgCommon.UnreadManage)
3661 foreach (int idx in _curList.SelectedIndices)
3663 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3666 foreach (int idx in _curList.SelectedIndices)
3668 ChangeCacheStyleRead(false, idx);
3672 foreach (TabPage tb in ListTab.TabPages)
3674 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3676 if (this._cfgCommon.TabIconDisp)
3678 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3682 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3685 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3690 private void DoRefresh()
3692 if (_curTab != null)
3694 switch (_statuses.Tabs[_curTab.Text].TabType)
3696 case MyCommon.TabUsageType.Mentions:
3697 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
3699 case MyCommon.TabUsageType.DirectMessage:
3700 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
3702 case MyCommon.TabUsageType.Favorites:
3703 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
3705 //case MyCommon.TabUsageType.Profile:
3707 case MyCommon.TabUsageType.PublicSearch:
3709 TabClass tb = _statuses.Tabs[_curTab.Text];
3710 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3711 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, _curTab.Text);
3713 case MyCommon.TabUsageType.UserTimeline:
3714 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, _curTab.Text);
3716 case MyCommon.TabUsageType.Lists:
3718 TabClass tab = _statuses.Tabs[_curTab.Text];
3719 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3720 GetTimeline(MyCommon.WORKERTYPE.List, 1, _curTab.Text);
3723 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3729 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3733 private void DoRefreshMore()
3736 if (_curTab != null)
3738 switch (_statuses.Tabs[_curTab.Text].TabType)
3740 case MyCommon.TabUsageType.Mentions:
3741 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
3743 case MyCommon.TabUsageType.DirectMessage:
3744 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
3746 case MyCommon.TabUsageType.Favorites:
3747 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, "");
3749 case MyCommon.TabUsageType.Profile:
3752 case MyCommon.TabUsageType.PublicSearch:
3754 TabClass tb = _statuses.Tabs[_curTab.Text];
3755 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3756 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, _curTab.Text);
3758 case MyCommon.TabUsageType.UserTimeline:
3759 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, _curTab.Text);
3761 case MyCommon.TabUsageType.Lists:
3763 TabClass tab = _statuses.Tabs[_curTab.Text];
3764 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3765 GetTimeline(MyCommon.WORKERTYPE.List, -1, _curTab.Text);
3768 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3774 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3778 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3780 DialogResult result;
3781 string uid = tw.Username.ToLower();
3785 result = SettingDialog.ShowDialog(this);
3792 if (result == DialogResult.OK)
3796 var oldIconSz = this._cfgCommon.IconSize;
3798 this.SettingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3800 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3801 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3802 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3803 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3804 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3805 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3807 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3808 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3809 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3810 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3812 ImageSelector.Reset(tw, SettingDialog.TwitterConfiguration);
3816 if (this._cfgCommon.TabIconDisp)
3818 ListTab.DrawItem -= ListTab_DrawItem;
3819 ListTab.DrawMode = TabDrawMode.Normal;
3820 ListTab.ImageList = this.TabImage;
3824 ListTab.DrawItem -= ListTab_DrawItem;
3825 ListTab.DrawItem += ListTab_DrawItem;
3826 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3827 ListTab.ImageList = null;
3830 catch (Exception ex)
3832 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3833 ex.Data["IsTerminatePermission"] = false;
3839 if (!this._cfgCommon.UnreadManage)
3841 ReadedStripMenuItem.Enabled = false;
3842 UnreadStripMenuItem.Enabled = false;
3843 if (this._cfgCommon.TabIconDisp)
3845 foreach (TabPage myTab in ListTab.TabPages)
3847 myTab.ImageIndex = -1;
3853 ReadedStripMenuItem.Enabled = true;
3854 UnreadStripMenuItem.Enabled = true;
3857 catch (Exception ex)
3859 ex.Data["Instance"] = "ListTab(UnreadManage)";
3860 ex.Data["IsTerminatePermission"] = false;
3867 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3869 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3870 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3871 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3873 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3874 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3875 _fntUnread = this._cfgLocal.FontUnread;
3876 _clUnread = this._cfgLocal.ColorUnread;
3877 _fntReaded = this._cfgLocal.FontRead;
3878 _clReaded = this._cfgLocal.ColorRead;
3879 _clFav = this._cfgLocal.ColorFav;
3880 _clOWL = this._cfgLocal.ColorOWL;
3881 _clRetweet = this._cfgLocal.ColorRetweet;
3882 _fntDetail = this._cfgLocal.FontDetail;
3883 _clDetail = this._cfgLocal.ColorDetail;
3884 _clDetailLink = this._cfgLocal.ColorDetailLink;
3885 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3886 _clSelf = this._cfgLocal.ColorSelf;
3887 _clAtSelf = this._cfgLocal.ColorAtSelf;
3888 _clTarget = this._cfgLocal.ColorTarget;
3889 _clAtTarget = this._cfgLocal.ColorAtTarget;
3890 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3891 _clAtTo = this._cfgLocal.ColorAtTo;
3892 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3893 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3894 _clInputFont = this._cfgLocal.ColorInputFont;
3895 _fntInputFont = this._cfgLocal.FontInputFont;
3896 _brsBackColorMine.Dispose();
3897 _brsBackColorAt.Dispose();
3898 _brsBackColorYou.Dispose();
3899 _brsBackColorAtYou.Dispose();
3900 _brsBackColorAtFromTarget.Dispose();
3901 _brsBackColorAtTo.Dispose();
3902 _brsBackColorNone.Dispose();
3903 _brsBackColorMine = new SolidBrush(_clSelf);
3904 _brsBackColorAt = new SolidBrush(_clAtSelf);
3905 _brsBackColorYou = new SolidBrush(_clTarget);
3906 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3907 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3908 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3909 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3913 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3914 StatusText.Font = _fntInputFont;
3915 StatusText.ForeColor = _clInputFont;
3917 catch (Exception ex)
3919 MessageBox.Show(ex.Message);
3924 InitDetailHtmlFormat();
3926 catch (Exception ex)
3928 ex.Data["Instance"] = "Font";
3929 ex.Data["IsTerminatePermission"] = false;
3935 _statuses.SetUnreadManage(this._cfgCommon.UnreadManage);
3937 catch (Exception ex)
3939 ex.Data["Instance"] = "_statuses";
3940 ex.Data["IsTerminatePermission"] = false;
3946 foreach (TabPage tb in ListTab.TabPages)
3948 if (this._cfgCommon.TabIconDisp)
3950 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3957 catch (Exception ex)
3959 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3960 ex.Data["IsTerminatePermission"] = false;
3966 var oldIconCol = _iconCol;
3968 if (this._cfgCommon.IconSize != oldIconSz)
3969 ApplyListViewIconSize(this._cfgCommon.IconSize);
3971 foreach (TabPage tp in ListTab.TabPages)
3973 DetailsListView lst = (DetailsListView)tp.Tag;
3975 using (ControlTransaction.Update(lst))
3977 lst.GridLines = this._cfgCommon.ShowGrid;
3978 lst.Font = _fntReaded;
3979 lst.BackColor = _clListBackcolor;
3981 if (_iconCol != oldIconCol)
3986 catch (Exception ex)
3988 ex.Data["Instance"] = "ListView(IconSize)";
3989 ex.Data["IsTerminatePermission"] = false;
3993 SetMainWindowTitle();
3994 SetNotifyIconText();
3996 this.PurgeListViewItemCache();
3997 if (_curList != null) _curList.Refresh();
4000 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4001 if (this._cfgCommon.HotkeyEnabled)
4003 ///グローバルホットキーの登録。設定で変更可能にするかも
4004 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4005 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4006 modKey |= HookGlobalHotkey.ModKeys.Alt;
4007 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4008 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4009 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4010 modKey |= HookGlobalHotkey.ModKeys.Shift;
4011 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4012 modKey |= HookGlobalHotkey.ModKeys.Win;
4014 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4017 if (uid != tw.Username) this.doGetFollowersMenu();
4019 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4022 StatusText_TextChanged(null, null);
4030 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4032 this.TopMost = this._cfgCommon.AlwaysTop;
4033 SaveConfigsAll(false);
4039 private void SetTabAlignment()
4041 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4042 if (ListTab.Alignment == newAlignment) return;
4045 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
4046 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
4047 SaveSelectedStatus(selId, focusedId);
4049 ListTab.Alignment = newAlignment;
4052 foreach (TabPage tab in ListTab.TabPages)
4054 DetailsListView lst = (DetailsListView)tab.Tag;
4055 TabClass tabInfo = _statuses.Tabs[tab.Text];
4056 using (ControlTransaction.Update(lst))
4058 this.SelectListItem(lst,
4059 tabInfo.IndexOf(selId[tab.Text]),
4060 tabInfo.IndexOf(focusedId[tab.Text]));
4065 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4071 case MyCommon.IconSizes.IconNone:
4074 case MyCommon.IconSizes.Icon16:
4077 case MyCommon.IconSizes.Icon24:
4080 case MyCommon.IconSizes.Icon48:
4083 case MyCommon.IconSizes.Icon48_2:
4091 // ディスプレイの DPI 設定を考慮したサイズを設定する
4092 _listViewImageList.ImageSize = new Size(
4094 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4098 _listViewImageList.ImageSize = new Size(1, 1);
4102 private void ResetColumns(DetailsListView list)
4104 using (ControlTransaction.Update(list))
4105 using (ControlTransaction.Layout(list, false))
4108 list.ColumnClick -= MyList_ColumnClick;
4109 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4110 list.ColumnReordered -= MyList_ColumnReordered;
4111 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4113 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4114 list.Columns.Clear();
4115 cols.ForEach(col => col.Dispose());
4118 InitColumns(list, true);
4120 list.ColumnClick += MyList_ColumnClick;
4121 list.DrawColumnHeader += MyList_DrawColumnHeader;
4122 list.ColumnReordered += MyList_ColumnReordered;
4123 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4127 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4129 if (e.Url.AbsoluteUri != "about:blank")
4132 OpenUriAsync(e.Url.OriginalString);
4136 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4138 if (e.Url.Scheme == "data")
4140 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4142 else if (e.Url.AbsoluteUri != "about:blank")
4146 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4147 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4150 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4151 int i = urlStr.IndexOf('#');
4152 if (i == -1) return;
4154 string hash = urlStr.Substring(i);
4155 HashSupl.AddItem(hash);
4156 HashMgr.AddHashToHistory(hash.Trim(), false);
4157 AddNewTabForSearch(hash);
4162 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4163 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4165 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4166 if (this._cfgCommon.OpenUserTimeline)
4168 if (MyCommon.IsKeyDown(Keys.Control))
4169 OpenUriAsync(e.Url.OriginalString);
4171 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4175 if (MyCommon.IsKeyDown(Keys.Control))
4176 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4178 OpenUriAsync(e.Url.OriginalString);
4183 OpenUriAsync(e.Url.OriginalString);
4189 public void AddNewTabForSearch(string searchWord)
4191 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4192 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4194 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4196 foreach (TabPage tp in ListTab.TabPages)
4198 if (tb.TabName == tp.Text)
4200 ListTab.SelectedTab = tp;
4207 string tabName = searchWord;
4208 for (int i = 0; i <= 100; i++)
4210 if (_statuses.ContainsTab(tabName))
4216 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4217 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4219 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4221 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4222 cmb.Items.Add(searchWord);
4223 cmb.Text = searchWord;
4226 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4229 private void ShowUserTimeline()
4231 if (!this.ExistCurrentPost) return;
4232 AddNewTabForUserTimeline(_curPost.ScreenName);
4235 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4237 if (e.KeyCode == Keys.Escape)
4239 TabPage relTp = ListTab.SelectedTab;
4240 RemoveSpecifiedTab(relTp.Text, false);
4242 e.SuppressKeyPress = true;
4246 public void AddNewTabForUserTimeline(string user)
4248 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4249 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4251 if (tb.User == user)
4253 foreach (TabPage tp in ListTab.TabPages)
4255 if (tb.TabName == tp.Text)
4257 ListTab.SelectedTab = tp;
4264 string tabName = "user:" + user;
4265 while (_statuses.ContainsTab(tabName))
4270 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4271 _statuses.Tabs[tabName].User = user;
4272 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4274 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4278 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, tabName);
4281 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4284 foreach (TabPage tb in ListTab.TabPages)
4286 if (tb.Text == tabName) return false;
4290 if (tabName == Properties.Resources.AddNewTabText1) return false;
4295 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4296 tabType == MyCommon.TabUsageType.Favorites ||
4297 tabType == MyCommon.TabUsageType.Home ||
4298 tabType == MyCommon.TabUsageType.Mentions ||
4299 tabType == MyCommon.TabUsageType.Related)
4301 if (_statuses.GetTabByType(tabType) != null) return false;
4305 TabPage _tabPage = new TabPage();
4306 DetailsListView _listCustom = new DetailsListView();
4308 int cnt = ListTab.TabPages.Count;
4310 ///ToDo:Create and set controls follow tabtypes
4312 using (ControlTransaction.Update(_listCustom))
4313 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4314 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4315 using (ControlTransaction.Layout(this.SplitContainer1, false))
4316 using (ControlTransaction.Layout(this.ListTab, false))
4317 using (ControlTransaction.Layout(this))
4318 using (ControlTransaction.Layout(_tabPage, false))
4322 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4324 label = new Label();
4325 label.Dock = DockStyle.Top;
4326 label.Name = "labelUser";
4327 if (tabType == MyCommon.TabUsageType.Lists)
4329 label.Text = listInfo.ToString();
4333 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4335 label.TextAlign = ContentAlignment.MiddleLeft;
4336 using (ComboBox tmpComboBox = new ComboBox())
4338 label.Height = tmpComboBox.Height;
4340 _tabPage.Controls.Add(label);
4345 if (tabType == MyCommon.TabUsageType.PublicSearch)
4349 Label lbl = new Label();
4350 ComboBox cmb = new ComboBox();
4351 Button btn = new Button();
4352 ComboBox cmbLang = new ComboBox();
4354 pnl.SuspendLayout();
4356 pnl.Controls.Add(cmb);
4357 pnl.Controls.Add(cmbLang);
4358 pnl.Controls.Add(btn);
4359 pnl.Controls.Add(lbl);
4360 pnl.Name = "panelSearch";
4361 pnl.Dock = DockStyle.Top;
4362 pnl.Height = cmb.Height;
4363 pnl.Enter += SearchControls_Enter;
4364 pnl.Leave += SearchControls_Leave;
4367 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4368 cmb.Dock = DockStyle.Fill;
4369 cmb.Name = "comboSearch";
4370 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4371 cmb.ImeMode = ImeMode.NoControl;
4372 cmb.TabStop = false;
4373 cmb.AutoCompleteMode = AutoCompleteMode.None;
4374 cmb.KeyDown += SearchComboBox_KeyDown;
4376 if (_statuses.ContainsTab(tabName))
4378 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4379 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4383 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4384 cmbLang.Dock = DockStyle.Right;
4386 cmbLang.Name = "comboLang";
4387 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4388 cmbLang.TabStop = false;
4389 cmbLang.Items.Add("");
4390 cmbLang.Items.Add("ja");
4391 cmbLang.Items.Add("en");
4392 cmbLang.Items.Add("ar");
4393 cmbLang.Items.Add("da");
4394 cmbLang.Items.Add("nl");
4395 cmbLang.Items.Add("fa");
4396 cmbLang.Items.Add("fi");
4397 cmbLang.Items.Add("fr");
4398 cmbLang.Items.Add("de");
4399 cmbLang.Items.Add("hu");
4400 cmbLang.Items.Add("is");
4401 cmbLang.Items.Add("it");
4402 cmbLang.Items.Add("no");
4403 cmbLang.Items.Add("pl");
4404 cmbLang.Items.Add("pt");
4405 cmbLang.Items.Add("ru");
4406 cmbLang.Items.Add("es");
4407 cmbLang.Items.Add("sv");
4408 cmbLang.Items.Add("th");
4409 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4411 lbl.Text = "Search(C-S-f)";
4412 lbl.Name = "label1";
4413 lbl.Dock = DockStyle.Left;
4415 lbl.Height = cmb.Height;
4416 lbl.TextAlign = ContentAlignment.MiddleLeft;
4418 btn.Text = "Search";
4419 btn.Name = "buttonSearch";
4420 btn.UseVisualStyleBackColor = true;
4421 btn.Dock = DockStyle.Right;
4422 btn.TabStop = false;
4423 btn.Click += SearchButton_Click;
4426 this.ListTab.Controls.Add(_tabPage);
4427 _tabPage.Controls.Add(_listCustom);
4429 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4430 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4432 _tabPage.Location = new Point(4, 4);
4433 _tabPage.Name = "CTab" + cnt.ToString();
4434 _tabPage.Size = new Size(380, 260);
4435 _tabPage.TabIndex = 2 + cnt;
4436 _tabPage.Text = tabName;
4437 _tabPage.UseVisualStyleBackColor = true;
4439 _listCustom.AllowColumnReorder = true;
4440 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4441 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4442 _listCustom.Dock = DockStyle.Fill;
4443 _listCustom.FullRowSelect = true;
4444 _listCustom.HideSelection = false;
4445 _listCustom.Location = new Point(0, 0);
4446 _listCustom.Margin = new Padding(0);
4447 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4448 _listCustom.ShowItemToolTips = true;
4449 _listCustom.Size = new Size(380, 260);
4450 _listCustom.UseCompatibleStateImageBehavior = false;
4451 _listCustom.View = View.Details;
4452 _listCustom.OwnerDraw = true;
4453 _listCustom.VirtualMode = true;
4454 _listCustom.Font = _fntReaded;
4455 _listCustom.BackColor = _clListBackcolor;
4457 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4458 _listCustom.AllowDrop = true;
4460 _listCustom.SmallImageList = _listViewImageList;
4462 InitColumns(_listCustom, startup);
4464 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4465 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4466 _listCustom.ColumnClick += MyList_ColumnClick;
4467 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4468 _listCustom.DragDrop += TweenMain_DragDrop;
4469 _listCustom.DragEnter += TweenMain_DragEnter;
4470 _listCustom.DragOver += TweenMain_DragOver;
4471 _listCustom.DrawItem += MyList_DrawItem;
4472 _listCustom.MouseClick += MyList_MouseClick;
4473 _listCustom.ColumnReordered += MyList_ColumnReordered;
4474 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4475 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4476 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4477 _listCustom.DrawSubItem += MyList_DrawSubItem;
4478 _listCustom.HScrolled += MyList_HScrolled;
4480 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4483 _tabPage.Tag = _listCustom;
4487 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4489 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4493 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4494 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4495 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4501 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4502 if (_tabPage == null) return false;
4504 SetListProperty(); //他のタブに列幅等を反映
4506 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4509 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4510 _tabPage.Tag = null;
4512 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4513 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4514 using (ControlTransaction.Layout(this.SplitContainer1, false))
4515 using (ControlTransaction.Layout(this.ListTab, false))
4516 using (ControlTransaction.Layout(this))
4517 using (ControlTransaction.Layout(_tabPage, false))
4519 if (this.ListTab.SelectedTab == _tabPage)
4521 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4522 this._beforeSelectedTab = null;
4524 this.ListTab.Controls.Remove(_tabPage);
4527 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4529 using (Control label = _tabPage.Controls["labelUser"])
4531 _tabPage.Controls.Remove(label);
4534 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4536 using (Control pnl = _tabPage.Controls["panelSearch"])
4538 pnl.Enter -= SearchControls_Enter;
4539 pnl.Leave -= SearchControls_Leave;
4540 _tabPage.Controls.Remove(pnl);
4542 foreach (Control ctrl in pnl.Controls)
4544 if (ctrl.Name == "buttonSearch")
4546 ctrl.Click -= SearchButton_Click;
4548 else if (ctrl.Name == "comboSearch")
4550 ctrl.KeyDown -= SearchComboBox_KeyDown;
4552 pnl.Controls.Remove(ctrl);
4558 _tabPage.Controls.Remove(_listCustom);
4560 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4561 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4562 _listCustom.ColumnClick -= MyList_ColumnClick;
4563 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4564 _listCustom.DragDrop -= TweenMain_DragDrop;
4565 _listCustom.DragEnter -= TweenMain_DragEnter;
4566 _listCustom.DragOver -= TweenMain_DragOver;
4567 _listCustom.DrawItem -= MyList_DrawItem;
4568 _listCustom.MouseClick -= MyList_MouseClick;
4569 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4570 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4571 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4572 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4573 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4574 _listCustom.HScrolled -= MyList_HScrolled;
4576 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4577 _listCustom.Columns.Clear();
4578 cols.ForEach(col => col.Dispose());
4581 _listCustom.ContextMenuStrip = null;
4582 _listCustom.ColumnHeaderContextMenuStrip = null;
4583 _listCustom.Font = null;
4585 _listCustom.SmallImageList = null;
4586 _listCustom.ListViewItemSorter = null;
4589 if (_curTab.Equals(_tabPage))
4596 this.PurgeListViewItemCache();
4600 _listCustom.Dispose();
4601 _statuses.RemoveTab(TabName);
4603 foreach (TabPage tp in ListTab.TabPages)
4605 DetailsListView lst = (DetailsListView)tp.Tag;
4606 var count = _statuses.Tabs[tp.Text].AllCount;
4607 if (lst.VirtualListSize != count)
4609 lst.VirtualListSize = count;
4616 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4618 this.PurgeListViewItemCache();
4619 _beforeSelectedTab = e.TabPage;
4622 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4626 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4629 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4630 if (!dragEnableRectangle.Contains(e.Location))
4632 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4633 tn = ListTab.SelectedTab.Text;
4636 if (string.IsNullOrEmpty(tn)) return;
4638 foreach (TabPage tb in ListTab.TabPages)
4642 ListTab.DoDragDrop(tb, DragDropEffects.All);
4652 Point cpos = new Point(e.X, e.Y);
4653 for (int i = 0; i < ListTab.TabPages.Count; i++)
4655 Rectangle rect = ListTab.GetTabRect(i);
4656 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4657 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4659 _rclickTabName = ListTab.TabPages[i].Text;
4665 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4667 //_curList.Refresh();
4669 SetMainWindowTitle();
4670 SetStatusLabelUrl();
4671 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4672 TabMenuControl(ListTab.SelectedTab.Text);
4673 this.PushSelectPostChain();
4676 private void SetListProperty()
4678 //削除などで見つからない場合は処理せず
4679 if (_curList == null) return;
4680 if (!_isColumnChanged) return;
4682 int[] dispOrder = new int[_curList.Columns.Count];
4683 for (int i = 0; i < _curList.Columns.Count; i++)
4685 for (int j = 0; j < _curList.Columns.Count; j++)
4687 if (_curList.Columns[j].DisplayIndex == i)
4696 foreach (TabPage tb in ListTab.TabPages)
4698 if (!tb.Equals(_curTab))
4700 if (tb.Tag != null && tb.Controls.Count > 0)
4702 DetailsListView lst = (DetailsListView)tb.Tag;
4703 for (int i = 0; i < lst.Columns.Count; i++)
4705 lst.Columns[dispOrder[i]].DisplayIndex = i;
4706 lst.Columns[i].Width = _curList.Columns[i].Width;
4712 _isColumnChanged = false;
4715 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4719 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4720 || PostBrowser.StatusText.StartsWith("data"))
4722 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4724 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4726 SetStatusLabelUrl();
4734 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4736 if (e.KeyChar == '@')
4738 if (!this._cfgCommon.UseAtIdSupplement) return;
4740 int cnt = AtIdSupl.ItemCount;
4741 ShowSuplDialog(StatusText, AtIdSupl);
4742 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4745 else if (e.KeyChar == '#')
4747 if (!this._cfgCommon.UseHashSupplement) return;
4748 ShowSuplDialog(StatusText, HashSupl);
4753 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4755 ShowSuplDialog(owner, dialog, 0, "");
4758 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4760 ShowSuplDialog(owner, dialog, offset, "");
4763 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4765 dialog.StartsWith = startswith;
4772 dialog.ShowDialog();
4774 this.TopMost = this._cfgCommon.AlwaysTop;
4775 int selStart = owner.SelectionStart;
4778 if (dialog.DialogResult == DialogResult.OK)
4780 if (!string.IsNullOrEmpty(dialog.inputText))
4784 fHalf = owner.Text.Substring(0, selStart - offset);
4786 if (selStart < owner.Text.Length)
4788 eHalf = owner.Text.Substring(selStart);
4790 owner.Text = fHalf + dialog.inputText + eHalf;
4791 owner.SelectionStart = selStart + dialog.inputText.Length;
4798 fHalf = owner.Text.Substring(0, selStart);
4800 if (selStart < owner.Text.Length)
4802 eHalf = owner.Text.Substring(selStart);
4804 owner.Text = fHalf + eHalf;
4807 owner.SelectionStart = selStart;
4813 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4816 if (!e.Alt && !e.Control && !e.Shift)
4818 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4820 bool isSpace = false;
4821 foreach (char c in StatusText.Text.ToCharArray())
4823 if (c == ' ' || c == ' ')
4836 StatusText.Text = "";
4837 JumpUnreadMenuItem_Click(null, null);
4841 this.StatusText_TextChanged(null, null);
4844 private void StatusText_TextChanged(object sender, EventArgs e)
4847 int pLen = GetRestStatusCount(true, false);
4848 lblLen.Text = pLen.ToString();
4851 StatusText.ForeColor = Color.Red;
4855 StatusText.ForeColor = _clInputFont;
4857 if (string.IsNullOrEmpty(StatusText.Text))
4859 _reply_to_id = null;
4860 _reply_to_name = null;
4864 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4867 var statusText = this.StatusText.Text;
4868 statusText = statusText.Replace("\r\n", "\n");
4870 int pLen = 140 - statusText.Length;
4871 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4872 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && this._cfgCommon.PostShiftEnter) ||
4873 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !this._cfgCommon.PostShiftEnter) ||
4874 (!isAuto && isAddFooter))
4876 if (this._cfgLocal.UseRecommendStatus)
4877 pLen -= SettingDialog.RecommendStatusText.Length;
4878 else if (this._cfgLocal.StatusText.Length > 0)
4879 pLen -= this._cfgLocal.StatusText.Length + 1;
4881 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4883 pLen -= HashMgr.UseHash.Length + 1;
4885 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4887 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4889 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4891 string before = m.Result("${before}");
4892 string url = m.Result("${url}");
4893 string protocol = m.Result("${protocol}");
4894 string domain = m.Result("${domain}");
4895 string path = m.Result("${path}");
4896 if (protocol.Length == 0)
4898 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4903 bool last_url_invalid_match = false;
4904 string lasturl = null;
4905 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4907 lasturl = mm.ToString();
4908 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4909 if (!last_url_invalid_match)
4911 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4915 if (path.Length != 0)
4917 if (last_url_invalid_match)
4919 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4921 pLen += path.Length;
4926 int shortUrlLength = protocol == "https://"
4927 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
4928 : SettingDialog.TwitterConfiguration.ShortUrlLength;
4930 pLen += url.Length - shortUrlLength;
4933 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
4935 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4938 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
4940 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
4945 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4947 this.itemCacheLock.EnterUpgradeableReadLock();
4950 if (_curList.Equals(sender))
4952 if (_itemCache != null &&
4953 e.StartIndex >= _itemCacheIndex &&
4954 e.EndIndex < _itemCacheIndex + _itemCache.Length)
4956 //If the newly requested cache is a subset of the old cache,
4957 //no need to rebuild everything, so do nothing.
4961 //Now we need to rebuild the cache.
4962 CreateCache(e.StartIndex, e.EndIndex);
4965 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
4968 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4970 ListViewItem item = null;
4971 PostClass cacheItemPost = null;
4973 if (_curList.Equals(sender))
4974 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
4978 //A cache miss, so create a new ListViewItem and pass it back.
4979 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4982 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
4987 string[] sitem = {"", "", "", "", "", "", "", ""};
4988 item = new ImageListViewItem(sitem);
4992 // e.Item に値をセットする前に await しないこと
4995 await ((ImageListViewItem)item).GetImageAsync();
4998 private void CreateCache(int StartIndex, int EndIndex)
5000 this.itemCacheLock.EnterWriteLock();
5003 var tabInfo = _statuses.Tabs[_curTab.Text];
5005 //キャッシュ要求(要求範囲±30を作成)
5007 if (StartIndex < 0) StartIndex = 0;
5009 if (EndIndex >= tabInfo.AllCount) EndIndex = tabInfo.AllCount - 1;
5010 _postCache = tabInfo[StartIndex, EndIndex]; //配列で取得
5011 _itemCacheIndex = StartIndex;
5013 _itemCache = new ListViewItem[0] {};
5014 Array.Resize(ref _itemCache, _postCache.Length);
5016 for (int i = 0; i < _postCache.Length; i++)
5018 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5023 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5025 _itemCacheIndex = -1;
5028 finally { this.itemCacheLock.ExitWriteLock(); }
5032 /// DetailsListView のための ListViewItem のキャッシュを消去する
5034 private void PurgeListViewItemCache()
5036 this.itemCacheLock.EnterWriteLock();
5039 this._itemCache = null;
5040 this._itemCacheIndex = -1;
5041 this._postCache = null;
5043 finally { this.itemCacheLock.ExitWriteLock(); }
5046 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5048 this.itemCacheLock.EnterReadLock();
5051 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5053 item = this._itemCache[index - _itemCacheIndex];
5054 post = this._postCache[index - _itemCacheIndex];
5058 finally { this.itemCacheLock.ExitReadLock(); }
5065 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5067 StringBuilder mk = new StringBuilder();
5068 //if (Post.IsDeleted) mk.Append("×");
5069 //if (Post.IsMark) mk.Append("♪");
5070 //if (Post.IsProtect) mk.Append("Ю");
5071 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5072 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5073 ImageListViewItem itm;
5074 if (Post.RetweetedId == null)
5076 string[] sitem= {"",
5078 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5079 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5084 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5088 string[] sitem = {"",
5090 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5091 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5092 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5096 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5098 itm.StateIndex = Post.StateIndex;
5100 bool read = Post.IsRead;
5101 //未読管理していなかったら既読として扱う
5102 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5103 ChangeItemStyleRead(read, itm, Post, null);
5104 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5109 /// 全てのタブの振り分けルールを反映し直します
5111 private void ApplyPostFilters()
5115 this.Cursor = Cursors.WaitCursor;
5117 this.PurgeListViewItemCache();
5118 this._curPost = null;
5119 this._curItemIndex = -1;
5120 this._statuses.FilterAll();
5122 foreach (TabPage tabPage in this.ListTab.TabPages)
5124 var tab = this._statuses.Tabs[tabPage.Text];
5126 var listview = (DetailsListView)tabPage.Tag;
5127 listview.VirtualListSize = tab.AllCount;
5129 if (this._cfgCommon.TabIconDisp)
5131 if (tab.UnreadCount > 0)
5132 tabPage.ImageIndex = 0;
5134 tabPage.ImageIndex = -1;
5138 if (!this._cfgCommon.TabIconDisp)
5139 this.ListTab.Refresh();
5143 this.Cursor = Cursors.Default;
5147 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5149 e.DrawDefault = true;
5152 private void MyList_HScrolled(object sender, EventArgs e)
5154 DetailsListView listView = (DetailsListView)sender;
5158 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5160 if (e.State == 0) return;
5161 e.DrawDefault = false;
5163 SolidBrush brs2 = null;
5164 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5166 if (e.Item.BackColor == _clSelf)
5167 brs2 = _brsBackColorMine;
5168 else if (e.Item.BackColor == _clAtSelf)
5169 brs2 = _brsBackColorAt;
5170 else if (e.Item.BackColor == _clTarget)
5171 brs2 = _brsBackColorYou;
5172 else if (e.Item.BackColor == _clAtTarget)
5173 brs2 = _brsBackColorAtYou;
5174 else if (e.Item.BackColor == _clAtFromTarget)
5175 brs2 = _brsBackColorAtFromTarget;
5176 else if (e.Item.BackColor == _clAtTo)
5177 brs2 = _brsBackColorAtTo;
5179 brs2 = _brsBackColorNone;
5184 if (((Control)sender).Focused)
5185 brs2 = _brsHighLight;
5187 brs2 = _brsDeactiveSelection;
5189 e.Graphics.FillRectangle(brs2, e.Bounds);
5190 e.DrawFocusRectangle();
5191 this.DrawListViewItemIcon(e);
5194 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5196 if (e.ItemState == 0) return;
5198 if (e.ColumnIndex > 0)
5201 RectangleF rct = e.Bounds;
5202 rct.Width = e.Header.Width;
5203 int fontHeight = e.Item.Font.Height;
5206 rct.Y += fontHeight;
5207 rct.Height -= fontHeight;
5211 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5213 //if (heightDiff > fontHeight * 0.7)
5215 // rct.Height += fontHeight;
5216 // drawLineCount += 1;
5219 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5220 if (!_iconCol && drawLineCount <= 1)
5222 //rct.Inflate(0, heightDiff / -2);
5223 //rct.Height += fontHeight / 2;
5225 else if (heightDiff < fontHeight * 0.7)
5227 //最終行が70%以上欠けていたら、最終行は表示しない
5228 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5229 rct.Height = (fontHeight * drawLineCount) - 1;
5236 //if (!_iconCol && drawLineCount > 1)
5238 // rct.Y += fontHeight * 0.2;
5239 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5244 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5245 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5250 Rectangle rctB = e.Bounds;
5251 rctB.Width = e.Header.Width;
5252 rctB.Height = fontHeight;
5254 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5256 TextRenderer.DrawText(e.Graphics,
5257 e.Item.SubItems[2].Text,
5259 Rectangle.Round(rct),
5261 TextFormatFlags.WordBreak |
5262 TextFormatFlags.EndEllipsis |
5263 TextFormatFlags.GlyphOverhangPadding |
5264 TextFormatFlags.NoPrefix);
5265 TextRenderer.DrawText(e.Graphics,
5266 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 + "]",
5270 TextFormatFlags.SingleLine |
5271 TextFormatFlags.EndEllipsis |
5272 TextFormatFlags.GlyphOverhangPadding |
5273 TextFormatFlags.NoPrefix);
5276 else if (drawLineCount == 1)
5278 TextRenderer.DrawText(e.Graphics,
5281 Rectangle.Round(rct),
5283 TextFormatFlags.SingleLine |
5284 TextFormatFlags.EndEllipsis |
5285 TextFormatFlags.GlyphOverhangPadding |
5286 TextFormatFlags.NoPrefix |
5287 TextFormatFlags.VerticalCenter);
5291 TextRenderer.DrawText(e.Graphics,
5294 Rectangle.Round(rct),
5296 TextFormatFlags.WordBreak |
5297 TextFormatFlags.EndEllipsis |
5298 TextFormatFlags.GlyphOverhangPadding |
5299 TextFormatFlags.NoPrefix);
5301 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5306 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5308 if (_iconSz == 0) return;
5310 ImageListViewItem item = (ImageListViewItem)e.Item;
5312 //e.Bounds.Leftが常に0を指すから自前で計算
5313 Rectangle itemRect = item.Bounds;
5314 var col0 = e.Item.ListView.Columns[0];
5315 itemRect.Width = col0.Width;
5317 if (col0.DisplayIndex > 0)
5319 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5321 if (clm.DisplayIndex < col0.DisplayIndex)
5322 itemRect.X += clm.Width;
5326 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5327 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5328 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5331 var img = item.Image;
5334 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5335 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5337 if (iconRect.Width > 0)
5339 e.Graphics.FillRectangle(Brushes.White, iconRect);
5340 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5343 e.Graphics.DrawImage(img.Image, iconRect);
5345 catch (ArgumentException)
5347 item.RefreshImageAsync();
5353 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5354 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5357 if (item.StateIndex > -1)
5359 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5360 if (stateRect.Width > 0)
5362 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5363 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5364 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5369 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5371 base.ScaleControl(factor, specified);
5373 const int baseDpi = 96;
5375 // デザイン時の DPI (96dpi) との比を更新する
5376 this.currentScaleFactor = new SizeF(
5377 this.CurrentAutoScaleDimensions.Width / baseDpi,
5378 this.CurrentAutoScaleDimensions.Height / baseDpi);
5381 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5383 // ImageListViewItem item = (ImageListViewItem)e.Item;
5384 // if (item.StateImageIndex > -1)
5386 // ////e.Bounds.Leftが常に0を指すから自前で計算
5387 // //Rectangle itemRect = item.Bounds;
5388 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5390 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5392 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5394 // // itemRect.X += clm.Width;
5398 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5399 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5401 // if (rct.Width > 0)
5403 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5404 // //e.Graphics.FillRectangle(Brushes.White, rct);
5405 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5406 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5411 private void DoTabSearch(string _word,
5421 if (_curList.VirtualListSize == 0)
5423 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5426 if (_curList.SelectedIndices.Count > 0)
5428 cidx = _curList.SelectedIndices[0];
5430 toIdx = _curList.VirtualListSize;
5434 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5435 if (_curList.SelectedIndices.Count > 0)
5436 cidx = _curList.SelectedIndices[0];
5440 case SEARCHTYPE.NextSearch: //次を検索
5441 if (_curList.SelectedIndices.Count > 0)
5443 cidx = _curList.SelectedIndices[0] + 1;
5444 if (cidx > toIdx) cidx = toIdx;
5451 case SEARCHTYPE.PrevSearch: //前を検索
5452 if (_curList.SelectedIndices.Count > 0)
5454 cidx = _curList.SelectedIndices[0] - 1;
5455 if (cidx < 0) cidx = 0;
5466 RegexOptions regOpt = RegexOptions.None;
5467 StringComparison fndOpt = StringComparison.Ordinal;
5470 regOpt = RegexOptions.IgnoreCase;
5471 fndOpt = StringComparison.OrdinalIgnoreCase;
5482 _search = new Regex(_word, regOpt);
5483 for (int idx = cidx; idx != toIdx; idx += stp)
5488 post = _statuses[_curTab.Text, idx];
5494 if (_search.IsMatch(post.Nickname)
5495 || _search.IsMatch(post.TextFromApi)
5496 || _search.IsMatch(post.ScreenName))
5498 SelectListItem(_curList, idx);
5499 _curList.EnsureVisible(idx);
5504 catch (ArgumentException)
5506 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5513 for (int idx = cidx; idx != toIdx; idx += stp)
5518 post = _statuses[_curTab.Text, idx];
5524 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5525 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5526 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5528 SelectListItem(_curList, idx);
5529 _curList.EnsureVisible(idx);
5539 case SEARCHTYPE.DialogSearch:
5540 case SEARCHTYPE.NextSearch:
5544 case SEARCHTYPE.PrevSearch:
5546 cidx = _curList.VirtualListSize - 1;
5553 catch (ArgumentOutOfRangeException)
5556 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5559 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5562 this.ShowSearchDialog();
5565 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5567 var previousSearch = this.SearchDialog.ResultOptions;
5568 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5570 this.SearchDialog.Reset();
5571 this.ShowSearchDialog();
5577 previousSearch.Query,
5578 previousSearch.CaseSensitive,
5579 previousSearch.UseRegex,
5580 SEARCHTYPE.NextSearch);
5583 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5585 var previousSearch = this.SearchDialog.ResultOptions;
5586 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5588 this.SearchDialog.Reset();
5589 this.ShowSearchDialog();
5595 previousSearch.Query,
5596 previousSearch.CaseSensitive,
5597 previousSearch.UseRegex,
5598 SEARCHTYPE.PrevSearch);
5602 /// 検索ダイアログを表示し、検索を実行します
5604 private void ShowSearchDialog()
5606 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5607 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5608 this.SearchDialog.DisableNewTabButton = false;
5610 this.SearchDialog.DisableNewTabButton = true;
5612 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5614 this.TopMost = this._cfgCommon.AlwaysTop;
5617 this.TopMost = this._cfgCommon.AlwaysTop;
5619 var searchOptions = this.SearchDialog.ResultOptions;
5620 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5622 if (searchOptions.NewTab)
5624 var tabName = searchOptions.Query;
5628 tabName = this._statuses.MakeTabName(tabName);
5630 catch (TabException ex)
5632 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5635 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5636 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5638 var filter = new PostFilterRule
5640 FilterBody = new[] { searchOptions.Query },
5641 UseRegex = searchOptions.UseRegex,
5642 CaseSensitive = searchOptions.CaseSensitive,
5644 this._statuses.Tabs[tabName].AddFilter(filter);
5646 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5647 .First(x => x.Text == tabName);
5649 this.ListTab.SelectedTab = tabPage;
5650 this.ListTabSelect(tabPage);
5652 this.ApplyPostFilters();
5653 this.SaveConfigsTabs();
5658 searchOptions.Query,
5659 searchOptions.CaseSensitive,
5660 searchOptions.UseRegex,
5661 SEARCHTYPE.DialogSearch);
5664 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5666 this.AddNewTabForSearch(searchOptions.Query);
5670 private void AboutMenuItem_Click(object sender, EventArgs e)
5672 using (TweenAboutBox about = new TweenAboutBox())
5674 about.ShowDialog(this);
5676 this.TopMost = this._cfgCommon.AlwaysTop;
5679 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5681 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5683 DetailsListView lst = null;
5685 if (ImageSelector.Enabled)
5689 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5692 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5695 ListTab.SelectedIndex = i;
5696 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5697 //_curTab = ListTab.TabPages[i];
5702 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5703 if (idx == -1 && bgnIdx > 0)
5705 for (int i = 0; i < bgnIdx; i++)
5707 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5710 ListTab.SelectedIndex = i;
5711 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5712 //_curTab = ListTab.TabPages[i];
5718 //全部調べたが未読見つからず→先頭タブの最新発言へ
5721 ListTab.SelectedIndex = 0;
5722 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5723 //_curTab = ListTab.TabPages[0];
5724 if (_statuses.SortOrder == SortOrder.Ascending)
5725 idx = lst.VirtualListSize - 1;
5730 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5732 SelectListItem(lst, idx);
5733 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5735 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5736 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5742 lst.EnsureVisible(idx);
5747 lst.EnsureVisible(idx);
5753 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5755 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5757 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5758 OpenUriAsync(MyCommon.GetStatusUrl(post));
5762 private void FavorareMenuItem_Click(object sender, EventArgs e)
5764 if (_curList.SelectedIndices.Count > 0)
5766 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5767 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5771 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5773 await this.CheckNewVersion(false);
5776 private void RunTweenUp()
5778 ProcessStartInfo pinfo = new ProcessStartInfo();
5779 pinfo.UseShellExecute = true;
5780 pinfo.WorkingDirectory = MyCommon.settingPath;
5781 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5782 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5785 Process.Start(pinfo);
5789 MessageBox.Show("Failed to execute TweenUp3.exe.");
5793 public class VersionInfo
5795 public Version Version { get; set; }
5796 public Uri DownloadUri { get; set; }
5797 public string ReleaseNote { get; set; }
5801 /// OpenTween の最新バージョンの情報を取得します
5803 public async Task<VersionInfo> GetVersionInfoAsync()
5805 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5806 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5808 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5809 .ConfigureAwait(false);
5811 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5812 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5814 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5815 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5817 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5819 return new VersionInfo
5821 Version = Version.Parse(msgHeader[0]),
5822 DownloadUri = new Uri(msgHeader[1]),
5823 ReleaseNote = msgBody,
5827 private async Task CheckNewVersion(bool startup = false)
5829 if (ApplicationSettings.VersionInfoUrl == null)
5830 return; // 更新チェック無効化
5834 var versionInfo = await this.GetVersionInfoAsync();
5836 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5841 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5842 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5843 msgtext = MyCommon.ReplaceAppName(msgtext);
5845 MessageBox.Show(msgtext,
5846 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5847 MessageBoxButtons.OK, MessageBoxIcon.Information);
5852 using (var dialog = new UpdateDialog())
5854 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5855 MyCommon.GetReadableVersion(versionInfo.Version));
5856 dialog.DetailsText = versionInfo.ReleaseNote;
5858 if (dialog.ShowDialog(this) == DialogResult.Yes)
5860 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5866 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5869 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5870 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5871 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5876 private void Colorize()
5880 //件数関連の場合、タイトル即時書き換え
5881 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5882 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5883 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5884 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5886 SetMainWindowTitle();
5888 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5889 foreach (TabPage tb in ListTab.TabPages)
5891 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5893 if (this._cfgCommon.TabIconDisp)
5895 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5899 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5902 public string createDetailHtml(string orgdata)
5904 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5907 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5909 if (sender.Equals(displayItem))
5911 this.ClearUserPicture();
5913 var img = displayItem.Image;
5917 img = await img.CloneAsync();
5919 UserPicture.Image = img;
5923 UserPicture.ShowErrorImage();
5928 private void DispSelectedPost()
5930 DispSelectedPost(false);
5933 private PostClass displayPost = new PostClass();
5936 /// サムネイルの表示処理を表すタスク
5938 private Task thumbnailTask = null;
5941 /// サムネイル表示に使用する CancellationToken の生成元
5943 private CancellationTokenSource thumbnailTokenSource = null;
5945 private void DispSelectedPost(bool forceupdate)
5947 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5950 var oldDisplayPost = this.displayPost;
5951 this.displayPost = this._curPost;
5953 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5956 if (displayItem != null)
5958 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
5961 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
5962 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
5964 using (ControlTransaction.Update(this.TableLayoutPanel1))
5966 var sourceText = "";
5967 string sourceUrl = null;
5970 var mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
5973 var src = mc.Groups["sourceurl"].Value;
5974 if (Regex.IsMatch(src, "^https?://"))
5977 sourceUrl = "https://twitter.com/" + src;
5980 if (_curPost.Source != null)
5981 sourceText = _curPost.Source;
5983 SourceLinkLabel.Text = sourceText;
5984 SourceLinkLabel.Tag = sourceUrl;
5985 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
5991 nameText = "DM FROM <- ";
5993 nameText = "DM TO -> ";
5999 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6000 if (_curPost.RetweetedId != null)
6001 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6003 NameLabel.Text = nameText;
6004 NameLabel.Tag = _curPost.ScreenName;
6006 var nameForeColor = SystemColors.ControlText;
6007 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6008 nameForeColor = this._clOWL;
6009 if (_curPost.RetweetedId != null)
6010 nameForeColor = this._clRetweet;
6012 nameForeColor = this._clFav;
6013 NameLabel.ForeColor = nameForeColor;
6015 this.ClearUserPicture();
6017 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6019 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6022 UserPicture.Image = image != null ? image.Clone() : null;
6026 UserPicture.ShowErrorImage();
6030 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6032 if (DumpPostClassToolStripMenuItem.Checked)
6034 StringBuilder sb = new StringBuilder(512);
6036 sb.Append("-----Start PostClass Dump<br>");
6037 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6038 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6039 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6040 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6041 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6042 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6043 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6044 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6045 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6046 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6047 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6048 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6049 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6050 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6051 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6053 foreach (string nm in _curPost.ReplyToList)
6055 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6058 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6059 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6060 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6061 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6062 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6063 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6064 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6065 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6066 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6067 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6068 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6069 sb.Append("-----End PostClass Dump<br>");
6071 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6075 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6076 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6077 if (_curPost.StatusId != oldDisplayPost.StatusId)
6079 this.PostBrowser.DocumentText =
6080 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6082 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6084 this.SplitContainer3.Panel2Collapsed = true;
6086 if (this._cfgCommon.PreviewEnable)
6088 if (this.thumbnailTokenSource != null)
6090 var oldTokenSource = this.thumbnailTokenSource;
6092 var cancelTask = Task.Run(() => oldTokenSource.Cancel());
6094 Task.WhenAll(this.thumbnailTask, cancelTask)
6095 .ContinueWith(_ => oldTokenSource.Dispose(), TaskScheduler.Default);
6098 this.thumbnailTokenSource = new CancellationTokenSource();
6100 var token = this.thumbnailTokenSource.Token;
6101 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6108 private void MatomeMenuItem_Click(object sender, EventArgs e)
6110 OpenApplicationWebsite();
6113 private void OpenApplicationWebsite()
6115 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6118 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6120 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6123 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6125 if (ListTab.SelectedTab != null)
6127 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6129 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6130 if (pnl.Controls["comboSearch"].Focused ||
6131 pnl.Controls["comboLang"].Focused ||
6132 pnl.Controls["buttonSearch"].Focused) return;
6134 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6135 if (State == ModifierState.NotFlags) return;
6136 if (State != ModifierState.None) _anchorFlag = false;
6137 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6140 e.SuppressKeyPress = true;
6145 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6147 ModifierState state = ModifierState.None;
6148 if (sControl) state = state | ModifierState.Ctrl;
6149 if (sShift) state = state | ModifierState.Shift;
6150 if (sAlt) state = state | ModifierState.Alt;
6155 private enum ModifierState
6167 //PostBrowser = 102,
6171 private enum FocusedControl : int
6179 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6181 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6182 if (Focused == FocusedControl.ListTab)
6184 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6185 Modifier == ModifierState.Ctrl ||
6186 Modifier == ModifierState.None ||
6187 Modifier == ModifierState.Shift)
6189 if (KeyCode == Keys.J)
6191 SendKeys.Send("{DOWN}");
6194 else if (KeyCode == Keys.K)
6196 SendKeys.Send("{UP}");
6200 if (Modifier == ModifierState.Shift ||
6201 Modifier == ModifierState.None)
6203 if (KeyCode == Keys.F)
6205 SendKeys.Send("{PGDN}");
6208 else if (KeyCode == Keys.B)
6210 SendKeys.Send("{PGUP}");
6219 case ModifierState.None:
6224 OpenApplicationWebsite();
6227 MenuItemSearchNext_Click(null, null);
6233 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
6236 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
6239 if (Focused != FocusedControl.StatusText)
6245 case Keys.ProcessKey:
6246 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6247 JumpUnreadMenuItem_Click(null, null);
6250 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6251 ShowRelatedStatusesMenuItem_Click(null, null);
6255 if (Focused == FocusedControl.ListTab)
6268 case Keys.OemPeriod:
6272 if (this.StatusText.Enabled) this.StatusText.Focus();
6275 MakeReplyOrDirectStatus();
6282 _anchorFlag = false;
6302 // ] in_reply_to参照元へ戻る
6303 GoInReplyToPostTree();
6306 // [ in_reply_toへジャンプ
6307 GoBackInReplyToPostTree();
6310 if (ListTab.SelectedTab != null)
6312 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6313 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6315 TabPage relTp = ListTab.SelectedTab;
6316 RemoveSpecifiedTab(relTp.Text, false);
6324 else if (Focused == FocusedControl.PostBrowser)
6331 //スクロールを発生させるため、true を返す
6336 case ModifierState.Ctrl:
6341 MakeReplyOrDirectStatus(false, true);
6347 MakeReplyOrDirectStatus(false, false);
6350 FavoriteChange(true);
6353 doRepliedStatusOpen();
6359 ReadedStripMenuItem_Click(null, null);
6362 HashManageMenuItem_Click(null, null);
6365 UrlConvertAutoToolStripMenuItem_Click(null, null);
6368 if (Focused != FocusedControl.PostBrowser)
6370 MultiLineMenuItem_Click(null, null);
6375 MenuItemSubSearch_Click(null, null);
6382 MoveToHomeToolStripMenuItem_Click(null, null);
6386 MoveToFavToolStripMenuItem_Click(null, null);
6390 StatusOpenMenuItem_Click(null, null);
6394 OpenURLMenuItem_Click(null, null);
6398 if (Focused == FocusedControl.ListTab)
6405 return false; //スルーする
6423 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6424 int tabNo = KeyCode - Keys.D1;
6425 if (ListTab.TabPages.Count < tabNo)
6427 ListTab.SelectedIndex = tabNo;
6428 ListTabSelect(ListTab.TabPages[tabNo]);
6431 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6432 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6436 else if (Focused == FocusedControl.StatusText)
6442 StatusText.SelectAll();
6446 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6448 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6450 if (KeyCode == Keys.Up)
6453 if (_hisIdx < 0) _hisIdx = 0;
6458 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6460 StatusText.Text = _history[_hisIdx].status;
6461 _reply_to_id = _history[_hisIdx].inReplyToId;
6462 _reply_to_name = _history[_hisIdx].inReplyToName;
6463 StatusText.SelectionStart = StatusText.Text.Length;
6467 if (ListTab.SelectedIndex == 0)
6469 ListTab.SelectedIndex = ListTab.TabCount - 1;
6473 ListTab.SelectedIndex -= 1;
6479 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6481 ListTab.SelectedIndex = 0;
6485 ListTab.SelectedIndex += 1;
6493 //フォーカスPostBrowserもしくは関係なし
6497 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6501 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6502 if (!string.IsNullOrEmpty(_selText))
6506 Clipboard.SetDataObject(_selText, false, 5, 100);
6508 catch (Exception ex)
6510 MessageBox.Show(ex.Message);
6515 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6516 MultiLineMenuItem_Click(null, null);
6521 case ModifierState.Shift:
6526 MenuItemSearchPrev_Click(null, null);
6532 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
6535 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
6539 if (Focused != FocusedControl.StatusText)
6541 if (KeyCode == Keys.R)
6548 if (Focused == FocusedControl.ListTab)
6568 GoBackInReplyToPostTree(true, false);
6571 GoBackInReplyToPostTree(true, true);
6575 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6580 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6584 this.GoBackSelectPostChain();
6589 case ModifierState.Alt:
6593 doReTweetOfficial(true);
6596 if (_curPost != null)
6598 doShowUserStatus(_curPost.ScreenName, false);
6603 ScrollDownPostBrowser(false);
6606 ScrollDownPostBrowser(true);
6609 PageDownPostBrowser(false);
6612 PageDownPostBrowser(true);
6615 if (Focused == FocusedControl.ListTab)
6617 // 別タブの同じ書き込みへ(ALT+←/→)
6618 if (KeyCode == Keys.Right)
6620 GoSamePostToAnotherTab(false);
6623 else if (KeyCode == Keys.Left)
6625 GoSamePostToAnotherTab(true);
6630 case ModifierState.Ctrl | ModifierState.Shift:
6634 MakeReplyOrDirectStatus(false, true, true);
6640 if (ListTab.SelectedTab != null)
6642 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6644 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6650 FavoriteChange(false);
6653 UnreadStripMenuItem_Click(null, null);
6656 HashToggleMenuItem_Click(null, null);
6659 ImageSelectMenuItem_Click(null, null);
6665 FavorareMenuItem_Click(null, null);
6668 if (Focused == FocusedControl.StatusText)
6674 if (_curList != null && _curList.VirtualListSize != 0 &&
6675 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6677 idx = _curList.SelectedIndices[0] - 1;
6678 SelectListItem(_curList, idx);
6679 _curList.EnsureVisible(idx);
6684 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6685 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6687 idx = _curList.SelectedIndices[0] + 1;
6688 SelectListItem(_curList, idx);
6689 _curList.EnsureVisible(idx);
6694 if (StatusText.SelectionStart > 0)
6696 int endidx = StatusText.SelectionStart - 1;
6697 string startstr = "";
6698 bool pressed = false;
6699 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6701 char c = StatusText.Text[i];
6702 if (Char.IsLetterOrDigit(c) || c == '_')
6709 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6710 int cnt = AtIdSupl.ItemCount;
6711 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6712 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6717 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6718 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6730 else if (Focused == FocusedControl.ListTab)
6732 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6744 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6745 int colNo = KeyCode - Keys.D1;
6746 if (lst.Columns.Count < colNo) return false;
6747 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6748 if (col == null) return false;
6749 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6752 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6753 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6758 case ModifierState.Ctrl | ModifierState.Alt:
6759 if (KeyCode == Keys.S)
6761 FavoritesRetweetOriginal();
6764 else if (KeyCode == Keys.R)
6766 FavoritesRetweetUnofficial();
6769 else if (KeyCode == Keys.H)
6771 OpenUserAppointUrl();
6775 case ModifierState.Alt | ModifierState.Shift:
6776 if (Focused == FocusedControl.PostBrowser)
6778 if (KeyCode == Keys.R)
6779 doReTweetUnofficial();
6780 else if (KeyCode == Keys.C)
6787 if (!this.ExistCurrentPost) return false;
6788 doTranslation(_curPost.TextFromApi);
6791 doReTweetUnofficial();
6797 this.tweetThumbnail1.ScrollUp();
6800 this.tweetThumbnail1.ScrollDown();
6803 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6805 if (!this.SplitContainer3.Panel2Collapsed)
6807 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6817 private void ScrollDownPostBrowser(bool forward)
6819 var doc = PostBrowser.Document;
6820 if (doc == null) return;
6822 var tags = doc.GetElementsByTagName("html");
6826 tags[0].ScrollTop += this._fntDetail.Height;
6828 tags[0].ScrollTop -= this._fntDetail.Height;
6832 private void PageDownPostBrowser(bool forward)
6834 var doc = PostBrowser.Document;
6835 if (doc == null) return;
6837 var tags = doc.GetElementsByTagName("html");
6841 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6843 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6847 private void GoNextTab(bool forward)
6849 int idx = ListTab.SelectedIndex;
6853 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6858 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6860 ListTab.SelectedIndex = idx;
6861 ListTabSelect(ListTab.TabPages[idx]);
6864 private void CopyStot()
6867 StringBuilder sb = new StringBuilder();
6868 bool IsProtected = false;
6870 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6871 foreach (int idx in _curList.SelectedIndices)
6873 PostClass post = _statuses[_curTab.Text, idx];
6879 if (post.IsDeleted) continue;
6882 if (post.RetweetedId != null)
6883 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6885 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6889 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6894 MessageBox.Show(Properties.Resources.CopyStotText1);
6898 clstr = sb.ToString();
6901 Clipboard.SetDataObject(clstr, false, 5, 100);
6903 catch (Exception ex)
6905 MessageBox.Show(ex.Message);
6910 private void CopyIdUri()
6913 StringBuilder sb = new StringBuilder();
6914 if (this._curTab == null) return;
6915 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
6916 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
6917 foreach (int idx in _curList.SelectedIndices)
6919 var post = _statuses[_curTab.Text, idx];
6920 sb.Append(MyCommon.GetStatusUrl(post));
6921 sb.Append(Environment.NewLine);
6925 clstr = sb.ToString();
6928 Clipboard.SetDataObject(clstr, false, 5, 100);
6930 catch (Exception ex)
6932 MessageBox.Show(ex.Message);
6937 private void GoFav(bool forward)
6939 if (_curList.VirtualListSize == 0) return;
6946 if (_curList.SelectedIndices.Count == 0)
6952 fIdx = _curList.SelectedIndices[0] + 1;
6953 if (fIdx > _curList.VirtualListSize - 1) return;
6955 toIdx = _curList.VirtualListSize;
6960 if (_curList.SelectedIndices.Count == 0)
6962 fIdx = _curList.VirtualListSize - 1;
6966 fIdx = _curList.SelectedIndices[0] - 1;
6967 if (fIdx < 0) return;
6973 for (int idx = fIdx; idx != toIdx; idx += stp)
6975 if (_statuses[_curTab.Text, idx].IsFav)
6977 SelectListItem(_curList, idx);
6978 _curList.EnsureVisible(idx);
6984 private void GoSamePostToAnotherTab(bool left)
6986 if (_curList.VirtualListSize == 0) return;
6992 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
6993 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
6995 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7000 if (ListTab.SelectedIndex == 0)
7006 fIdx = ListTab.SelectedIndex - 1;
7014 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7020 fIdx = ListTab.SelectedIndex + 1;
7022 toIdx = ListTab.TabCount;
7027 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7029 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7030 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7032 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7034 ListTab.SelectedIndex = tabidx;
7035 ListTabSelect(ListTab.TabPages[tabidx]);
7036 SelectListItem(_curList, idx);
7037 _curList.EnsureVisible(idx);
7046 private void GoPost(bool forward)
7048 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7055 fIdx = _curList.SelectedIndices[0] + 1;
7056 if (fIdx > _curList.VirtualListSize - 1) return;
7057 toIdx = _curList.VirtualListSize;
7062 fIdx = _curList.SelectedIndices[0] - 1;
7063 if (fIdx < 0) return;
7069 if (_curPost.RetweetedId == null)
7071 name = _curPost.ScreenName;
7075 name = _curPost.RetweetedBy;
7077 for (int idx = fIdx; idx != toIdx; idx += stp)
7079 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7081 if (_statuses[_curTab.Text, idx].ScreenName == name)
7083 SelectListItem(_curList, idx);
7084 _curList.EnsureVisible(idx);
7090 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7092 SelectListItem(_curList, idx);
7093 _curList.EnsureVisible(idx);
7100 private void GoRelPost(bool forward)
7102 if (_curList.SelectedIndices.Count == 0) return;
7109 fIdx = _curList.SelectedIndices[0] + 1;
7110 if (fIdx > _curList.VirtualListSize - 1) return;
7111 toIdx = _curList.VirtualListSize;
7116 fIdx = _curList.SelectedIndices[0] - 1;
7117 if (fIdx < 0) return;
7124 if (_curPost == null) return;
7125 _anchorPost = _curPost;
7130 if (_anchorPost == null) return;
7133 for (int idx = fIdx; idx != toIdx; idx += stp)
7135 PostClass post = _statuses[_curTab.Text, idx];
7136 if (post.ScreenName == _anchorPost.ScreenName ||
7137 post.RetweetedBy == _anchorPost.ScreenName ||
7138 post.ScreenName == _anchorPost.RetweetedBy ||
7139 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7140 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7141 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7142 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7143 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7145 SelectListItem(_curList, idx);
7146 _curList.EnsureVisible(idx);
7152 private void GoAnchor()
7154 if (_anchorPost == null) return;
7155 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7156 if (idx == -1) return;
7158 SelectListItem(_curList, idx);
7159 _curList.EnsureVisible(idx);
7162 private void GoTopEnd(bool GoTop)
7169 _item = _curList.GetItemAt(0, 25);
7177 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7179 idx = _curList.VirtualListSize - 1;
7183 SelectListItem(_curList, idx);
7186 private void GoMiddle()
7193 _item = _curList.GetItemAt(0, 0);
7203 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7206 idx2 = _curList.VirtualListSize - 1;
7212 idx3 = (idx1 + idx2) / 2;
7214 SelectListItem(_curList, idx3);
7217 private void GoLast()
7219 if (_curList.VirtualListSize == 0) return;
7221 if (_statuses.SortOrder == SortOrder.Ascending)
7223 SelectListItem(_curList, _curList.VirtualListSize - 1);
7224 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7228 SelectListItem(_curList, 0);
7229 _curList.EnsureVisible(0);
7233 private void MoveTop()
7235 if (_curList.SelectedIndices.Count == 0) return;
7236 int idx = _curList.SelectedIndices[0];
7237 if (_statuses.SortOrder == SortOrder.Ascending)
7239 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7243 _curList.EnsureVisible(0);
7245 _curList.EnsureVisible(idx);
7248 private void GoInReplyToPostTree()
7250 if (_curPost == null) return;
7252 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7254 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7256 PostClass post = null;
7257 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7258 if (string.IsNullOrEmpty(r) && post != null)
7260 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7261 _curPost.InReplyToUser = post.InReplyToUser;
7262 _curPost.IsReply = post.IsReply;
7263 this.PurgeListViewItemCache();
7264 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7268 this.StatusLabel.Text = r;
7272 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7274 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7276 replyChains = new Stack<ReplyChain>();
7278 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7281 string inReplyToTabName;
7282 long inReplyToId = _curPost.InReplyToStatusId.Value;
7283 string inReplyToUser = _curPost.InReplyToUser;
7284 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7286 var inReplyToPosts = from tab in _statuses.Tabs.Values
7287 orderby tab != curTabClass
7288 from post in tab.Posts.Values
7289 where post.StatusId == inReplyToId
7290 let index = tab.IndexOf(post.StatusId)
7292 select new {Tab = tab, Index = index};
7296 var inReplyPost = inReplyToPosts.First();
7297 inReplyToTabName = inReplyPost.Tab.TabName;
7298 inReplyToIndex = inReplyPost.Index;
7300 catch (InvalidOperationException)
7302 PostClass post = null;
7303 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7304 if (string.IsNullOrEmpty(r) && post != null)
7307 _statuses.AddPost(post);
7308 _statuses.DistributePosts();
7309 //_statuses.SubmitUpdate(null, null, null, false);
7310 this.RefreshTimeline(false);
7313 var inReplyPost = inReplyToPosts.First();
7314 inReplyToTabName = inReplyPost.Tab.TabName;
7315 inReplyToIndex = inReplyPost.Index;
7317 catch (InvalidOperationException)
7319 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7325 this.StatusLabel.Text = r;
7326 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7331 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7332 DetailsListView listView = (DetailsListView)tabPage.Tag;
7334 if (_curTab != tabPage)
7336 this.ListTab.SelectTab(tabPage);
7339 this.SelectListItem(listView, inReplyToIndex);
7340 listView.EnsureVisible(inReplyToIndex);
7343 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7345 if (_curPost == null) return;
7347 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7348 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7352 if (_curPost.InReplyToStatusId != null)
7354 var posts = from t in _statuses.Tabs
7355 from p in t.Value.Posts
7356 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7357 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7359 orderby isForward ? indexOf : indexOf * -1
7360 orderby t.Value != curTabClass
7361 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7364 var postList = posts.ToList();
7365 for (int i = postList.Count - 1; i >= 0; i--)
7368 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7370 postList.RemoveAt(index);
7373 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7374 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7375 if (post == null) post = postList.First();
7376 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7377 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7378 SelectListItem(listView, post.Index);
7379 listView.EnsureVisible(post.Index);
7381 catch (InvalidOperationException)
7389 if (replyChains == null || replyChains.Count < 1)
7391 var posts = from t in _statuses.Tabs
7392 from p in t.Value.Posts
7393 where p.Value.InReplyToStatusId == _curPost.StatusId
7394 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7397 orderby t.Value != curTabClass
7398 select new {Tab = t.Value, Index = indexOf};
7401 var post = posts.First();
7402 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7403 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7404 SelectListItem(listView, post.Index);
7405 listView.EnsureVisible(post.Index);
7407 catch (InvalidOperationException)
7414 ReplyChain chainHead = replyChains.Pop();
7415 if (chainHead.InReplyToId == _curPost.StatusId)
7417 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7426 ListTab.SelectTab(chainHead.OriginalTab);
7432 SelectListItem(_curList, idx);
7433 _curList.EnsureVisible(idx);
7439 this.GoBackInReplyToPostTree(parallel);
7445 private void GoBackSelectPostChain()
7447 if (this.selectPostChains.Count > 1)
7456 this.selectPostChains.Pop();
7457 var tabPostPair = this.selectPostChains.Peek();
7459 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7461 if (tabPostPair.Item2 != null)
7463 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7464 if (idx == -1) continue; //該当ポストが存在しないので無視
7467 tp = tabPostPair.Item1;
7469 this.selectPostChains.Pop();
7471 catch (InvalidOperationException)
7477 while (this.selectPostChains.Count > 1);
7482 //履歴が残り1つであればクリアしておく
7483 if (this.selectPostChains.Count == 1)
7484 this.selectPostChains.Clear();
7488 DetailsListView lst = (DetailsListView)tp.Tag;
7489 this.ListTab.SelectedTab = tp;
7492 SelectListItem(lst, idx);
7493 lst.EnsureVisible(idx);
7499 private void PushSelectPostChain()
7501 int count = this.selectPostChains.Count;
7504 var p = this.selectPostChains.Peek();
7505 if (p.Item1 == this._curTab)
7507 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7508 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7511 if (count >= 2500) TrimPostChain();
7512 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7515 private void TrimPostChain()
7517 if (this.selectPostChains.Count <= 2000) return;
7518 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7519 for (int i = 0; i < 2000; i++)
7521 p.Push(this.selectPostChains.Pop());
7523 this.selectPostChains.Clear();
7524 for (int i = 0; i < 2000; i++)
7526 this.selectPostChains.Push(p.Pop());
7530 private bool GoStatus(long statusId)
7532 if (statusId == 0) return false;
7533 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7535 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7537 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7538 ListTab.SelectedIndex = tabidx;
7539 ListTabSelect(ListTab.TabPages[tabidx]);
7540 SelectListItem(_curList, idx);
7541 _curList.EnsureVisible(idx);
7548 private bool GoDirectMessage(long statusId)
7550 if (statusId == 0) return false;
7551 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7553 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7555 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7556 ListTab.SelectedIndex = tabidx;
7557 ListTabSelect(ListTab.TabPages[tabidx]);
7558 SelectListItem(_curList, idx);
7559 _curList.EnsureVisible(idx);
7566 private void MyList_MouseClick(object sender, MouseEventArgs e)
7568 _anchorFlag = false;
7571 private void StatusText_Enter(object sender, EventArgs e)
7573 // フォーカスの戻り先を StatusText に設定
7574 this.Tag = StatusText;
7575 StatusText.BackColor = _clInputBackcolor;
7578 public Color InputBackColor
7580 get { return _clInputBackcolor; }
7581 set { _clInputBackcolor = value; }
7584 private void StatusText_Leave(object sender, EventArgs e)
7586 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7587 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7588 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7591 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7593 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7594 if (State == ModifierState.NotFlags) return;
7595 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7598 e.SuppressKeyPress = true;
7601 this.StatusText_TextChanged(null, null);
7604 private void SaveConfigsAll(bool ifModified)
7608 SaveConfigsCommon();
7615 if (_modifySettingCommon) SaveConfigsCommon();
7616 if (_modifySettingLocal) SaveConfigsLocal();
7617 if (_modifySettingAtId) SaveConfigsAtId();
7621 private void SaveConfigsAtId()
7623 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7625 _modifySettingAtId = false;
7626 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7630 private void SaveConfigsCommon()
7632 if (_ignoreConfigSave) return;
7634 _modifySettingCommon = false;
7637 _cfgCommon.UserName = tw.Username;
7638 _cfgCommon.UserId = tw.UserId;
7639 _cfgCommon.Password = tw.Password;
7640 _cfgCommon.Token = tw.AccessToken;
7641 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7642 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7644 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7645 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7646 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7647 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7648 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7649 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7650 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7651 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7653 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7656 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7657 switch (_statuses.SortMode)
7659 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7660 _cfgCommon.SortColumn = 1;
7662 case IdComparerClass.ComparerMode.Data: //本文
7663 _cfgCommon.SortColumn = 2;
7665 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7666 _cfgCommon.SortColumn = 3;
7668 case IdComparerClass.ComparerMode.Name: //名前
7669 _cfgCommon.SortColumn = 4;
7671 case IdComparerClass.ComparerMode.Source: //Source
7672 _cfgCommon.SortColumn = 7;
7676 _cfgCommon.HashTags = HashMgr.HashHistories;
7677 if (HashMgr.IsPermanent)
7679 _cfgCommon.HashSelected = HashMgr.UseHash;
7683 _cfgCommon.HashSelected = "";
7685 _cfgCommon.HashIsHead = HashMgr.IsHead;
7686 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7687 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7688 if (ToolStripFocusLockMenuItem != null &&
7689 ToolStripFocusLockMenuItem.IsDisposed == false)
7691 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7693 _cfgCommon.TrackWord = tw.TrackWord;
7694 _cfgCommon.AllAtReply = tw.AllAtReply;
7695 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7696 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7697 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7703 private void SaveConfigsLocal()
7705 if (_ignoreConfigSave) return;
7708 _modifySettingLocal = false;
7709 _cfgLocal.FormSize = _mySize;
7710 _cfgLocal.FormLocation = _myLoc;
7711 _cfgLocal.SplitterDistance = _mySpDis;
7712 _cfgLocal.PreviewDistance = _mySpDis3;
7713 _cfgLocal.StatusMultiline = StatusText.Multiline;
7714 _cfgLocal.StatusTextHeight = _mySpDis2;
7716 _cfgLocal.FontUnread = _fntUnread;
7717 _cfgLocal.ColorUnread = _clUnread;
7718 _cfgLocal.FontRead = _fntReaded;
7719 _cfgLocal.ColorRead = _clReaded;
7720 _cfgLocal.FontDetail = _fntDetail;
7721 _cfgLocal.ColorDetail = _clDetail;
7722 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7723 _cfgLocal.ColorDetailLink = _clDetailLink;
7724 _cfgLocal.ColorFav = _clFav;
7725 _cfgLocal.ColorOWL = _clOWL;
7726 _cfgLocal.ColorRetweet = _clRetweet;
7727 _cfgLocal.ColorSelf = _clSelf;
7728 _cfgLocal.ColorAtSelf = _clAtSelf;
7729 _cfgLocal.ColorTarget = _clTarget;
7730 _cfgLocal.ColorAtTarget = _clAtTarget;
7731 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7732 _cfgLocal.ColorAtTo = _clAtTo;
7733 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7734 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7735 _cfgLocal.ColorInputFont = _clInputFont;
7736 _cfgLocal.FontInputFont = _fntInputFont;
7738 if (_ignoreConfigSave) return;
7743 private void SaveConfigsTabs()
7745 SettingTabs tabSetting = new SettingTabs();
7746 for (int i = 0; i < ListTab.TabPages.Count; i++)
7748 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7753 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7756 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7757 if (ret != DialogResult.OK)
7760 var match = Twitter.StatusUrlRegex.Match(inputText);
7763 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7764 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7768 var statusId = long.Parse(match.Groups["StatusId"].Value);
7770 var post = this._statuses[statusId];
7775 post = await Task.Run(() =>
7777 PostClass newPost = null;
7779 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7780 if (!string.IsNullOrEmpty(err))
7781 throw new WebApiException(err);
7786 catch (WebApiException ex)
7788 var message = ex.Message;
7789 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7790 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7797 this.OpenRelatedTab(post);
7799 catch (TabException ex)
7801 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7805 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7807 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7808 Properties.Resources.SaveLogMenuItem_ClickText2,
7809 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7810 if (rslt == DialogResult.Cancel) return;
7812 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7813 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7814 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7815 SaveFileDialog1.FilterIndex = 0;
7816 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7817 SaveFileDialog1.RestoreDirectory = true;
7819 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7821 if (!SaveFileDialog1.ValidateNames) return;
7822 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7824 if (rslt == DialogResult.Yes)
7827 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7829 PostClass post = _statuses[_curTab.Text, idx];
7830 string protect = "";
7831 if (post.IsProtect) protect = "Protect";
7832 sw.WriteLine(post.Nickname + "\t" +
7833 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7834 post.CreatedAt.ToString() + "\t" +
7835 post.ScreenName + "\t" +
7836 post.StatusId.ToString() + "\t" +
7837 post.ImageUrl + "\t" +
7838 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7844 foreach (int idx in _curList.SelectedIndices)
7846 PostClass post = _statuses[_curTab.Text, idx];
7847 string protect = "";
7848 if (post.IsProtect) protect = "Protect";
7849 sw.WriteLine(post.Nickname + "\t" +
7850 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7851 post.CreatedAt.ToString() + "\t" +
7852 post.ScreenName + "\t" +
7853 post.StatusId.ToString() + "\t" +
7854 post.ImageUrl + "\t" +
7855 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7861 this.TopMost = this._cfgCommon.AlwaysTop;
7864 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
7866 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7867 if (State == ModifierState.NotFlags) return;
7868 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
7871 e.IsInputKey = true;
7874 public bool TabRename(ref string tabName)
7877 string newTabText = null;
7878 using (InputTabName inputName = new InputTabName())
7880 inputName.TabName = tabName;
7881 inputName.ShowDialog();
7882 if (inputName.DialogResult == DialogResult.Cancel) return false;
7883 newTabText = inputName.TabName;
7885 this.TopMost = this._cfgCommon.AlwaysTop;
7886 if (!string.IsNullOrEmpty(newTabText))
7889 for (int i = 0; i < ListTab.TabCount; i++)
7891 if (ListTab.TabPages[i].Text == newTabText)
7893 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
7894 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7898 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
7899 for (int i = 0; i < ListTab.TabCount; i++)
7901 if (ListTab.TabPages[i].Text == tabName)
7903 ListTab.TabPages[i].Text = newTabText;
7906 _statuses.RenameTab(tabName, newTabText);
7908 for (int i = 0; i < ListTab.TabCount; i++)
7910 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
7912 if (ListTab.TabPages[i].Text == tabName)
7914 ListTab.TabPages[i].Text = newTabText;
7918 SaveConfigsCommon();
7920 _rclickTabName = newTabText;
7921 tabName = newTabText;
7930 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7932 if (e.Button == MouseButtons.Middle)
7934 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7936 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7938 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7939 this.SaveConfigsTabs();
7946 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7948 string tn = ListTab.SelectedTab.Text;
7952 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7954 if (this._cfgCommon.TabMouseLock) return;
7955 Point cpos = new Point(e.X, e.Y);
7956 if (e.Button == MouseButtons.Left)
7958 for (int i = 0; i < ListTab.TabPages.Count; i++)
7960 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7963 _tabMouseDownPoint = e.Location;
7974 private void ListTab_DragEnter(object sender, DragEventArgs e)
7976 if (e.Data.GetDataPresent(typeof(TabPage)))
7977 e.Effect = DragDropEffects.Move;
7979 e.Effect = DragDropEffects.None;
7982 private void ListTab_DragDrop(object sender, DragEventArgs e)
7984 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7989 Point cpos = new Point(e.X, e.Y);
7990 Point spos = ListTab.PointToClient(cpos);
7992 for (i = 0; i < ListTab.TabPages.Count; i++)
7994 Rectangle rect = ListTab.GetTabRect(i);
7995 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7996 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7998 tn = ListTab.TabPages[i].Text;
7999 if (spos.X <= (rect.Left + rect.Right) / 2)
8008 //タブのないところにドロップ->最後尾へ移動
8009 if (string.IsNullOrEmpty(tn))
8011 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8013 i = ListTab.TabPages.Count - 1;
8016 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8017 if (tp.Text == tn) return;
8019 ReOrderTab(tp.Text, tn, bef);
8022 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8025 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8027 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8030 using (ControlTransaction.Layout(this.ListTab))
8033 for (int j = 0; j < ListTab.TabPages.Count; j++)
8035 if (ListTab.TabPages[j].Text == targetTabText)
8037 mTp = ListTab.TabPages[j];
8038 ListTab.TabPages.Remove(mTp);
8039 if (j < baseIndex) baseIndex -= 1;
8043 if (isBeforeBaseTab)
8044 ListTab.TabPages.Insert(baseIndex, mTp);
8046 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8052 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8054 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8055 //isReply:true=@,false=DM
8056 if (!StatusText.Enabled) return;
8057 if (_curList == null) return;
8058 if (_curTab == null) return;
8059 if (!this.ExistCurrentPost) return;
8061 // 複数あてリプライはReplyではなく通常ポスト
8062 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8063 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8064 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8066 if (_curList.SelectedIndices.Count > 0)
8069 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8072 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8075 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8076 StatusText.SelectionStart = StatusText.Text.Length;
8078 _reply_to_id = null;
8079 _reply_to_name = null;
8082 if (string.IsNullOrEmpty(StatusText.Text))
8086 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8087 StatusText.Text = "@" + _curPost.ScreenName + " ";
8088 if (_curPost.RetweetedId != null)
8090 _reply_to_id = _curPost.RetweetedId.Value;
8094 _reply_to_id = _curPost.StatusId;
8096 _reply_to_name = _curPost.ScreenName;
8104 //1件選んでEnter or DoubleClick
8105 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8107 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8110 if (_curPost.RetweetedId != null)
8112 _reply_to_id = _curPost.RetweetedId.Value;
8116 _reply_to_id = _curPost.StatusId;
8118 _reply_to_name = _curPost.ScreenName;
8122 if (!StatusText.Text.StartsWith("@"))
8125 if (StatusText.Text.StartsWith(". "))
8128 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8129 _reply_to_id = null;
8130 _reply_to_name = null;
8135 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8136 if (_curPost.RetweetedId != null)
8138 _reply_to_id = _curPost.RetweetedId.Value;
8142 _reply_to_id = _curPost.StatusId;
8144 _reply_to_name = _curPost.ScreenName;
8151 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8152 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8153 _reply_to_id = null;
8154 _reply_to_name = null;
8159 //1件選んでCtrl-Rの場合(返信先操作せず)
8160 int sidx = StatusText.SelectionStart;
8161 string id = "@" + _curPost.ScreenName + " ";
8164 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8169 StatusText.Text = StatusText.Text.Insert(sidx, id);
8171 //if (StatusText.Text.StartsWith("@"))
8174 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8175 // sidx += 5 + _curPost.ScreenName.Length;
8180 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8181 // sidx += 3 + _curPost.ScreenName.Length;
8183 StatusText.SelectionStart = sidx;
8186 //_reply_to_name = null;
8194 if (!isAuto && !isReply) return;
8196 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8200 //Enter or DoubleClick
8202 string sTxt = StatusText.Text;
8203 if (!sTxt.StartsWith(". "))
8206 _reply_to_id = null;
8207 _reply_to_name = null;
8209 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8211 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8212 if (!sTxt.Contains("@" + post.ScreenName + " "))
8214 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8215 //sTxt = "@" + post.ScreenName + " " + sTxt;
8218 StatusText.Text = sTxt;
8223 if (_curList.SelectedIndices.Count > 1)
8228 int sidx = StatusText.SelectionStart;
8229 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8231 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8232 if (!ids.Contains("@" + post.ScreenName + " ") &&
8233 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8235 ids += "@" + post.ScreenName + " ";
8239 foreach (string nm in post.ReplyToList)
8241 if (!ids.Contains("@" + nm + " ") &&
8242 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8244 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8246 ids += "@" + m.Result("${id}") + " ";
8248 ids += "@" + nm + " ";
8253 if (ids.Length == 0) return;
8254 if (!StatusText.Text.StartsWith(". "))
8256 StatusText.Text = ". " + StatusText.Text;
8258 _reply_to_id = null;
8259 _reply_to_name = null;
8263 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8268 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8270 //if (StatusText.Text.StartsWith("@"))
8272 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8273 // sidx += 2 + ids.Length;
8277 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8278 // sidx += 1 + ids.Length;
8280 StatusText.SelectionStart = sidx;
8286 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8289 int sidx = StatusText.SelectionStart;
8290 PostClass post = _curPost;
8291 if (!ids.Contains("@" + post.ScreenName + " ") &&
8292 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8294 ids += "@" + post.ScreenName + " ";
8296 foreach (string nm in post.ReplyToList)
8298 if (!ids.Contains("@" + nm + " ") &&
8299 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8301 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8303 ids += "@" + m.Result("${id}") + " ";
8305 ids += "@" + nm + " ";
8308 if (!string.IsNullOrEmpty(post.RetweetedBy))
8310 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8311 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8313 ids += "@" + post.RetweetedBy + " ";
8316 if (ids.Length == 0) return;
8317 if (string.IsNullOrEmpty(StatusText.Text))
8320 StatusText.Text = ids;
8321 StatusText.SelectionStart = ids.Length;
8323 if (post.RetweetedId != null)
8325 _reply_to_id = post.RetweetedId.Value;
8329 _reply_to_id = post.StatusId;
8331 _reply_to_name = post.ScreenName;
8337 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8342 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8344 StatusText.SelectionStart = sidx;
8350 StatusText.SelectionStart = StatusText.Text.Length;
8355 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8360 private static int iconCnt = 0;
8361 private static int blinkCnt = 0;
8362 private static bool blink = false;
8363 private static bool idle = false;
8365 private void RefreshTasktrayIcon(bool forceRefresh)
8367 if (_colorize) Colorize();
8368 if (!TimerRefreshIcon.Enabled) return;
8369 //Static usCheckCnt As int = 0
8371 //Static iconDlListTopItem As ListViewItem = null
8373 if (forceRefresh) idle = false;
8375 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8376 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8378 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8380 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8386 //if (usCheckCnt > 300) //1min
8389 // if (!this.IsReceivedUserStream)
8391 // TraceOut("ReconnectUserStream");
8392 // tw.ReconnectUserStream();
8397 foreach (BackgroundWorker bw in this._bw)
8399 if (bw != null && bw.IsBusy)
8414 SaveConfigsAll(true);
8419 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8421 _myStatusError = false;
8425 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8426 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8428 if (blinkCnt > 0) return;
8430 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8432 NotifyIcon1.Icon = ReplyIcon;
8436 NotifyIcon1.Icon = ReplyIconBlink;
8444 //優先度:エラー→オフライン→アイドル
8448 NotifyIcon1.Icon = NIconAtRed;
8451 if (_myStatusOnline)
8453 NotifyIcon1.Icon = NIconAt;
8457 NotifyIcon1.Icon = NIconAtSmoke;
8461 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8464 this.RefreshTasktrayIcon(false);
8467 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8469 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8470 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8472 if (ListTab != null && ListTab.SelectedTab != null)
8473 _rclickTabName = ListTab.SelectedTab.Text;
8478 if (_statuses == null) return;
8479 if (_statuses.Tabs == null) return;
8481 TabClass tb = _statuses.Tabs[_rclickTabName];
8482 if (tb == null) return;
8484 NotifyDispMenuItem.Checked = tb.Notify;
8485 this.NotifyTbMenuItem.Checked = tb.Notify;
8487 soundfileListup = true;
8488 SoundFileComboBox.Items.Clear();
8489 this.SoundFileTbComboBox.Items.Clear();
8490 SoundFileComboBox.Items.Add("");
8491 this.SoundFileTbComboBox.Items.Add("");
8492 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8493 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8495 oDir = oDir.GetDirectories("Sounds")[0];
8497 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8499 SoundFileComboBox.Items.Add(oFile.Name);
8500 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8502 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8503 if (idx == -1) idx = 0;
8504 SoundFileComboBox.SelectedIndex = idx;
8505 this.SoundFileTbComboBox.SelectedIndex = idx;
8506 soundfileListup = false;
8507 UreadManageMenuItem.Checked = tb.UnreadManage;
8508 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8510 TabMenuControl(_rclickTabName);
8513 private void TabMenuControl(string tabName)
8515 this.FilterEditMenuItem.Enabled = true;
8516 this.EditRuleTbMenuItem.Enabled = true;
8518 if (_statuses.IsDefaultTab(tabName))
8520 this.ProtectTabMenuItem.Enabled = false;
8521 this.ProtectTbMenuItem.Enabled = false;
8525 this.ProtectTabMenuItem.Enabled = true;
8526 this.ProtectTbMenuItem.Enabled = true;
8529 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8531 this.ProtectTabMenuItem.Checked = true;
8532 this.ProtectTbMenuItem.Checked = true;
8533 this.DeleteTabMenuItem.Enabled = false;
8534 this.DeleteTbMenuItem.Enabled = false;
8538 this.ProtectTabMenuItem.Checked = false;
8539 this.ProtectTbMenuItem.Checked = false;
8540 this.DeleteTabMenuItem.Enabled = true;
8541 this.DeleteTbMenuItem.Enabled = true;
8545 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8547 var checkState = ((ToolStripMenuItem)sender).Checked;
8550 this.ProtectTbMenuItem.Checked = checkState;
8551 this.ProtectTabMenuItem.Checked = checkState;
8554 this.DeleteTabMenuItem.Enabled = !checkState;
8555 this.DeleteTbMenuItem.Enabled = !checkState;
8557 if (string.IsNullOrEmpty(_rclickTabName)) return;
8558 _statuses.Tabs[_rclickTabName].Protected = checkState;
8563 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8565 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8566 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8568 if (string.IsNullOrEmpty(_rclickTabName)) return;
8569 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8574 public void ChangeTabUnreadManage(string tabName, bool isManage)
8577 for (idx = 0; idx < ListTab.TabCount; idx++)
8579 if (ListTab.TabPages[idx].Text == tabName) break;
8582 _statuses.SetTabUnreadManage(tabName, isManage);
8583 if (this._cfgCommon.TabIconDisp)
8585 if (_statuses.Tabs[tabName].UnreadCount > 0)
8586 ListTab.TabPages[idx].ImageIndex = 0;
8588 ListTab.TabPages[idx].ImageIndex = -1;
8591 if (_curTab.Text == tabName)
8593 this.PurgeListViewItemCache();
8597 SetMainWindowTitle();
8598 SetStatusLabelUrl();
8599 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8602 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8604 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8605 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8607 if (string.IsNullOrEmpty(_rclickTabName)) return;
8609 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8614 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8616 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8618 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8623 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8625 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8627 RemoveSpecifiedTab(_rclickTabName, true);
8631 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8633 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8634 fltDialog.SetCurrent(_rclickTabName);
8635 fltDialog.ShowDialog(this);
8636 this.TopMost = this._cfgCommon.AlwaysTop;
8638 this.ApplyPostFilters();
8642 private void AddTabMenuItem_Click(object sender, EventArgs e)
8644 string tabName = null;
8645 MyCommon.TabUsageType tabUsage;
8646 using (InputTabName inputName = new InputTabName())
8648 inputName.TabName = _statuses.GetUniqueTabName();
8649 inputName.IsShowUsage = true;
8650 inputName.ShowDialog();
8651 if (inputName.DialogResult == DialogResult.Cancel) return;
8652 tabName = inputName.TabName;
8653 tabUsage = inputName.Usage;
8655 this.TopMost = this._cfgCommon.AlwaysTop;
8656 if (!string.IsNullOrEmpty(tabName))
8659 ListElement list = null;
8660 if (tabUsage == MyCommon.TabUsageType.Lists)
8662 using (ListAvailable listAvail = new ListAvailable())
8664 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8665 if (listAvail.SelectedList == null) return;
8666 list = listAvail.SelectedList;
8669 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8671 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8672 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8678 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8680 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8681 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8682 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8684 if (tabUsage == MyCommon.TabUsageType.Lists)
8686 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8687 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8688 GetTimeline(MyCommon.WORKERTYPE.List, 1, tabName);
8694 private void TabMenuItem_Click(object sender, EventArgs e)
8697 foreach (int idx in _curList.SelectedIndices)
8701 if (!SelectTab(out tabName)) return;
8703 fltDialog.SetCurrent(tabName);
8704 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8706 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8710 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8712 fltDialog.ShowDialog(this);
8713 this.TopMost = this._cfgCommon.AlwaysTop;
8716 this.ApplyPostFilters();
8718 if (this.ListTab.SelectedTab != null &&
8719 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8721 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8725 protected override bool ProcessDialogKey(Keys keyData)
8727 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8728 if ((keyData & Keys.KeyCode) == Keys.Enter)
8730 if (StatusText.Focused)
8732 bool _NewLine = false;
8735 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8737 if (StatusText.Multiline)
8739 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8741 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8745 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8749 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8751 if (StatusText.Multiline)
8753 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8755 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8759 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8765 if (StatusText.Multiline)
8767 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8769 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8770 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8774 if (((keyData & Keys.Shift) == Keys.Shift) ||
8775 (((keyData & Keys.Control) != Keys.Control) &&
8776 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8782 int pos1 = StatusText.SelectionStart;
8783 if (StatusText.SelectionLength > 0)
8785 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8787 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8788 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8793 PostButton_Click(null, null);
8797 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8798 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8799 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8801 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8806 return base.ProcessDialogKey(keyData);
8809 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8811 MakeReplyOrDirectStatus(false, true, true);
8814 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8819 if (_curList.SelectedIndices.Count == 0) return;
8822 if (!SelectTab(out tabName)) return;
8826 MoveOrCopy(ref mv, ref mk);
8828 List<string> ids = new List<string>();
8829 foreach (int idx in _curList.SelectedIndices)
8831 PostClass post = _statuses[_curTab.Text, idx];
8832 if (!ids.Contains(post.ScreenName))
8834 PostFilterRule fc = new PostFilterRule();
8835 ids.Add(post.ScreenName);
8836 if (post.RetweetedId == null)
8838 fc.FilterName = post.ScreenName;
8842 fc.FilterName = post.RetweetedBy;
8844 fc.UseNameField = true;
8845 fc.MoveMatches = mv;
8846 fc.MarkMatches = mk;
8847 fc.UseRegex = false;
8848 fc.FilterByUrl = false;
8849 _statuses.Tabs[tabName].AddFilter(fc);
8854 List<string> atids = new List<string>();
8855 foreach (string id in ids)
8857 atids.Add("@" + id);
8859 int cnt = AtIdSupl.ItemCount;
8860 AtIdSupl.AddRangeItem(atids.ToArray());
8861 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
8864 this.ApplyPostFilters();
8868 private bool SelectTab(out string tabName)
8875 using (var dialog = new TabsDialog(_statuses))
8877 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8879 var selectedTab = dialog.SelectedTab;
8880 tabName = selectedTab == null ? null : selectedTab.TabName;
8883 ListTab.SelectedTab.Focus();
8885 if (tabName == null)
8887 using (InputTabName inputName = new InputTabName())
8889 inputName.TabName = _statuses.GetUniqueTabName();
8890 inputName.ShowDialog();
8891 if (inputName.DialogResult == DialogResult.Cancel) return false;
8892 tabName = inputName.TabName;
8894 this.TopMost = this._cfgCommon.AlwaysTop;
8895 if (!string.IsNullOrEmpty(tabName))
8897 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
8899 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8900 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8918 private void MoveOrCopy(ref bool move, ref bool mark)
8922 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8923 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8931 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8932 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8938 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8943 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8948 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8950 if (StatusText.Focused)
8953 StatusText.SelectAll();
8957 // ListView上でのCtrl+A
8958 for (int i = 0; i < _curList.VirtualListSize; i++)
8960 _curList.SelectedIndices.Add(i);
8965 private void MoveMiddle()
8971 if (_curList.SelectedIndices.Count == 0) return;
8973 int idx = _curList.SelectedIndices[0];
8975 _item = _curList.GetItemAt(0, 25);
8981 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8983 idx2 = _curList.VirtualListSize - 1;
8987 idx -= Math.Abs(idx1 - idx2) / 2;
8988 if (idx < 0) idx = 0;
8990 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8991 _curList.EnsureVisible(idx);
8994 private void OpenURLMenuItem_Click(object sender, EventArgs e)
8996 if (PostBrowser.Document.Links.Count > 0)
8998 UrlDialog.ClearUrl();
9000 string openUrlStr = "";
9002 if (PostBrowser.Document.Links.Count == 1)
9007 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9009 catch (ArgumentException)
9018 if (string.IsNullOrEmpty(urlStr)) return;
9019 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9023 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9026 string linkText = "";
9030 urlStr = linkElm.GetAttribute("title");
9031 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9032 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9033 linkText = linkElm.InnerText;
9034 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9036 linkText = "@" + linkText;
9039 catch (ArgumentException)
9048 if (string.IsNullOrEmpty(urlStr)) continue;
9049 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9053 if (UrlDialog.ShowDialog() == DialogResult.OK)
9055 openUrlStr = UrlDialog.SelectedUrl;
9062 this.TopMost = this._cfgCommon.AlwaysTop;
9064 if (string.IsNullOrEmpty(openUrlStr)) return;
9066 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9067 openUrlStr.StartsWith("https://twitter.com/search?q="))
9070 string urlStr = Uri.UnescapeDataString(openUrlStr);
9071 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9072 HashSupl.AddItem(hash);
9073 HashMgr.AddHashToHistory(hash.Trim(), false);
9074 AddNewTabForSearch(hash);
9079 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9080 if (this._cfgCommon.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9081 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9083 OpenUriAsync(openUrlStr);
9089 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9091 if (string.IsNullOrEmpty(_rclickTabName)) return;
9092 ClearTab(_rclickTabName, true);
9095 private void ClearTab(string tabName, bool showWarning)
9099 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9100 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9106 _statuses.ClearTabIds(tabName);
9107 if (ListTab.SelectedTab.Text == tabName)
9110 _anchorFlag = false;
9111 this.PurgeListViewItemCache();
9115 foreach (TabPage tb in ListTab.TabPages)
9117 if (tb.Text == tabName)
9120 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9124 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9126 SetMainWindowTitle();
9127 SetStatusLabelUrl();
9130 private static long followers = 0;
9132 private void SetMainWindowTitle()
9135 StringBuilder ttl = new StringBuilder(256);
9138 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9139 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9140 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9141 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9143 foreach (var tab in _statuses.Tabs.Values)
9145 ur += tab.UnreadCount;
9150 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9151 ttl.Append(Application.ProductName);
9153 switch (this._cfgCommon.DispLatestPost)
9155 case MyCommon.DispTitleEnum.Ver:
9156 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9158 case MyCommon.DispTitleEnum.Post:
9159 if (_history != null && _history.Count > 1)
9160 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9162 case MyCommon.DispTitleEnum.UnreadRepCount:
9163 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9165 case MyCommon.DispTitleEnum.UnreadAllCount:
9166 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9168 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9169 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9171 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9172 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9174 case MyCommon.DispTitleEnum.OwnStatus:
9175 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9176 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9182 this.Text = ttl.ToString();
9184 catch (AccessViolationException)
9186 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9190 private string GetStatusLabelText()
9193 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9194 if (_statuses == null) return "";
9195 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9196 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9197 if (tbRep == null || tbDm == null) return "";
9198 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9203 StringBuilder slbl = new StringBuilder(256);
9206 foreach (var tab in _statuses.Tabs.Values)
9208 ur += tab.UnreadCount;
9210 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9212 tur = tab.UnreadCount;
9223 UnreadAtCounter = urat;
9225 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9226 if (this._cfgCommon.TimelinePeriod == 0)
9228 slbl.Append(Properties.Resources.SetStatusLabelText2);
9232 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9234 return slbl.ToString();
9237 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9241 if (this.InvokeRequired && !this.IsDisposed)
9243 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9247 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9248 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9250 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9254 catch (ObjectDisposedException)
9258 catch (InvalidOperationException)
9264 private void SetStatusLabelUrl()
9266 StatusLabelUrl.Text = GetStatusLabelText();
9269 public void SetStatusLabel(string text)
9271 StatusLabel.Text = text;
9274 private static StringBuilder ur = new StringBuilder(64);
9276 private void SetNotifyIconText()
9278 // タスクトレイアイコンのツールチップテキスト書き換え
9280 ur.Remove(0, ur.Length);
9281 if (this._cfgCommon.DispUsername)
9283 ur.Append(tw.Username);
9286 ur.Append(Application.ProductName);
9288 ur.Append("(Debug Build)");
9290 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9293 ur.Append(UnreadCounter);
9295 ur.Append(UnreadAtCounter);
9298 NotifyIcon1.Text = ur.ToString();
9301 internal void CheckReplyTo(string StatusText)
9305 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9307 foreach (Match hm in m)
9309 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9311 hstr += "#" + hm.Result("$3") + " ";
9312 HashSupl.AddItem("#" + hm.Result("$3"));
9315 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9317 hstr += HashMgr.UseHash;
9319 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9321 // 本当にリプライ先指定すべきかどうかの判定
9322 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9324 if (this._cfgCommon.UseAtIdSupplement)
9326 int bCnt = AtIdSupl.ItemCount;
9327 foreach (Match mid in m)
9329 AtIdSupl.AddItem(mid.Result("${id}"));
9331 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9334 // リプライ先ステータスIDの指定がない場合は指定しない
9335 if (_reply_to_id == null) return;
9337 // リプライ先ユーザー名がない場合も指定しない
9338 if (string.IsNullOrEmpty(_reply_to_name))
9340 _reply_to_id = null;
9345 // 次の条件を満たす場合に in_reply_to_status_id 指定
9346 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9347 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9348 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9352 if (StatusText.StartsWith("@"))
9354 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9358 foreach (Match mid in m)
9360 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9365 _reply_to_id = null;
9366 _reply_to_name = null;
9370 private void TweenMain_Resize(object sender, EventArgs e)
9372 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9374 this.Visible = false;
9376 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9378 this.ClientSize = _cfgLocal.FormSize;
9379 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9380 this.DesktopLocation = _cfgLocal.FormLocation;
9381 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9382 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9383 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9385 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9388 StatusText.Multiline = _cfgLocal.StatusMultiline;
9389 if (StatusText.Multiline)
9391 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9392 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9394 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9396 StatusText.Height = _cfgLocal.StatusTextHeight;
9400 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9402 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9405 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9407 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9409 _initialLayout = false;
9411 if (this.WindowState != FormWindowState.Minimized)
9413 _formWindowState = this.WindowState;
9417 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9419 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9420 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9421 if (PlaySoundMenuItem.Checked)
9423 this._cfgCommon.PlaySound = true;
9427 this._cfgCommon.PlaySound = false;
9429 _modifySettingCommon = true;
9432 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9434 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9436 _mySpDis = SplitContainer1.SplitterDistance;
9437 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9438 _modifySettingLocal = true;
9442 private void doRepliedStatusOpen()
9444 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9446 if (MyCommon.IsKeyDown(Keys.Shift))
9448 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9451 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9453 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9454 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9458 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9460 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9461 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9462 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9465 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9470 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9472 doRepliedStatusOpen();
9476 /// UserPicture.Image に設定されている画像を破棄します。
9478 private void ClearUserPicture()
9480 if (this.UserPicture.Image != null)
9482 var oldImage = this.UserPicture.Image;
9483 this.UserPicture.Image = null;
9488 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9490 //発言詳細のアイコン右クリック時のメニュー制御
9491 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9493 string name = _curPost.ImageUrl;
9494 if (name != null && name.Length > 0)
9496 int idx = name.LastIndexOf('/');
9499 name = Path.GetFileName(name.Substring(idx));
9500 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9502 name = name.Replace("_normal", "");
9503 this.IconNameToolStripMenuItem.Text = name;
9504 this.IconNameToolStripMenuItem.Enabled = true;
9508 this.IconNameToolStripMenuItem.Enabled = false;
9509 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9514 this.IconNameToolStripMenuItem.Enabled = false;
9515 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9518 this.ReloadIconToolStripMenuItem.Enabled = true;
9520 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9522 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9526 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9531 this.IconNameToolStripMenuItem.Enabled = false;
9532 this.ReloadIconToolStripMenuItem.Enabled = false;
9533 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9534 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9539 this.IconNameToolStripMenuItem.Enabled = false;
9540 this.ReloadIconToolStripMenuItem.Enabled = false;
9541 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9542 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9544 if (NameLabel.Tag != null)
9546 string id = (string)NameLabel.Tag;
9547 if (id == tw.Username)
9549 FollowToolStripMenuItem.Enabled = false;
9550 UnFollowToolStripMenuItem.Enabled = false;
9551 ShowFriendShipToolStripMenuItem.Enabled = false;
9552 ShowUserStatusToolStripMenuItem.Enabled = true;
9553 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9554 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9555 ListManageUserContextToolStripMenuItem3.Enabled = true;
9559 FollowToolStripMenuItem.Enabled = true;
9560 UnFollowToolStripMenuItem.Enabled = true;
9561 ShowFriendShipToolStripMenuItem.Enabled = true;
9562 ShowUserStatusToolStripMenuItem.Enabled = true;
9563 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9564 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9565 ListManageUserContextToolStripMenuItem3.Enabled = true;
9570 FollowToolStripMenuItem.Enabled = false;
9571 UnFollowToolStripMenuItem.Enabled = false;
9572 ShowFriendShipToolStripMenuItem.Enabled = false;
9573 ShowUserStatusToolStripMenuItem.Enabled = false;
9574 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9575 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9576 ListManageUserContextToolStripMenuItem3.Enabled = false;
9580 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9582 if (_curPost == null) return;
9583 string name = _curPost.ImageUrl;
9584 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9587 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9589 if (this._curPost == null) return;
9591 await this.UserPicture.SetImageFromTask(async () =>
9593 var imageUrl = this._curPost.ImageUrl;
9595 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9596 .ConfigureAwait(false);
9598 return await image.CloneAsync()
9599 .ConfigureAwait(false);
9603 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9605 if (_curPost == null) return;
9606 string name = _curPost.ImageUrl;
9607 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9609 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9611 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9617 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9619 if (_curPost == null) return;
9620 string name = _curPost.ImageUrl;
9622 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9624 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9628 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9630 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9632 using (Graphics g = Graphics.FromImage(bmp2))
9634 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9635 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9637 bmp2.Save(this.SaveFileDialog1.FileName);
9643 //処理中にキャッシュアウトする可能性あり
9648 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9650 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9651 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9652 _modifySettingLocal = true;
9655 private void StatusText_MultilineChanged(object sender, EventArgs e)
9657 if (this.StatusText.Multiline)
9658 this.StatusText.ScrollBars = ScrollBars.Vertical;
9660 this.StatusText.ScrollBars = ScrollBars.None;
9662 _modifySettingLocal = true;
9665 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9668 StatusText.Multiline = MultiLineMenuItem.Checked;
9669 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9670 if (MultiLineMenuItem.Checked)
9672 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9673 SplitContainer2.SplitterDistance = 0;
9675 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9679 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9681 _modifySettingLocal = true;
9684 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9686 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9687 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9689 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9690 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9691 //Appendix A. Collected ABNF for URI
9692 //http://www.ietf.org/rfc/rfc3986.txt
9696 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9698 if (StatusText.SelectionLength > 0)
9700 string tmp = StatusText.SelectedText;
9701 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9702 if (tmp.StartsWith("http"))
9704 // 文字列が選択されている場合はその文字列について処理
9706 //nico.ms使用、nicovideoにマッチしたら変換
9707 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9709 result = nicoms.Shorten(tmp);
9711 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9713 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9716 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9717 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9718 result = resultUri.ToString();
9720 catch (WebApiException e)
9722 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9725 catch (UriFormatException e)
9727 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9736 if (!string.IsNullOrEmpty(result))
9738 urlUndo undotmp = new urlUndo();
9740 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9741 StatusText.SelectedText = result;
9744 undotmp.Before = tmp;
9745 undotmp.After = result;
9747 if (urlUndoBuffer == null)
9749 urlUndoBuffer = new List<urlUndo>();
9750 UrlUndoToolStripMenuItem.Enabled = true;
9753 urlUndoBuffer.Add(undotmp);
9759 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9760 @"(?<url>(?<protocol>https?://)" +
9761 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9762 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9763 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9764 // 正規表現にマッチしたURL文字列をtinyurl化
9765 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9767 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9768 string tmp = mt.Result("${url}");
9769 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9770 urlUndo undotmp = new urlUndo();
9773 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9775 //nico.ms使用、nicovideoにマッチしたら変換
9776 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9778 result = nicoms.Shorten(tmp);
9780 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9782 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9785 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9786 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9787 result = resultUri.ToString();
9789 catch (HttpRequestException e)
9791 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9792 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9793 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9795 this.StatusLabel.Text = Converter_Type + ":" + message;
9798 catch (WebApiException e)
9800 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9803 catch (UriFormatException e)
9805 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9814 if (!string.IsNullOrEmpty(result))
9816 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9817 StatusText.SelectedText = result;
9819 undotmp.Before = mt.Result("${url}");
9820 undotmp.After = result;
9822 if (urlUndoBuffer == null)
9824 urlUndoBuffer = new List<urlUndo>();
9825 UrlUndoToolStripMenuItem.Enabled = true;
9828 urlUndoBuffer.Add(undotmp);
9836 private void doUrlUndo()
9838 if (urlUndoBuffer != null)
9840 string tmp = StatusText.Text;
9841 foreach (urlUndo data in urlUndoBuffer)
9843 tmp = tmp.Replace(data.After, data.Before);
9845 StatusText.Text = tmp;
9846 urlUndoBuffer = null;
9847 UrlUndoToolStripMenuItem.Enabled = false;
9848 StatusText.SelectionStart = 0;
9849 StatusText.SelectionLength = 0;
9853 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9855 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9858 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9860 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9863 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9865 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9868 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9870 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9873 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9875 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9877 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9878 Random rnd = new Random();
9879 // 前回使用した短縮URLサービス以外を選択する
9882 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9884 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9885 await UrlConvertAsync(svc);
9889 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9894 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9896 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9897 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9898 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9899 _modifySettingCommon = true;
9902 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9904 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9905 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9906 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9907 _modifySettingCommon = true;
9910 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9912 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9913 MenuStrip1.Tag = new Object();
9914 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9917 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9919 if (this.Tag != null) // 設定された戻り先へ遷移
9921 if (this.Tag == this.ListTab.SelectedTab)
9922 ((Control)this.ListTab.SelectedTab.Tag).Select();
9924 ((Control)this.Tag).Select();
9926 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9928 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9930 this.Tag = ListTab.SelectedTab.Tag;
9931 ((Control)this.Tag).Select();
9934 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9935 MenuStrip1.Tag = null;
9938 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9940 DetailsListView lst = (DetailsListView)sender;
9941 if (_cfgLocal == null) return;
9945 _cfgLocal.Width1 = lst.Columns[0].Width;
9946 _cfgLocal.Width3 = lst.Columns[1].Width;
9950 int[] darr = new int[lst.Columns.Count];
9951 for (int i = 0; i < lst.Columns.Count; i++)
9953 darr[lst.Columns[i].DisplayIndex] = i;
9955 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9957 for (int i = 0; i < lst.Columns.Count; i++)
9962 _cfgLocal.DisplayIndex1 = i;
9965 _cfgLocal.DisplayIndex2 = i;
9968 _cfgLocal.DisplayIndex3 = i;
9971 _cfgLocal.DisplayIndex4 = i;
9974 _cfgLocal.DisplayIndex5 = i;
9977 _cfgLocal.DisplayIndex6 = i;
9980 _cfgLocal.DisplayIndex7 = i;
9983 _cfgLocal.DisplayIndex8 = i;
9987 _cfgLocal.Width1 = lst.Columns[0].Width;
9988 _cfgLocal.Width2 = lst.Columns[1].Width;
9989 _cfgLocal.Width3 = lst.Columns[2].Width;
9990 _cfgLocal.Width4 = lst.Columns[3].Width;
9991 _cfgLocal.Width5 = lst.Columns[4].Width;
9992 _cfgLocal.Width6 = lst.Columns[5].Width;
9993 _cfgLocal.Width7 = lst.Columns[6].Width;
9994 _cfgLocal.Width8 = lst.Columns[7].Width;
9996 _modifySettingLocal = true;
9997 _isColumnChanged = true;
10000 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10002 DetailsListView lst = (DetailsListView)sender;
10003 if (_cfgLocal == null) return;
10006 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10008 _cfgLocal.Width1 = lst.Columns[0].Width;
10009 _modifySettingLocal = true;
10010 _isColumnChanged = true;
10012 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10014 _cfgLocal.Width3 = lst.Columns[1].Width;
10015 _modifySettingLocal = true;
10016 _isColumnChanged = true;
10021 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10023 _cfgLocal.Width1 = lst.Columns[0].Width;
10024 _modifySettingLocal = true;
10025 _isColumnChanged = true;
10027 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10029 _cfgLocal.Width2 = lst.Columns[1].Width;
10030 _modifySettingLocal = true;
10031 _isColumnChanged = true;
10033 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10035 _cfgLocal.Width3 = lst.Columns[2].Width;
10036 _modifySettingLocal = true;
10037 _isColumnChanged = true;
10039 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10041 _cfgLocal.Width4 = lst.Columns[3].Width;
10042 _modifySettingLocal = true;
10043 _isColumnChanged = true;
10045 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10047 _cfgLocal.Width5 = lst.Columns[4].Width;
10048 _modifySettingLocal = true;
10049 _isColumnChanged = true;
10051 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10053 _cfgLocal.Width6 = lst.Columns[5].Width;
10054 _modifySettingLocal = true;
10055 _isColumnChanged = true;
10057 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10059 _cfgLocal.Width7 = lst.Columns[6].Width;
10060 _modifySettingLocal = true;
10061 _isColumnChanged = true;
10063 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10065 _cfgLocal.Width8 = lst.Columns[7].Width;
10066 _modifySettingLocal = true;
10067 _isColumnChanged = true;
10070 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10073 // SaveConfigsLocal();
10077 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10079 //発言詳細で「選択文字列をコピー」を行う
10080 //WebBrowserコンポーネントのインスタンスを渡す
10081 Type typ = ComponentInstance.ActiveXInstance.GetType();
10082 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10083 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10084 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10087 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10090 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10093 Clipboard.SetDataObject(_selText, false, 5, 100);
10095 catch (Exception ex)
10097 MessageBox.Show(ex.Message);
10101 private void doSearchToolStrip(string url)
10103 //発言詳細で「選択文字列で検索」(選択文字列取得)
10104 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10106 if (_selText != null)
10108 if (url == Properties.Resources.SearchItem4Url)
10111 AddNewTabForSearch(_selText);
10115 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10120 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10123 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10126 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10128 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10131 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10133 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10136 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10138 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10141 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10145 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10146 foreach (Match m in mc)
10148 if (m.Groups["url"].Value == this._postBrowserStatusText)
10150 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10156 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10158 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10160 catch (Exception ex)
10162 MessageBox.Show(ex.Message);
10166 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10168 // URLコピーの項目の表示/非表示
10169 if (PostBrowser.StatusText.StartsWith("http"))
10171 this._postBrowserStatusText = PostBrowser.StatusText;
10172 string name = GetUserId();
10173 UrlCopyContextMenuItem.Enabled = true;
10176 FollowContextMenuItem.Enabled = true;
10177 RemoveContextMenuItem.Enabled = true;
10178 FriendshipContextMenuItem.Enabled = true;
10179 ShowUserStatusContextMenuItem.Enabled = true;
10180 SearchPostsDetailToolStripMenuItem.Enabled = true;
10181 IdFilterAddMenuItem.Enabled = true;
10182 ListManageUserContextToolStripMenuItem.Enabled = true;
10183 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10187 FollowContextMenuItem.Enabled = false;
10188 RemoveContextMenuItem.Enabled = false;
10189 FriendshipContextMenuItem.Enabled = false;
10190 ShowUserStatusContextMenuItem.Enabled = false;
10191 SearchPostsDetailToolStripMenuItem.Enabled = false;
10192 IdFilterAddMenuItem.Enabled = false;
10193 ListManageUserContextToolStripMenuItem.Enabled = false;
10194 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10197 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10198 UseHashtagMenuItem.Enabled = true;
10200 UseHashtagMenuItem.Enabled = false;
10204 this._postBrowserStatusText = "";
10205 UrlCopyContextMenuItem.Enabled = false;
10206 FollowContextMenuItem.Enabled = false;
10207 RemoveContextMenuItem.Enabled = false;
10208 FriendshipContextMenuItem.Enabled = false;
10209 ShowUserStatusContextMenuItem.Enabled = false;
10210 SearchPostsDetailToolStripMenuItem.Enabled = false;
10211 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10212 UseHashtagMenuItem.Enabled = false;
10213 IdFilterAddMenuItem.Enabled = false;
10214 ListManageUserContextToolStripMenuItem.Enabled = false;
10216 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10217 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10218 if (_selText == null)
10220 SelectionSearchContextMenuItem.Enabled = false;
10221 SelectionCopyContextMenuItem.Enabled = false;
10222 SelectionTranslationToolStripMenuItem.Enabled = false;
10226 SelectionSearchContextMenuItem.Enabled = true;
10227 SelectionCopyContextMenuItem.Enabled = true;
10228 SelectionTranslationToolStripMenuItem.Enabled = true;
10230 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10231 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10232 bool fAllFlag = false;
10233 foreach (Match mu in ma)
10235 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10241 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10243 if (_curPost == null)
10244 TranslationToolStripMenuItem.Enabled = false;
10246 TranslationToolStripMenuItem.Enabled = true;
10251 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10253 //発言詳細の選択文字列で現在のタブを検索
10254 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10256 if (_selText != null)
10258 var searchOptions = new SearchWordDialog.SearchOptions(
10259 SearchWordDialog.SearchType.Timeline,
10262 caseSensitive: false,
10265 this.SearchDialog.ResultOptions = searchOptions;
10268 searchOptions.Query,
10269 searchOptions.CaseSensitive,
10270 searchOptions.UseRegex,
10271 SEARCHTYPE.NextSearch);
10275 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10277 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10278 _modifySettingLocal = true;
10281 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10283 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10285 SelectMedia_DragDrop(e);
10287 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10289 var url = GetUrlFromDataObject(e.Data);
10292 if (url.Item2 == null)
10293 appendText = url.Item1;
10295 appendText = url.Item2 + " " + url.Item1;
10297 if (this.StatusText.TextLength == 0)
10298 this.StatusText.Text = appendText;
10300 this.StatusText.Text += " " + appendText;
10302 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10304 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10305 if (data != null) StatusText.Text += data;
10310 /// IDataObject から URL とタイトルの対を取得します
10313 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10315 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10316 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10317 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10319 if (data.GetDataPresent("text/x-moz-url"))
10321 // Firefox, Google Chrome で利用可能
10322 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10324 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10326 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10327 if (lines.Length < 2)
10328 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10330 return new Tuple<string, string>(lines[0], lines[1]);
10333 else if (data.GetDataPresent("IESiteModeToUrl"))
10335 // Internet Exproler 用
10336 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10338 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10340 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10341 if (lines.Length < 2)
10342 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10344 return new Tuple<string, string>(lines[0], lines[1]);
10347 else if (data.GetDataPresent("UniformResourceLocatorW"))
10351 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10353 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10354 return new Tuple<string, string>(url, null);
10358 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10361 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10363 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10365 SelectMedia_DragEnter(e);
10369 private void TweenMain_DragOver(object sender, DragEventArgs e)
10371 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10373 SelectMedia_DragOver(e);
10375 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10377 e.Effect = DragDropEffects.Copy;
10379 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10381 e.Effect = DragDropEffects.Copy;
10385 e.Effect = DragDropEffects.None;
10389 public bool IsNetworkAvailable()
10392 nw = MyCommon.IsNetworkAvailable();
10393 _myStatusOnline = nw;
10397 public Task OpenUriAsync(string UriString)
10399 return Task.Run(() =>
10401 string myPath = UriString;
10405 var configBrowserPath = this._cfgLocal.BrowserPath;
10406 if (!string.IsNullOrEmpty(configBrowserPath))
10408 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10410 int sep = configBrowserPath.IndexOf("\"", 2);
10411 string browserPath = configBrowserPath.Substring(1, sep - 1);
10413 if (sep < configBrowserPath.Length - 1)
10415 arg = configBrowserPath.Substring(sep + 1);
10417 myPath = arg + " " + myPath;
10418 System.Diagnostics.Process.Start(browserPath, myPath);
10422 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10427 System.Diagnostics.Process.Start(myPath);
10432 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10437 private void ListTabSelect(TabPage _tab)
10441 this.PurgeListViewItemCache();
10444 _curList = (DetailsListView)_tab.Tag;
10445 if (_curList.SelectedIndices.Count > 0)
10447 _curItemIndex = _curList.SelectedIndices[0];
10448 _curPost = GetCurTabPost(_curItemIndex);
10452 _curItemIndex = -1;
10456 _anchorPost = null;
10457 _anchorFlag = false;
10461 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10465 for (int i = 0; i < _curList.Columns.Count; i++)
10467 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10472 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10474 ListTabSelect(e.TabPage);
10477 private void SelectListItem(DetailsListView LView, int Index)
10480 Rectangle bnd = new Rectangle();
10482 var item = LView.FocusedItem;
10491 LView.SelectedIndices.Clear();
10493 while (LView.SelectedIndices.Count > 0);
10494 item = LView.Items[Index];
10495 item.Selected = true;
10496 item.Focused = true;
10498 if (flg) LView.Invalidate(bnd);
10501 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10504 Rectangle bnd = new Rectangle();
10506 var item = LView.FocusedItem;
10514 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10518 LView.SelectedIndices.Clear();
10520 while (LView.SelectedIndices.Count > 0);
10521 foreach (int idx in Index)
10523 if (idx > -1 && LView.VirtualListSize > idx)
10525 LView.SelectedIndices.Add(idx);
10526 if (fIdx == -1) fIdx = idx;
10530 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10532 LView.SelectionMark = FocusedIndex[1];
10534 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10536 LView.Items[FocusedIndex[0]].Focused = true;
10538 else if (fIdx > -1)
10540 LView.Items[fIdx].Focused = true;
10543 if (flg) LView.Invalidate(bnd);
10546 private void RunAsync(GetWorkerArg args)
10548 BackgroundWorker bw = null;
10549 if (args.type != MyCommon.WORKERTYPE.Follower)
10551 for (int i = 0; i < _bw.Length; i++)
10553 if (_bw[i] != null && !_bw[i].IsBusy)
10561 for (int i = 0; i < _bw.Length; i++)
10563 if (_bw[i] == null)
10565 _bw[i] = new BackgroundWorker();
10567 bw.WorkerReportsProgress = true;
10568 bw.WorkerSupportsCancellation = true;
10569 bw.DoWork += GetTimelineWorker_DoWork;
10570 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10571 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10579 if (_bwFollower == null)
10581 _bwFollower = new BackgroundWorker();
10583 bw.WorkerReportsProgress = true;
10584 bw.WorkerSupportsCancellation = true;
10585 bw.DoWork += GetTimelineWorker_DoWork;
10586 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10587 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10591 if (_bwFollower.IsBusy == false)
10595 if (bw == null) return;
10597 bw.RunWorkerAsync(args);
10600 private void StartUserStream()
10602 tw.NewPostFromStream += tw_NewPostFromStream;
10603 tw.UserStreamStarted += tw_UserStreamStarted;
10604 tw.UserStreamStopped += tw_UserStreamStopped;
10605 tw.PostDeleted += tw_PostDeleted;
10606 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10608 MenuItemUserStream.Text = "&UserStream ■";
10609 MenuItemUserStream.Enabled = true;
10610 StopToolStripMenuItem.Text = "&Start";
10611 StopToolStripMenuItem.Enabled = true;
10612 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
10615 private async void TweenMain_Shown(object sender, EventArgs e)
10619 PostBrowser.Url = new Uri("about:blank");
10620 PostBrowser.DocumentText = ""; //発言詳細部初期化
10626 NotifyIcon1.Visible = true;
10628 if (this.IsNetworkAvailable())
10630 this.RefreshMuteUserIdsAsync();
10631 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, "");
10632 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10633 if (this._cfgCommon.StartupFollowers)
10635 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10637 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10639 _waitTimeline = true;
10640 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
10642 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
10644 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
10645 if (this._cfgCommon.GetFav)
10648 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
10650 _waitPubSearch = true;
10651 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, ""); //tabname="":全タブ
10652 _waitUserTimeline = true;
10653 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, ""); //tabname="":全タブ
10655 GetTimeline(MyCommon.WORKERTYPE.List, 1, ""); //tabname="":全タブ
10658 while (this.IsInitialRead())
10660 await Task.Delay(5000);
10663 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10665 if (MyCommon._endingFlag)
10669 if (MyCommon._endingFlag) return;
10671 if (ApplicationSettings.VersionInfoUrl != null)
10673 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10674 if (this._cfgCommon.StartupVersion)
10675 await this.CheckNewVersion(true);
10679 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10680 this.VerUpMenuItem.Enabled = false;
10681 this.VerUpMenuItem.Available = false;
10682 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10686 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10687 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10690 if (!tw.GetNoRetweetSuccess)
10691 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10694 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10695 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10697 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10698 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10700 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10701 SettingStripMenuItem_Click(null, null);
10708 TimerTimeline.Enabled = true;
10711 private bool IsInitialRead()
10713 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10716 private void doGetFollowersMenu()
10718 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, "");
10719 DispSelectedPost(true);
10722 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10724 doGetFollowersMenu();
10727 private void doReTweetUnofficial()
10730 if (this.ExistCurrentPost)
10732 if (_curPost.IsDm ||
10733 !StatusText.Enabled) return;
10735 if (_curPost.IsProtect)
10737 MessageBox.Show("Protected.");
10740 string rtdata = _curPost.Text;
10741 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10743 this._reply_to_id = null;
10744 this._reply_to_name = null;
10746 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10748 StatusText.SelectionStart = 0;
10749 StatusText.Focus();
10753 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10755 doReTweetUnofficial();
10758 private void doReTweetOfficial(bool isConfirm)
10761 if (this.ExistCurrentPost)
10763 if (_curPost.IsProtect)
10765 MessageBox.Show("Protected.");
10766 _DoFavRetweetFlags = false;
10769 if (_curList.SelectedIndices.Count > 15)
10771 MessageBox.Show(Properties.Resources.RetweetLimitText);
10772 _DoFavRetweetFlags = false;
10775 else if (_curList.SelectedIndices.Count > 1)
10777 string QuestionText = Properties.Resources.RetweetQuestion2;
10778 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10779 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10781 case DialogResult.Cancel:
10782 case DialogResult.No:
10783 _DoFavRetweetFlags = false;
10789 if (_curPost.IsDm || _curPost.IsMe)
10791 _DoFavRetweetFlags = false;
10794 if (!this._cfgCommon.RetweetNoConfirm)
10796 string Questiontext = Properties.Resources.RetweetQuestion1;
10797 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10798 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10800 _DoFavRetweetFlags = false;
10805 GetWorkerArg args = new GetWorkerArg();
10806 args.ids = new List<long>();
10807 args.sIds = new List<long>();
10808 args.tName = _curTab.Text;
10809 args.type = MyCommon.WORKERTYPE.Retweet;
10810 foreach (int idx in _curList.SelectedIndices)
10812 PostClass post = GetCurTabPost(idx);
10813 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10819 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10821 doReTweetOfficial(true);
10824 private void FavoritesRetweetOriginal()
10826 if (!this.ExistCurrentPost) return;
10827 _DoFavRetweetFlags = true;
10828 doReTweetOfficial(true);
10829 if (_DoFavRetweetFlags)
10831 _DoFavRetweetFlags = false;
10832 FavoriteChange(true, false);
10836 private void FavoritesRetweetUnofficial()
10838 if (this.ExistCurrentPost && !_curPost.IsDm)
10840 _DoFavRetweetFlags = true;
10841 FavoriteChange(true);
10842 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10844 _DoFavRetweetFlags = false;
10845 doReTweetUnofficial();
10851 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10853 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10854 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10855 /// <returns>復元されたツイート本文</returns>
10856 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10858 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10861 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10863 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10865 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10869 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10871 statusHtml = statusHtml.Replace("<br>", " ");
10873 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10874 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10875 statusHtml = statusHtml.Replace(" ", " ");
10877 return WebUtility.HtmlDecode(statusHtml);
10880 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10882 if (_curPost != null)
10883 DispSelectedPost(true);
10886 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10888 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10889 DebugModeToolStripMenuItem.Visible = true;
10891 DebugModeToolStripMenuItem.Visible = false;
10894 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10896 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10899 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10901 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10904 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10906 if (TraceOutToolStripMenuItem.Checked)
10907 MyCommon.TraceFlag = true;
10909 MyCommon.TraceFlag = false;
10912 private void TweenMain_Deactivate(object sender, EventArgs e)
10914 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10915 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10918 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10920 if (string.IsNullOrEmpty(_rclickTabName)) return;
10921 TabRename(ref _rclickTabName);
10924 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10926 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10929 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10931 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10935 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
10937 e.Result = tw.GetInfoApi();
10940 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10942 StringBuilder tmp = new StringBuilder();
10944 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
10948 var result = (TwitterApiStatus)dlg.Result;
10950 if (result == null)
10952 var accessLevel = result.AccessLevel;
10953 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
10954 var mediaLimit = result.MediaUploadLimit;
10956 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
10957 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
10958 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
10959 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
10962 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
10963 SetStatusLabelUrl();
10966 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
10967 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
10968 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
10972 tmp.Append(Properties.Resources.ApiInfo5);
10976 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10979 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
10982 if (_curPost != null) id = _curPost.ScreenName;
10986 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
10988 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
10989 e.Result = arg.tw.PostFollowCommand(arg.id);
10992 private void FollowCommand(string id)
10994 using (InputTabName inputName = new InputTabName())
10996 inputName.FormTitle = "Follow";
10997 inputName.FormDescription = Properties.Resources.FRMessage1;
10998 inputName.TabName = id;
10999 if (inputName.ShowDialog() == DialogResult.OK &&
11000 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11002 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11004 arg.id = inputName.TabName.Trim();
11005 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11006 FollowCommand_DoWork,
11010 _info.ShowDialog();
11011 string ret = (string)_info.Result;
11012 if (!string.IsNullOrEmpty(ret))
11013 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11015 MessageBox.Show(Properties.Resources.FRMessage3);
11021 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11024 if (_curPost != null) id = _curPost.ScreenName;
11025 RemoveCommand(id, false);
11028 private class FollowRemoveCommandArgs
11034 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11036 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11037 e.Result = arg.tw.PostRemoveCommand(arg.id);
11040 private void RemoveCommand(string id, bool skipInput)
11042 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11047 using (InputTabName inputName = new InputTabName())
11049 inputName.FormTitle = "Unfollow";
11050 inputName.FormDescription = Properties.Resources.FRMessage1;
11051 inputName.TabName = id;
11052 if (inputName.ShowDialog() == DialogResult.OK &&
11053 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11056 arg.id = inputName.TabName.Trim();
11065 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11066 RemoveCommand_DoWork,
11070 _info.ShowDialog();
11071 string ret = (string)_info.Result;
11072 if (!string.IsNullOrEmpty(ret))
11073 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11075 MessageBox.Show(Properties.Resources.FRMessage3);
11079 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11082 if (_curPost != null)
11083 id = _curPost.ScreenName;
11085 ShowFriendship(id);
11088 private class ShowFriendshipArgs
11091 public class FriendshipInfo
11093 public string id = "";
11094 public bool isFollowing = false;
11095 public bool isFollowed = false;
11096 public FriendshipInfo(string id)
11101 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11104 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11106 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11107 string result = "";
11108 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11110 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11111 if (!string.IsNullOrEmpty(rt))
11113 if (string.IsNullOrEmpty(result)) result = rt;
11119 private void ShowFriendship(string id)
11121 ShowFriendshipArgs args = new ShowFriendshipArgs();
11123 using (InputTabName inputName = new InputTabName())
11125 inputName.FormTitle = "Show Friendships";
11126 inputName.FormDescription = Properties.Resources.FRMessage1;
11127 inputName.TabName = id;
11128 if (inputName.ShowDialog() == DialogResult.OK &&
11129 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11132 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11133 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11134 ShowFriendship_DoWork,
11138 _info.ShowDialog();
11139 ret = (string)_info.Result;
11141 string result = "";
11142 if (string.IsNullOrEmpty(ret))
11144 if (args.ids[0].isFollowing)
11146 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11150 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11152 if (args.ids[0].isFollowed)
11154 result += Properties.Resources.GetFriendshipInfo3;
11158 result += Properties.Resources.GetFriendshipInfo4;
11160 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11166 MessageBox.Show(result);
11171 private void ShowFriendship(string[] ids)
11173 foreach (string id in ids)
11176 ShowFriendshipArgs args = new ShowFriendshipArgs();
11178 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11179 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11180 ShowFriendship_DoWork,
11184 _info.ShowDialog();
11185 ret = (string)_info.Result;
11187 string result = "";
11188 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11190 if (string.IsNullOrEmpty(ret))
11193 if (fInfo.isFollowing)
11195 ff += Properties.Resources.GetFriendshipInfo1;
11199 ff += Properties.Resources.GetFriendshipInfo2;
11202 ff += System.Environment.NewLine + " ";
11203 if (fInfo.isFollowed)
11205 ff += Properties.Resources.GetFriendshipInfo3;
11209 ff += Properties.Resources.GetFriendshipInfo4;
11211 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11212 if (fInfo.isFollowing)
11214 if (MessageBox.Show(
11215 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11216 MessageBoxButtons.YesNo,
11217 MessageBoxIcon.Question,
11218 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11220 RemoveCommand(fInfo.id, true);
11225 MessageBox.Show(result);
11230 MessageBox.Show(ret);
11235 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11237 doShowUserStatus(tw.Username, false);
11238 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11240 // doShowUserStatus(tw.Username, false);
11244 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11249 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11250 // URLから切り出した文字列を渡す
11252 public bool IsTwitterId(string name)
11254 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11255 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11257 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11260 private string GetUserId()
11262 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11263 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11264 return m.Result("${ScreenName}");
11269 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11271 string name = GetUserId();
11272 if (name != null) FollowCommand(name);
11275 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11277 string name = GetUserId();
11278 if (name != null) RemoveCommand(name, false);
11281 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11283 string name = GetUserId();
11284 if (name != null) ShowFriendship(name);
11287 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11289 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11290 List<string> ids = new List<string>();
11291 foreach (Match mu in ma)
11293 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11295 ids.Add(mu.Result("${ScreenName}"));
11298 ShowFriendship(ids.ToArray());
11301 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11303 string name = GetUserId();
11304 if (name != null) ShowUserStatus(name);
11307 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11309 string name = GetUserId();
11310 if (name != null) AddNewTabForUserTimeline(name);
11313 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11315 string name = GetUserId();
11316 if (name != null) AddNewTabForSearch("@" + name);
11319 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11321 _modifySettingCommon = true;
11324 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11326 _modifySettingCommon = true;
11329 private void doQuote()
11333 if (this.ExistCurrentPost)
11335 if (_curPost.IsDm ||
11336 !StatusText.Enabled) return;
11338 if (_curPost.IsProtect)
11340 MessageBox.Show("Protected.");
11343 string rtdata = _curPost.Text;
11344 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11346 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11347 if (_curPost.RetweetedId == null)
11349 _reply_to_id = _curPost.StatusId;
11353 _reply_to_id = _curPost.RetweetedId.Value;
11355 _reply_to_name = _curPost.ScreenName;
11357 StatusText.SelectionStart = 0;
11358 StatusText.Focus();
11362 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11367 private void SearchButton_Click(object sender, EventArgs e)
11370 Control pnl = ((Control)sender).Parent;
11371 if (pnl == null) return;
11372 string tbName = pnl.Parent.Text;
11373 TabClass tb = _statuses.Tabs[tbName];
11374 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11375 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11376 cmb.Text = cmb.Text.Trim();
11377 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11378 bool Quote = false;
11379 StringBuilder buf = new StringBuilder();
11380 char[] c = cmb.Text.ToCharArray();
11381 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11383 if (cnt > cmb.Text.Length - 4)
11385 buf.Append(cmb.Text.Substring(cnt));
11394 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11396 buf.Append(" OR ");
11401 buf.Append(c[cnt]);
11403 cmb.Text = buf.ToString();
11405 tb.SearchWords = cmb.Text;
11406 tb.SearchLang = cmbLang.Text;
11407 if (string.IsNullOrEmpty(cmb.Text))
11409 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11413 if (tb.IsQueryChanged())
11415 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11416 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11417 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11418 cmb.Text = tb.SearchWords;
11420 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11421 this.PurgeListViewItemCache();
11422 lst.VirtualListSize = 0;
11423 _statuses.ClearTabIds(tbName);
11424 SaveConfigsTabs(); //検索条件の保存
11427 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, tbName);
11428 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11431 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11437 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11439 if (_statuses.RemovedTab.Count == 0)
11441 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11446 TabClass tb = _statuses.RemovedTab.Pop();
11447 if (tb.TabType == MyCommon.TabUsageType.Related)
11449 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11450 if (relatedTab != null)
11452 // 関連発言なら既存のタブを置き換える
11453 tb.TabName = relatedTab.TabName;
11454 this.ClearTab(tb.TabName, false);
11455 _statuses.Tabs[tb.TabName] = tb;
11456 for (int i = 0; i < ListTab.TabPages.Count; i++)
11458 if (tb.TabName == ListTab.TabPages[i].Text)
11460 ListTab.SelectedIndex = i;
11461 ListTabSelect(ListTab.TabPages[i]);
11468 const string TabName = "Related Tweets";
11469 string renamed = TabName;
11470 for (int i = 2; i <= 100; i++)
11472 if (!_statuses.ContainsTab(renamed)) break;
11473 renamed = TabName + i.ToString();
11475 tb.TabName = renamed;
11476 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11477 _statuses.Tabs.Add(renamed, tb); // 後に
11478 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11479 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11484 string renamed = tb.TabName;
11485 for (int i = 1; i < int.MaxValue; i++)
11487 if (!_statuses.ContainsTab(renamed)) break;
11488 renamed = tb.TabName + "(" + i.ToString() + ")";
11490 tb.TabName = renamed;
11491 _statuses.Tabs.Add(renamed, tb); // 先に
11492 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11493 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11494 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11500 private void doMoveToRTHome()
11502 if (_curList.SelectedIndices.Count > 0)
11504 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11505 if (post.RetweetedId != null)
11507 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11512 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11517 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11519 string name = GetUserId();
11525 if (_curList.SelectedIndices.Count == 0) return;
11528 if (!SelectTab(out tabName)) return;
11532 MoveOrCopy(ref mv, ref mk);
11534 PostFilterRule fc = new PostFilterRule();
11535 fc.FilterName = name;
11536 fc.UseNameField = true;
11537 fc.MoveMatches = mv;
11538 fc.MarkMatches = mk;
11539 fc.UseRegex = false;
11540 fc.FilterByUrl = false;
11541 _statuses.Tabs[tabName].AddFilter(fc);
11543 this.ApplyPostFilters();
11548 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11552 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11554 if (menuItem.Owner == this.ContextMenuPostBrowser)
11556 user = GetUserId();
11557 if (user == null) return;
11559 else if (this._curPost != null)
11561 user = this._curPost.ScreenName;
11568 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11570 string res = this.tw.GetListsApi();
11572 if (!string.IsNullOrEmpty(res))
11574 MessageBox.Show("Failed to get lists. (" + res + ")");
11579 using (MyLists listSelectForm = new MyLists(user, this.tw))
11581 listSelectForm.ShowDialog(this);
11585 private void SearchControls_Enter(object sender, EventArgs e)
11587 Control pnl = (Control)sender;
11588 foreach (Control ctl in pnl.Controls)
11590 ctl.TabStop = true;
11594 private void SearchControls_Leave(object sender, EventArgs e)
11596 Control pnl = (Control)sender;
11597 foreach (Control ctl in pnl.Controls)
11599 ctl.TabStop = false;
11603 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11605 if (ListTab.SelectedTab != null)
11607 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11608 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11612 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11614 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11617 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
11618 HashStripSplitButton.Text = HashMgr.UseHash;
11619 HashToggleMenuItem.Checked = true;
11620 HashToggleToolStripMenuItem.Checked = true;
11622 _modifySettingCommon = true;
11626 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11628 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11631 private void HashManageMenuItem_Click(object sender, EventArgs e)
11633 DialogResult rslt = DialogResult.Cancel;
11636 rslt = HashMgr.ShowDialog();
11642 this.TopMost = this._cfgCommon.AlwaysTop;
11643 if (rslt == DialogResult.Cancel) return;
11644 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11646 HashStripSplitButton.Text = HashMgr.UseHash;
11647 HashToggleMenuItem.Checked = true;
11648 HashToggleToolStripMenuItem.Checked = true;
11652 HashStripSplitButton.Text = "#[-]";
11653 HashToggleMenuItem.Checked = false;
11654 HashToggleToolStripMenuItem.Checked = false;
11656 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11658 // int sidx = StatusText.SelectionStart;
11659 // string hash = HashMgr.UseHash + " ";
11662 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11663 // hash = " " + hash;
11665 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11666 // sidx += hash.Length;
11667 // StatusText.SelectionStart = sidx;
11668 // StatusText.Focus();
11670 _modifySettingCommon = true;
11671 this.StatusText_TextChanged(null, null);
11674 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11676 HashMgr.ToggleHash();
11677 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11679 HashStripSplitButton.Text = HashMgr.UseHash;
11680 HashToggleMenuItem.Checked = true;
11681 HashToggleToolStripMenuItem.Checked = true;
11685 HashStripSplitButton.Text = "#[-]";
11686 HashToggleMenuItem.Checked = false;
11687 HashToggleToolStripMenuItem.Checked = false;
11689 _modifySettingCommon = true;
11690 this.StatusText_TextChanged(null, null);
11693 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11695 HashToggleMenuItem_Click(null, null);
11698 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11700 if (ListTab.SelectedTab == null) return;
11701 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11702 if (!this.ExistCurrentPost)
11704 this.ReplyOpMenuItem.Enabled = false;
11705 this.ReplyAllOpMenuItem.Enabled = false;
11706 this.DmOpMenuItem.Enabled = false;
11707 this.ShowProfMenuItem.Enabled = false;
11708 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11709 this.ListManageMenuItem.Enabled = false;
11710 this.OpenFavOpMenuItem.Enabled = false;
11711 this.CreateTabRuleOpMenuItem.Enabled = false;
11712 this.CreateIdRuleOpMenuItem.Enabled = false;
11713 this.ReadOpMenuItem.Enabled = false;
11714 this.UnreadOpMenuItem.Enabled = false;
11718 this.ReplyOpMenuItem.Enabled = true;
11719 this.ReplyAllOpMenuItem.Enabled = true;
11720 this.DmOpMenuItem.Enabled = true;
11721 this.ShowProfMenuItem.Enabled = true;
11722 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11723 this.ListManageMenuItem.Enabled = true;
11724 this.OpenFavOpMenuItem.Enabled = true;
11725 this.CreateTabRuleOpMenuItem.Enabled = true;
11726 this.CreateIdRuleOpMenuItem.Enabled = true;
11727 this.ReadOpMenuItem.Enabled = true;
11728 this.UnreadOpMenuItem.Enabled = true;
11731 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11733 this.FavOpMenuItem.Enabled = false;
11734 this.UnFavOpMenuItem.Enabled = false;
11735 this.OpenStatusOpMenuItem.Enabled = false;
11736 this.OpenFavotterOpMenuItem.Enabled = false;
11737 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11738 this.RtOpMenuItem.Enabled = false;
11739 this.RtUnOpMenuItem.Enabled = false;
11740 this.QtOpMenuItem.Enabled = false;
11741 this.FavoriteRetweetMenuItem.Enabled = false;
11742 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11743 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11747 this.FavOpMenuItem.Enabled = true;
11748 this.UnFavOpMenuItem.Enabled = true;
11749 this.OpenStatusOpMenuItem.Enabled = true;
11750 this.OpenFavotterOpMenuItem.Enabled = true;
11751 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11755 this.RtOpMenuItem.Enabled = false;
11756 this.FavoriteRetweetMenuItem.Enabled = false;
11757 this.DelOpMenuItem.Enabled = true;
11761 this.DelOpMenuItem.Enabled = false;
11762 if (_curPost.IsProtect)
11764 this.RtOpMenuItem.Enabled = false;
11765 this.RtUnOpMenuItem.Enabled = false;
11766 this.QtOpMenuItem.Enabled = false;
11767 this.FavoriteRetweetMenuItem.Enabled = false;
11768 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11772 this.RtOpMenuItem.Enabled = true;
11773 this.RtUnOpMenuItem.Enabled = true;
11774 this.QtOpMenuItem.Enabled = true;
11775 this.FavoriteRetweetMenuItem.Enabled = true;
11776 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11781 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11783 this.RefreshPrevOpMenuItem.Enabled = true;
11787 this.RefreshPrevOpMenuItem.Enabled = false;
11789 if (!this.ExistCurrentPost
11790 || _curPost.InReplyToStatusId == null)
11792 OpenRepSourceOpMenuItem.Enabled = false;
11796 OpenRepSourceOpMenuItem.Enabled = true;
11798 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11800 OpenRterHomeMenuItem.Enabled = false;
11804 OpenRterHomeMenuItem.Enabled = true;
11808 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11810 ContextMenuTabProperty_Opening(sender, null);
11813 public Twitter TwitterInstance
11818 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11820 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
11822 _mySpDis3 = SplitContainer3.SplitterDistance;
11823 _modifySettingLocal = true;
11827 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11829 if (_statuses.RemovedTab.Count == 0)
11831 UndoRemoveTabMenuItem.Enabled = false;
11835 UndoRemoveTabMenuItem.Enabled = true;
11837 if (ListTab.SelectedTab != null)
11839 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11840 PublicSearchQueryMenuItem.Enabled = true;
11842 PublicSearchQueryMenuItem.Enabled = false;
11846 PublicSearchQueryMenuItem.Enabled = false;
11848 if (!this.ExistCurrentPost)
11850 this.CopySTOTMenuItem.Enabled = false;
11851 this.CopyURLMenuItem.Enabled = false;
11852 this.CopyUserIdStripMenuItem.Enabled = false;
11856 this.CopySTOTMenuItem.Enabled = true;
11857 this.CopyURLMenuItem.Enabled = true;
11858 this.CopyUserIdStripMenuItem.Enabled = true;
11859 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11860 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11864 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11866 SetNotifyIconText();
11869 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11872 if (_curPost != null)
11874 id = _curPost.ScreenName;
11876 ShowUserStatus(id);
11879 private class GetUserInfoArgs
11883 public TwitterUser user;
11886 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
11888 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
11889 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
11892 private void doShowUserStatus(string id, bool ShowInputDialog)
11894 TwitterUser user = null;
11895 GetUserInfoArgs args = new GetUserInfoArgs();
11896 if (ShowInputDialog)
11898 using (InputTabName inputName = new InputTabName())
11900 inputName.FormTitle = "Show UserStatus";
11901 inputName.FormDescription = Properties.Resources.FRMessage1;
11902 inputName.TabName = id;
11903 if (inputName.ShowDialog() == DialogResult.OK &&
11904 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11906 id = inputName.TabName.Trim();
11910 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
11911 GetUserInfo_DoWork,
11915 _info.ShowDialog();
11916 string ret = (string)_info.Result;
11917 if (string.IsNullOrEmpty(ret))
11918 doShowUserStatus(args.user);
11920 MessageBox.Show(ret);
11930 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
11931 GetUserInfo_DoWork,
11935 _info.ShowDialog();
11936 string ret = (string)_info.Result;
11937 if (string.IsNullOrEmpty(ret))
11939 doShowUserStatus(args.user);
11943 MessageBox.Show(ret);
11949 private async void doShowUserStatus(TwitterUser user)
11951 using (var userDialog = new UserInfoDialog(this, this.tw))
11953 var showUserTask = userDialog.ShowUserAsync(user);
11954 userDialog.ShowDialog(this);
11957 this.BringToFront();
11959 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11960 await showUserTask;
11964 private void ShowUserStatus(string id, bool ShowInputDialog)
11966 doShowUserStatus(id, ShowInputDialog);
11969 private void ShowUserStatus(string id)
11971 doShowUserStatus(id, true);
11974 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
11976 if (NameLabel.Tag != null)
11978 string id = (string)NameLabel.Tag;
11979 if (id != tw.Username)
11986 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
11988 if (NameLabel.Tag != null)
11990 string id = (string)NameLabel.Tag;
11991 if (id != tw.Username)
11993 RemoveCommand(id, false);
11998 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12000 if (NameLabel.Tag != null)
12002 string id = (string)NameLabel.Tag;
12003 if (id != tw.Username)
12005 ShowFriendship(id);
12010 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12012 if (NameLabel.Tag != null)
12014 string id = (string)NameLabel.Tag;
12015 ShowUserStatus(id, false);
12019 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12021 if (NameLabel.Tag != null)
12023 string id = (string)NameLabel.Tag;
12024 AddNewTabForUserTimeline(id);
12028 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12030 if (NameLabel.Tag != null)
12032 string id = (string)NameLabel.Tag;
12033 AddNewTabForSearch("@" + id);
12037 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12039 if (_curPost != null)
12041 ShowUserStatus(_curPost.ScreenName, false);
12045 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12050 if (_curPost.RetweetedId != null)
12052 statusid = _curPost.RetweetedId.Value;
12056 statusid = _curPost.StatusId;
12058 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12060 e.Result = counter;
12063 private void RtCountMenuItem_Click(object sender, EventArgs e)
12065 if (this.ExistCurrentPost)
12067 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12068 GetRetweet_DoWork))
12070 int retweet_count = 0;
12073 _info.ShowDialog();
12074 retweet_count = (int)_info.Result;
12075 if (retweet_count < 0)
12077 MessageBox.Show(Properties.Resources.RtCountText2);
12081 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12087 private HookGlobalHotkey _hookGlobalHotkey;
12090 _hookGlobalHotkey = new HookGlobalHotkey(this);
12092 // この呼び出しは、Windows フォーム デザイナで必要です。
12093 InitializeComponent();
12095 // InitializeComponent() 呼び出しの後で初期化を追加します。
12097 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12098 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12099 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12100 this.gh.NotifyClicked += GrowlHelper_Callback;
12102 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12103 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12105 this._apiGauge = new ToolStripAPIGauge();
12106 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12107 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12109 this.ImageSelector.Visible = false;
12110 this.ImageSelector.Enabled = false;
12111 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12113 this.ReplaceAppName();
12116 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12118 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12121 this.Visible = false;
12123 else if (Form.ActiveForm == null)
12125 this.Visible = true;
12126 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12128 this.BringToFront();
12129 this.StatusText.Focus();
12133 private void UserPicture_MouseEnter(object sender, EventArgs e)
12135 this.UserPicture.Cursor = Cursors.Hand;
12138 private void UserPicture_MouseLeave(object sender, EventArgs e)
12140 this.UserPicture.Cursor = Cursors.Default;
12143 private void UserPicture_DoubleClick(object sender, EventArgs e)
12145 if (NameLabel.Tag != null)
12147 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12151 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12153 this.MultiLineMenuItem.PerformClick();
12156 public PostClass CurPost
12158 get { return _curPost; }
12162 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12164 if (ImageSelector.Visible)
12165 ImageSelector.EndSelection();
12167 ImageSelector.BeginSelection();
12170 private void SelectMedia_DragEnter(DragEventArgs e)
12172 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12174 e.Effect = DragDropEffects.Copy;
12177 e.Effect = DragDropEffects.None;
12180 private void SelectMedia_DragOver(DragEventArgs e)
12185 private void SelectMedia_DragDrop(DragEventArgs e)
12188 this.BringToFront();
12189 ImageSelector.BeginSelection(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0]);
12190 StatusText.Focus();
12193 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12195 TimelinePanel.Visible = false;
12196 TimelinePanel.Enabled = false;
12199 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12201 TimelinePanel.Visible = true;
12202 TimelinePanel.Enabled = true;
12203 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12206 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12208 this.AllowDrop = false;
12211 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12213 this.AllowDrop = true;
12216 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12218 if (ImageSelector.Visible)
12220 _modifySettingCommon = true;
12221 SaveConfigsAll(true);
12223 if (ImageSelector.ServiceName.Equals("Twitter"))
12224 this.StatusText_TextChanged(null, null);
12228 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12230 this.StatusText_TextChanged(null, null);
12234 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12236 using (ListManage form = new ListManage(tw))
12238 form.ShowDialog(this);
12242 public bool ModifySettingCommon
12244 set { _modifySettingCommon = value; }
12247 public bool ModifySettingLocal
12249 set { _modifySettingLocal = value; }
12252 public bool ModifySettingAtId
12254 set { _modifySettingAtId = value; }
12257 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12259 string link = (string)SourceLinkLabel.Tag;
12260 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12262 OpenUriAsync(link);
12266 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12268 string link = (string)SourceLinkLabel.Tag;
12269 if (!string.IsNullOrEmpty(link))
12271 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12275 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12277 SetStatusLabelUrl();
12280 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12282 if (this.ExistCurrentPost && !_curPost.IsDm)
12283 RtCountMenuItem.Enabled = true;
12285 RtCountMenuItem.Enabled = false;
12287 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12288 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12290 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12293 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12298 private void CopyUserId()
12300 if (_curPost == null) return;
12301 string clstr = _curPost.ScreenName;
12304 Clipboard.SetDataObject(clstr, false, 5, 100);
12306 catch (Exception ex)
12308 MessageBox.Show(ex.Message);
12312 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12314 if (this.ExistCurrentPost && !_curPost.IsDm)
12318 this.OpenRelatedTab(this._curPost);
12320 catch (TabException ex)
12322 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12328 /// 指定されたツイートに対する関連発言タブを開きます
12330 /// <param name="post">表示する対象となるツイート</param>
12331 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12332 private void OpenRelatedTab(PostClass post)
12334 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12337 if (tabRelated == null)
12339 tabName = this._statuses.MakeTabName("Related Tweets");
12341 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12342 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12344 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12345 tabRelated.UnreadManage = false;
12346 tabRelated.Notify = false;
12350 tabName = tabRelated.TabName;
12353 tabRelated.RelationTargetPost = post;
12354 this.ClearTab(tabName, false);
12356 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12358 var tabPage = this.ListTab.TabPages[i];
12359 if (tabName == tabPage.Text)
12361 this.ListTab.SelectedIndex = i;
12362 this.ListTabSelect(tabPage);
12367 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, tabName);
12370 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12372 StringBuilder buf = new StringBuilder();
12373 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12374 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12375 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12376 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12377 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12380 private void tw_UserIdChanged()
12382 this._modifySettingCommon = true;
12385 #region "Userstream"
12386 private bool _isActiveUserstream = false;
12388 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12392 if (InvokeRequired && !IsDisposed)
12394 Invoke((Action) (() =>
12396 _statuses.RemovePostReserve(e.StatusId);
12397 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12399 this.PurgeListViewItemCache();
12400 ((DetailsListView)_curTab.Tag).Update();
12401 if (_curPost != null && _curPost.StatusId == e.StatusId) DispSelectedPost(true);
12407 catch (ObjectDisposedException)
12411 catch (InvalidOperationException)
12417 private void tw_NewPostFromStream(object sender, EventArgs e)
12419 if (this._cfgCommon.ReadOldPosts)
12421 _statuses.SetRead(); //新着時未読クリア
12424 int rsltAddCount = _statuses.DistributePosts();
12427 DateTime tm = DateTime.Now;
12428 if (_tlTimestamps.ContainsKey(tm))
12430 _tlTimestamps[tm] += rsltAddCount;
12434 _tlTimestamps.Add(tm, rsltAddCount);
12436 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12437 List<DateTime> keys = new List<DateTime>();
12439 foreach (DateTime key in _tlTimestamps.Keys)
12441 if (key.CompareTo(oneHour) < 0)
12444 _tlCount += _tlTimestamps[key];
12446 foreach (DateTime key in keys)
12448 _tlTimestamps.Remove(key);
12452 //Static DateTime before = Now;
12453 //if (before.Subtract(Now).Seconds > -5) return;
12457 if (this._cfgCommon.UserstreamPeriod > 0) return;
12461 if (InvokeRequired && !IsDisposed)
12463 Invoke(new Action<bool>(RefreshTimeline), true);
12467 catch (ObjectDisposedException)
12471 catch (InvalidOperationException)
12477 private void tw_UserStreamStarted(object sender, EventArgs e)
12479 this._isActiveUserstream = true;
12482 if (InvokeRequired && !IsDisposed)
12484 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12488 catch (ObjectDisposedException)
12492 catch (InvalidOperationException)
12497 MenuItemUserStream.Text = "&UserStream ▶";
12498 MenuItemUserStream.Enabled = true;
12499 StopToolStripMenuItem.Text = "&Stop";
12500 StopToolStripMenuItem.Enabled = true;
12502 StatusLabel.Text = "UserStream Started.";
12505 private void tw_UserStreamStopped(object sender, EventArgs e)
12507 this._isActiveUserstream = false;
12510 if (InvokeRequired && !IsDisposed)
12512 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12516 catch (ObjectDisposedException)
12520 catch (InvalidOperationException)
12525 MenuItemUserStream.Text = "&UserStream ■";
12526 MenuItemUserStream.Enabled = true;
12527 StopToolStripMenuItem.Text = "&Start";
12528 StopToolStripMenuItem.Enabled = true;
12530 StatusLabel.Text = "UserStream Stopped.";
12533 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12537 if (InvokeRequired && !IsDisposed)
12539 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12543 catch (ObjectDisposedException)
12547 catch (InvalidOperationException)
12551 var ev = e.EventData;
12552 StatusLabel.Text = "Event: " + ev.Event;
12553 //if (ev.Event == "favorite")
12555 // NotifyFavorite(ev);
12558 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12560 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12562 this.PurgeListViewItemCache();
12563 ((DetailsListView)_curTab.Tag).Update();
12565 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12567 RemovePostFromFavTab(new long[] {ev.Id});
12572 private void NotifyEvent(Twitter.FormattedEvent ev)
12575 if (BalloonRequired(ev))
12577 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12578 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12579 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12580 StringBuilder title = new StringBuilder();
12581 if (this._cfgCommon.DispUsername)
12583 title.Append(tw.Username);
12584 title.Append(" - ");
12590 title.Append(Application.ProductName);
12591 title.Append(" [");
12592 title.Append(ev.Event.ToUpper());
12593 title.Append("] by ");
12594 if (!string.IsNullOrEmpty(ev.Username))
12596 title.Append(ev.Username.ToString());
12600 //title.Append("");
12603 if (!string.IsNullOrEmpty(ev.Target))
12605 //NotifyIcon1.BalloonTipText = ev.Target;
12610 //NotifyIcon1.BalloonTipText = " ";
12613 //NotifyIcon1.ShowBalloonTip(500);
12614 if (this._cfgCommon.IsUseNotifyGrowl)
12616 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
12617 ev.Id.ToString(), title.ToString(), text);
12621 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12622 NotifyIcon1.BalloonTipTitle = title.ToString();
12623 NotifyIcon1.BalloonTipText = text;
12624 NotifyIcon1.ShowBalloonTip(500);
12629 string snd = SettingDialog.EventSoundFile;
12630 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
12632 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
12636 string dir = Application.StartupPath;
12637 if (Directory.Exists(Path.Combine(dir, "Sounds")))
12639 dir = Path.Combine(dir, "Sounds");
12641 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
12653 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
12655 MenuItemUserStream.Enabled = false;
12656 if (StopRefreshAllMenuItem.Checked)
12658 StopRefreshAllMenuItem.Checked = false;
12661 if (this._isActiveUserstream)
12663 tw.StopUserStream();
12667 tw.StartUserStream();
12671 private static string inputTrack = "";
12673 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
12675 if (TrackToolStripMenuItem.Checked)
12677 using (InputTabName inputForm = new InputTabName())
12679 inputForm.TabName = inputTrack;
12680 inputForm.FormTitle = "Input track word";
12681 inputForm.FormDescription = "Track word";
12682 if (inputForm.ShowDialog() != DialogResult.OK)
12684 TrackToolStripMenuItem.Checked = false;
12687 inputTrack = inputForm.TabName.Trim();
12689 if (!inputTrack.Equals(tw.TrackWord))
12691 tw.TrackWord = inputTrack;
12692 this._modifySettingCommon = true;
12693 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
12694 tw.ReconnectUserStream();
12700 tw.ReconnectUserStream();
12702 this._modifySettingCommon = true;
12705 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
12707 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
12708 this._modifySettingCommon = true;
12709 tw.ReconnectUserStream();
12712 private void EventViewerMenuItem_Click(object sender, EventArgs e)
12714 if (evtDialog == null || evtDialog.IsDisposed)
12717 evtDialog = new EventViewerDialog();
12718 evtDialog.Owner = this;
12720 Point pos = evtDialog.Location;
12721 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
12722 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
12723 evtDialog.Location = pos;
12725 evtDialog.EventSource = tw.StoredEvent;
12726 if (!evtDialog.Visible)
12728 evtDialog.Show(this);
12732 evtDialog.Activate();
12734 this.TopMost = this._cfgCommon.AlwaysTop;
12738 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12740 MyCommon._endingFlag = true;
12744 Application.Restart();
12748 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12752 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12754 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12757 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12759 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
12762 private async Task doTranslation(string str)
12764 if (string.IsNullOrEmpty(str))
12767 var bing = new Bing();
12770 var translatedText = await bing.TranslateAsync(str,
12772 langTo: this._cfgCommon.TranslateLanguage);
12774 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
12776 catch (HttpRequestException e)
12778 this.StatusLabel.Text = "Err:" + e.Message;
12782 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
12784 if (!this.ExistCurrentPost)
12787 await this.doTranslation(this._curPost.TextFromApi);
12790 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
12792 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
12793 await this.doTranslation(text);
12796 private bool ExistCurrentPost
12800 if (_curPost == null) return false;
12801 if (_curPost.IsDeleted) return false;
12806 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12808 ShowUserTimeline();
12811 public bool FavEventChangeUnread
12813 get { return SettingDialog.FavEventUnread; }
12816 private string GetUserIdFromCurPostOrInput(string caption)
12819 if (_curPost != null)
12821 id = _curPost.ScreenName;
12823 using (InputTabName inputName = new InputTabName())
12825 inputName.FormTitle = caption;
12826 inputName.FormDescription = Properties.Resources.FRMessage1;
12827 inputName.TabName = id;
12828 if (inputName.ShowDialog() == DialogResult.OK &&
12829 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12831 id = inputName.TabName.Trim();
12841 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12843 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12844 if (!string.IsNullOrEmpty(id))
12846 AddNewTabForUserTimeline(id);
12850 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12852 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12853 if (!string.IsNullOrEmpty(id))
12855 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12859 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12861 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12864 private void TimelineRefreshEnableChange(bool isEnable)
12868 tw.StartUserStream();
12872 tw.StopUserStream();
12874 TimerTimeline.Enabled = isEnable;
12877 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12879 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12882 private void OpenUserAppointUrl()
12884 if (this._cfgCommon.UserAppointUrl != null)
12886 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
12888 if (_curPost != null)
12890 string xUrl = this._cfgCommon.UserAppointUrl;
12891 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12892 if (_curPost.RetweetedId != null)
12894 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
12898 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
12900 OpenUriAsync(xUrl);
12905 OpenUriAsync(this._cfgCommon.UserAppointUrl);
12910 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12912 OpenUserAppointUrl();
12915 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
12917 string selText = SourceLinkLabel.Text;
12920 Clipboard.SetDataObject(selText, false, 5, 100);
12922 catch (Exception ex)
12924 MessageBox.Show(ex.Message);
12928 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
12930 string selText = (string)SourceLinkLabel.Tag;
12933 Clipboard.SetDataObject(selText, false, 5, 100);
12935 catch (Exception ex)
12937 MessageBox.Show(ex.Message);
12941 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
12943 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
12945 SourceCopyMenuItem.Enabled = false;
12946 SourceUrlCopyMenuItem.Enabled = false;
12950 SourceCopyMenuItem.Enabled = true;
12951 SourceUrlCopyMenuItem.Enabled = true;
12955 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12957 if (Form.ActiveForm == null)
12959 this.BeginInvoke((Action) (() =>
12961 this.Visible = true;
12962 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12964 this.BringToFront();
12965 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12967 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12971 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12977 private void ReplaceAppName()
12979 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12980 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12983 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12985 this.SplitContainer3.Panel2Collapsed = false;
12987 // PreviewDistance が起動のたびに広がっていく問題の回避策
12988 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
12989 // None で開いた後に設定するようにする
12990 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
12991 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
12994 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12996 this.OpenThumbnailPicture(e.Thumbnail);
12999 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13001 this.OpenUriAsync(e.ImageUrl);
13004 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13006 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13009 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13011 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13014 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13016 if (e.KeyCode == Keys.Space)
13018 this.JumpUnreadMenuItem_Click(null, null);
13020 e.SuppressKeyPress = true;
13024 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13026 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13027 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13028 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13029 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13030 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13032 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13035 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13037 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13040 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13042 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13045 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13047 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13050 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13052 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13055 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13057 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13060 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13062 if (this._cfgCommon.IconSize == iconSize) return;
13064 var oldIconCol = _iconCol;
13066 this._cfgCommon.IconSize = iconSize;
13067 ApplyListViewIconSize(iconSize);
13069 if (_iconCol != oldIconCol)
13071 foreach (TabPage tp in ListTab.TabPages)
13073 ResetColumns((DetailsListView)tp.Tag);
13077 if (_curList != null) _curList.Refresh();
13079 _modifySettingCommon = true;
13082 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13084 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13085 if (this._cfgCommon.SortOrderLock == state) return;
13087 this._cfgCommon.SortOrderLock = state;
13089 _modifySettingCommon = true;