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;
763 SettingDialog.TwitterApiUrl = _cfgCommon.TwitterUrl;
766 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
767 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
769 SettingDialog.UserAccounts = _cfgCommon.UserAccounts;
771 //新着取得時のリストスクロールをするか。trueならスクロールしない
772 ListLockMenuItem.Checked = _cfgCommon.ListLock;
773 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
775 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
776 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
778 SettingDialog.TinyUrlResolve = _cfgCommon.TinyUrlResolve;
780 SettingDialog.SelectedProxyType = _cfgLocal.ProxyType;
781 SettingDialog.ProxyAddress = _cfgLocal.ProxyAddress;
782 SettingDialog.ProxyPort = _cfgLocal.ProxyPort;
783 SettingDialog.ProxyUser = _cfgLocal.ProxyUser;
784 SettingDialog.ProxyPassword = _cfgLocal.ProxyPassword;
786 SettingDialog.UrlConvertAuto = false;
787 //SettingDialog.UrlConvertAuto = _cfgCommon.UrlConvertAuto;
789 SettingDialog.DefaultTimeOut = _cfgCommon.DefaultTimeOut;
790 SettingDialog.EventNotifyEnabled = _cfgCommon.EventNotifyEnabled;
791 SettingDialog.EventNotifyFlag = _cfgCommon.EventNotifyFlag;
792 SettingDialog.IsMyEventNotifyFlag = _cfgCommon.IsMyEventNotifyFlag;
793 SettingDialog.ForceEventNotify = _cfgCommon.ForceEventNotify;
794 SettingDialog.FavEventUnread = _cfgCommon.FavEventUnread;
795 SettingDialog.TranslateLanguage = _cfgCommon.TranslateLanguage;
796 SettingDialog.EventSoundFile = _cfgCommon.EventSoundFile;
798 //廃止サービスが選択されていた場合bit.lyへ読み替え
799 if (_cfgCommon.AutoShortUrlFirst < 0)
800 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
802 SettingDialog.AutoShortUrlFirst = _cfgCommon.AutoShortUrlFirst;
803 SettingDialog.BitlyUser = _cfgCommon.BilyUser;
804 SettingDialog.BitlyPwd = _cfgCommon.BitlyPwd;
805 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
807 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
808 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
810 //Regex statregex = new Regex("^0*");
811 SettingDialog.RecommendStatusText = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
813 SettingDialog.Nicoms = _cfgCommon.Nicoms;
815 SettingDialog.UserAppointUrl = _cfgCommon.UserAppointUrl;
817 SettingDialog.EnableImgAzyobuziNet = _cfgCommon.EnableImgAzyobuziNet;
818 SettingDialog.ImgAzyobuziNetDisabledInDM = _cfgCommon.ImgAzyobuziNetDisabledInDM;
819 SettingDialog.MapThumbnailProvider = _cfgCommon.MapThumbnailProvider;
820 SettingDialog.MapThumbnailHeight = _cfgCommon.MapThumbnailHeight;
821 SettingDialog.MapThumbnailWidth = _cfgCommon.MapThumbnailWidth;
822 SettingDialog.MapThumbnailZoom = _cfgCommon.MapThumbnailZoom;
823 SettingDialog.IsRemoveSameEvent = _cfgCommon.IsRemoveSameEvent;
826 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
827 HashMgr = new HashtagManage(HashSupl,
828 _cfgCommon.HashTags.ToArray(),
829 _cfgCommon.HashSelected,
830 _cfgCommon.HashIsPermanent,
831 _cfgCommon.HashIsHead,
832 _cfgCommon.HashIsNotAddToAtReply);
833 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
837 Networking.Initialize();
840 this.IconCache = new ImageCache();
842 bool saveRequired = false;
843 bool firstRun = false;
845 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
846 if (string.IsNullOrEmpty(tw.Username))
850 SettingDialog.ShowInTaskbar = true;
852 //設定せずにキャンセルされた場合はプログラム終了
853 if (SettingDialog.ShowDialog(this) == DialogResult.Cancel)
855 Application.Exit(); //強制終了
858 //設定されたが、依然ユーザー名とパスワードが未設定ならプログラム終了
859 if (string.IsNullOrEmpty(tw.Username))
861 Application.Exit(); //強制終了
864 SettingDialog.ShowInTaskbar = false;
868 _fntUnread = this._cfgLocal.FontUnread;
869 _clUnread = this._cfgLocal.ColorUnread;
870 _fntReaded = this._cfgLocal.FontRead;
871 _clReaded = this._cfgLocal.ColorRead;
872 _clFav = this._cfgLocal.ColorFav;
873 _clOWL = this._cfgLocal.ColorOWL;
874 _clRetweet = this._cfgLocal.ColorRetweet;
875 _fntDetail = this._cfgLocal.FontDetail;
876 _clDetail = this._cfgLocal.ColorDetail;
877 _clDetailLink = this._cfgLocal.ColorDetailLink;
878 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
879 _clSelf = this._cfgLocal.ColorSelf;
880 _clAtSelf = this._cfgLocal.ColorAtSelf;
881 _clTarget = this._cfgLocal.ColorTarget;
882 _clAtTarget = this._cfgLocal.ColorAtTarget;
883 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
884 _clAtTo = this._cfgLocal.ColorAtTo;
885 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
886 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
887 _clInputFont = this._cfgLocal.ColorInputFont;
888 _fntInputFont = this._cfgLocal.FontInputFont;
890 //他の設定項目は、随時設定画面で保持している値を読み出して使用
893 _brsBackColorMine = new SolidBrush(_clSelf);
894 _brsBackColorAt = new SolidBrush(_clAtSelf);
895 _brsBackColorYou = new SolidBrush(_clTarget);
896 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
897 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
898 _brsBackColorAtTo = new SolidBrush(_clAtTo);
899 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
900 _brsBackColorNone = new SolidBrush(_clListBackcolor);
902 InitDetailHtmlFormat();
904 if (this._cfgCommon.HotkeyEnabled)
907 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
908 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
909 modKey |= HookGlobalHotkey.ModKeys.Alt;
910 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
911 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
912 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
913 modKey |= HookGlobalHotkey.ModKeys.Shift;
914 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
915 modKey |= HookGlobalHotkey.ModKeys.Win;
917 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
921 Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut);
922 Networking.SetWebProxy(this.SettingDialog.SelectedProxyType,
923 this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort,
924 this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword);
926 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
927 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
928 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
929 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
930 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
931 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
932 tw.TrackWord = _cfgCommon.TrackWord;
933 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
934 tw.AllAtReply = _cfgCommon.AllAtReply;
935 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
938 ImageSelector.Initialize(tw, SettingDialog.TwitterConfiguration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
941 this.ClientSize = _cfgLocal.FormSize;
942 _mySize = _cfgLocal.FormSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
943 _myLoc = _cfgLocal.FormLocation;
945 if (this.WindowState != FormWindowState.Minimized)
947 this.DesktopLocation = _cfgLocal.FormLocation;
948 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
949 bool outOfScreen = true;
950 if (Screen.AllScreens.Length == 1) //ハングするとの報告
952 foreach (Screen scr in Screen.AllScreens)
954 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
962 this.DesktopLocation = new Point(0, 0);
963 _myLoc = this.DesktopLocation;
967 this.TopMost = this._cfgCommon.AlwaysTop;
968 _mySpDis = _cfgLocal.SplitterDistance;
969 _mySpDis2 = _cfgLocal.StatusTextHeight;
970 _mySpDis3 = _cfgLocal.PreviewDistance;
973 _mySpDis3 = _mySize.Width - 150;
974 if (_mySpDis3 < 1) _mySpDis3 = 50;
975 _cfgLocal.PreviewDistance = _mySpDis3;
977 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
978 //this.Tween_ClientSizeChanged(this, null);
979 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
980 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
982 StatusText.Font = _fntInputFont;
983 StatusText.ForeColor = _clInputFont;
985 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
986 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
988 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
989 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
991 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
992 if (this._cfgCommon.UnreadManage == false)
994 ReadedStripMenuItem.Enabled = false;
995 UnreadStripMenuItem.Enabled = false;
998 if (this._cfgCommon.IsUseNotifyGrowl)
1002 TimerTimeline.AutoReset = true;
1003 TimerTimeline.SynchronizingObject = this;
1005 TimerTimeline.Interval = 1000;
1006 TimerTimeline.Enabled = true;
1009 TimerRefreshIcon.Interval = 200;
1010 TimerRefreshIcon.Enabled = true;
1013 StatusLabel.Text = "";
1014 StatusLabel.AutoToolTip = false;
1015 StatusLabel.ToolTipText = "";
1017 lblLen.Text = GetRestStatusCount(true, false).ToString();
1019 ////////////////////////////////////////////////////////////////////////////////
1020 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
1021 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
1022 switch (_cfgCommon.SortColumn)
1024 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1028 mode = IdComparerClass.ComparerMode.Id; //Idソートに読み替え
1031 mode = IdComparerClass.ComparerMode.Nickname;
1034 mode = IdComparerClass.ComparerMode.Data;
1037 mode = IdComparerClass.ComparerMode.Id;
1040 mode = IdComparerClass.ComparerMode.Name;
1043 mode = IdComparerClass.ComparerMode.Source;
1046 _statuses.SortMode = mode;
1047 ////////////////////////////////////////////////////////////////////////////////
1049 ApplyListViewIconSize(this._cfgCommon.IconSize);
1051 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1052 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1053 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1054 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1055 SourceLinkLabel.Text = ""; //Source部分初期化
1057 //<<<<<<<<タブ関連>>>>>>>
1058 //デフォルトタブの存在チェック、ない場合には追加
1059 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1062 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1064 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1068 tab.TabType = MyCommon.TabUsageType.Home;
1071 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1074 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1076 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1080 tab.TabType = MyCommon.TabUsageType.Mentions;
1083 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1086 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1088 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1092 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1095 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1098 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1100 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1104 tab.TabType = MyCommon.TabUsageType.Favorites;
1107 foreach (var tab in _statuses.Tabs.Values)
1109 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1111 tab.TabType = MyCommon.TabUsageType.UserDefined;
1113 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1114 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1117 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1118 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1119 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1120 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1122 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1124 this.Visible = true;
1126 _curTab = ListTab.SelectedTab;
1128 _curList = (DetailsListView)_curTab.Tag;
1129 SetMainWindowTitle();
1130 SetNotifyIconText();
1132 if (this._cfgCommon.TabIconDisp)
1134 ListTab.DrawMode = TabDrawMode.Normal;
1138 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1139 ListTab.DrawItem += ListTab_DrawItem;
1140 ListTab.ImageList = null;
1143 _ignoreConfigSave = false;
1144 this.TweenMain_Resize(null, null);
1145 if (saveRequired) SaveConfigsAll(false);
1149 tw.VerifyCredentials();
1150 foreach (UserAccount ua in _cfgCommon.UserAccounts)
1152 if (ua.Username.ToLower() == tw.Username.ToLower())
1154 ua.UserId = tw.UserId;
1159 foreach (UserAccount ua in SettingDialog.UserAccounts)
1161 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1163 ua.UserId = tw.UserId;
1170 // 初回起動時だけ右下のメニューを目立たせる
1171 HashStripSplitButton.ShowDropDown();
1178 private void InitDetailHtmlFormat()
1180 if (this._cfgCommon.IsMonospace)
1182 detailHtmlFormatHeader = detailHtmlFormatMono1;
1183 detailHtmlFormatFooter = detailHtmlFormatMono7;
1187 detailHtmlFormatHeader = detailHtmlFormat1;
1188 detailHtmlFormatFooter = detailHtmlFormat7;
1190 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();
1191 if (this._cfgCommon.IsMonospace)
1193 detailHtmlFormatHeader += detailHtmlFormatMono6;
1197 detailHtmlFormatHeader += detailHtmlFormat6;
1201 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1206 txt = ListTab.TabPages[e.Index].Text;
1213 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1214 if (e.State == DrawItemState.Selected)
1216 e.DrawFocusRectangle();
1221 if (_statuses.Tabs[txt].UnreadCount > 0)
1224 fore = System.Drawing.SystemBrushes.ControlText;
1228 fore = System.Drawing.SystemBrushes.ControlText;
1230 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1233 private void LoadConfig()
1235 _cfgCommon = SettingCommon.Load();
1236 SettingCommon.Instance = this._cfgCommon;
1237 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1239 _cfgCommon.UserAccounts = new List<UserAccount>();
1240 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1242 UserAccount account = new UserAccount();
1243 account.Username = _cfgCommon.UserName;
1244 account.UserId = _cfgCommon.UserId;
1245 account.Token = _cfgCommon.Token;
1246 account.TokenSecret = _cfgCommon.TokenSecret;
1248 _cfgCommon.UserAccounts.Add(account);
1251 _cfgLocal = SettingLocal.Load();
1252 List<TabClass> tabs = SettingTabs.Load().Tabs;
1253 foreach (TabClass tb in tabs)
1257 _statuses.Tabs.Add(tb.TabName, tb);
1261 tb.TabName = _statuses.GetUniqueTabName();
1262 _statuses.Tabs.Add(tb.TabName, tb);
1265 if (_statuses.Tabs.Count == 0)
1267 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1268 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1269 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1270 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1274 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1276 if (!TimerTimeline.Enabled) return;
1280 private IntervalChangedEventArgs ResetTimers = new IntervalChangedEventArgs();
1282 private static int homeCounter = 0;
1283 private static int mentionCounter = 0;
1284 private static int dmCounter = 0;
1285 private static int pubSearchCounter = 0;
1286 private static int userTimelineCounter = 0;
1287 private static int listsCounter = 0;
1288 private static int usCounter = 0;
1289 private static int ResumeWait = 0;
1290 private static int refreshFollowers = 0;
1292 private void TimerTimeline_Elapsed(object sender, EventArgs e)
1294 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1295 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1296 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1297 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1298 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1299 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1300 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1301 Interlocked.Increment(ref refreshFollowers);
1304 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1306 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1307 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1308 ResetTimers.Timeline = false;
1310 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1312 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1313 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply) GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1314 ResetTimers.Reply = false;
1316 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1318 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1319 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage) GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1320 ResetTimers.DirectMessage = false;
1322 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1324 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1325 if (!ResetTimers.PublicSearch) GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1326 ResetTimers.PublicSearch = false;
1328 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1330 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1331 if (!ResetTimers.UserTimeline) GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1332 ResetTimers.UserTimeline = false;
1334 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1336 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1337 if (!ResetTimers.Lists) GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1338 ResetTimers.Lists = false;
1340 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1342 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1343 if (this._isActiveUserstream) RefreshTimeline(true);
1344 ResetTimers.UserStream = false;
1346 if (refreshFollowers > 6 * 3600)
1348 Interlocked.Exchange(ref refreshFollowers, 0);
1349 doGetFollowersMenu();
1350 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
1351 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1355 Interlocked.Increment(ref ResumeWait);
1356 if (ResumeWait > 30)
1359 Interlocked.Exchange(ref ResumeWait, 0);
1360 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
1361 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
1362 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
1363 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, "");
1364 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, "");
1365 GetTimeline(MyCommon.WORKERTYPE.List, 1, "");
1366 doGetFollowersMenu();
1367 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
1372 private void RefreshTimeline(bool isUserStream)
1374 if (isUserStream) this.RefreshTasktrayIcon(true);
1376 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1377 long topId = GetScrollPos(ref smode);
1378 int befCnt = _curList.VirtualListSize;
1381 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
1382 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
1383 SaveSelectedStatus(selId, focusedId);
1386 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1389 PostClass[] notifyPosts = null;
1390 string soundFile = "";
1392 bool isMention = false;
1393 bool isDelete = false;
1394 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1396 if (MyCommon._endingFlag) return;
1401 foreach (TabPage tab in ListTab.TabPages)
1403 DetailsListView lst = (DetailsListView)tab.Tag;
1404 TabClass tabInfo = _statuses.Tabs[tab.Text];
1405 using (ControlTransaction.Update(lst))
1407 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1409 if (lst.Equals(_curList))
1411 this.PurgeListViewItemCache();
1415 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1421 this.SelectListItem(lst,
1422 tabInfo.IndexOf(selId[tab.Text]),
1423 tabInfo.IndexOf(focusedId[tab.Text]));
1426 if (tabInfo.UnreadCount > 0)
1427 if (this._cfgCommon.TabIconDisp)
1428 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1430 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1434 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1443 if (befCnt != _curList.VirtualListSize)
1449 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1453 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1460 if (_curList.VirtualListSize > 0 && _statuses.IndexOf(_curTab.Text, topId) > -1)
1462 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1463 _curList.EnsureVisible(_statuses.IndexOf(_curTab.Text, topId));
1469 catch (Exception ex)
1471 ex.Data["Msg"] = "Ref2";
1477 NotifyNewPosts(notifyPosts,
1480 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1482 SetMainWindowTitle();
1483 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1485 HashSupl.AddRangeItem(tw.GetHashList());
1489 private long GetScrollPos(ref int smode)
1492 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1494 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
1496 if (_statuses.SortOrder == SortOrder.Ascending)
1499 if (ListLockMenuItem.Checked)
1504 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1509 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1511 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1512 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1513 if (_item.Index == _curList.VirtualListSize - 1)
1520 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1528 if (ListLockMenuItem.Checked)
1531 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1536 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1539 _item = _curList.GetItemAt(0, 10); //一番上
1540 if (_item == null) _item = _curList.Items[0];
1541 if (_item.Index == 0)
1547 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1556 if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1567 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, long[]> focusedId)
1569 if (MyCommon._endingFlag) return;
1570 foreach (TabPage tab in ListTab.TabPages)
1572 var lst = (DetailsListView)tab.Tag;
1573 var tabInfo = _statuses.Tabs[tab.Text];
1574 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1576 selId.Add(tab.Text, tabInfo.GetId(lst.SelectedIndices));
1580 selId.Add(tab.Text, new long[1] {-2});
1583 var fIds = new long[2]; // 0 = focus, 1 = selection mark
1584 var item = lst.FocusedItem;
1585 fIds[0] = (item != null) ? tabInfo.GetId(item.Index) : -2;
1586 var mIdx = lst.SelectionMark;
1587 fIds[1] = (mIdx > -1) ? tabInfo.GetId(mIdx) : -2;
1588 focusedId.Add(tab.Text, fIds);
1593 private bool BalloonRequired()
1595 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1596 ev.Eventtype = MyCommon.EVENTTYPE.None;
1598 return BalloonRequired(ev);
1601 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1603 return SettingDialog.EventNotifyEnabled && (type & SettingDialog.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1606 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1608 return (ev.Eventtype & SettingDialog.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1611 private bool BalloonRequired(Twitter.FormattedEvent ev)
1614 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1615 (NewPostPopMenuItem.Checked || (SettingDialog.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1619 this._cfgCommon.LimitBalloon &&
1621 this.WindowState == FormWindowState.Minimized ||
1623 Form.ActiveForm == null
1626 !this._cfgCommon.LimitBalloon
1629 !NativeMethods.IsScreenSaverRunning())
1639 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1641 if (notifyPosts != null &&
1642 notifyPosts.Length > 0 &&
1643 this._cfgCommon.ReadOwnPost &&
1644 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1650 if (BalloonRequired())
1652 if (notifyPosts != null && notifyPosts.Length > 0)
1654 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1655 if (this._cfgCommon.IsUseNotifyGrowl)
1657 StringBuilder sb = new StringBuilder();
1661 foreach (PostClass post in notifyPosts)
1663 if (!(notifyPosts.Length > 3))
1669 if (post.IsReply && !post.IsExcludeReply) reply = true;
1670 if (post.IsDm) dm = true;
1671 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1672 switch (this._cfgCommon.NameBalloon)
1674 case MyCommon.NameBalloonEnum.UserID:
1675 sb.Append(post.ScreenName).Append(" : ");
1677 case MyCommon.NameBalloonEnum.NickName:
1678 sb.Append(post.Nickname).Append(" : ");
1681 sb.Append(post.TextFromApi);
1682 if (notifyPosts.Length > 3)
1684 if (notifyPosts.Last() != post) continue;
1687 StringBuilder title = new StringBuilder();
1688 GrowlHelper.NotifyType nt;
1689 if (this._cfgCommon.DispUsername)
1691 title.Append(tw.Username);
1692 title.Append(" - ");
1700 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1701 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1702 title.Append(Application.ProductName);
1703 title.Append(" [DM] ");
1704 title.Append(Properties.Resources.RefreshDirectMessageText1);
1706 title.Append(addCount);
1707 title.Append(Properties.Resources.RefreshDirectMessageText2);
1708 nt = GrowlHelper.NotifyType.DirectMessage;
1712 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1713 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1714 title.Append(Application.ProductName);
1715 title.Append(" [Reply!] ");
1716 title.Append(Properties.Resources.RefreshTimelineText1);
1718 title.Append(addCount);
1719 title.Append(Properties.Resources.RefreshTimelineText2);
1720 nt = GrowlHelper.NotifyType.Reply;
1724 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1725 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1726 title.Append(Application.ProductName);
1728 title.Append(Properties.Resources.RefreshTimelineText1);
1730 title.Append(addCount);
1731 title.Append(Properties.Resources.RefreshTimelineText2);
1732 nt = GrowlHelper.NotifyType.Notify;
1734 string bText = sb.ToString();
1735 if (string.IsNullOrEmpty(bText)) return;
1737 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1738 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1743 StringBuilder sb = new StringBuilder();
1746 foreach (PostClass post in notifyPosts)
1748 if (post.IsReply && !post.IsExcludeReply) reply = true;
1749 if (post.IsDm) dm = true;
1750 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1751 switch (this._cfgCommon.NameBalloon)
1753 case MyCommon.NameBalloonEnum.UserID:
1754 sb.Append(post.ScreenName).Append(" : ");
1756 case MyCommon.NameBalloonEnum.NickName:
1757 sb.Append(post.Nickname).Append(" : ");
1760 sb.Append(post.TextFromApi);
1763 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1764 StringBuilder title = new StringBuilder();
1766 if (this._cfgCommon.DispUsername)
1768 title.Append(tw.Username);
1769 title.Append(" - ");
1777 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1778 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1779 ntIcon = ToolTipIcon.Warning;
1780 title.Append(Application.ProductName);
1781 title.Append(" [DM] ");
1782 title.Append(Properties.Resources.RefreshDirectMessageText1);
1784 title.Append(addCount);
1785 title.Append(Properties.Resources.RefreshDirectMessageText2);
1789 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1790 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1791 ntIcon = ToolTipIcon.Warning;
1792 title.Append(Application.ProductName);
1793 title.Append(" [Reply!] ");
1794 title.Append(Properties.Resources.RefreshTimelineText1);
1796 title.Append(addCount);
1797 title.Append(Properties.Resources.RefreshTimelineText2);
1801 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1802 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1803 ntIcon = ToolTipIcon.Info;
1804 title.Append(Application.ProductName);
1806 title.Append(Properties.Resources.RefreshTimelineText1);
1808 title.Append(addCount);
1809 title.Append(Properties.Resources.RefreshTimelineText2);
1811 string bText = sb.ToString();
1812 if (string.IsNullOrEmpty(bText)) return;
1813 //NotifyIcon1.BalloonTipText = sb.ToString();
1814 //NotifyIcon1.ShowBalloonTip(500);
1815 NotifyIcon1.BalloonTipTitle = title.ToString();
1816 NotifyIcon1.BalloonTipText = bText;
1817 NotifyIcon1.BalloonTipIcon = ntIcon;
1818 NotifyIcon1.ShowBalloonTip(500);
1824 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1828 string dir = Application.StartupPath;
1829 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1831 dir = Path.Combine(dir, "Sounds");
1833 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1843 //mentions新着時に画面ブリンク
1844 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1846 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1850 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1852 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1854 _curItemIndex = _curList.SelectedIndices[0];
1855 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1859 _curPost = GetCurTabPost(_curItemIndex);
1861 catch (ArgumentException)
1866 this.PushSelectPostChain();
1868 if (this._cfgCommon.UnreadManage) _statuses.SetReadAllTab(true, _curTab.Text, _curItemIndex);
1870 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1876 private void ChangeCacheStyleRead(bool Read, int Index)
1878 var tabInfo = _statuses.Tabs[_curTab.Text];
1879 //Read:true=既読 false=未読
1880 //未読管理していなかったら既読として扱う
1881 if (!tabInfo.UnreadManage ||
1882 !this._cfgCommon.UnreadManage) Read = true;
1885 ListViewItem itm = null;
1886 PostClass post = null;
1888 this.TryGetListViewItemCache(Index, out itm, out post);
1890 if (itm == null || post == null)
1892 itm = ((DetailsListView)_curTab.Tag).Items[Index];
1893 post = tabInfo[Index];
1896 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1899 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1906 Item.SubItems[5].Text = "";
1911 Item.SubItems[5].Text = "★";
1917 else if (Post.RetweetedId != null)
1919 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1921 else if (Read || !this._cfgCommon.UseUnreadStyle)
1926 if (DList == null || Item.Index == -1)
1928 Item.ForeColor = cl;
1929 if (this._cfgCommon.UseUnreadStyle)
1935 if (this._cfgCommon.UseUnreadStyle)
1936 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1938 DList.ChangeItemForeColor(Item.Index, cl);
1939 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1943 private void ColorizeList()
1945 //Index:更新対象のListviewItem.Index。Colorを返す。
1946 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1949 _post = _anchorPost;
1953 if (_post == null) return;
1955 var itemColors = new Color[] { };
1958 this.itemCacheLock.EnterReadLock();
1961 if (this._itemCache == null) return;
1964 from i in Enumerable.Range(0, this._itemCache.Length)
1965 select this.JudgeColor(_post, this._postCache[i]);
1967 itemColors = query.ToArray();
1968 itemIndex = _itemCacheIndex;
1970 finally { this.itemCacheLock.ExitReadLock(); }
1972 if (itemIndex < 0) return;
1974 foreach (var backColor in itemColors)
1976 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
1977 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
1978 _curList.ChangeItemBackColor(itemIndex++, backColor);
1982 private void ColorizeList(ListViewItem Item, int Index)
1984 //Index:更新対象のListviewItem.Index。Colorを返す。
1985 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1988 _post = _anchorPost;
1992 PostClass tPost = GetCurTabPost(Index);
1994 if (_post == null) return;
1996 if (Item.Index == -1)
1997 Item.BackColor = JudgeColor(_post, tPost);
1999 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2002 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2005 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2008 else if (TargetPost.IsMe)
2011 else if (TargetPost.IsReply)
2014 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2016 cl = _clAtFromTarget;
2017 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2020 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2025 cl = _clListBackcolor;
2030 private async void PostButton_Click(object sender, EventArgs e)
2032 if (StatusText.Text.Trim().Length == 0)
2034 if (!ImageSelector.Enabled)
2041 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2043 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2045 MessageBoxButtons.YesNoCancel,
2046 MessageBoxIcon.Question);
2049 case DialogResult.Yes:
2050 doReTweetOfficial(false);
2051 StatusText.Text = "";
2053 case DialogResult.Cancel:
2058 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2060 if (SettingDialog.Nicoms)
2062 StatusText.SelectionStart = StatusText.Text.Length;
2063 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2065 //if (SettingDialog.UrlConvertAuto)
2067 // StatusText.SelectionStart = StatusText.Text.Length;
2068 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2070 //else if (SettingDialog.Nicoms)
2072 // StatusText.SelectionStart = StatusText.Text.Length;
2073 // UrlConvert(UrlConverter.Nicoms);
2075 StatusText.SelectionStart = StatusText.Text.Length;
2076 GetWorkerArg args = new GetWorkerArg();
2078 args.type = MyCommon.WORKERTYPE.PostMessage;
2079 CheckReplyTo(StatusText.Text);
2082 int adjustCount = 0;
2083 string tmpStatus = StatusText.Text.Trim();
2084 if (ToolStripMenuItemApiCommandEvasion.Checked)
2087 if (Regex.IsMatch(tmpStatus,
2088 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2089 RegexOptions.IgnoreCase)
2090 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2093 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2096 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2099 bool isCutOff = false;
2100 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2101 if (StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
2103 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2104 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2106 if (this._cfgCommon.PostShiftEnter)
2108 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2110 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2112 isRemoveFooter = true;
2114 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2116 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2119 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2120 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2122 isRemoveFooter = true;
2133 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2141 if (HashMgr.IsNotAddToAtReply)
2143 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2146 header = HashMgr.UseHash + " ";
2148 footer = " " + HashMgr.UseHash;
2153 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2156 header = HashMgr.UseHash + " ";
2158 footer = " " + HashMgr.UseHash;
2161 if (!isRemoveFooter)
2163 if (this._cfgLocal.UseRecommendStatus)
2165 footer += SettingDialog.RecommendStatusText;
2167 // テキストボックスに入力されている文字列を使用する
2168 footer += " " + this._cfgLocal.StatusText.Trim();
2171 args.status.status = header + StatusText.Text + footer;
2173 if (ToolStripMenuItemApiCommandEvasion.Checked)
2176 if (Regex.IsMatch(args.status.status,
2177 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2178 RegexOptions.IgnoreCase)
2179 && args.status.status.EndsWith(" .") == false) args.status.status += " .";
2182 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2185 Match mc2 = Regex.Match(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2186 if (mc2.Success) args.status.status = Regex.Replace(args.status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2189 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2191 // 文中の全角スペースを半角スペース1個にする
2192 args.status.status = args.status.status.Replace(" ", " ");
2195 if (isCutOff && args.status.status.Length > 140)
2197 args.status.status = args.status.status.Substring(0, 140);
2198 string AtId = @"(@|@)[a-z0-9_/]+$";
2199 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2200 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2201 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2202 Match mc = Regex.Match(args.status.status, pattern, RegexOptions.IgnoreCase);
2205 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2206 args.status.status = args.status.status.Substring(0, 140 - mc.Value.Length);
2208 if (MessageBox.Show(args.status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2211 args.status.inReplyToId = _reply_to_id;
2212 args.status.inReplyToName = _reply_to_name;
2213 if (ImageSelector.Visible)
2216 if (!ImageSelector.TryGetSelectedMedia(out args.status.imageService, out args.status.imagePath))
2222 _reply_to_id = null;
2223 _reply_to_name = null;
2224 StatusText.Text = "";
2225 _history.Add(new PostingStatus());
2226 _hisIdx = _history.Count - 1;
2227 if (!ToolStripFocusLockMenuItem.Checked)
2228 ((Control)ListTab.SelectedTab.Tag).Focus();
2229 urlUndoBuffer = null;
2230 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2233 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2235 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeUriString(StatusText.Text.Substring(7)));
2236 await this.OpenUriAsync(tmp);
2240 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2242 MyCommon._endingFlag = true;
2246 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2248 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2250 //_endingFlag=false:フォームの×ボタン
2252 this.Visible = false;
2256 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2257 _ignoreConfigSave = true;
2258 MyCommon._endingFlag = true;
2259 TimerTimeline.Enabled = false;
2260 TimerRefreshIcon.Enabled = false;
2264 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2266 this.Visible = true;
2267 if (this.WindowState == FormWindowState.Minimized)
2269 this.WindowState = FormWindowState.Normal;
2272 this.BringToFront();
2275 private static int errorCount = 0;
2277 private static bool CheckAccountValid()
2279 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2285 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2294 private void GetTimelineWorker_DoWork(object sender, DoWorkEventArgs e)
2296 BackgroundWorker bw = (BackgroundWorker)sender;
2297 if (bw.CancellationPending || MyCommon._endingFlag)
2303 Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
2305 MyApplication.InitCulture();
2308 GetWorkerResult rslt = new GetWorkerResult();
2310 bool read = !this._cfgCommon.UnreadManage;
2311 if (_initial && this._cfgCommon.UnreadManage) read = this._cfgCommon.Read;
2313 GetWorkerArg args = (GetWorkerArg)e.Argument;
2315 if (!CheckAccountValid())
2317 rslt.retMsg = "Auth error. Check your account";
2318 rslt.type = MyCommon.WORKERTYPE.ErrorState; //エラー表示のみ行ない、後処理キャンセル
2319 rslt.tName = args.tName;
2324 bw.ReportProgress(0, ""); //Notifyアイコンアニメーション開始
2328 case MyCommon.WORKERTYPE.Timeline:
2329 case MyCommon.WORKERTYPE.Reply:
2330 bw.ReportProgress(50, MakeStatusMessage(args, false));
2331 ret = tw.GetTimelineApi(read, args.type, args.page == -1, _initial);
2333 if (string.IsNullOrEmpty(ret) && args.type == MyCommon.WORKERTYPE.Timeline && this._cfgCommon.ReadOldPosts)
2334 _statuses.SetRead();
2336 rslt.addCount = _statuses.DistributePosts();
2338 case MyCommon.WORKERTYPE.DirectMessegeRcv: //送信分もまとめて取得
2339 bw.ReportProgress(50, MakeStatusMessage(args, false));
2340 ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, args.page == -1);
2341 if (string.IsNullOrEmpty(ret)) ret = tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, args.page == -1);
2342 rslt.addCount = _statuses.DistributePosts();
2345 case MyCommon.WORKERTYPE.FavAdd:
2349 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2351 for (int i = 0; i <= args.ids.Count - 1; i++)
2353 var post = tab.Posts[args.ids[i]];
2356 bw.ReportProgress(50, MakeStatusMessage(args, false));
2359 if (post.RetweetedId == null)
2360 ret = tw.PostFavAdd(post.StatusId);
2362 ret = tw.PostFavAdd(post.RetweetedId.Value);
2364 if (ret.Length == 0)
2366 args.sIds.Add(post.StatusId);
2367 post.IsFav = true; //リスト再描画必要
2368 _favTimestamps.Add(DateTime.Now);
2369 if (string.IsNullOrEmpty(post.RelTabName))
2371 //検索,リストUserTimeline.Relatedタブからのfavは、favタブへ追加せず。それ以外は追加
2372 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(post.StatusId, post.IsRead, false);
2376 //検索,リスト,UserTimeline.Relatedタブからのfavで、TLでも取得済みならfav反映
2377 if (_statuses.ContainsKey(post.StatusId))
2379 PostClass postTl = _statuses[post.StatusId];
2380 postTl.IsFav = true;
2381 _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).Add(postTl.StatusId, postTl.IsRead, false);
2384 //検索,リスト,UserTimeline,Relatedの各タブに反映
2385 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2387 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = true;
2393 rslt.sIds = args.sIds;
2397 case MyCommon.WORKERTYPE.FavRemove:
2401 if (_statuses.Tabs.TryGetValue(args.tName, out tab))
2403 for (int i = 0; i <= args.ids.Count - 1; i++)
2405 var post = tab.Posts[args.ids[i]];
2408 bw.ReportProgress(50, MakeStatusMessage(args, false));
2411 if (post.RetweetedId == null)
2412 ret = tw.PostFavRemove(post.StatusId);
2414 ret = tw.PostFavRemove(post.RetweetedId.Value);
2416 if (ret.Length == 0)
2418 args.sIds.Add(post.StatusId);
2419 post.IsFav = false; //リスト再描画必要
2420 if (_statuses.ContainsKey(post.StatusId)) _statuses[post.StatusId].IsFav = false;
2421 //検索,リスト,UserTimeline,Relatedの各タブに反映
2422 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch | MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.UserTimeline | MyCommon.TabUsageType.Related))
2424 if (tb.Contains(post.StatusId)) tb.Posts[post.StatusId].IsFav = false;
2430 rslt.sIds = args.sIds;
2434 case MyCommon.WORKERTYPE.PostMessage:
2435 bw.ReportProgress(200);
2436 if (args.status.imagePath == null || args.status.imagePath.Length == 0 || string.IsNullOrEmpty(args.status.imagePath[0]))
2438 ret = tw.PostStatus(args.status.status, args.status.inReplyToId);
2442 var service = ImageSelector.GetService(args.status.imageService);
2445 service.PostStatusAsync(args.status.status, args.status.inReplyToId, args.status.imagePath)
2448 catch (AggregateException ex)
2450 ret = ex.InnerException.Message;
2453 bw.ReportProgress(300);
2454 rslt.status = args.status;
2456 case MyCommon.WORKERTYPE.Retweet:
2457 bw.ReportProgress(200);
2458 for (int i = 0; i <= args.ids.Count - 1; i++)
2460 ret = tw.PostRetweet(args.ids[i], read);
2462 bw.ReportProgress(300);
2464 case MyCommon.WORKERTYPE.Follower:
2465 bw.ReportProgress(50, Properties.Resources.UpdateFollowersMenuItem1_ClickText1);
2468 tw.RefreshFollowerIds();
2470 catch (WebApiException ex) { ret = ex.Message; }
2472 case MyCommon.WORKERTYPE.NoRetweetIds:
2475 tw.RefreshNoRetweetIds();
2477 catch (WebApiException ex) { ret = ex.Message; }
2479 case MyCommon.WORKERTYPE.Configuration:
2482 this.SettingDialog.TwitterConfiguration = tw.ConfigurationApi();
2484 catch (WebApiException ex) { ret = ex.Message; }
2486 case MyCommon.WORKERTYPE.Favorites:
2487 bw.ReportProgress(50, MakeStatusMessage(args, false));
2488 ret = tw.GetFavoritesApi(read, args.type, args.page == -1);
2489 rslt.addCount = _statuses.DistributePosts();
2491 case MyCommon.WORKERTYPE.PublicSearch:
2492 bw.ReportProgress(50, MakeStatusMessage(args, false));
2493 if (string.IsNullOrEmpty(args.tName))
2495 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
2497 //if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetPhoenixSearch(read, tb, false);
2498 if (!string.IsNullOrEmpty(tb.SearchWords)) ret = tw.GetSearch(read, tb, false);
2503 TabClass tb = _statuses.GetTabByName(args.tName);
2506 //ret = tw.GetPhoenixSearch(read, tb, false);
2507 ret = tw.GetSearch(read, tb, false);
2508 if (string.IsNullOrEmpty(ret) && args.page == -1)
2510 //ret = tw.GetPhoenixSearch(read, tb, true)
2511 ret = tw.GetSearch(read, tb, true);
2516 rslt.addCount = _statuses.DistributePosts();
2518 case MyCommon.WORKERTYPE.UserTimeline:
2519 bw.ReportProgress(50, MakeStatusMessage(args, false));
2521 if (this._cfgCommon.UseAdditionalCount) count = this._cfgCommon.UserTimelineCountApi;
2522 if (string.IsNullOrEmpty(args.tName))
2524 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
2526 if (!string.IsNullOrEmpty(tb.User)) ret = tw.GetUserTimelineApi(read, count, tb.User, tb, false);
2531 TabClass tb = _statuses.GetTabByName(args.tName);
2534 ret = tw.GetUserTimelineApi(read, count, tb.User, tb, args.page == -1);
2538 rslt.addCount = _statuses.DistributePosts();
2540 case MyCommon.WORKERTYPE.List:
2541 bw.ReportProgress(50, MakeStatusMessage(args, false));
2542 if (string.IsNullOrEmpty(args.tName))
2545 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists))
2547 if (tb.ListInfo != null && tb.ListInfo.Id != 0) ret = tw.GetListStatus(read, tb, false, _initial);
2553 TabClass tb = _statuses.GetTabByName(args.tName);
2556 ret = tw.GetListStatus(read, tb, args.page == -1, _initial);
2560 rslt.addCount = _statuses.DistributePosts();
2563 case MyCommon.WORKERTYPE.Related:
2565 bw.ReportProgress(50, MakeStatusMessage(args, false));
2566 TabClass tab = _statuses.GetTabByName(args.tName);
2567 ret = tw.GetRelatedResult(read, tab);
2568 rslt.addCount = _statuses.DistributePosts();
2572 case MyCommon.WORKERTYPE.BlockIds:
2573 bw.ReportProgress(50, Properties.Resources.UpdateBlockUserText1);
2576 tw.RefreshBlockIds();
2578 catch (WebApiException ex) { ret = ex.Message; }
2582 if (bw.CancellationPending)
2589 if (args.type == MyCommon.WORKERTYPE.FavAdd)
2591 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2592 for (int i = _favTimestamps.Count - 1; i >= 0; i--)
2594 if (_favTimestamps[i].CompareTo(oneHour) < 0)
2596 _favTimestamps.RemoveAt(i);
2600 if (args.type == MyCommon.WORKERTYPE.Timeline && !_initial)
2604 DateTime tm = DateTime.Now;
2605 if (_tlTimestamps.ContainsKey(tm))
2606 _tlTimestamps[tm] += rslt.addCount;
2608 _tlTimestamps.Add(tm, rslt.addCount);
2610 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2611 List<DateTime> keys = new List<DateTime>();
2613 foreach (DateTime key in _tlTimestamps.Keys)
2615 if (key.CompareTo(oneHour) < 0)
2621 _tlCount += _tlTimestamps[key];
2624 foreach (DateTime key in keys)
2626 _tlTimestamps.Remove(key);
2633 bw.ReportProgress(100, MakeStatusMessage(args, true)); //ステータス書き換え、Notifyアイコンアニメーション開始
2636 rslt.type = args.type;
2637 rslt.tName = args.tName;
2642 private string MakeStatusMessage(GetWorkerArg AsyncArg, bool Finish)
2648 switch (AsyncArg.type)
2650 case MyCommon.WORKERTYPE.Timeline:
2651 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2653 case MyCommon.WORKERTYPE.Reply:
2654 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2656 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2657 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 + AsyncArg.page.ToString() + Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6;
2659 case MyCommon.WORKERTYPE.FavAdd:
2660 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2661 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2663 case MyCommon.WORKERTYPE.FavRemove:
2664 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 + AsyncArg.page.ToString() + "/" + AsyncArg.ids.Count.ToString() +
2665 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 + (AsyncArg.page - AsyncArg.sIds.Count - 1).ToString();
2667 case MyCommon.WORKERTYPE.Favorites:
2668 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19;
2670 case MyCommon.WORKERTYPE.PublicSearch:
2671 smsg = "Search refreshing...";
2673 case MyCommon.WORKERTYPE.List:
2674 smsg = "List refreshing...";
2676 case MyCommon.WORKERTYPE.Related:
2677 smsg = "Related refreshing...";
2679 case MyCommon.WORKERTYPE.UserTimeline:
2680 smsg = "UserTimeline refreshing...";
2687 switch (AsyncArg.type)
2689 case MyCommon.WORKERTYPE.Timeline:
2690 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1;
2692 case MyCommon.WORKERTYPE.Reply:
2693 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9;
2695 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2696 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11;
2698 case MyCommon.WORKERTYPE.DirectMessegeSnt:
2699 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText13;
2701 case MyCommon.WORKERTYPE.FavAdd:
2704 case MyCommon.WORKERTYPE.FavRemove:
2707 case MyCommon.WORKERTYPE.Favorites:
2708 smsg = Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20;
2710 case MyCommon.WORKERTYPE.Follower:
2711 smsg = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2713 case MyCommon.WORKERTYPE.NoRetweetIds:
2714 smsg = "NoRetweetIds refreshed";
2716 case MyCommon.WORKERTYPE.Configuration:
2719 case MyCommon.WORKERTYPE.PublicSearch:
2720 smsg = "Search refreshed";
2722 case MyCommon.WORKERTYPE.List:
2723 smsg = "List refreshed";
2725 case MyCommon.WORKERTYPE.Related:
2726 smsg = "Related refreshed";
2728 case MyCommon.WORKERTYPE.UserTimeline:
2729 smsg = "UserTimeline refreshed";
2731 case MyCommon.WORKERTYPE.BlockIds:
2732 smsg = Properties.Resources.UpdateBlockUserText3;
2739 private void GetTimelineWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
2741 if (MyCommon._endingFlag) return;
2742 if (e.ProgressPercentage > 100)
2745 if (e.ProgressPercentage == 200) //開始
2746 StatusLabel.Text = "Posting...";
2747 if (e.ProgressPercentage == 300) //終了
2748 StatusLabel.Text = Properties.Resources.PostWorker_RunWorkerCompletedText4;
2752 string smsg = (string)e.UserState;
2753 if (smsg.Length > 0) StatusLabel.Text = smsg;
2757 private void GetTimelineWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2759 if (MyCommon._endingFlag || e.Cancelled) return; //キャンセル
2761 if (e.Error != null)
2763 _myStatusError = true;
2764 _waitTimeline = false;
2768 _waitPubSearch = false;
2769 _waitUserTimeline = false;
2771 throw new Exception("BackgroundWorker Exception", e.Error);
2774 GetWorkerResult rslt = (GetWorkerResult)e.Result;
2777 if (rslt.retMsg.Length > 0)
2779 _myStatusError = true;
2780 StatusLabel.Text = rslt.retMsg;
2783 if (rslt.type == MyCommon.WORKERTYPE.ErrorState) return;
2785 if (rslt.type == MyCommon.WORKERTYPE.FavRemove)
2787 this.RemovePostFromFavTab(rslt.sIds.ToArray());
2791 //bool busy = false;
2792 //foreach (BackgroundWorker bw in _bw)
2794 // if (bw != null && bw.IsBusy)
2800 //if (!busy) RefreshTimeline(); //background処理なければ、リスト反映
2801 if (rslt.type == MyCommon.WORKERTYPE.Timeline ||
2802 rslt.type == MyCommon.WORKERTYPE.Reply ||
2803 rslt.type == MyCommon.WORKERTYPE.List ||
2804 rslt.type == MyCommon.WORKERTYPE.PublicSearch ||
2805 rslt.type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
2806 rslt.type == MyCommon.WORKERTYPE.DirectMessegeSnt ||
2807 rslt.type == MyCommon.WORKERTYPE.Favorites ||
2808 rslt.type == MyCommon.WORKERTYPE.Follower ||
2809 rslt.type == MyCommon.WORKERTYPE.NoRetweetIds ||
2810 rslt.type == MyCommon.WORKERTYPE.FavAdd ||
2811 rslt.type == MyCommon.WORKERTYPE.FavRemove ||
2812 rslt.type == MyCommon.WORKERTYPE.Related ||
2813 rslt.type == MyCommon.WORKERTYPE.UserTimeline ||
2814 rslt.type == MyCommon.WORKERTYPE.BlockIds ||
2815 rslt.type == MyCommon.WORKERTYPE.Configuration)
2817 RefreshTimeline(false); //リスト反映
2822 case MyCommon.WORKERTYPE.Timeline:
2823 _waitTimeline = false;
2826 // //API使用時の取得調整は別途考える(カウント調整?)
2829 case MyCommon.WORKERTYPE.Reply:
2831 if (rslt.newDM && !_initial)
2833 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
2836 case MyCommon.WORKERTYPE.Favorites:
2839 case MyCommon.WORKERTYPE.DirectMessegeRcv:
2842 case MyCommon.WORKERTYPE.FavAdd:
2843 case MyCommon.WORKERTYPE.FavRemove:
2844 if (_curList != null && _curTab != null)
2846 using (ControlTransaction.Update(this._curList))
2848 if (rslt.type == MyCommon.WORKERTYPE.FavRemove && _statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.Favorites)
2854 for (int i = 0; i <= rslt.sIds.Count - 1; i++)
2856 if (_curTab.Text.Equals(rslt.tName))
2858 int idx = _statuses.Tabs[rslt.tName].IndexOf(rslt.sIds[i]);
2861 PostClass post = null;
2862 TabClass tb = _statuses.Tabs[rslt.tName];
2865 if (tb.TabType == MyCommon.TabUsageType.Lists || tb.TabType == MyCommon.TabUsageType.PublicSearch)
2867 post = tb.Posts[rslt.sIds[i]];
2871 post = _statuses[rslt.sIds[i]];
2873 ChangeCacheStyleRead(post.IsRead, idx);
2875 if (idx == _curItemIndex) DispSelectedPost(true); //選択アイテム再表示
2883 case MyCommon.WORKERTYPE.PostMessage:
2884 if (string.IsNullOrEmpty(rslt.retMsg) ||
2885 rslt.retMsg.StartsWith("OK:") ||
2886 rslt.retMsg == "Warn:Status is a duplicate.")
2888 _postTimestamps.Add(DateTime.Now);
2889 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2890 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2892 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2894 _postTimestamps.RemoveAt(i);
2898 if (!HashMgr.IsPermanent && !string.IsNullOrEmpty(HashMgr.UseHash))
2900 HashMgr.ClearHashtag();
2901 this.HashStripSplitButton.Text = "#[-]";
2902 this.HashToggleMenuItem.Checked = false;
2903 this.HashToggleToolStripMenuItem.Checked = false;
2905 SetMainWindowTitle();
2913 retry = MessageBox.Show(string.Format("{0} ---> [ " + rslt.retMsg + " ]" + Environment.NewLine + "\"" + rslt.status.status + "\"" + Environment.NewLine + "{1}",
2914 Properties.Resources.StatusUpdateFailed1,
2915 Properties.Resources.StatusUpdateFailed2),
2916 "Failed to update status",
2917 MessageBoxButtons.RetryCancel,
2918 MessageBoxIcon.Question);
2922 retry = DialogResult.Abort;
2924 if (retry == DialogResult.Retry)
2926 GetWorkerArg args = new GetWorkerArg();
2928 args.type = MyCommon.WORKERTYPE.PostMessage;
2929 args.status = rslt.status;
2934 if (ToolStripFocusLockMenuItem.Checked)
2936 //連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2937 StatusText_Enter(StatusText, new EventArgs());
2941 if (rslt.retMsg.Length == 0 && this._cfgCommon.PostAndGet)
2943 if (_isActiveUserstream)
2945 RefreshTimeline(true);
2949 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2953 case MyCommon.WORKERTYPE.Retweet:
2954 if (rslt.retMsg.Length == 0)
2956 _postTimestamps.Add(DateTime.Now);
2957 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
2958 for (int i = _postTimestamps.Count - 1; i >= 0; i--)
2960 if (_postTimestamps[i].CompareTo(oneHour) < 0)
2962 _postTimestamps.RemoveAt(i);
2965 if (!_isActiveUserstream && this._cfgCommon.PostAndGet) GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
2968 case MyCommon.WORKERTYPE.Follower:
2969 //_waitFollower = false;
2970 this.PurgeListViewItemCache();
2971 if (_curList != null) _curList.Refresh();
2973 case MyCommon.WORKERTYPE.NoRetweetIds:
2975 case MyCommon.WORKERTYPE.Configuration:
2976 //_waitFollower = false
2977 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit != 0)
2979 foreach (var service in this.ImageSelector.GetServices())
2981 service.UpdateTwitterConfiguration(this.SettingDialog.TwitterConfiguration);
2984 this.PurgeListViewItemCache();
2985 if (_curList != null) _curList.Refresh();
2987 case MyCommon.WORKERTYPE.PublicSearch:
2988 _waitPubSearch = false;
2990 case MyCommon.WORKERTYPE.UserTimeline:
2991 _waitUserTimeline = false;
2993 case MyCommon.WORKERTYPE.List:
2996 case MyCommon.WORKERTYPE.Related:
2997 TabClass tab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
2998 if (tab != null && tab.RelationTargetPost != null && tab.Contains(tab.RelationTargetPost.StatusId))
3000 foreach (TabPage tp in ListTab.TabPages)
3002 if (tp.Text == tab.TabName)
3004 ((DetailsListView)tp.Tag).SelectedIndices.Add(tab.IndexOf(tab.RelationTargetPost.StatusId));
3005 ((DetailsListView)tp.Tag).Items[tab.IndexOf(tab.RelationTargetPost.StatusId)].Focused = true;
3014 private async Task RefreshMuteUserIdsAsync()
3016 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3020 await tw.RefreshMuteUserIdsAsync();
3022 catch (WebApiException ex)
3024 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3028 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3031 private void RemovePostFromFavTab(Int64[] ids)
3033 string favTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Favorites).TabName;
3035 if (_curTab.Text.Equals(favTabName))
3037 if (_curList.FocusedItem != null)
3038 fidx = _curList.FocusedItem.Index;
3039 else if (_curList.TopItem != null)
3040 fidx = _curList.TopItem.Index;
3045 foreach (long i in ids)
3049 _statuses.RemoveFavPost(i);
3056 if (_curTab != null && _curTab.Text.Equals(favTabName))
3058 this.PurgeListViewItemCache();
3060 //_curItemIndex = -1;
3062 foreach (TabPage tp in ListTab.TabPages)
3064 if (tp.Text == favTabName)
3066 ((DetailsListView)tp.Tag).VirtualListSize = _statuses.Tabs[favTabName].AllCount;
3070 if (_curTab.Text.Equals(favTabName))
3074 _curList.SelectedIndices.Clear();
3076 while (_curList.SelectedIndices.Count > 0);
3078 if (_statuses.Tabs[favTabName].AllCount > 0)
3080 if (_statuses.Tabs[favTabName].AllCount - 1 > fidx && fidx > -1)
3082 _curList.SelectedIndices.Add(fidx);
3086 _curList.SelectedIndices.Add(_statuses.Tabs[favTabName].AllCount - 1);
3088 if (_curList.SelectedIndices.Count > 0)
3090 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3091 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3097 private static Dictionary<MyCommon.WORKERTYPE, DateTime> lastTime = new Dictionary<MyCommon.WORKERTYPE, DateTime>();
3099 private void GetTimeline(MyCommon.WORKERTYPE WkType, int fromPage, string tabName)
3101 if (!this.IsNetworkAvailable()) return;
3104 GetWorkerArg args = new GetWorkerArg();
3105 args.page = fromPage;
3107 args.tName = tabName;
3109 if (!lastTime.ContainsKey(WkType)) lastTime.Add(WkType, new DateTime());
3110 double period = DateTime.Now.Subtract(lastTime[WkType]).TotalSeconds;
3111 if (period > 1 || period < -1)
3113 lastTime[WkType] = DateTime.Now;
3117 //Timeline取得モードの場合はReplyも同時に取得
3118 //if (!SettingDialog.UseAPI &&
3120 // WkType == MyCommon.WORKERTYPE.Timeline &&
3121 // SettingDialog.CheckReply)
3123 // //TimerReply.Enabled = false;
3124 // _mentionCounter = SettingDialog.ReplyPeriodInt;
3125 // GetWorkerArg _args = new GetWorkerArg();
3126 // _args.page = fromPage;
3127 // _args.endPage = toPage;
3128 // _args.type = MyCommon.WORKERTYPE.Reply;
3133 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3135 if (e.Button == MouseButtons.Left)
3137 this.Visible = true;
3138 if (this.WindowState == FormWindowState.Minimized)
3140 this.WindowState = _formWindowState;
3143 this.BringToFront();
3147 private void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3149 switch (this._cfgCommon.ListDoubleClickAction)
3152 MakeReplyOrDirectStatus();
3155 FavoriteChange(true);
3158 if (_curPost != null)
3159 ShowUserStatus(_curPost.ScreenName, false);
3165 ShowRelatedStatusesMenuItem_Click(null, null);
3168 MoveToHomeToolStripMenuItem_Click(null, null);
3171 StatusOpenMenuItem_Click(null, null);
3179 private void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3181 FavoriteChange(true);
3184 private void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3186 FavoriteChange(false);
3190 private void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3192 FavoritesRetweetOriginal();
3195 private void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3197 FavoritesRetweetUnofficial();
3200 private void FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3202 //trueでFavAdd,falseでFavRemove
3203 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3204 || !this.ExistCurrentPost) return;
3207 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3209 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3210 _DoFavRetweetFlags = false;
3213 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3217 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3218 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3219 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3220 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3222 _DoFavRetweetFlags = false;
3228 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3229 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3236 GetWorkerArg args = new GetWorkerArg();
3237 args.ids = new List<long>();
3238 args.sIds = new List<long>();
3239 args.tName = _curTab.Text;
3242 args.type = MyCommon.WORKERTYPE.FavAdd;
3246 args.type = MyCommon.WORKERTYPE.FavRemove;
3248 foreach (int idx in _curList.SelectedIndices)
3250 PostClass post = GetCurTabPost(idx);
3253 if (!post.IsFav) args.ids.Add(post.StatusId);
3257 if (post.IsFav) args.ids.Add(post.StatusId);
3260 if (args.ids.Count == 0)
3263 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3265 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3273 private PostClass GetCurTabPost(int Index)
3275 this.itemCacheLock.EnterReadLock();
3278 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3279 return _postCache[Index - _itemCacheIndex];
3281 finally { this.itemCacheLock.ExitReadLock(); }
3283 return _statuses[_curTab.Text, Index];
3287 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3289 if (_curList.SelectedIndices.Count > 0)
3290 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3291 else if (_curList.SelectedIndices.Count == 0)
3292 OpenUriAsync(MyCommon.TwitterUrl);
3295 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3297 if (_curList.SelectedIndices.Count > 0)
3298 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3301 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3303 if ((!_initialLayout) && this.Visible)
3305 if (this.WindowState == FormWindowState.Normal)
3307 _mySize = this.ClientSize;
3308 _mySpDis = this.SplitContainer1.SplitterDistance;
3309 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3310 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3311 _modifySettingLocal = true;
3316 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3318 if (this._cfgCommon.SortOrderLock) return;
3319 IdComparerClass.ComparerMode mode = IdComparerClass.ComparerMode.Id;
3322 mode = IdComparerClass.ComparerMode.Id;
3330 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3334 mode = IdComparerClass.ComparerMode.Nickname;
3337 mode = IdComparerClass.ComparerMode.Data;
3340 mode = IdComparerClass.ComparerMode.Id;
3343 mode = IdComparerClass.ComparerMode.Name;
3346 mode = IdComparerClass.ComparerMode.Source;
3350 _statuses.ToggleSortOrder(mode);
3353 DetailsListView list = (DetailsListView)sender;
3356 list.Columns[0].Text = ColumnOrgText[0];
3357 list.Columns[1].Text = ColumnText[2];
3361 for (int i = 0; i <= 7; i++)
3363 list.Columns[i].Text = ColumnOrgText[i];
3365 list.Columns[e.Column].Text = ColumnText[e.Column];
3368 this.PurgeListViewItemCache();
3370 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3372 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3375 SelectListItem(_curList, idx);
3376 _curList.EnsureVisible(idx);
3380 _modifySettingCommon = true;
3383 private void TweenMain_LocationChanged(object sender, EventArgs e)
3385 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3387 _myLoc = this.DesktopLocation;
3388 _modifySettingLocal = true;
3392 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3394 if (ListTab.SelectedTab == null) return;
3395 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3396 if (!this.ExistCurrentPost)
3398 ReplyStripMenuItem.Enabled = false;
3399 ReplyAllStripMenuItem.Enabled = false;
3400 DMStripMenuItem.Enabled = false;
3401 ShowProfileMenuItem.Enabled = false;
3402 ShowUserTimelineContextMenuItem.Enabled = false;
3403 ListManageUserContextToolStripMenuItem2.Enabled = false;
3404 MoveToFavToolStripMenuItem.Enabled = false;
3405 TabMenuItem.Enabled = false;
3406 IDRuleMenuItem.Enabled = false;
3407 ReadedStripMenuItem.Enabled = false;
3408 UnreadStripMenuItem.Enabled = false;
3412 ShowProfileMenuItem.Enabled = true;
3413 ListManageUserContextToolStripMenuItem2.Enabled = true;
3414 ReplyStripMenuItem.Enabled = true;
3415 ReplyAllStripMenuItem.Enabled = true;
3416 DMStripMenuItem.Enabled = true;
3417 ShowUserTimelineContextMenuItem.Enabled = true;
3418 MoveToFavToolStripMenuItem.Enabled = true;
3419 TabMenuItem.Enabled = true;
3420 IDRuleMenuItem.Enabled = true;
3421 ReadedStripMenuItem.Enabled = true;
3422 UnreadStripMenuItem.Enabled = true;
3424 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3425 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3427 FavAddToolStripMenuItem.Enabled = false;
3428 FavRemoveToolStripMenuItem.Enabled = false;
3429 StatusOpenMenuItem.Enabled = false;
3430 FavorareMenuItem.Enabled = false;
3431 ShowRelatedStatusesMenuItem.Enabled = false;
3433 ReTweetStripMenuItem.Enabled = false;
3434 ReTweetOriginalStripMenuItem.Enabled = false;
3435 QuoteStripMenuItem.Enabled = false;
3436 FavoriteRetweetContextMenu.Enabled = false;
3437 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3438 if (this.ExistCurrentPost && _curPost.IsDm)
3439 DeleteStripMenuItem.Enabled = true;
3441 DeleteStripMenuItem.Enabled = false;
3445 FavAddToolStripMenuItem.Enabled = true;
3446 FavRemoveToolStripMenuItem.Enabled = true;
3447 StatusOpenMenuItem.Enabled = true;
3448 FavorareMenuItem.Enabled = true;
3449 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3453 ReTweetOriginalStripMenuItem.Enabled = false;
3454 FavoriteRetweetContextMenu.Enabled = false;
3455 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3457 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3461 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3463 DeleteStripMenuItem.Enabled = true;
3467 if (string.IsNullOrEmpty(_curPost.RetweetedBy))
3469 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3473 DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3475 DeleteStripMenuItem.Enabled = false;
3476 if (_curPost.IsProtect)
3478 ReTweetOriginalStripMenuItem.Enabled = false;
3479 ReTweetStripMenuItem.Enabled = false;
3480 QuoteStripMenuItem.Enabled = false;
3481 FavoriteRetweetContextMenu.Enabled = false;
3482 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3486 ReTweetOriginalStripMenuItem.Enabled = true;
3487 ReTweetStripMenuItem.Enabled = true;
3488 QuoteStripMenuItem.Enabled = true;
3489 FavoriteRetweetContextMenu.Enabled = true;
3490 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3494 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3496 // RefreshMoreStripMenuItem.Enabled = true;
3500 // RefreshMoreStripMenuItem.Enabled = false;
3502 if (!this.ExistCurrentPost
3503 || _curPost.InReplyToStatusId == null)
3505 RepliedStatusOpenMenuItem.Enabled = false;
3509 RepliedStatusOpenMenuItem.Enabled = true;
3511 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3513 MoveToRTHomeMenuItem.Enabled = false;
3517 MoveToRTHomeMenuItem.Enabled = true;
3521 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3523 MakeReplyOrDirectStatus(false, true);
3526 private void DMStripMenuItem_Click(object sender, EventArgs e)
3528 MakeReplyOrDirectStatus(false, false);
3531 private void doStatusDelete()
3533 if (_curTab == null || _curList == null) return;
3534 if (_statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
3536 bool myPost = false;
3537 foreach (int idx in _curList.SelectedIndices)
3539 if (GetCurTabPost(idx).IsMe ||
3540 GetCurTabPost(idx).RetweetedBy.ToLower() == tw.Username.ToLower())
3546 if (!myPost) return;
3550 if (_curList.SelectedIndices.Count == 0)
3554 string tmp = string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine);
3556 if (MessageBox.Show(tmp, Properties.Resources.DeleteStripMenuItem_ClickText2,
3557 MessageBoxButtons.OKCancel,
3558 MessageBoxIcon.Question) == DialogResult.Cancel) return;
3561 if (_curList.FocusedItem != null)
3562 fidx = _curList.FocusedItem.Index;
3563 else if (_curList.TopItem != null)
3564 fidx = _curList.TopItem.Index;
3570 this.Cursor = Cursors.WaitCursor;
3573 foreach (long Id in _statuses.GetId(_curTab.Text, _curList.SelectedIndices))
3576 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage)
3578 rtn = tw.RemoveDirectMessage(Id, _statuses[Id]);
3582 if (_statuses[Id].IsMe || _statuses[Id].RetweetedBy.ToLower() == tw.Username.ToLower())
3583 rtn = tw.RemoveStatus(Id);
3594 _statuses.RemovePost(Id);
3599 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; //失敗
3601 StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; //成功
3603 this.PurgeListViewItemCache();
3606 foreach (TabPage tb in ListTab.TabPages)
3608 ((DetailsListView)tb.Tag).VirtualListSize = _statuses.Tabs[tb.Text].AllCount;
3609 if (_curTab.Equals(tb))
3613 _curList.SelectedIndices.Clear();
3615 while (_curList.SelectedIndices.Count > 0);
3617 if (_statuses.Tabs[tb.Text].AllCount > 0)
3619 if (_statuses.Tabs[tb.Text].AllCount - 1 > fidx && fidx > -1)
3620 _curList.SelectedIndices.Add(fidx);
3622 _curList.SelectedIndices.Add(_statuses.Tabs[tb.Text].AllCount - 1);
3624 if (_curList.SelectedIndices.Count > 0)
3626 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3627 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3631 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3633 if (this._cfgCommon.TabIconDisp)
3635 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3639 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3643 this.Cursor = Cursors.Default;
3647 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3652 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3654 using (ControlTransaction.Update(this._curList))
3656 if (this._cfgCommon.UnreadManage)
3658 foreach (int idx in _curList.SelectedIndices)
3660 _statuses.SetReadAllTab(true, _curTab.Text, idx);
3663 foreach (int idx in _curList.SelectedIndices)
3665 ChangeCacheStyleRead(true, idx);
3669 foreach (TabPage tb in ListTab.TabPages)
3671 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3673 if (this._cfgCommon.TabIconDisp)
3675 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3679 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3682 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3684 using (ControlTransaction.Update(this._curList))
3686 if (this._cfgCommon.UnreadManage)
3688 foreach (int idx in _curList.SelectedIndices)
3690 _statuses.SetReadAllTab(false, _curTab.Text, idx);
3693 foreach (int idx in _curList.SelectedIndices)
3695 ChangeCacheStyleRead(false, idx);
3699 foreach (TabPage tb in ListTab.TabPages)
3701 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3703 if (this._cfgCommon.TabIconDisp)
3705 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3709 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3712 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
3717 private void DoRefresh()
3719 if (_curTab != null)
3721 switch (_statuses.Tabs[_curTab.Text].TabType)
3723 case MyCommon.TabUsageType.Mentions:
3724 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
3726 case MyCommon.TabUsageType.DirectMessage:
3727 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
3729 case MyCommon.TabUsageType.Favorites:
3730 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
3732 //case MyCommon.TabUsageType.Profile:
3734 case MyCommon.TabUsageType.PublicSearch:
3736 TabClass tb = _statuses.Tabs[_curTab.Text];
3737 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3738 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, _curTab.Text);
3740 case MyCommon.TabUsageType.UserTimeline:
3741 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, _curTab.Text);
3743 case MyCommon.TabUsageType.Lists:
3745 TabClass tab = _statuses.Tabs[_curTab.Text];
3746 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3747 GetTimeline(MyCommon.WORKERTYPE.List, 1, _curTab.Text);
3750 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3756 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
3760 private void DoRefreshMore()
3763 if (_curTab != null)
3765 switch (_statuses.Tabs[_curTab.Text].TabType)
3767 case MyCommon.TabUsageType.Mentions:
3768 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
3770 case MyCommon.TabUsageType.DirectMessage:
3771 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
3773 case MyCommon.TabUsageType.Favorites:
3774 GetTimeline(MyCommon.WORKERTYPE.Favorites, -1, "");
3776 case MyCommon.TabUsageType.Profile:
3779 case MyCommon.TabUsageType.PublicSearch:
3781 TabClass tb = _statuses.Tabs[_curTab.Text];
3782 if (string.IsNullOrEmpty(tb.SearchWords)) return;
3783 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, -1, _curTab.Text);
3785 case MyCommon.TabUsageType.UserTimeline:
3786 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, -1, _curTab.Text);
3788 case MyCommon.TabUsageType.Lists:
3790 TabClass tab = _statuses.Tabs[_curTab.Text];
3791 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
3792 GetTimeline(MyCommon.WORKERTYPE.List, -1, _curTab.Text);
3795 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3801 GetTimeline(MyCommon.WORKERTYPE.Timeline, -1, "");
3805 private void SettingStripMenuItem_Click(object sender, EventArgs e)
3807 DialogResult result;
3808 string uid = tw.Username.ToLower();
3812 result = SettingDialog.ShowDialog(this);
3819 if (result == DialogResult.OK)
3823 var oldIconSz = this._cfgCommon.IconSize;
3825 this.SettingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3827 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3828 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3829 ShortUrl.Instance.DisableExpanding = !SettingDialog.TinyUrlResolve;
3830 ShortUrl.Instance.BitlyId = SettingDialog.BitlyUser;
3831 ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd;
3832 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
3834 Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut);
3835 Networking.SetWebProxy(this.SettingDialog.SelectedProxyType,
3836 this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort,
3837 this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword);
3839 ImageSelector.Reset(tw, SettingDialog.TwitterConfiguration);
3843 if (this._cfgCommon.TabIconDisp)
3845 ListTab.DrawItem -= ListTab_DrawItem;
3846 ListTab.DrawMode = TabDrawMode.Normal;
3847 ListTab.ImageList = this.TabImage;
3851 ListTab.DrawItem -= ListTab_DrawItem;
3852 ListTab.DrawItem += ListTab_DrawItem;
3853 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3854 ListTab.ImageList = null;
3857 catch (Exception ex)
3859 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3860 ex.Data["IsTerminatePermission"] = false;
3866 if (!this._cfgCommon.UnreadManage)
3868 ReadedStripMenuItem.Enabled = false;
3869 UnreadStripMenuItem.Enabled = false;
3870 if (this._cfgCommon.TabIconDisp)
3872 foreach (TabPage myTab in ListTab.TabPages)
3874 myTab.ImageIndex = -1;
3880 ReadedStripMenuItem.Enabled = true;
3881 UnreadStripMenuItem.Enabled = true;
3884 catch (Exception ex)
3886 ex.Data["Instance"] = "ListTab(UnreadManage)";
3887 ex.Data["IsTerminatePermission"] = false;
3894 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3896 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3897 imgazyobizinet.Enabled = this.SettingDialog.EnableImgAzyobuziNet;
3898 imgazyobizinet.DisabledInDM = this.SettingDialog.ImgAzyobuziNetDisabledInDM;
3900 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3901 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3902 _fntUnread = this._cfgLocal.FontUnread;
3903 _clUnread = this._cfgLocal.ColorUnread;
3904 _fntReaded = this._cfgLocal.FontRead;
3905 _clReaded = this._cfgLocal.ColorRead;
3906 _clFav = this._cfgLocal.ColorFav;
3907 _clOWL = this._cfgLocal.ColorOWL;
3908 _clRetweet = this._cfgLocal.ColorRetweet;
3909 _fntDetail = this._cfgLocal.FontDetail;
3910 _clDetail = this._cfgLocal.ColorDetail;
3911 _clDetailLink = this._cfgLocal.ColorDetailLink;
3912 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3913 _clSelf = this._cfgLocal.ColorSelf;
3914 _clAtSelf = this._cfgLocal.ColorAtSelf;
3915 _clTarget = this._cfgLocal.ColorTarget;
3916 _clAtTarget = this._cfgLocal.ColorAtTarget;
3917 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3918 _clAtTo = this._cfgLocal.ColorAtTo;
3919 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3920 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3921 _clInputFont = this._cfgLocal.ColorInputFont;
3922 _fntInputFont = this._cfgLocal.FontInputFont;
3923 _brsBackColorMine.Dispose();
3924 _brsBackColorAt.Dispose();
3925 _brsBackColorYou.Dispose();
3926 _brsBackColorAtYou.Dispose();
3927 _brsBackColorAtFromTarget.Dispose();
3928 _brsBackColorAtTo.Dispose();
3929 _brsBackColorNone.Dispose();
3930 _brsBackColorMine = new SolidBrush(_clSelf);
3931 _brsBackColorAt = new SolidBrush(_clAtSelf);
3932 _brsBackColorYou = new SolidBrush(_clTarget);
3933 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3934 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3935 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3936 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3940 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3941 StatusText.Font = _fntInputFont;
3942 StatusText.ForeColor = _clInputFont;
3944 catch (Exception ex)
3946 MessageBox.Show(ex.Message);
3951 InitDetailHtmlFormat();
3953 catch (Exception ex)
3955 ex.Data["Instance"] = "Font";
3956 ex.Data["IsTerminatePermission"] = false;
3962 _statuses.SetUnreadManage(this._cfgCommon.UnreadManage);
3964 catch (Exception ex)
3966 ex.Data["Instance"] = "_statuses";
3967 ex.Data["IsTerminatePermission"] = false;
3973 foreach (TabPage tb in ListTab.TabPages)
3975 if (this._cfgCommon.TabIconDisp)
3977 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3984 catch (Exception ex)
3986 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3987 ex.Data["IsTerminatePermission"] = false;
3993 var oldIconCol = _iconCol;
3995 if (this._cfgCommon.IconSize != oldIconSz)
3996 ApplyListViewIconSize(this._cfgCommon.IconSize);
3998 foreach (TabPage tp in ListTab.TabPages)
4000 DetailsListView lst = (DetailsListView)tp.Tag;
4002 using (ControlTransaction.Update(lst))
4004 lst.GridLines = this._cfgCommon.ShowGrid;
4005 lst.Font = _fntReaded;
4006 lst.BackColor = _clListBackcolor;
4008 if (_iconCol != oldIconCol)
4013 catch (Exception ex)
4015 ex.Data["Instance"] = "ListView(IconSize)";
4016 ex.Data["IsTerminatePermission"] = false;
4020 SetMainWindowTitle();
4021 SetNotifyIconText();
4023 this.PurgeListViewItemCache();
4024 if (_curList != null) _curList.Refresh();
4027 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4028 if (this._cfgCommon.HotkeyEnabled)
4030 ///グローバルホットキーの登録。設定で変更可能にするかも
4031 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4032 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4033 modKey |= HookGlobalHotkey.ModKeys.Alt;
4034 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4035 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4036 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4037 modKey |= HookGlobalHotkey.ModKeys.Shift;
4038 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4039 modKey |= HookGlobalHotkey.ModKeys.Win;
4041 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4044 if (uid != tw.Username) this.doGetFollowersMenu();
4046 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4049 StatusText_TextChanged(null, null);
4057 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4059 this.TopMost = this._cfgCommon.AlwaysTop;
4060 SaveConfigsAll(false);
4066 private void SetTabAlignment()
4068 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4069 if (ListTab.Alignment == newAlignment) return;
4072 Dictionary<string, long[]> selId = new Dictionary<string, long[]>();
4073 Dictionary<string, long[]> focusedId = new Dictionary<string, long[]>();
4074 SaveSelectedStatus(selId, focusedId);
4076 ListTab.Alignment = newAlignment;
4079 foreach (TabPage tab in ListTab.TabPages)
4081 DetailsListView lst = (DetailsListView)tab.Tag;
4082 TabClass tabInfo = _statuses.Tabs[tab.Text];
4083 using (ControlTransaction.Update(lst))
4085 this.SelectListItem(lst,
4086 tabInfo.IndexOf(selId[tab.Text]),
4087 tabInfo.IndexOf(focusedId[tab.Text]));
4092 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4098 case MyCommon.IconSizes.IconNone:
4101 case MyCommon.IconSizes.Icon16:
4104 case MyCommon.IconSizes.Icon24:
4107 case MyCommon.IconSizes.Icon48:
4110 case MyCommon.IconSizes.Icon48_2:
4118 // ディスプレイの DPI 設定を考慮したサイズを設定する
4119 _listViewImageList.ImageSize = new Size(
4121 (int)Math.Ceiling(this._iconSz * this.currentScaleFactor.Height));
4125 _listViewImageList.ImageSize = new Size(1, 1);
4129 private void ResetColumns(DetailsListView list)
4131 using (ControlTransaction.Update(list))
4132 using (ControlTransaction.Layout(list, false))
4135 list.ColumnClick -= MyList_ColumnClick;
4136 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4137 list.ColumnReordered -= MyList_ColumnReordered;
4138 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4140 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4141 list.Columns.Clear();
4142 cols.ForEach(col => col.Dispose());
4145 InitColumns(list, true);
4147 list.ColumnClick += MyList_ColumnClick;
4148 list.DrawColumnHeader += MyList_DrawColumnHeader;
4149 list.ColumnReordered += MyList_ColumnReordered;
4150 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4154 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4156 if (e.Url.AbsoluteUri != "about:blank")
4159 OpenUriAsync(e.Url.OriginalString);
4163 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4165 if (e.Url.Scheme == "data")
4167 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4169 else if (e.Url.AbsoluteUri != "about:blank")
4173 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4174 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4177 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4178 int i = urlStr.IndexOf('#');
4179 if (i == -1) return;
4181 string hash = urlStr.Substring(i);
4182 HashSupl.AddItem(hash);
4183 HashMgr.AddHashToHistory(hash.Trim(), false);
4184 AddNewTabForSearch(hash);
4189 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4190 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4192 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4193 if (this._cfgCommon.OpenUserTimeline)
4195 if (MyCommon.IsKeyDown(Keys.Control))
4196 OpenUriAsync(e.Url.OriginalString);
4198 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4202 if (MyCommon.IsKeyDown(Keys.Control))
4203 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4205 OpenUriAsync(e.Url.OriginalString);
4210 OpenUriAsync(e.Url.OriginalString);
4216 public void AddNewTabForSearch(string searchWord)
4218 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4219 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4221 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4223 foreach (TabPage tp in ListTab.TabPages)
4225 if (tb.TabName == tp.Text)
4227 ListTab.SelectedTab = tp;
4234 string tabName = searchWord;
4235 for (int i = 0; i <= 100; i++)
4237 if (_statuses.ContainsTab(tabName))
4243 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4244 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4246 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4248 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4249 cmb.Items.Add(searchWord);
4250 cmb.Text = searchWord;
4253 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4256 private void ShowUserTimeline()
4258 if (!this.ExistCurrentPost) return;
4259 AddNewTabForUserTimeline(_curPost.ScreenName);
4262 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4264 if (e.KeyCode == Keys.Escape)
4266 TabPage relTp = ListTab.SelectedTab;
4267 RemoveSpecifiedTab(relTp.Text, false);
4269 e.SuppressKeyPress = true;
4273 public void AddNewTabForUserTimeline(string user)
4275 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4276 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4278 if (tb.User == user)
4280 foreach (TabPage tp in ListTab.TabPages)
4282 if (tb.TabName == tp.Text)
4284 ListTab.SelectedTab = tp;
4291 string tabName = "user:" + user;
4292 while (_statuses.ContainsTab(tabName))
4297 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4298 _statuses.Tabs[tabName].User = user;
4299 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4301 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4305 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, tabName);
4308 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4311 foreach (TabPage tb in ListTab.TabPages)
4313 if (tb.Text == tabName) return false;
4317 if (tabName == Properties.Resources.AddNewTabText1) return false;
4322 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4323 tabType == MyCommon.TabUsageType.Favorites ||
4324 tabType == MyCommon.TabUsageType.Home ||
4325 tabType == MyCommon.TabUsageType.Mentions ||
4326 tabType == MyCommon.TabUsageType.Related)
4328 if (_statuses.GetTabByType(tabType) != null) return false;
4332 TabPage _tabPage = new TabPage();
4333 DetailsListView _listCustom = new DetailsListView();
4335 int cnt = ListTab.TabPages.Count;
4337 ///ToDo:Create and set controls follow tabtypes
4339 using (ControlTransaction.Update(_listCustom))
4340 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4341 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4342 using (ControlTransaction.Layout(this.SplitContainer1, false))
4343 using (ControlTransaction.Layout(this.ListTab, false))
4344 using (ControlTransaction.Layout(this))
4345 using (ControlTransaction.Layout(_tabPage, false))
4349 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4351 label = new Label();
4352 label.Dock = DockStyle.Top;
4353 label.Name = "labelUser";
4354 if (tabType == MyCommon.TabUsageType.Lists)
4356 label.Text = listInfo.ToString();
4360 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4362 label.TextAlign = ContentAlignment.MiddleLeft;
4363 using (ComboBox tmpComboBox = new ComboBox())
4365 label.Height = tmpComboBox.Height;
4367 _tabPage.Controls.Add(label);
4372 if (tabType == MyCommon.TabUsageType.PublicSearch)
4376 Label lbl = new Label();
4377 ComboBox cmb = new ComboBox();
4378 Button btn = new Button();
4379 ComboBox cmbLang = new ComboBox();
4381 pnl.SuspendLayout();
4383 pnl.Controls.Add(cmb);
4384 pnl.Controls.Add(cmbLang);
4385 pnl.Controls.Add(btn);
4386 pnl.Controls.Add(lbl);
4387 pnl.Name = "panelSearch";
4388 pnl.Dock = DockStyle.Top;
4389 pnl.Height = cmb.Height;
4390 pnl.Enter += SearchControls_Enter;
4391 pnl.Leave += SearchControls_Leave;
4394 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4395 cmb.Dock = DockStyle.Fill;
4396 cmb.Name = "comboSearch";
4397 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4398 cmb.ImeMode = ImeMode.NoControl;
4399 cmb.TabStop = false;
4400 cmb.AutoCompleteMode = AutoCompleteMode.None;
4401 cmb.KeyDown += SearchComboBox_KeyDown;
4403 if (_statuses.ContainsTab(tabName))
4405 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4406 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4410 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4411 cmbLang.Dock = DockStyle.Right;
4413 cmbLang.Name = "comboLang";
4414 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4415 cmbLang.TabStop = false;
4416 cmbLang.Items.Add("");
4417 cmbLang.Items.Add("ja");
4418 cmbLang.Items.Add("en");
4419 cmbLang.Items.Add("ar");
4420 cmbLang.Items.Add("da");
4421 cmbLang.Items.Add("nl");
4422 cmbLang.Items.Add("fa");
4423 cmbLang.Items.Add("fi");
4424 cmbLang.Items.Add("fr");
4425 cmbLang.Items.Add("de");
4426 cmbLang.Items.Add("hu");
4427 cmbLang.Items.Add("is");
4428 cmbLang.Items.Add("it");
4429 cmbLang.Items.Add("no");
4430 cmbLang.Items.Add("pl");
4431 cmbLang.Items.Add("pt");
4432 cmbLang.Items.Add("ru");
4433 cmbLang.Items.Add("es");
4434 cmbLang.Items.Add("sv");
4435 cmbLang.Items.Add("th");
4436 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4438 lbl.Text = "Search(C-S-f)";
4439 lbl.Name = "label1";
4440 lbl.Dock = DockStyle.Left;
4442 lbl.Height = cmb.Height;
4443 lbl.TextAlign = ContentAlignment.MiddleLeft;
4445 btn.Text = "Search";
4446 btn.Name = "buttonSearch";
4447 btn.UseVisualStyleBackColor = true;
4448 btn.Dock = DockStyle.Right;
4449 btn.TabStop = false;
4450 btn.Click += SearchButton_Click;
4453 this.ListTab.Controls.Add(_tabPage);
4454 _tabPage.Controls.Add(_listCustom);
4456 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4457 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4459 _tabPage.Location = new Point(4, 4);
4460 _tabPage.Name = "CTab" + cnt.ToString();
4461 _tabPage.Size = new Size(380, 260);
4462 _tabPage.TabIndex = 2 + cnt;
4463 _tabPage.Text = tabName;
4464 _tabPage.UseVisualStyleBackColor = true;
4466 _listCustom.AllowColumnReorder = true;
4467 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4468 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4469 _listCustom.Dock = DockStyle.Fill;
4470 _listCustom.FullRowSelect = true;
4471 _listCustom.HideSelection = false;
4472 _listCustom.Location = new Point(0, 0);
4473 _listCustom.Margin = new Padding(0);
4474 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4475 _listCustom.ShowItemToolTips = true;
4476 _listCustom.Size = new Size(380, 260);
4477 _listCustom.UseCompatibleStateImageBehavior = false;
4478 _listCustom.View = View.Details;
4479 _listCustom.OwnerDraw = true;
4480 _listCustom.VirtualMode = true;
4481 _listCustom.Font = _fntReaded;
4482 _listCustom.BackColor = _clListBackcolor;
4484 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4485 _listCustom.AllowDrop = true;
4487 _listCustom.SmallImageList = _listViewImageList;
4489 InitColumns(_listCustom, startup);
4491 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4492 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4493 _listCustom.ColumnClick += MyList_ColumnClick;
4494 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4495 _listCustom.DragDrop += TweenMain_DragDrop;
4496 _listCustom.DragEnter += TweenMain_DragEnter;
4497 _listCustom.DragOver += TweenMain_DragOver;
4498 _listCustom.DrawItem += MyList_DrawItem;
4499 _listCustom.MouseClick += MyList_MouseClick;
4500 _listCustom.ColumnReordered += MyList_ColumnReordered;
4501 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4502 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4503 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4504 _listCustom.DrawSubItem += MyList_DrawSubItem;
4505 _listCustom.HScrolled += MyList_HScrolled;
4507 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4510 _tabPage.Tag = _listCustom;
4514 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4516 if (_statuses.IsDefaultTab(TabName) || _statuses.Tabs[TabName].Protected) return false;
4520 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4521 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4522 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4528 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault<TabPage>(tp => tp.Text == TabName);
4529 if (_tabPage == null) return false;
4531 SetListProperty(); //他のタブに列幅等を反映
4533 MyCommon.TabUsageType tabType = _statuses.Tabs[TabName].TabType;
4536 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4537 _tabPage.Tag = null;
4539 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4540 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4541 using (ControlTransaction.Layout(this.SplitContainer1, false))
4542 using (ControlTransaction.Layout(this.ListTab, false))
4543 using (ControlTransaction.Layout(this))
4544 using (ControlTransaction.Layout(_tabPage, false))
4546 if (this.ListTab.SelectedTab == _tabPage)
4548 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4549 this._beforeSelectedTab = null;
4551 this.ListTab.Controls.Remove(_tabPage);
4554 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4556 using (Control label = _tabPage.Controls["labelUser"])
4558 _tabPage.Controls.Remove(label);
4561 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4563 using (Control pnl = _tabPage.Controls["panelSearch"])
4565 pnl.Enter -= SearchControls_Enter;
4566 pnl.Leave -= SearchControls_Leave;
4567 _tabPage.Controls.Remove(pnl);
4569 foreach (Control ctrl in pnl.Controls)
4571 if (ctrl.Name == "buttonSearch")
4573 ctrl.Click -= SearchButton_Click;
4575 else if (ctrl.Name == "comboSearch")
4577 ctrl.KeyDown -= SearchComboBox_KeyDown;
4579 pnl.Controls.Remove(ctrl);
4585 _tabPage.Controls.Remove(_listCustom);
4587 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4588 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4589 _listCustom.ColumnClick -= MyList_ColumnClick;
4590 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4591 _listCustom.DragDrop -= TweenMain_DragDrop;
4592 _listCustom.DragEnter -= TweenMain_DragEnter;
4593 _listCustom.DragOver -= TweenMain_DragOver;
4594 _listCustom.DrawItem -= MyList_DrawItem;
4595 _listCustom.MouseClick -= MyList_MouseClick;
4596 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4597 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4598 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4599 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4600 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4601 _listCustom.HScrolled -= MyList_HScrolled;
4603 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4604 _listCustom.Columns.Clear();
4605 cols.ForEach(col => col.Dispose());
4608 _listCustom.ContextMenuStrip = null;
4609 _listCustom.ColumnHeaderContextMenuStrip = null;
4610 _listCustom.Font = null;
4612 _listCustom.SmallImageList = null;
4613 _listCustom.ListViewItemSorter = null;
4616 if (_curTab.Equals(_tabPage))
4623 this.PurgeListViewItemCache();
4627 _listCustom.Dispose();
4628 _statuses.RemoveTab(TabName);
4630 foreach (TabPage tp in ListTab.TabPages)
4632 DetailsListView lst = (DetailsListView)tp.Tag;
4633 var count = _statuses.Tabs[tp.Text].AllCount;
4634 if (lst.VirtualListSize != count)
4636 lst.VirtualListSize = count;
4643 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4645 this.PurgeListViewItemCache();
4646 _beforeSelectedTab = e.TabPage;
4649 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4653 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4656 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4657 if (!dragEnableRectangle.Contains(e.Location))
4659 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4660 tn = ListTab.SelectedTab.Text;
4663 if (string.IsNullOrEmpty(tn)) return;
4665 foreach (TabPage tb in ListTab.TabPages)
4669 ListTab.DoDragDrop(tb, DragDropEffects.All);
4679 Point cpos = new Point(e.X, e.Y);
4680 for (int i = 0; i < ListTab.TabPages.Count; i++)
4682 Rectangle rect = ListTab.GetTabRect(i);
4683 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4684 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4686 _rclickTabName = ListTab.TabPages[i].Text;
4692 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4694 //_curList.Refresh();
4696 SetMainWindowTitle();
4697 SetStatusLabelUrl();
4698 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4699 TabMenuControl(ListTab.SelectedTab.Text);
4700 this.PushSelectPostChain();
4703 private void SetListProperty()
4705 //削除などで見つからない場合は処理せず
4706 if (_curList == null) return;
4707 if (!_isColumnChanged) return;
4709 int[] dispOrder = new int[_curList.Columns.Count];
4710 for (int i = 0; i < _curList.Columns.Count; i++)
4712 for (int j = 0; j < _curList.Columns.Count; j++)
4714 if (_curList.Columns[j].DisplayIndex == i)
4723 foreach (TabPage tb in ListTab.TabPages)
4725 if (!tb.Equals(_curTab))
4727 if (tb.Tag != null && tb.Controls.Count > 0)
4729 DetailsListView lst = (DetailsListView)tb.Tag;
4730 for (int i = 0; i < lst.Columns.Count; i++)
4732 lst.Columns[dispOrder[i]].DisplayIndex = i;
4733 lst.Columns[i].Width = _curList.Columns[i].Width;
4739 _isColumnChanged = false;
4742 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4746 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
4747 || PostBrowser.StatusText.StartsWith("data"))
4749 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4751 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4753 SetStatusLabelUrl();
4761 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4763 if (e.KeyChar == '@')
4765 if (!this._cfgCommon.UseAtIdSupplement) return;
4767 int cnt = AtIdSupl.ItemCount;
4768 ShowSuplDialog(StatusText, AtIdSupl);
4769 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
4772 else if (e.KeyChar == '#')
4774 if (!this._cfgCommon.UseHashSupplement) return;
4775 ShowSuplDialog(StatusText, HashSupl);
4780 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4782 ShowSuplDialog(owner, dialog, 0, "");
4785 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4787 ShowSuplDialog(owner, dialog, offset, "");
4790 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4792 dialog.StartsWith = startswith;
4799 dialog.ShowDialog();
4801 this.TopMost = this._cfgCommon.AlwaysTop;
4802 int selStart = owner.SelectionStart;
4805 if (dialog.DialogResult == DialogResult.OK)
4807 if (!string.IsNullOrEmpty(dialog.inputText))
4811 fHalf = owner.Text.Substring(0, selStart - offset);
4813 if (selStart < owner.Text.Length)
4815 eHalf = owner.Text.Substring(selStart);
4817 owner.Text = fHalf + dialog.inputText + eHalf;
4818 owner.SelectionStart = selStart + dialog.inputText.Length;
4825 fHalf = owner.Text.Substring(0, selStart);
4827 if (selStart < owner.Text.Length)
4829 eHalf = owner.Text.Substring(selStart);
4831 owner.Text = fHalf + eHalf;
4834 owner.SelectionStart = selStart;
4840 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4843 if (!e.Alt && !e.Control && !e.Shift)
4845 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4847 bool isSpace = false;
4848 foreach (char c in StatusText.Text.ToCharArray())
4850 if (c == ' ' || c == ' ')
4863 StatusText.Text = "";
4864 JumpUnreadMenuItem_Click(null, null);
4868 this.StatusText_TextChanged(null, null);
4871 private void StatusText_TextChanged(object sender, EventArgs e)
4874 int pLen = GetRestStatusCount(true, false);
4875 lblLen.Text = pLen.ToString();
4878 StatusText.ForeColor = Color.Red;
4882 StatusText.ForeColor = _clInputFont;
4884 if (string.IsNullOrEmpty(StatusText.Text))
4886 _reply_to_id = null;
4887 _reply_to_name = null;
4891 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
4894 var statusText = this.StatusText.Text;
4895 statusText = statusText.Replace("\r\n", "\n");
4897 int pLen = 140 - statusText.Length;
4898 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
4899 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && this._cfgCommon.PostShiftEnter) ||
4900 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !this._cfgCommon.PostShiftEnter) ||
4901 (!isAuto && isAddFooter))
4903 if (this._cfgLocal.UseRecommendStatus)
4904 pLen -= SettingDialog.RecommendStatusText.Length;
4905 else if (this._cfgLocal.StatusText.Length > 0)
4906 pLen -= this._cfgLocal.StatusText.Length + 1;
4908 if (!string.IsNullOrEmpty(HashMgr.UseHash))
4910 pLen -= HashMgr.UseHash.Length + 1;
4912 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
4914 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4916 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
4918 string before = m.Result("${before}");
4919 string url = m.Result("${url}");
4920 string protocol = m.Result("${protocol}");
4921 string domain = m.Result("${domain}");
4922 string path = m.Result("${path}");
4923 if (protocol.Length == 0)
4925 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
4930 bool last_url_invalid_match = false;
4931 string lasturl = null;
4932 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
4934 lasturl = mm.ToString();
4935 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
4936 if (!last_url_invalid_match)
4938 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4942 if (path.Length != 0)
4944 if (last_url_invalid_match)
4946 pLen += lasturl.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4948 pLen += path.Length;
4953 int shortUrlLength = protocol == "https://"
4954 ? SettingDialog.TwitterConfiguration.ShortUrlLengthHttps
4955 : SettingDialog.TwitterConfiguration.ShortUrlLength;
4957 pLen += url.Length - shortUrlLength;
4960 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
4962 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
4965 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
4967 pLen -= SettingDialog.TwitterConfiguration.CharactersReservedPerMedia;
4972 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4974 this.itemCacheLock.EnterUpgradeableReadLock();
4977 if (_curList.Equals(sender))
4979 if (_itemCache != null &&
4980 e.StartIndex >= _itemCacheIndex &&
4981 e.EndIndex < _itemCacheIndex + _itemCache.Length)
4983 //If the newly requested cache is a subset of the old cache,
4984 //no need to rebuild everything, so do nothing.
4988 //Now we need to rebuild the cache.
4989 CreateCache(e.StartIndex, e.EndIndex);
4992 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
4995 private async void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4997 ListViewItem item = null;
4998 PostClass cacheItemPost = null;
5000 if (_curList.Equals(sender))
5001 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5005 //A cache miss, so create a new ListViewItem and pass it back.
5006 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5009 item = this.CreateItem(tb, _statuses[tb.Text, e.ItemIndex], e.ItemIndex);
5014 string[] sitem = {"", "", "", "", "", "", "", ""};
5015 item = new ImageListViewItem(sitem);
5019 // e.Item に値をセットする前に await しないこと
5022 await ((ImageListViewItem)item).GetImageAsync();
5025 private void CreateCache(int StartIndex, int EndIndex)
5027 this.itemCacheLock.EnterWriteLock();
5030 var tabInfo = _statuses.Tabs[_curTab.Text];
5032 //キャッシュ要求(要求範囲±30を作成)
5034 if (StartIndex < 0) StartIndex = 0;
5036 if (EndIndex >= tabInfo.AllCount) EndIndex = tabInfo.AllCount - 1;
5037 _postCache = tabInfo[StartIndex, EndIndex]; //配列で取得
5038 _itemCacheIndex = StartIndex;
5040 _itemCache = new ListViewItem[0] {};
5041 Array.Resize(ref _itemCache, _postCache.Length);
5043 for (int i = 0; i < _postCache.Length; i++)
5045 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5050 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5052 _itemCacheIndex = -1;
5055 finally { this.itemCacheLock.ExitWriteLock(); }
5059 /// DetailsListView のための ListViewItem のキャッシュを消去する
5061 private void PurgeListViewItemCache()
5063 this.itemCacheLock.EnterWriteLock();
5066 this._itemCache = null;
5067 this._itemCacheIndex = -1;
5068 this._postCache = null;
5070 finally { this.itemCacheLock.ExitWriteLock(); }
5073 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5075 this.itemCacheLock.EnterReadLock();
5078 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5080 item = this._itemCache[index - _itemCacheIndex];
5081 post = this._postCache[index - _itemCacheIndex];
5085 finally { this.itemCacheLock.ExitReadLock(); }
5092 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5094 StringBuilder mk = new StringBuilder();
5095 //if (Post.IsDeleted) mk.Append("×");
5096 //if (Post.IsMark) mk.Append("♪");
5097 //if (Post.IsProtect) mk.Append("Ю");
5098 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5099 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5100 ImageListViewItem itm;
5101 if (Post.RetweetedId == null)
5103 string[] sitem= {"",
5105 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5106 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5111 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5115 string[] sitem = {"",
5117 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5118 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5119 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5123 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5125 itm.StateIndex = Post.StateIndex;
5127 bool read = Post.IsRead;
5128 //未読管理していなかったら既読として扱う
5129 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5130 ChangeItemStyleRead(read, itm, Post, null);
5131 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5136 /// 全てのタブの振り分けルールを反映し直します
5138 private void ApplyPostFilters()
5142 this.Cursor = Cursors.WaitCursor;
5144 this.PurgeListViewItemCache();
5145 this._curPost = null;
5146 this._curItemIndex = -1;
5147 this._statuses.FilterAll();
5149 foreach (TabPage tabPage in this.ListTab.TabPages)
5151 var tab = this._statuses.Tabs[tabPage.Text];
5153 var listview = (DetailsListView)tabPage.Tag;
5154 listview.VirtualListSize = tab.AllCount;
5156 if (this._cfgCommon.TabIconDisp)
5158 if (tab.UnreadCount > 0)
5159 tabPage.ImageIndex = 0;
5161 tabPage.ImageIndex = -1;
5165 if (!this._cfgCommon.TabIconDisp)
5166 this.ListTab.Refresh();
5170 this.Cursor = Cursors.Default;
5174 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5176 e.DrawDefault = true;
5179 private void MyList_HScrolled(object sender, EventArgs e)
5181 DetailsListView listView = (DetailsListView)sender;
5185 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5187 if (e.State == 0) return;
5188 e.DrawDefault = false;
5190 SolidBrush brs2 = null;
5191 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5193 if (e.Item.BackColor == _clSelf)
5194 brs2 = _brsBackColorMine;
5195 else if (e.Item.BackColor == _clAtSelf)
5196 brs2 = _brsBackColorAt;
5197 else if (e.Item.BackColor == _clTarget)
5198 brs2 = _brsBackColorYou;
5199 else if (e.Item.BackColor == _clAtTarget)
5200 brs2 = _brsBackColorAtYou;
5201 else if (e.Item.BackColor == _clAtFromTarget)
5202 brs2 = _brsBackColorAtFromTarget;
5203 else if (e.Item.BackColor == _clAtTo)
5204 brs2 = _brsBackColorAtTo;
5206 brs2 = _brsBackColorNone;
5211 if (((Control)sender).Focused)
5212 brs2 = _brsHighLight;
5214 brs2 = _brsDeactiveSelection;
5216 e.Graphics.FillRectangle(brs2, e.Bounds);
5217 e.DrawFocusRectangle();
5218 this.DrawListViewItemIcon(e);
5221 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5223 if (e.ItemState == 0) return;
5225 if (e.ColumnIndex > 0)
5228 RectangleF rct = e.Bounds;
5229 rct.Width = e.Header.Width;
5230 int fontHeight = e.Item.Font.Height;
5233 rct.Y += fontHeight;
5234 rct.Height -= fontHeight;
5238 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5240 //if (heightDiff > fontHeight * 0.7)
5242 // rct.Height += fontHeight;
5243 // drawLineCount += 1;
5246 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5247 if (!_iconCol && drawLineCount <= 1)
5249 //rct.Inflate(0, heightDiff / -2);
5250 //rct.Height += fontHeight / 2;
5252 else if (heightDiff < fontHeight * 0.7)
5254 //最終行が70%以上欠けていたら、最終行は表示しない
5255 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5256 rct.Height = (fontHeight * drawLineCount) - 1;
5263 //if (!_iconCol && drawLineCount > 1)
5265 // rct.Y += fontHeight * 0.2;
5266 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5271 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5272 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5277 Rectangle rctB = e.Bounds;
5278 rctB.Width = e.Header.Width;
5279 rctB.Height = fontHeight;
5281 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5283 TextRenderer.DrawText(e.Graphics,
5284 e.Item.SubItems[2].Text,
5286 Rectangle.Round(rct),
5288 TextFormatFlags.WordBreak |
5289 TextFormatFlags.EndEllipsis |
5290 TextFormatFlags.GlyphOverhangPadding |
5291 TextFormatFlags.NoPrefix);
5292 TextRenderer.DrawText(e.Graphics,
5293 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 + "]",
5297 TextFormatFlags.SingleLine |
5298 TextFormatFlags.EndEllipsis |
5299 TextFormatFlags.GlyphOverhangPadding |
5300 TextFormatFlags.NoPrefix);
5303 else if (drawLineCount == 1)
5305 TextRenderer.DrawText(e.Graphics,
5308 Rectangle.Round(rct),
5310 TextFormatFlags.SingleLine |
5311 TextFormatFlags.EndEllipsis |
5312 TextFormatFlags.GlyphOverhangPadding |
5313 TextFormatFlags.NoPrefix |
5314 TextFormatFlags.VerticalCenter);
5318 TextRenderer.DrawText(e.Graphics,
5321 Rectangle.Round(rct),
5323 TextFormatFlags.WordBreak |
5324 TextFormatFlags.EndEllipsis |
5325 TextFormatFlags.GlyphOverhangPadding |
5326 TextFormatFlags.NoPrefix);
5328 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5333 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5335 if (_iconSz == 0) return;
5337 ImageListViewItem item = (ImageListViewItem)e.Item;
5339 //e.Bounds.Leftが常に0を指すから自前で計算
5340 Rectangle itemRect = item.Bounds;
5341 var col0 = e.Item.ListView.Columns[0];
5342 itemRect.Width = col0.Width;
5344 if (col0.DisplayIndex > 0)
5346 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5348 if (clm.DisplayIndex < col0.DisplayIndex)
5349 itemRect.X += clm.Width;
5353 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5354 var realIconSize = new SizeF(this._iconSz * this.currentScaleFactor.Width, this._iconSz * this.currentScaleFactor.Height).ToSize();
5355 var realStateSize = new SizeF(16 * this.currentScaleFactor.Width, 16 * this.currentScaleFactor.Height).ToSize();
5358 var img = item.Image;
5361 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5362 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5364 if (iconRect.Width > 0)
5366 e.Graphics.FillRectangle(Brushes.White, iconRect);
5367 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5370 e.Graphics.DrawImage(img.Image, iconRect);
5372 catch (ArgumentException)
5374 item.RefreshImageAsync();
5380 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5381 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5384 if (item.StateIndex > -1)
5386 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5387 if (stateRect.Width > 0)
5389 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5390 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5391 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5396 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5398 base.ScaleControl(factor, specified);
5400 const int baseDpi = 96;
5402 // デザイン時の DPI (96dpi) との比を更新する
5403 this.currentScaleFactor = new SizeF(
5404 this.CurrentAutoScaleDimensions.Width / baseDpi,
5405 this.CurrentAutoScaleDimensions.Height / baseDpi);
5408 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5410 // ImageListViewItem item = (ImageListViewItem)e.Item;
5411 // if (item.StateImageIndex > -1)
5413 // ////e.Bounds.Leftが常に0を指すから自前で計算
5414 // //Rectangle itemRect = item.Bounds;
5415 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5417 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5419 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5421 // // itemRect.X += clm.Width;
5425 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5426 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5428 // if (rct.Width > 0)
5430 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5431 // //e.Graphics.FillRectangle(Brushes.White, rct);
5432 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5433 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5438 private void DoTabSearch(string _word,
5448 if (_curList.VirtualListSize == 0)
5450 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5453 if (_curList.SelectedIndices.Count > 0)
5455 cidx = _curList.SelectedIndices[0];
5457 toIdx = _curList.VirtualListSize;
5461 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5462 if (_curList.SelectedIndices.Count > 0)
5463 cidx = _curList.SelectedIndices[0];
5467 case SEARCHTYPE.NextSearch: //次を検索
5468 if (_curList.SelectedIndices.Count > 0)
5470 cidx = _curList.SelectedIndices[0] + 1;
5471 if (cidx > toIdx) cidx = toIdx;
5478 case SEARCHTYPE.PrevSearch: //前を検索
5479 if (_curList.SelectedIndices.Count > 0)
5481 cidx = _curList.SelectedIndices[0] - 1;
5482 if (cidx < 0) cidx = 0;
5493 RegexOptions regOpt = RegexOptions.None;
5494 StringComparison fndOpt = StringComparison.Ordinal;
5497 regOpt = RegexOptions.IgnoreCase;
5498 fndOpt = StringComparison.OrdinalIgnoreCase;
5509 _search = new Regex(_word, regOpt);
5510 for (int idx = cidx; idx != toIdx; idx += stp)
5515 post = _statuses[_curTab.Text, idx];
5521 if (_search.IsMatch(post.Nickname)
5522 || _search.IsMatch(post.TextFromApi)
5523 || _search.IsMatch(post.ScreenName))
5525 SelectListItem(_curList, idx);
5526 _curList.EnsureVisible(idx);
5531 catch (ArgumentException)
5533 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5540 for (int idx = cidx; idx != toIdx; idx += stp)
5545 post = _statuses[_curTab.Text, idx];
5551 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5552 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5553 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5555 SelectListItem(_curList, idx);
5556 _curList.EnsureVisible(idx);
5566 case SEARCHTYPE.DialogSearch:
5567 case SEARCHTYPE.NextSearch:
5571 case SEARCHTYPE.PrevSearch:
5573 cidx = _curList.VirtualListSize - 1;
5580 catch (ArgumentOutOfRangeException)
5583 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5586 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5589 this.ShowSearchDialog();
5592 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5594 var previousSearch = this.SearchDialog.ResultOptions;
5595 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5597 this.SearchDialog.Reset();
5598 this.ShowSearchDialog();
5604 previousSearch.Query,
5605 previousSearch.CaseSensitive,
5606 previousSearch.UseRegex,
5607 SEARCHTYPE.NextSearch);
5610 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5612 var previousSearch = this.SearchDialog.ResultOptions;
5613 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5615 this.SearchDialog.Reset();
5616 this.ShowSearchDialog();
5622 previousSearch.Query,
5623 previousSearch.CaseSensitive,
5624 previousSearch.UseRegex,
5625 SEARCHTYPE.PrevSearch);
5629 /// 検索ダイアログを表示し、検索を実行します
5631 private void ShowSearchDialog()
5633 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5634 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5635 this.SearchDialog.DisableNewTabButton = false;
5637 this.SearchDialog.DisableNewTabButton = true;
5639 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5641 this.TopMost = this._cfgCommon.AlwaysTop;
5644 this.TopMost = this._cfgCommon.AlwaysTop;
5646 var searchOptions = this.SearchDialog.ResultOptions;
5647 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5649 if (searchOptions.NewTab)
5651 var tabName = searchOptions.Query;
5655 tabName = this._statuses.MakeTabName(tabName);
5657 catch (TabException ex)
5659 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5662 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5663 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5665 var filter = new PostFilterRule
5667 FilterBody = new[] { searchOptions.Query },
5668 UseRegex = searchOptions.UseRegex,
5669 CaseSensitive = searchOptions.CaseSensitive,
5671 this._statuses.Tabs[tabName].AddFilter(filter);
5673 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5674 .First(x => x.Text == tabName);
5676 this.ListTab.SelectedTab = tabPage;
5677 this.ListTabSelect(tabPage);
5679 this.ApplyPostFilters();
5680 this.SaveConfigsTabs();
5685 searchOptions.Query,
5686 searchOptions.CaseSensitive,
5687 searchOptions.UseRegex,
5688 SEARCHTYPE.DialogSearch);
5691 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5693 this.AddNewTabForSearch(searchOptions.Query);
5697 private void AboutMenuItem_Click(object sender, EventArgs e)
5699 using (TweenAboutBox about = new TweenAboutBox())
5701 about.ShowDialog(this);
5703 this.TopMost = this._cfgCommon.AlwaysTop;
5706 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5708 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5710 DetailsListView lst = null;
5712 if (ImageSelector.Enabled)
5716 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5719 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5722 ListTab.SelectedIndex = i;
5723 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5724 //_curTab = ListTab.TabPages[i];
5729 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5730 if (idx == -1 && bgnIdx > 0)
5732 for (int i = 0; i < bgnIdx; i++)
5734 idx = _statuses.GetOldestUnreadIndex(ListTab.TabPages[i].Text);
5737 ListTab.SelectedIndex = i;
5738 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5739 //_curTab = ListTab.TabPages[i];
5745 //全部調べたが未読見つからず→先頭タブの最新発言へ
5748 ListTab.SelectedIndex = 0;
5749 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5750 //_curTab = ListTab.TabPages[0];
5751 if (_statuses.SortOrder == SortOrder.Ascending)
5752 idx = lst.VirtualListSize - 1;
5757 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5759 SelectListItem(lst, idx);
5760 if (_statuses.SortMode == IdComparerClass.ComparerMode.Id)
5762 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5763 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5769 lst.EnsureVisible(idx);
5774 lst.EnsureVisible(idx);
5780 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
5782 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5784 var post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5785 OpenUriAsync(MyCommon.GetStatusUrl(post));
5789 private void FavorareMenuItem_Click(object sender, EventArgs e)
5791 if (_curList.SelectedIndices.Count > 0)
5793 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[0]];
5794 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5798 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5800 await this.CheckNewVersion(false);
5803 private void RunTweenUp()
5805 ProcessStartInfo pinfo = new ProcessStartInfo();
5806 pinfo.UseShellExecute = true;
5807 pinfo.WorkingDirectory = MyCommon.settingPath;
5808 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5809 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5812 Process.Start(pinfo);
5816 MessageBox.Show("Failed to execute TweenUp3.exe.");
5820 public class VersionInfo
5822 public Version Version { get; set; }
5823 public Uri DownloadUri { get; set; }
5824 public string ReleaseNote { get; set; }
5828 /// OpenTween の最新バージョンの情報を取得します
5830 public async Task<VersionInfo> GetVersionInfoAsync()
5832 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5833 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5835 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5836 .ConfigureAwait(false);
5838 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5839 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5841 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5842 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5844 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5846 return new VersionInfo
5848 Version = Version.Parse(msgHeader[0]),
5849 DownloadUri = new Uri(msgHeader[1]),
5850 ReleaseNote = msgBody,
5854 private async Task CheckNewVersion(bool startup = false)
5856 if (ApplicationSettings.VersionInfoUrl == null)
5857 return; // 更新チェック無効化
5861 var versionInfo = await this.GetVersionInfoAsync();
5863 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5868 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5869 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5870 msgtext = MyCommon.ReplaceAppName(msgtext);
5872 MessageBox.Show(msgtext,
5873 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5874 MessageBoxButtons.OK, MessageBoxIcon.Information);
5879 using (var dialog = new UpdateDialog())
5881 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5882 MyCommon.GetReadableVersion(versionInfo.Version));
5883 dialog.DetailsText = versionInfo.ReleaseNote;
5885 if (dialog.ShowDialog(this) == DialogResult.Yes)
5887 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
5893 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5896 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5897 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5898 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5903 private void Colorize()
5907 //件数関連の場合、タイトル即時書き換え
5908 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5909 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5910 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5911 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5913 SetMainWindowTitle();
5915 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
5916 foreach (TabPage tb in ListTab.TabPages)
5918 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5920 if (this._cfgCommon.TabIconDisp)
5922 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5926 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5929 public string createDetailHtml(string orgdata)
5931 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5934 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
5936 if (sender.Equals(displayItem))
5938 this.ClearUserPicture();
5940 var img = displayItem.Image;
5944 img = await img.CloneAsync();
5946 UserPicture.Image = img;
5950 UserPicture.ShowErrorImage();
5955 private void DispSelectedPost()
5957 DispSelectedPost(false);
5960 private PostClass displayPost = new PostClass();
5963 /// サムネイルの表示処理を表すタスク
5965 private Task thumbnailTask = null;
5968 /// サムネイル表示に使用する CancellationToken の生成元
5970 private CancellationTokenSource thumbnailTokenSource = null;
5972 private void DispSelectedPost(bool forceupdate)
5974 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5977 var oldDisplayPost = this.displayPost;
5978 this.displayPost = this._curPost;
5980 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5983 if (displayItem != null)
5985 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
5988 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
5989 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
5991 using (ControlTransaction.Update(this.TableLayoutPanel1))
5993 var sourceText = "";
5994 string sourceUrl = null;
5997 var mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6000 var src = mc.Groups["sourceurl"].Value;
6001 if (Regex.IsMatch(src, "^https?://"))
6004 sourceUrl = "https://twitter.com/" + src;
6007 if (_curPost.Source != null)
6008 sourceText = _curPost.Source;
6010 SourceLinkLabel.Text = sourceText;
6011 SourceLinkLabel.Tag = sourceUrl;
6012 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6018 nameText = "DM FROM <- ";
6020 nameText = "DM TO -> ";
6026 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6027 if (_curPost.RetweetedId != null)
6028 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6030 NameLabel.Text = nameText;
6031 NameLabel.Tag = _curPost.ScreenName;
6033 var nameForeColor = SystemColors.ControlText;
6034 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6035 nameForeColor = this._clOWL;
6036 if (_curPost.RetweetedId != null)
6037 nameForeColor = this._clRetweet;
6039 nameForeColor = this._clFav;
6040 NameLabel.ForeColor = nameForeColor;
6042 this.ClearUserPicture();
6044 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6046 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6049 UserPicture.Image = image != null ? image.Clone() : null;
6053 UserPicture.ShowErrorImage();
6057 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6059 if (DumpPostClassToolStripMenuItem.Checked)
6061 StringBuilder sb = new StringBuilder(512);
6063 sb.Append("-----Start PostClass Dump<br>");
6064 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6065 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6066 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6067 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6068 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6069 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6070 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6071 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6072 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6073 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6074 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6075 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6076 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6077 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6078 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6080 foreach (string nm in _curPost.ReplyToList)
6082 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6085 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6086 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6087 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6088 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6089 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6090 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6091 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6092 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6093 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6094 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6095 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6096 sb.Append("-----End PostClass Dump<br>");
6098 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6102 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6103 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6104 if (_curPost.StatusId != oldDisplayPost.StatusId)
6106 this.PostBrowser.DocumentText =
6107 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6109 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6111 this.SplitContainer3.Panel2Collapsed = true;
6113 if (this._cfgCommon.PreviewEnable)
6115 if (this.thumbnailTokenSource != null)
6117 var oldTokenSource = this.thumbnailTokenSource;
6119 var cancelTask = Task.Run(() => oldTokenSource.Cancel());
6121 Task.WhenAll(this.thumbnailTask, cancelTask)
6122 .ContinueWith(_ => oldTokenSource.Dispose(), TaskScheduler.Default);
6125 this.thumbnailTokenSource = new CancellationTokenSource();
6127 var token = this.thumbnailTokenSource.Token;
6128 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6135 private void MatomeMenuItem_Click(object sender, EventArgs e)
6137 OpenApplicationWebsite();
6140 private void OpenApplicationWebsite()
6142 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6145 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6147 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6150 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6152 if (ListTab.SelectedTab != null)
6154 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6156 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6157 if (pnl.Controls["comboSearch"].Focused ||
6158 pnl.Controls["comboLang"].Focused ||
6159 pnl.Controls["buttonSearch"].Focused) return;
6161 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6162 if (State == ModifierState.NotFlags) return;
6163 if (State != ModifierState.None) _anchorFlag = false;
6164 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6167 e.SuppressKeyPress = true;
6172 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6174 ModifierState state = ModifierState.None;
6175 if (sControl) state = state | ModifierState.Ctrl;
6176 if (sShift) state = state | ModifierState.Shift;
6177 if (sAlt) state = state | ModifierState.Alt;
6182 private enum ModifierState
6194 //PostBrowser = 102,
6198 private enum FocusedControl : int
6206 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6208 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6209 if (Focused == FocusedControl.ListTab)
6211 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6212 Modifier == ModifierState.Ctrl ||
6213 Modifier == ModifierState.None ||
6214 Modifier == ModifierState.Shift)
6216 if (KeyCode == Keys.J)
6218 SendKeys.Send("{DOWN}");
6221 else if (KeyCode == Keys.K)
6223 SendKeys.Send("{UP}");
6227 if (Modifier == ModifierState.Shift ||
6228 Modifier == ModifierState.None)
6230 if (KeyCode == Keys.F)
6232 SendKeys.Send("{PGDN}");
6235 else if (KeyCode == Keys.B)
6237 SendKeys.Send("{PGUP}");
6246 case ModifierState.None:
6251 OpenApplicationWebsite();
6254 MenuItemSearchNext_Click(null, null);
6260 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
6263 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
6266 if (Focused != FocusedControl.StatusText)
6272 case Keys.ProcessKey:
6273 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6274 JumpUnreadMenuItem_Click(null, null);
6277 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6278 ShowRelatedStatusesMenuItem_Click(null, null);
6282 if (Focused == FocusedControl.ListTab)
6295 case Keys.OemPeriod:
6299 if (this.StatusText.Enabled) this.StatusText.Focus();
6302 MakeReplyOrDirectStatus();
6309 _anchorFlag = false;
6329 // ] in_reply_to参照元へ戻る
6330 GoInReplyToPostTree();
6333 // [ in_reply_toへジャンプ
6334 GoBackInReplyToPostTree();
6337 if (ListTab.SelectedTab != null)
6339 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6340 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6342 TabPage relTp = ListTab.SelectedTab;
6343 RemoveSpecifiedTab(relTp.Text, false);
6351 else if (Focused == FocusedControl.PostBrowser)
6358 //スクロールを発生させるため、true を返す
6363 case ModifierState.Ctrl:
6368 MakeReplyOrDirectStatus(false, true);
6374 MakeReplyOrDirectStatus(false, false);
6377 FavoriteChange(true);
6380 doRepliedStatusOpen();
6386 ReadedStripMenuItem_Click(null, null);
6389 HashManageMenuItem_Click(null, null);
6392 UrlConvertAutoToolStripMenuItem_Click(null, null);
6395 if (Focused != FocusedControl.PostBrowser)
6397 MultiLineMenuItem_Click(null, null);
6402 MenuItemSubSearch_Click(null, null);
6409 MoveToHomeToolStripMenuItem_Click(null, null);
6413 MoveToFavToolStripMenuItem_Click(null, null);
6417 StatusOpenMenuItem_Click(null, null);
6421 OpenURLMenuItem_Click(null, null);
6425 if (Focused == FocusedControl.ListTab)
6432 return false; //スルーする
6450 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6451 int tabNo = KeyCode - Keys.D1;
6452 if (ListTab.TabPages.Count < tabNo)
6454 ListTab.SelectedIndex = tabNo;
6455 ListTabSelect(ListTab.TabPages[tabNo]);
6458 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6459 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
6463 else if (Focused == FocusedControl.StatusText)
6469 StatusText.SelectAll();
6473 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6475 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6477 if (KeyCode == Keys.Up)
6480 if (_hisIdx < 0) _hisIdx = 0;
6485 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6487 StatusText.Text = _history[_hisIdx].status;
6488 _reply_to_id = _history[_hisIdx].inReplyToId;
6489 _reply_to_name = _history[_hisIdx].inReplyToName;
6490 StatusText.SelectionStart = StatusText.Text.Length;
6494 if (ListTab.SelectedIndex == 0)
6496 ListTab.SelectedIndex = ListTab.TabCount - 1;
6500 ListTab.SelectedIndex -= 1;
6506 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6508 ListTab.SelectedIndex = 0;
6512 ListTab.SelectedIndex += 1;
6520 //フォーカスPostBrowserもしくは関係なし
6524 PostBrowser.Document.ExecCommand("SelectAll", false, null);
6528 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
6529 if (!string.IsNullOrEmpty(_selText))
6533 Clipboard.SetDataObject(_selText, false, 5, 100);
6535 catch (Exception ex)
6537 MessageBox.Show(ex.Message);
6542 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6543 MultiLineMenuItem_Click(null, null);
6548 case ModifierState.Shift:
6553 MenuItemSearchPrev_Click(null, null);
6559 GetTimeline(MyCommon.WORKERTYPE.Reply, -1, "");
6562 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, -1, "");
6566 if (Focused != FocusedControl.StatusText)
6568 if (KeyCode == Keys.R)
6575 if (Focused == FocusedControl.ListTab)
6595 GoBackInReplyToPostTree(true, false);
6598 GoBackInReplyToPostTree(true, true);
6602 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6607 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6611 this.GoBackSelectPostChain();
6616 case ModifierState.Alt:
6620 doReTweetOfficial(true);
6623 if (_curPost != null)
6625 doShowUserStatus(_curPost.ScreenName, false);
6630 ScrollDownPostBrowser(false);
6633 ScrollDownPostBrowser(true);
6636 PageDownPostBrowser(false);
6639 PageDownPostBrowser(true);
6642 if (Focused == FocusedControl.ListTab)
6644 // 別タブの同じ書き込みへ(ALT+←/→)
6645 if (KeyCode == Keys.Right)
6647 GoSamePostToAnotherTab(false);
6650 else if (KeyCode == Keys.Left)
6652 GoSamePostToAnotherTab(true);
6657 case ModifierState.Ctrl | ModifierState.Shift:
6661 MakeReplyOrDirectStatus(false, true, true);
6667 if (ListTab.SelectedTab != null)
6669 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6671 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
6677 FavoriteChange(false);
6680 UnreadStripMenuItem_Click(null, null);
6683 HashToggleMenuItem_Click(null, null);
6686 ImageSelectMenuItem_Click(null, null);
6692 FavorareMenuItem_Click(null, null);
6695 if (Focused == FocusedControl.StatusText)
6701 if (_curList != null && _curList.VirtualListSize != 0 &&
6702 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6704 idx = _curList.SelectedIndices[0] - 1;
6705 SelectListItem(_curList, idx);
6706 _curList.EnsureVisible(idx);
6711 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6712 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6714 idx = _curList.SelectedIndices[0] + 1;
6715 SelectListItem(_curList, idx);
6716 _curList.EnsureVisible(idx);
6721 if (StatusText.SelectionStart > 0)
6723 int endidx = StatusText.SelectionStart - 1;
6724 string startstr = "";
6725 bool pressed = false;
6726 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6728 char c = StatusText.Text[i];
6729 if (Char.IsLetterOrDigit(c) || c == '_')
6736 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6737 int cnt = AtIdSupl.ItemCount;
6738 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6739 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6744 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6745 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6757 else if (Focused == FocusedControl.ListTab)
6759 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
6771 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6772 int colNo = KeyCode - Keys.D1;
6773 if (lst.Columns.Count < colNo) return false;
6774 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
6775 if (col == null) return false;
6776 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6779 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
6780 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
6785 case ModifierState.Ctrl | ModifierState.Alt:
6786 if (KeyCode == Keys.S)
6788 FavoritesRetweetOriginal();
6791 else if (KeyCode == Keys.R)
6793 FavoritesRetweetUnofficial();
6796 else if (KeyCode == Keys.H)
6798 OpenUserAppointUrl();
6802 case ModifierState.Alt | ModifierState.Shift:
6803 if (Focused == FocusedControl.PostBrowser)
6805 if (KeyCode == Keys.R)
6806 doReTweetUnofficial();
6807 else if (KeyCode == Keys.C)
6814 if (!this.ExistCurrentPost) return false;
6815 doTranslation(_curPost.TextFromApi);
6818 doReTweetUnofficial();
6824 this.tweetThumbnail1.ScrollUp();
6827 this.tweetThumbnail1.ScrollDown();
6830 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
6832 if (!this.SplitContainer3.Panel2Collapsed)
6834 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
6844 private void ScrollDownPostBrowser(bool forward)
6846 var doc = PostBrowser.Document;
6847 if (doc == null) return;
6849 var tags = doc.GetElementsByTagName("html");
6853 tags[0].ScrollTop += this._fntDetail.Height;
6855 tags[0].ScrollTop -= this._fntDetail.Height;
6859 private void PageDownPostBrowser(bool forward)
6861 var doc = PostBrowser.Document;
6862 if (doc == null) return;
6864 var tags = doc.GetElementsByTagName("html");
6868 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6870 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
6874 private void GoNextTab(bool forward)
6876 int idx = ListTab.SelectedIndex;
6880 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6885 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6887 ListTab.SelectedIndex = idx;
6888 ListTabSelect(ListTab.TabPages[idx]);
6891 private void CopyStot()
6894 StringBuilder sb = new StringBuilder();
6895 bool IsProtected = false;
6897 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6898 foreach (int idx in _curList.SelectedIndices)
6900 PostClass post = _statuses[_curTab.Text, idx];
6906 if (post.IsDeleted) continue;
6909 if (post.RetweetedId != null)
6910 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6912 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6916 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6921 MessageBox.Show(Properties.Resources.CopyStotText1);
6925 clstr = sb.ToString();
6928 Clipboard.SetDataObject(clstr, false, 5, 100);
6930 catch (Exception ex)
6932 MessageBox.Show(ex.Message);
6937 private void CopyIdUri()
6940 StringBuilder sb = new StringBuilder();
6941 if (this._curTab == null) return;
6942 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
6943 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
6944 foreach (int idx in _curList.SelectedIndices)
6946 var post = _statuses[_curTab.Text, idx];
6947 sb.Append(MyCommon.GetStatusUrl(post));
6948 sb.Append(Environment.NewLine);
6952 clstr = sb.ToString();
6955 Clipboard.SetDataObject(clstr, false, 5, 100);
6957 catch (Exception ex)
6959 MessageBox.Show(ex.Message);
6964 private void GoFav(bool forward)
6966 if (_curList.VirtualListSize == 0) return;
6973 if (_curList.SelectedIndices.Count == 0)
6979 fIdx = _curList.SelectedIndices[0] + 1;
6980 if (fIdx > _curList.VirtualListSize - 1) return;
6982 toIdx = _curList.VirtualListSize;
6987 if (_curList.SelectedIndices.Count == 0)
6989 fIdx = _curList.VirtualListSize - 1;
6993 fIdx = _curList.SelectedIndices[0] - 1;
6994 if (fIdx < 0) return;
7000 for (int idx = fIdx; idx != toIdx; idx += stp)
7002 if (_statuses[_curTab.Text, idx].IsFav)
7004 SelectListItem(_curList, idx);
7005 _curList.EnsureVisible(idx);
7011 private void GoSamePostToAnotherTab(bool left)
7013 if (_curList.VirtualListSize == 0) return;
7019 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7020 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7022 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7027 if (ListTab.SelectedIndex == 0)
7033 fIdx = ListTab.SelectedIndex - 1;
7041 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7047 fIdx = ListTab.SelectedIndex + 1;
7049 toIdx = ListTab.TabCount;
7054 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7056 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7057 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7059 if (_statuses[ListTab.TabPages[tabidx].Text, idx].StatusId == targetId)
7061 ListTab.SelectedIndex = tabidx;
7062 ListTabSelect(ListTab.TabPages[tabidx]);
7063 SelectListItem(_curList, idx);
7064 _curList.EnsureVisible(idx);
7073 private void GoPost(bool forward)
7075 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7082 fIdx = _curList.SelectedIndices[0] + 1;
7083 if (fIdx > _curList.VirtualListSize - 1) return;
7084 toIdx = _curList.VirtualListSize;
7089 fIdx = _curList.SelectedIndices[0] - 1;
7090 if (fIdx < 0) return;
7096 if (_curPost.RetweetedId == null)
7098 name = _curPost.ScreenName;
7102 name = _curPost.RetweetedBy;
7104 for (int idx = fIdx; idx != toIdx; idx += stp)
7106 if (_statuses[_curTab.Text, idx].RetweetedId == null)
7108 if (_statuses[_curTab.Text, idx].ScreenName == name)
7110 SelectListItem(_curList, idx);
7111 _curList.EnsureVisible(idx);
7117 if (_statuses[_curTab.Text, idx].RetweetedBy == name)
7119 SelectListItem(_curList, idx);
7120 _curList.EnsureVisible(idx);
7127 private void GoRelPost(bool forward)
7129 if (_curList.SelectedIndices.Count == 0) return;
7136 fIdx = _curList.SelectedIndices[0] + 1;
7137 if (fIdx > _curList.VirtualListSize - 1) return;
7138 toIdx = _curList.VirtualListSize;
7143 fIdx = _curList.SelectedIndices[0] - 1;
7144 if (fIdx < 0) return;
7151 if (_curPost == null) return;
7152 _anchorPost = _curPost;
7157 if (_anchorPost == null) return;
7160 for (int idx = fIdx; idx != toIdx; idx += stp)
7162 PostClass post = _statuses[_curTab.Text, idx];
7163 if (post.ScreenName == _anchorPost.ScreenName ||
7164 post.RetweetedBy == _anchorPost.ScreenName ||
7165 post.ScreenName == _anchorPost.RetweetedBy ||
7166 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7167 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7168 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7169 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7170 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7172 SelectListItem(_curList, idx);
7173 _curList.EnsureVisible(idx);
7179 private void GoAnchor()
7181 if (_anchorPost == null) return;
7182 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7183 if (idx == -1) return;
7185 SelectListItem(_curList, idx);
7186 _curList.EnsureVisible(idx);
7189 private void GoTopEnd(bool GoTop)
7196 _item = _curList.GetItemAt(0, 25);
7204 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7206 idx = _curList.VirtualListSize - 1;
7210 SelectListItem(_curList, idx);
7213 private void GoMiddle()
7220 _item = _curList.GetItemAt(0, 0);
7230 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7233 idx2 = _curList.VirtualListSize - 1;
7239 idx3 = (idx1 + idx2) / 2;
7241 SelectListItem(_curList, idx3);
7244 private void GoLast()
7246 if (_curList.VirtualListSize == 0) return;
7248 if (_statuses.SortOrder == SortOrder.Ascending)
7250 SelectListItem(_curList, _curList.VirtualListSize - 1);
7251 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7255 SelectListItem(_curList, 0);
7256 _curList.EnsureVisible(0);
7260 private void MoveTop()
7262 if (_curList.SelectedIndices.Count == 0) return;
7263 int idx = _curList.SelectedIndices[0];
7264 if (_statuses.SortOrder == SortOrder.Ascending)
7266 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7270 _curList.EnsureVisible(0);
7272 _curList.EnsureVisible(idx);
7275 private void GoInReplyToPostTree()
7277 if (_curPost == null) return;
7279 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7281 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7283 PostClass post = null;
7284 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7285 if (string.IsNullOrEmpty(r) && post != null)
7287 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7288 _curPost.InReplyToUser = post.InReplyToUser;
7289 _curPost.IsReply = post.IsReply;
7290 this.PurgeListViewItemCache();
7291 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7295 this.StatusLabel.Text = r;
7299 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7301 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7303 replyChains = new Stack<ReplyChain>();
7305 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7308 string inReplyToTabName;
7309 long inReplyToId = _curPost.InReplyToStatusId.Value;
7310 string inReplyToUser = _curPost.InReplyToUser;
7311 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7313 var inReplyToPosts = from tab in _statuses.Tabs.Values
7314 orderby tab != curTabClass
7315 from post in tab.Posts.Values
7316 where post.StatusId == inReplyToId
7317 let index = tab.IndexOf(post.StatusId)
7319 select new {Tab = tab, Index = index};
7323 var inReplyPost = inReplyToPosts.First();
7324 inReplyToTabName = inReplyPost.Tab.TabName;
7325 inReplyToIndex = inReplyPost.Index;
7327 catch (InvalidOperationException)
7329 PostClass post = null;
7330 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7331 if (string.IsNullOrEmpty(r) && post != null)
7334 _statuses.AddPost(post);
7335 _statuses.DistributePosts();
7336 //_statuses.SubmitUpdate(null, null, null, false);
7337 this.RefreshTimeline(false);
7340 var inReplyPost = inReplyToPosts.First();
7341 inReplyToTabName = inReplyPost.Tab.TabName;
7342 inReplyToIndex = inReplyPost.Index;
7344 catch (InvalidOperationException)
7346 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7352 this.StatusLabel.Text = r;
7353 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7358 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7359 DetailsListView listView = (DetailsListView)tabPage.Tag;
7361 if (_curTab != tabPage)
7363 this.ListTab.SelectTab(tabPage);
7366 this.SelectListItem(listView, inReplyToIndex);
7367 listView.EnsureVisible(inReplyToIndex);
7370 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7372 if (_curPost == null) return;
7374 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7375 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7379 if (_curPost.InReplyToStatusId != null)
7381 var posts = from t in _statuses.Tabs
7382 from p in t.Value.Posts
7383 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7384 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7386 orderby isForward ? indexOf : indexOf * -1
7387 orderby t.Value != curTabClass
7388 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7391 var postList = posts.ToList();
7392 for (int i = postList.Count - 1; i >= 0; i--)
7395 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7397 postList.RemoveAt(index);
7400 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7401 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7402 if (post == null) post = postList.First();
7403 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7404 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7405 SelectListItem(listView, post.Index);
7406 listView.EnsureVisible(post.Index);
7408 catch (InvalidOperationException)
7416 if (replyChains == null || replyChains.Count < 1)
7418 var posts = from t in _statuses.Tabs
7419 from p in t.Value.Posts
7420 where p.Value.InReplyToStatusId == _curPost.StatusId
7421 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7424 orderby t.Value != curTabClass
7425 select new {Tab = t.Value, Index = indexOf};
7428 var post = posts.First();
7429 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7430 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7431 SelectListItem(listView, post.Index);
7432 listView.EnsureVisible(post.Index);
7434 catch (InvalidOperationException)
7441 ReplyChain chainHead = replyChains.Pop();
7442 if (chainHead.InReplyToId == _curPost.StatusId)
7444 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7453 ListTab.SelectTab(chainHead.OriginalTab);
7459 SelectListItem(_curList, idx);
7460 _curList.EnsureVisible(idx);
7466 this.GoBackInReplyToPostTree(parallel);
7472 private void GoBackSelectPostChain()
7474 if (this.selectPostChains.Count > 1)
7483 this.selectPostChains.Pop();
7484 var tabPostPair = this.selectPostChains.Peek();
7486 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7488 if (tabPostPair.Item2 != null)
7490 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7491 if (idx == -1) continue; //該当ポストが存在しないので無視
7494 tp = tabPostPair.Item1;
7496 this.selectPostChains.Pop();
7498 catch (InvalidOperationException)
7504 while (this.selectPostChains.Count > 1);
7509 //履歴が残り1つであればクリアしておく
7510 if (this.selectPostChains.Count == 1)
7511 this.selectPostChains.Clear();
7515 DetailsListView lst = (DetailsListView)tp.Tag;
7516 this.ListTab.SelectedTab = tp;
7519 SelectListItem(lst, idx);
7520 lst.EnsureVisible(idx);
7526 private void PushSelectPostChain()
7528 int count = this.selectPostChains.Count;
7531 var p = this.selectPostChains.Peek();
7532 if (p.Item1 == this._curTab)
7534 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7535 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7538 if (count >= 2500) TrimPostChain();
7539 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7542 private void TrimPostChain()
7544 if (this.selectPostChains.Count <= 2000) return;
7545 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7546 for (int i = 0; i < 2000; i++)
7548 p.Push(this.selectPostChains.Pop());
7550 this.selectPostChains.Clear();
7551 for (int i = 0; i < 2000; i++)
7553 this.selectPostChains.Push(p.Pop());
7557 private bool GoStatus(long statusId)
7559 if (statusId == 0) return false;
7560 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7562 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7564 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7565 ListTab.SelectedIndex = tabidx;
7566 ListTabSelect(ListTab.TabPages[tabidx]);
7567 SelectListItem(_curList, idx);
7568 _curList.EnsureVisible(idx);
7575 private bool GoDirectMessage(long statusId)
7577 if (statusId == 0) return false;
7578 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7580 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7582 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7583 ListTab.SelectedIndex = tabidx;
7584 ListTabSelect(ListTab.TabPages[tabidx]);
7585 SelectListItem(_curList, idx);
7586 _curList.EnsureVisible(idx);
7593 private void MyList_MouseClick(object sender, MouseEventArgs e)
7595 _anchorFlag = false;
7598 private void StatusText_Enter(object sender, EventArgs e)
7600 // フォーカスの戻り先を StatusText に設定
7601 this.Tag = StatusText;
7602 StatusText.BackColor = _clInputBackcolor;
7605 public Color InputBackColor
7607 get { return _clInputBackcolor; }
7608 set { _clInputBackcolor = value; }
7611 private void StatusText_Leave(object sender, EventArgs e)
7613 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7614 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7615 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7618 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7620 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7621 if (State == ModifierState.NotFlags) return;
7622 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7625 e.SuppressKeyPress = true;
7628 this.StatusText_TextChanged(null, null);
7631 private void SaveConfigsAll(bool ifModified)
7635 SaveConfigsCommon();
7642 if (_modifySettingCommon) SaveConfigsCommon();
7643 if (_modifySettingLocal) SaveConfigsLocal();
7644 if (_modifySettingAtId) SaveConfigsAtId();
7648 private void SaveConfigsAtId()
7650 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7652 _modifySettingAtId = false;
7653 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7657 private void SaveConfigsCommon()
7659 if (_ignoreConfigSave) return;
7661 _modifySettingCommon = false;
7664 _cfgCommon.UserName = tw.Username;
7665 _cfgCommon.UserId = tw.UserId;
7666 _cfgCommon.Password = tw.Password;
7667 _cfgCommon.Token = tw.AccessToken;
7668 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7669 _cfgCommon.UserAccounts = SettingDialog.UserAccounts;
7671 _cfgCommon.TinyUrlResolve = SettingDialog.TinyUrlResolve;
7672 _cfgCommon.UrlConvertAuto = SettingDialog.UrlConvertAuto;
7673 _cfgCommon.DefaultTimeOut = SettingDialog.DefaultTimeOut;
7674 _cfgCommon.EventNotifyEnabled = SettingDialog.EventNotifyEnabled;
7675 _cfgCommon.EventNotifyFlag = SettingDialog.EventNotifyFlag;
7676 _cfgCommon.IsMyEventNotifyFlag = SettingDialog.IsMyEventNotifyFlag;
7677 _cfgCommon.ForceEventNotify = SettingDialog.ForceEventNotify;
7678 _cfgCommon.FavEventUnread = SettingDialog.FavEventUnread;
7679 _cfgCommon.TranslateLanguage = SettingDialog.TranslateLanguage;
7680 _cfgCommon.EventSoundFile = SettingDialog.EventSoundFile;
7681 _cfgCommon.AutoShortUrlFirst = SettingDialog.AutoShortUrlFirst;
7682 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7683 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7685 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7687 _cfgCommon.BilyUser = SettingDialog.BitlyUser;
7688 _cfgCommon.BitlyPwd = SettingDialog.BitlyPwd;
7690 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7691 switch (_statuses.SortMode)
7693 case IdComparerClass.ComparerMode.Nickname: //ニックネーム
7694 _cfgCommon.SortColumn = 1;
7696 case IdComparerClass.ComparerMode.Data: //本文
7697 _cfgCommon.SortColumn = 2;
7699 case IdComparerClass.ComparerMode.Id: //時刻=発言Id
7700 _cfgCommon.SortColumn = 3;
7702 case IdComparerClass.ComparerMode.Name: //名前
7703 _cfgCommon.SortColumn = 4;
7705 case IdComparerClass.ComparerMode.Source: //Source
7706 _cfgCommon.SortColumn = 7;
7710 _cfgCommon.Nicoms = SettingDialog.Nicoms;
7711 _cfgCommon.HashTags = HashMgr.HashHistories;
7712 if (HashMgr.IsPermanent)
7714 _cfgCommon.HashSelected = HashMgr.UseHash;
7718 _cfgCommon.HashSelected = "";
7720 _cfgCommon.HashIsHead = HashMgr.IsHead;
7721 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7722 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7723 _cfgCommon.TwitterUrl = SettingDialog.TwitterApiUrl;
7724 if (ToolStripFocusLockMenuItem != null &&
7725 ToolStripFocusLockMenuItem.IsDisposed == false)
7727 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7729 _cfgCommon.TrackWord = tw.TrackWord;
7730 _cfgCommon.AllAtReply = tw.AllAtReply;
7731 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7732 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7733 _cfgCommon.UserAppointUrl = SettingDialog.UserAppointUrl;
7734 _cfgCommon.EnableImgAzyobuziNet = SettingDialog.EnableImgAzyobuziNet;
7735 _cfgCommon.ImgAzyobuziNetDisabledInDM = SettingDialog.ImgAzyobuziNetDisabledInDM;
7736 _cfgCommon.MapThumbnailProvider = SettingDialog.MapThumbnailProvider;
7737 _cfgCommon.MapThumbnailHeight = SettingDialog.MapThumbnailHeight;
7738 _cfgCommon.MapThumbnailWidth = SettingDialog.MapThumbnailWidth;
7739 _cfgCommon.MapThumbnailZoom = SettingDialog.MapThumbnailZoom;
7740 _cfgCommon.IsRemoveSameEvent = SettingDialog.IsRemoveSameEvent;
7746 private void SaveConfigsLocal()
7748 if (_ignoreConfigSave) return;
7751 _modifySettingLocal = false;
7752 _cfgLocal.FormSize = _mySize;
7753 _cfgLocal.FormLocation = _myLoc;
7754 _cfgLocal.SplitterDistance = _mySpDis;
7755 _cfgLocal.PreviewDistance = _mySpDis3;
7756 _cfgLocal.StatusMultiline = StatusText.Multiline;
7757 _cfgLocal.StatusTextHeight = _mySpDis2;
7759 _cfgLocal.FontUnread = _fntUnread;
7760 _cfgLocal.ColorUnread = _clUnread;
7761 _cfgLocal.FontRead = _fntReaded;
7762 _cfgLocal.ColorRead = _clReaded;
7763 _cfgLocal.FontDetail = _fntDetail;
7764 _cfgLocal.ColorDetail = _clDetail;
7765 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7766 _cfgLocal.ColorDetailLink = _clDetailLink;
7767 _cfgLocal.ColorFav = _clFav;
7768 _cfgLocal.ColorOWL = _clOWL;
7769 _cfgLocal.ColorRetweet = _clRetweet;
7770 _cfgLocal.ColorSelf = _clSelf;
7771 _cfgLocal.ColorAtSelf = _clAtSelf;
7772 _cfgLocal.ColorTarget = _clTarget;
7773 _cfgLocal.ColorAtTarget = _clAtTarget;
7774 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7775 _cfgLocal.ColorAtTo = _clAtTo;
7776 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7777 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7778 _cfgLocal.ColorInputFont = _clInputFont;
7779 _cfgLocal.FontInputFont = _fntInputFont;
7781 _cfgLocal.ProxyType = SettingDialog.SelectedProxyType;
7782 _cfgLocal.ProxyAddress = SettingDialog.ProxyAddress;
7783 _cfgLocal.ProxyPort = SettingDialog.ProxyPort;
7784 _cfgLocal.ProxyUser = SettingDialog.ProxyUser;
7785 _cfgLocal.ProxyPassword = SettingDialog.ProxyPassword;
7786 if (_ignoreConfigSave) return;
7791 private void SaveConfigsTabs()
7793 SettingTabs tabSetting = new SettingTabs();
7794 for (int i = 0; i < ListTab.TabPages.Count; i++)
7796 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
7801 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7804 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7805 if (ret != DialogResult.OK)
7808 var match = Twitter.StatusUrlRegex.Match(inputText);
7811 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7812 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7816 var statusId = long.Parse(match.Groups["StatusId"].Value);
7818 var post = this._statuses[statusId];
7823 post = await Task.Run(() =>
7825 PostClass newPost = null;
7827 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
7828 if (!string.IsNullOrEmpty(err))
7829 throw new WebApiException(err);
7834 catch (WebApiException ex)
7836 var message = ex.Message;
7837 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
7838 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7845 this.OpenRelatedTab(post);
7847 catch (TabException ex)
7849 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7853 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7855 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7856 Properties.Resources.SaveLogMenuItem_ClickText2,
7857 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7858 if (rslt == DialogResult.Cancel) return;
7860 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7861 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7862 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7863 SaveFileDialog1.FilterIndex = 0;
7864 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7865 SaveFileDialog1.RestoreDirectory = true;
7867 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7869 if (!SaveFileDialog1.ValidateNames) return;
7870 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7872 if (rslt == DialogResult.Yes)
7875 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7877 PostClass post = _statuses[_curTab.Text, idx];
7878 string protect = "";
7879 if (post.IsProtect) protect = "Protect";
7880 sw.WriteLine(post.Nickname + "\t" +
7881 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7882 post.CreatedAt.ToString() + "\t" +
7883 post.ScreenName + "\t" +
7884 post.StatusId.ToString() + "\t" +
7885 post.ImageUrl + "\t" +
7886 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7892 foreach (int idx in _curList.SelectedIndices)
7894 PostClass post = _statuses[_curTab.Text, idx];
7895 string protect = "";
7896 if (post.IsProtect) protect = "Protect";
7897 sw.WriteLine(post.Nickname + "\t" +
7898 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7899 post.CreatedAt.ToString() + "\t" +
7900 post.ScreenName + "\t" +
7901 post.StatusId.ToString() + "\t" +
7902 post.ImageUrl + "\t" +
7903 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7909 this.TopMost = this._cfgCommon.AlwaysTop;
7912 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
7914 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7915 if (State == ModifierState.NotFlags) return;
7916 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
7919 e.IsInputKey = true;
7922 public bool TabRename(ref string tabName)
7925 string newTabText = null;
7926 using (InputTabName inputName = new InputTabName())
7928 inputName.TabName = tabName;
7929 inputName.ShowDialog();
7930 if (inputName.DialogResult == DialogResult.Cancel) return false;
7931 newTabText = inputName.TabName;
7933 this.TopMost = this._cfgCommon.AlwaysTop;
7934 if (!string.IsNullOrEmpty(newTabText))
7937 for (int i = 0; i < ListTab.TabCount; i++)
7939 if (ListTab.TabPages[i].Text == newTabText)
7941 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
7942 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7946 //タブ名のリスト作り直し(デフォルトタブ以外は再作成)
7947 for (int i = 0; i < ListTab.TabCount; i++)
7949 if (ListTab.TabPages[i].Text == tabName)
7951 ListTab.TabPages[i].Text = newTabText;
7954 _statuses.RenameTab(tabName, newTabText);
7956 for (int i = 0; i < ListTab.TabCount; i++)
7958 if (_statuses.IsDistributableTab(ListTab.TabPages[i].Text))
7960 if (ListTab.TabPages[i].Text == tabName)
7962 ListTab.TabPages[i].Text = newTabText;
7966 SaveConfigsCommon();
7968 _rclickTabName = newTabText;
7969 tabName = newTabText;
7978 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7980 if (e.Button == MouseButtons.Middle)
7982 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7984 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7986 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7987 this.SaveConfigsTabs();
7994 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7996 string tn = ListTab.SelectedTab.Text;
8000 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8002 if (this._cfgCommon.TabMouseLock) return;
8003 Point cpos = new Point(e.X, e.Y);
8004 if (e.Button == MouseButtons.Left)
8006 for (int i = 0; i < ListTab.TabPages.Count; i++)
8008 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8011 _tabMouseDownPoint = e.Location;
8022 private void ListTab_DragEnter(object sender, DragEventArgs e)
8024 if (e.Data.GetDataPresent(typeof(TabPage)))
8025 e.Effect = DragDropEffects.Move;
8027 e.Effect = DragDropEffects.None;
8030 private void ListTab_DragDrop(object sender, DragEventArgs e)
8032 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8037 Point cpos = new Point(e.X, e.Y);
8038 Point spos = ListTab.PointToClient(cpos);
8040 for (i = 0; i < ListTab.TabPages.Count; i++)
8042 Rectangle rect = ListTab.GetTabRect(i);
8043 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8044 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8046 tn = ListTab.TabPages[i].Text;
8047 if (spos.X <= (rect.Left + rect.Right) / 2)
8056 //タブのないところにドロップ->最後尾へ移動
8057 if (string.IsNullOrEmpty(tn))
8059 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8061 i = ListTab.TabPages.Count - 1;
8064 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8065 if (tp.Text == tn) return;
8067 ReOrderTab(tp.Text, tn, bef);
8070 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8073 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8075 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8078 using (ControlTransaction.Layout(this.ListTab))
8081 for (int j = 0; j < ListTab.TabPages.Count; j++)
8083 if (ListTab.TabPages[j].Text == targetTabText)
8085 mTp = ListTab.TabPages[j];
8086 ListTab.TabPages.Remove(mTp);
8087 if (j < baseIndex) baseIndex -= 1;
8091 if (isBeforeBaseTab)
8092 ListTab.TabPages.Insert(baseIndex, mTp);
8094 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8100 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8102 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8103 //isReply:true=@,false=DM
8104 if (!StatusText.Enabled) return;
8105 if (_curList == null) return;
8106 if (_curTab == null) return;
8107 if (!this.ExistCurrentPost) return;
8109 // 複数あてリプライはReplyではなく通常ポスト
8110 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8111 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8112 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8114 if (_curList.SelectedIndices.Count > 0)
8117 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8120 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8123 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8124 StatusText.SelectionStart = StatusText.Text.Length;
8126 _reply_to_id = null;
8127 _reply_to_name = null;
8130 if (string.IsNullOrEmpty(StatusText.Text))
8134 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8135 StatusText.Text = "@" + _curPost.ScreenName + " ";
8136 if (_curPost.RetweetedId != null)
8138 _reply_to_id = _curPost.RetweetedId.Value;
8142 _reply_to_id = _curPost.StatusId;
8144 _reply_to_name = _curPost.ScreenName;
8152 //1件選んでEnter or DoubleClick
8153 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8155 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8158 if (_curPost.RetweetedId != null)
8160 _reply_to_id = _curPost.RetweetedId.Value;
8164 _reply_to_id = _curPost.StatusId;
8166 _reply_to_name = _curPost.ScreenName;
8170 if (!StatusText.Text.StartsWith("@"))
8173 if (StatusText.Text.StartsWith(". "))
8176 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8177 _reply_to_id = null;
8178 _reply_to_name = null;
8183 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8184 if (_curPost.RetweetedId != null)
8186 _reply_to_id = _curPost.RetweetedId.Value;
8190 _reply_to_id = _curPost.StatusId;
8192 _reply_to_name = _curPost.ScreenName;
8199 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8200 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8201 _reply_to_id = null;
8202 _reply_to_name = null;
8207 //1件選んでCtrl-Rの場合(返信先操作せず)
8208 int sidx = StatusText.SelectionStart;
8209 string id = "@" + _curPost.ScreenName + " ";
8212 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8217 StatusText.Text = StatusText.Text.Insert(sidx, id);
8219 //if (StatusText.Text.StartsWith("@"))
8222 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8223 // sidx += 5 + _curPost.ScreenName.Length;
8228 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8229 // sidx += 3 + _curPost.ScreenName.Length;
8231 StatusText.SelectionStart = sidx;
8234 //_reply_to_name = null;
8242 if (!isAuto && !isReply) return;
8244 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8248 //Enter or DoubleClick
8250 string sTxt = StatusText.Text;
8251 if (!sTxt.StartsWith(". "))
8254 _reply_to_id = null;
8255 _reply_to_name = null;
8257 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8259 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8260 if (!sTxt.Contains("@" + post.ScreenName + " "))
8262 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8263 //sTxt = "@" + post.ScreenName + " " + sTxt;
8266 StatusText.Text = sTxt;
8271 if (_curList.SelectedIndices.Count > 1)
8276 int sidx = StatusText.SelectionStart;
8277 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8279 PostClass post = _statuses[_curTab.Text, _curList.SelectedIndices[cnt]];
8280 if (!ids.Contains("@" + post.ScreenName + " ") &&
8281 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8283 ids += "@" + post.ScreenName + " ";
8287 foreach (string nm in post.ReplyToList)
8289 if (!ids.Contains("@" + nm + " ") &&
8290 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8292 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8294 ids += "@" + m.Result("${id}") + " ";
8296 ids += "@" + nm + " ";
8301 if (ids.Length == 0) return;
8302 if (!StatusText.Text.StartsWith(". "))
8304 StatusText.Text = ". " + StatusText.Text;
8306 _reply_to_id = null;
8307 _reply_to_name = null;
8311 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8316 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8318 //if (StatusText.Text.StartsWith("@"))
8320 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8321 // sidx += 2 + ids.Length;
8325 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8326 // sidx += 1 + ids.Length;
8328 StatusText.SelectionStart = sidx;
8334 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8337 int sidx = StatusText.SelectionStart;
8338 PostClass post = _curPost;
8339 if (!ids.Contains("@" + post.ScreenName + " ") &&
8340 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8342 ids += "@" + post.ScreenName + " ";
8344 foreach (string nm in post.ReplyToList)
8346 if (!ids.Contains("@" + nm + " ") &&
8347 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8349 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8351 ids += "@" + m.Result("${id}") + " ";
8353 ids += "@" + nm + " ";
8356 if (!string.IsNullOrEmpty(post.RetweetedBy))
8358 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8359 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8361 ids += "@" + post.RetweetedBy + " ";
8364 if (ids.Length == 0) return;
8365 if (string.IsNullOrEmpty(StatusText.Text))
8368 StatusText.Text = ids;
8369 StatusText.SelectionStart = ids.Length;
8371 if (post.RetweetedId != null)
8373 _reply_to_id = post.RetweetedId.Value;
8377 _reply_to_id = post.StatusId;
8379 _reply_to_name = post.ScreenName;
8385 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8390 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8392 StatusText.SelectionStart = sidx;
8398 StatusText.SelectionStart = StatusText.Text.Length;
8403 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8408 private static int iconCnt = 0;
8409 private static int blinkCnt = 0;
8410 private static bool blink = false;
8411 private static bool idle = false;
8413 private void RefreshTasktrayIcon(bool forceRefresh)
8415 if (_colorize) Colorize();
8416 if (!TimerRefreshIcon.Enabled) return;
8417 //Static usCheckCnt As int = 0
8419 //Static iconDlListTopItem As ListViewItem = null
8421 if (forceRefresh) idle = false;
8423 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8424 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8426 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8428 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8434 //if (usCheckCnt > 300) //1min
8437 // if (!this.IsReceivedUserStream)
8439 // TraceOut("ReconnectUserStream");
8440 // tw.ReconnectUserStream();
8445 foreach (BackgroundWorker bw in this._bw)
8447 if (bw != null && bw.IsBusy)
8462 SaveConfigsAll(true);
8467 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8469 _myStatusError = false;
8473 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8474 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8476 if (blinkCnt > 0) return;
8478 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8480 NotifyIcon1.Icon = ReplyIcon;
8484 NotifyIcon1.Icon = ReplyIconBlink;
8492 //優先度:エラー→オフライン→アイドル
8496 NotifyIcon1.Icon = NIconAtRed;
8499 if (_myStatusOnline)
8501 NotifyIcon1.Icon = NIconAt;
8505 NotifyIcon1.Icon = NIconAtSmoke;
8509 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8512 this.RefreshTasktrayIcon(false);
8515 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8517 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8518 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8520 if (ListTab != null && ListTab.SelectedTab != null)
8521 _rclickTabName = ListTab.SelectedTab.Text;
8526 if (_statuses == null) return;
8527 if (_statuses.Tabs == null) return;
8529 TabClass tb = _statuses.Tabs[_rclickTabName];
8530 if (tb == null) return;
8532 NotifyDispMenuItem.Checked = tb.Notify;
8533 this.NotifyTbMenuItem.Checked = tb.Notify;
8535 soundfileListup = true;
8536 SoundFileComboBox.Items.Clear();
8537 this.SoundFileTbComboBox.Items.Clear();
8538 SoundFileComboBox.Items.Add("");
8539 this.SoundFileTbComboBox.Items.Add("");
8540 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8541 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8543 oDir = oDir.GetDirectories("Sounds")[0];
8545 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8547 SoundFileComboBox.Items.Add(oFile.Name);
8548 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8550 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8551 if (idx == -1) idx = 0;
8552 SoundFileComboBox.SelectedIndex = idx;
8553 this.SoundFileTbComboBox.SelectedIndex = idx;
8554 soundfileListup = false;
8555 UreadManageMenuItem.Checked = tb.UnreadManage;
8556 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8558 TabMenuControl(_rclickTabName);
8561 private void TabMenuControl(string tabName)
8563 this.FilterEditMenuItem.Enabled = true;
8564 this.EditRuleTbMenuItem.Enabled = true;
8566 if (_statuses.IsDefaultTab(tabName))
8568 this.ProtectTabMenuItem.Enabled = false;
8569 this.ProtectTbMenuItem.Enabled = false;
8573 this.ProtectTabMenuItem.Enabled = true;
8574 this.ProtectTbMenuItem.Enabled = true;
8577 if (_statuses.IsDefaultTab(tabName) || _statuses.Tabs[tabName].Protected)
8579 this.ProtectTabMenuItem.Checked = true;
8580 this.ProtectTbMenuItem.Checked = true;
8581 this.DeleteTabMenuItem.Enabled = false;
8582 this.DeleteTbMenuItem.Enabled = false;
8586 this.ProtectTabMenuItem.Checked = false;
8587 this.ProtectTbMenuItem.Checked = false;
8588 this.DeleteTabMenuItem.Enabled = true;
8589 this.DeleteTbMenuItem.Enabled = true;
8593 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8595 var checkState = ((ToolStripMenuItem)sender).Checked;
8598 this.ProtectTbMenuItem.Checked = checkState;
8599 this.ProtectTabMenuItem.Checked = checkState;
8602 this.DeleteTabMenuItem.Enabled = !checkState;
8603 this.DeleteTbMenuItem.Enabled = !checkState;
8605 if (string.IsNullOrEmpty(_rclickTabName)) return;
8606 _statuses.Tabs[_rclickTabName].Protected = checkState;
8611 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8613 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8614 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8616 if (string.IsNullOrEmpty(_rclickTabName)) return;
8617 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8622 public void ChangeTabUnreadManage(string tabName, bool isManage)
8625 for (idx = 0; idx < ListTab.TabCount; idx++)
8627 if (ListTab.TabPages[idx].Text == tabName) break;
8630 _statuses.SetTabUnreadManage(tabName, isManage);
8631 if (this._cfgCommon.TabIconDisp)
8633 if (_statuses.Tabs[tabName].UnreadCount > 0)
8634 ListTab.TabPages[idx].ImageIndex = 0;
8636 ListTab.TabPages[idx].ImageIndex = -1;
8639 if (_curTab.Text == tabName)
8641 this.PurgeListViewItemCache();
8645 SetMainWindowTitle();
8646 SetStatusLabelUrl();
8647 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8650 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8652 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8653 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8655 if (string.IsNullOrEmpty(_rclickTabName)) return;
8657 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8662 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8664 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8666 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8671 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8673 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8675 RemoveSpecifiedTab(_rclickTabName, true);
8679 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8681 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8682 fltDialog.SetCurrent(_rclickTabName);
8683 fltDialog.ShowDialog(this);
8684 this.TopMost = this._cfgCommon.AlwaysTop;
8686 this.ApplyPostFilters();
8690 private void AddTabMenuItem_Click(object sender, EventArgs e)
8692 string tabName = null;
8693 MyCommon.TabUsageType tabUsage;
8694 using (InputTabName inputName = new InputTabName())
8696 inputName.TabName = _statuses.GetUniqueTabName();
8697 inputName.IsShowUsage = true;
8698 inputName.ShowDialog();
8699 if (inputName.DialogResult == DialogResult.Cancel) return;
8700 tabName = inputName.TabName;
8701 tabUsage = inputName.Usage;
8703 this.TopMost = this._cfgCommon.AlwaysTop;
8704 if (!string.IsNullOrEmpty(tabName))
8707 ListElement list = null;
8708 if (tabUsage == MyCommon.TabUsageType.Lists)
8710 using (ListAvailable listAvail = new ListAvailable())
8712 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8713 if (listAvail.SelectedList == null) return;
8714 list = listAvail.SelectedList;
8717 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8719 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8720 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8726 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8728 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8729 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8730 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8732 if (tabUsage == MyCommon.TabUsageType.Lists)
8734 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8735 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
8736 GetTimeline(MyCommon.WORKERTYPE.List, 1, tabName);
8742 private void TabMenuItem_Click(object sender, EventArgs e)
8745 foreach (int idx in _curList.SelectedIndices)
8749 if (!SelectTab(out tabName)) return;
8751 fltDialog.SetCurrent(tabName);
8752 if (_statuses[_curTab.Text, idx].RetweetedId == null)
8754 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].ScreenName, _statuses[_curTab.Text, idx].TextFromApi);
8758 fltDialog.AddNewFilter(_statuses[_curTab.Text, idx].RetweetedBy, _statuses[_curTab.Text, idx].TextFromApi);
8760 fltDialog.ShowDialog(this);
8761 this.TopMost = this._cfgCommon.AlwaysTop;
8764 this.ApplyPostFilters();
8766 if (this.ListTab.SelectedTab != null &&
8767 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8769 _curPost = _statuses[this.ListTab.SelectedTab.Text, ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8773 protected override bool ProcessDialogKey(Keys keyData)
8775 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8776 if ((keyData & Keys.KeyCode) == Keys.Enter)
8778 if (StatusText.Focused)
8780 bool _NewLine = false;
8783 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8785 if (StatusText.Multiline)
8787 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8789 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8793 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8797 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8799 if (StatusText.Multiline)
8801 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8803 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8807 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8813 if (StatusText.Multiline)
8815 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8817 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8818 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8822 if (((keyData & Keys.Shift) == Keys.Shift) ||
8823 (((keyData & Keys.Control) != Keys.Control) &&
8824 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8830 int pos1 = StatusText.SelectionStart;
8831 if (StatusText.SelectionLength > 0)
8833 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8835 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8836 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8841 PostButton_Click(null, null);
8845 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8846 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8847 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8849 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8854 return base.ProcessDialogKey(keyData);
8857 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8859 MakeReplyOrDirectStatus(false, true, true);
8862 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8867 if (_curList.SelectedIndices.Count == 0) return;
8870 if (!SelectTab(out tabName)) return;
8874 MoveOrCopy(ref mv, ref mk);
8876 List<string> ids = new List<string>();
8877 foreach (int idx in _curList.SelectedIndices)
8879 PostClass post = _statuses[_curTab.Text, idx];
8880 if (!ids.Contains(post.ScreenName))
8882 PostFilterRule fc = new PostFilterRule();
8883 ids.Add(post.ScreenName);
8884 if (post.RetweetedId == null)
8886 fc.FilterName = post.ScreenName;
8890 fc.FilterName = post.RetweetedBy;
8892 fc.UseNameField = true;
8893 fc.MoveMatches = mv;
8894 fc.MarkMatches = mk;
8895 fc.UseRegex = false;
8896 fc.FilterByUrl = false;
8897 _statuses.Tabs[tabName].AddFilter(fc);
8902 List<string> atids = new List<string>();
8903 foreach (string id in ids)
8905 atids.Add("@" + id);
8907 int cnt = AtIdSupl.ItemCount;
8908 AtIdSupl.AddRangeItem(atids.ToArray());
8909 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
8912 this.ApplyPostFilters();
8916 private bool SelectTab(out string tabName)
8923 using (var dialog = new TabsDialog(_statuses))
8925 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8927 var selectedTab = dialog.SelectedTab;
8928 tabName = selectedTab == null ? null : selectedTab.TabName;
8931 ListTab.SelectedTab.Focus();
8933 if (tabName == null)
8935 using (InputTabName inputName = new InputTabName())
8937 inputName.TabName = _statuses.GetUniqueTabName();
8938 inputName.ShowDialog();
8939 if (inputName.DialogResult == DialogResult.Cancel) return false;
8940 tabName = inputName.TabName;
8942 this.TopMost = this._cfgCommon.AlwaysTop;
8943 if (!string.IsNullOrEmpty(tabName))
8945 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
8947 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8948 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8966 private void MoveOrCopy(ref bool move, ref bool mark)
8970 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8971 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8979 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8980 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8986 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8991 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8996 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8998 if (StatusText.Focused)
9001 StatusText.SelectAll();
9005 // ListView上でのCtrl+A
9006 for (int i = 0; i < _curList.VirtualListSize; i++)
9008 _curList.SelectedIndices.Add(i);
9013 private void MoveMiddle()
9019 if (_curList.SelectedIndices.Count == 0) return;
9021 int idx = _curList.SelectedIndices[0];
9023 _item = _curList.GetItemAt(0, 25);
9029 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9031 idx2 = _curList.VirtualListSize - 1;
9035 idx -= Math.Abs(idx1 - idx2) / 2;
9036 if (idx < 0) idx = 0;
9038 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9039 _curList.EnsureVisible(idx);
9042 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9044 if (PostBrowser.Document.Links.Count > 0)
9046 UrlDialog.ClearUrl();
9048 string openUrlStr = "";
9050 if (PostBrowser.Document.Links.Count == 1)
9055 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9057 catch (ArgumentException)
9066 if (string.IsNullOrEmpty(urlStr)) return;
9067 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9071 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9074 string linkText = "";
9078 urlStr = linkElm.GetAttribute("title");
9079 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9080 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9081 linkText = linkElm.InnerText;
9082 if (!linkText.StartsWith("http") && !linkText.StartsWith("#") && !linkText.Contains("."))
9084 linkText = "@" + linkText;
9087 catch (ArgumentException)
9096 if (string.IsNullOrEmpty(urlStr)) continue;
9097 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9101 if (UrlDialog.ShowDialog() == DialogResult.OK)
9103 openUrlStr = UrlDialog.SelectedUrl;
9110 this.TopMost = this._cfgCommon.AlwaysTop;
9112 if (string.IsNullOrEmpty(openUrlStr)) return;
9114 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9115 openUrlStr.StartsWith("https://twitter.com/search?q="))
9118 string urlStr = Uri.UnescapeDataString(openUrlStr);
9119 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9120 HashSupl.AddItem(hash);
9121 HashMgr.AddHashToHistory(hash.Trim(), false);
9122 AddNewTabForSearch(hash);
9127 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9128 if (this._cfgCommon.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9129 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9131 OpenUriAsync(openUrlStr);
9137 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9139 if (string.IsNullOrEmpty(_rclickTabName)) return;
9140 ClearTab(_rclickTabName, true);
9143 private void ClearTab(string tabName, bool showWarning)
9147 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9148 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9154 _statuses.ClearTabIds(tabName);
9155 if (ListTab.SelectedTab.Text == tabName)
9158 _anchorFlag = false;
9159 this.PurgeListViewItemCache();
9163 foreach (TabPage tb in ListTab.TabPages)
9165 if (tb.Text == tabName)
9168 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9172 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9174 SetMainWindowTitle();
9175 SetStatusLabelUrl();
9178 private static long followers = 0;
9180 private void SetMainWindowTitle()
9183 StringBuilder ttl = new StringBuilder(256);
9186 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9187 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9188 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9189 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9191 foreach (var tab in _statuses.Tabs.Values)
9193 ur += tab.UnreadCount;
9198 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9199 ttl.Append(Application.ProductName);
9201 switch (this._cfgCommon.DispLatestPost)
9203 case MyCommon.DispTitleEnum.Ver:
9204 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9206 case MyCommon.DispTitleEnum.Post:
9207 if (_history != null && _history.Count > 1)
9208 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9210 case MyCommon.DispTitleEnum.UnreadRepCount:
9211 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9213 case MyCommon.DispTitleEnum.UnreadAllCount:
9214 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9216 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9217 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9219 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9220 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9222 case MyCommon.DispTitleEnum.OwnStatus:
9223 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9224 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9230 this.Text = ttl.ToString();
9232 catch (AccessViolationException)
9234 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9238 private string GetStatusLabelText()
9241 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9242 if (_statuses == null) return "";
9243 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9244 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9245 if (tbRep == null || tbDm == null) return "";
9246 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9251 StringBuilder slbl = new StringBuilder(256);
9254 foreach (var tab in _statuses.Tabs.Values)
9256 ur += tab.UnreadCount;
9258 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9260 tur = tab.UnreadCount;
9271 UnreadAtCounter = urat;
9273 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9274 if (this._cfgCommon.TimelinePeriod == 0)
9276 slbl.Append(Properties.Resources.SetStatusLabelText2);
9280 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9282 return slbl.ToString();
9285 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9289 if (this.InvokeRequired && !this.IsDisposed)
9291 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9295 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9296 if (endpointName == "/statuses/home_timeline" || endpointName == null)
9298 this._apiGauge.ApiLimit = MyCommon.TwitterApiInfo.AccessLimit["/statuses/home_timeline"];
9302 catch (ObjectDisposedException)
9306 catch (InvalidOperationException)
9312 private void SetStatusLabelUrl()
9314 StatusLabelUrl.Text = GetStatusLabelText();
9317 public void SetStatusLabel(string text)
9319 StatusLabel.Text = text;
9322 private static StringBuilder ur = new StringBuilder(64);
9324 private void SetNotifyIconText()
9326 // タスクトレイアイコンのツールチップテキスト書き換え
9328 ur.Remove(0, ur.Length);
9329 if (this._cfgCommon.DispUsername)
9331 ur.Append(tw.Username);
9334 ur.Append(Application.ProductName);
9336 ur.Append("(Debug Build)");
9338 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9341 ur.Append(UnreadCounter);
9343 ur.Append(UnreadAtCounter);
9346 NotifyIcon1.Text = ur.ToString();
9349 internal void CheckReplyTo(string StatusText)
9353 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9355 foreach (Match hm in m)
9357 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9359 hstr += "#" + hm.Result("$3") + " ";
9360 HashSupl.AddItem("#" + hm.Result("$3"));
9363 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9365 hstr += HashMgr.UseHash;
9367 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9369 // 本当にリプライ先指定すべきかどうかの判定
9370 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9372 if (this._cfgCommon.UseAtIdSupplement)
9374 int bCnt = AtIdSupl.ItemCount;
9375 foreach (Match mid in m)
9377 AtIdSupl.AddItem(mid.Result("${id}"));
9379 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9382 // リプライ先ステータスIDの指定がない場合は指定しない
9383 if (_reply_to_id == null) return;
9385 // リプライ先ユーザー名がない場合も指定しない
9386 if (string.IsNullOrEmpty(_reply_to_name))
9388 _reply_to_id = null;
9393 // 次の条件を満たす場合に in_reply_to_status_id 指定
9394 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9395 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9396 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9400 if (StatusText.StartsWith("@"))
9402 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9406 foreach (Match mid in m)
9408 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9413 _reply_to_id = null;
9414 _reply_to_name = null;
9418 private void TweenMain_Resize(object sender, EventArgs e)
9420 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9422 this.Visible = false;
9424 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9426 this.ClientSize = _cfgLocal.FormSize;
9427 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9428 this.DesktopLocation = _cfgLocal.FormLocation;
9429 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9430 if (_cfgLocal.SplitterDistance > this.SplitContainer1.Panel1MinSize &&
9431 _cfgLocal.SplitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9433 this.SplitContainer1.SplitterDistance = _cfgLocal.SplitterDistance; //Splitterの位置設定
9436 StatusText.Multiline = _cfgLocal.StatusMultiline;
9437 if (StatusText.Multiline)
9439 int dis = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9440 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9442 SplitContainer2.SplitterDistance = SplitContainer2.Height - _cfgLocal.StatusTextHeight - SplitContainer2.SplitterWidth;
9444 StatusText.Height = _cfgLocal.StatusTextHeight;
9448 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9450 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9453 if (_cfgLocal.PreviewDistance > this.SplitContainer3.Panel1MinSize && _cfgLocal.PreviewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9455 this.SplitContainer3.SplitterDistance = _cfgLocal.PreviewDistance;
9457 _initialLayout = false;
9459 if (this.WindowState != FormWindowState.Minimized)
9461 _formWindowState = this.WindowState;
9465 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9467 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9468 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9469 if (PlaySoundMenuItem.Checked)
9471 this._cfgCommon.PlaySound = true;
9475 this._cfgCommon.PlaySound = false;
9477 _modifySettingCommon = true;
9480 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9482 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9484 _mySpDis = SplitContainer1.SplitterDistance;
9485 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9486 _modifySettingLocal = true;
9490 private void doRepliedStatusOpen()
9492 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9494 if (MyCommon.IsKeyDown(Keys.Shift))
9496 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9499 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9501 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9502 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9506 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9508 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9509 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9510 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9513 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9518 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9520 doRepliedStatusOpen();
9524 /// UserPicture.Image に設定されている画像を破棄します。
9526 private void ClearUserPicture()
9528 if (this.UserPicture.Image != null)
9530 var oldImage = this.UserPicture.Image;
9531 this.UserPicture.Image = null;
9536 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9538 //発言詳細のアイコン右クリック時のメニュー制御
9539 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9541 string name = _curPost.ImageUrl;
9542 if (name != null && name.Length > 0)
9544 int idx = name.LastIndexOf('/');
9547 name = Path.GetFileName(name.Substring(idx));
9548 if (name.Contains("_normal.") || name.EndsWith("_normal"))
9550 name = name.Replace("_normal", "");
9551 this.IconNameToolStripMenuItem.Text = name;
9552 this.IconNameToolStripMenuItem.Enabled = true;
9556 this.IconNameToolStripMenuItem.Enabled = false;
9557 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9562 this.IconNameToolStripMenuItem.Enabled = false;
9563 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9566 this.ReloadIconToolStripMenuItem.Enabled = true;
9568 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9570 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9574 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9579 this.IconNameToolStripMenuItem.Enabled = false;
9580 this.ReloadIconToolStripMenuItem.Enabled = false;
9581 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9582 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9587 this.IconNameToolStripMenuItem.Enabled = false;
9588 this.ReloadIconToolStripMenuItem.Enabled = false;
9589 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9590 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9592 if (NameLabel.Tag != null)
9594 string id = (string)NameLabel.Tag;
9595 if (id == tw.Username)
9597 FollowToolStripMenuItem.Enabled = false;
9598 UnFollowToolStripMenuItem.Enabled = false;
9599 ShowFriendShipToolStripMenuItem.Enabled = false;
9600 ShowUserStatusToolStripMenuItem.Enabled = true;
9601 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9602 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9603 ListManageUserContextToolStripMenuItem3.Enabled = true;
9607 FollowToolStripMenuItem.Enabled = true;
9608 UnFollowToolStripMenuItem.Enabled = true;
9609 ShowFriendShipToolStripMenuItem.Enabled = true;
9610 ShowUserStatusToolStripMenuItem.Enabled = true;
9611 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9612 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9613 ListManageUserContextToolStripMenuItem3.Enabled = true;
9618 FollowToolStripMenuItem.Enabled = false;
9619 UnFollowToolStripMenuItem.Enabled = false;
9620 ShowFriendShipToolStripMenuItem.Enabled = false;
9621 ShowUserStatusToolStripMenuItem.Enabled = false;
9622 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9623 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9624 ListManageUserContextToolStripMenuItem3.Enabled = false;
9628 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9630 if (_curPost == null) return;
9631 string name = _curPost.ImageUrl;
9632 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9635 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9637 if (this._curPost == null) return;
9639 await this.UserPicture.SetImageFromTask(async () =>
9641 var imageUrl = this._curPost.ImageUrl;
9643 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9644 .ConfigureAwait(false);
9646 return await image.CloneAsync()
9647 .ConfigureAwait(false);
9651 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9653 if (_curPost == null) return;
9654 string name = _curPost.ImageUrl;
9655 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9657 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9659 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9665 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9667 if (_curPost == null) return;
9668 string name = _curPost.ImageUrl;
9670 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9672 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9676 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
9678 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
9680 using (Graphics g = Graphics.FromImage(bmp2))
9682 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
9683 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
9685 bmp2.Save(this.SaveFileDialog1.FileName);
9691 //処理中にキャッシュアウトする可能性あり
9696 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9698 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9699 MultiLineMenuItem.Checked = this.StatusText.Multiline;
9700 _modifySettingLocal = true;
9703 private void StatusText_MultilineChanged(object sender, EventArgs e)
9705 if (this.StatusText.Multiline)
9706 this.StatusText.ScrollBars = ScrollBars.Vertical;
9708 this.StatusText.ScrollBars = ScrollBars.None;
9710 _modifySettingLocal = true;
9713 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9716 StatusText.Multiline = MultiLineMenuItem.Checked;
9717 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9718 if (MultiLineMenuItem.Checked)
9720 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9721 SplitContainer2.SplitterDistance = 0;
9723 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9727 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9729 _modifySettingLocal = true;
9732 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9734 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9735 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9737 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9738 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9739 //Appendix A. Collected ABNF for URI
9740 //http://www.ietf.org/rfc/rfc3986.txt
9744 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9746 if (StatusText.SelectionLength > 0)
9748 string tmp = StatusText.SelectedText;
9749 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9750 if (tmp.StartsWith("http"))
9752 // 文字列が選択されている場合はその文字列について処理
9754 //nico.ms使用、nicovideoにマッチしたら変換
9755 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9757 result = nicoms.Shorten(tmp);
9759 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9761 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9764 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9765 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9766 result = resultUri.ToString();
9768 catch (WebApiException e)
9770 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9773 catch (UriFormatException e)
9775 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9784 if (!string.IsNullOrEmpty(result))
9786 urlUndo undotmp = new urlUndo();
9788 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9789 StatusText.SelectedText = result;
9792 undotmp.Before = tmp;
9793 undotmp.After = result;
9795 if (urlUndoBuffer == null)
9797 urlUndoBuffer = new List<urlUndo>();
9798 UrlUndoToolStripMenuItem.Enabled = true;
9801 urlUndoBuffer.Add(undotmp);
9807 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9808 @"(?<url>(?<protocol>https?://)" +
9809 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9810 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9811 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9812 // 正規表現にマッチしたURL文字列をtinyurl化
9813 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9815 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9816 string tmp = mt.Result("${url}");
9817 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9818 urlUndo undotmp = new urlUndo();
9821 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9823 //nico.ms使用、nicovideoにマッチしたら変換
9824 if (SettingDialog.Nicoms && Regex.IsMatch(tmp, nico))
9826 result = nicoms.Shorten(tmp);
9828 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9830 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9833 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9834 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9835 result = resultUri.ToString();
9837 catch (HttpRequestException e)
9839 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9840 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9841 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9843 this.StatusLabel.Text = Converter_Type + ":" + message;
9846 catch (WebApiException e)
9848 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9851 catch (UriFormatException e)
9853 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9862 if (!string.IsNullOrEmpty(result))
9864 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9865 StatusText.SelectedText = result;
9867 undotmp.Before = mt.Result("${url}");
9868 undotmp.After = result;
9870 if (urlUndoBuffer == null)
9872 urlUndoBuffer = new List<urlUndo>();
9873 UrlUndoToolStripMenuItem.Enabled = true;
9876 urlUndoBuffer.Add(undotmp);
9884 private void doUrlUndo()
9886 if (urlUndoBuffer != null)
9888 string tmp = StatusText.Text;
9889 foreach (urlUndo data in urlUndoBuffer)
9891 tmp = tmp.Replace(data.After, data.Before);
9893 StatusText.Text = tmp;
9894 urlUndoBuffer = null;
9895 UrlUndoToolStripMenuItem.Enabled = false;
9896 StatusText.SelectionStart = 0;
9897 StatusText.SelectionLength = 0;
9901 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9903 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9906 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9908 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9911 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9913 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9916 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9918 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9921 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9923 if (!await UrlConvertAsync(SettingDialog.AutoShortUrlFirst))
9925 MyCommon.UrlConverter svc = SettingDialog.AutoShortUrlFirst;
9926 Random rnd = new Random();
9927 // 前回使用した短縮URLサービス以外を選択する
9930 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9932 while (svc == SettingDialog.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9933 await UrlConvertAsync(svc);
9937 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9942 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9944 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9945 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9946 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9947 _modifySettingCommon = true;
9950 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9952 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9953 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9954 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9955 _modifySettingCommon = true;
9958 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9960 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9961 MenuStrip1.Tag = new Object();
9962 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9965 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9967 if (this.Tag != null) // 設定された戻り先へ遷移
9969 if (this.Tag == this.ListTab.SelectedTab)
9970 ((Control)this.ListTab.SelectedTab.Tag).Select();
9972 ((Control)this.Tag).Select();
9974 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9976 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9978 this.Tag = ListTab.SelectedTab.Tag;
9979 ((Control)this.Tag).Select();
9982 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9983 MenuStrip1.Tag = null;
9986 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9988 DetailsListView lst = (DetailsListView)sender;
9989 if (_cfgLocal == null) return;
9993 _cfgLocal.Width1 = lst.Columns[0].Width;
9994 _cfgLocal.Width3 = lst.Columns[1].Width;
9998 int[] darr = new int[lst.Columns.Count];
9999 for (int i = 0; i < lst.Columns.Count; i++)
10001 darr[lst.Columns[i].DisplayIndex] = i;
10003 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10005 for (int i = 0; i < lst.Columns.Count; i++)
10010 _cfgLocal.DisplayIndex1 = i;
10013 _cfgLocal.DisplayIndex2 = i;
10016 _cfgLocal.DisplayIndex3 = i;
10019 _cfgLocal.DisplayIndex4 = i;
10022 _cfgLocal.DisplayIndex5 = i;
10025 _cfgLocal.DisplayIndex6 = i;
10028 _cfgLocal.DisplayIndex7 = i;
10031 _cfgLocal.DisplayIndex8 = i;
10035 _cfgLocal.Width1 = lst.Columns[0].Width;
10036 _cfgLocal.Width2 = lst.Columns[1].Width;
10037 _cfgLocal.Width3 = lst.Columns[2].Width;
10038 _cfgLocal.Width4 = lst.Columns[3].Width;
10039 _cfgLocal.Width5 = lst.Columns[4].Width;
10040 _cfgLocal.Width6 = lst.Columns[5].Width;
10041 _cfgLocal.Width7 = lst.Columns[6].Width;
10042 _cfgLocal.Width8 = lst.Columns[7].Width;
10044 _modifySettingLocal = true;
10045 _isColumnChanged = true;
10048 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10050 DetailsListView lst = (DetailsListView)sender;
10051 if (_cfgLocal == null) return;
10054 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10056 _cfgLocal.Width1 = lst.Columns[0].Width;
10057 _modifySettingLocal = true;
10058 _isColumnChanged = true;
10060 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10062 _cfgLocal.Width3 = lst.Columns[1].Width;
10063 _modifySettingLocal = true;
10064 _isColumnChanged = true;
10069 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10071 _cfgLocal.Width1 = lst.Columns[0].Width;
10072 _modifySettingLocal = true;
10073 _isColumnChanged = true;
10075 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10077 _cfgLocal.Width2 = lst.Columns[1].Width;
10078 _modifySettingLocal = true;
10079 _isColumnChanged = true;
10081 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10083 _cfgLocal.Width3 = lst.Columns[2].Width;
10084 _modifySettingLocal = true;
10085 _isColumnChanged = true;
10087 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10089 _cfgLocal.Width4 = lst.Columns[3].Width;
10090 _modifySettingLocal = true;
10091 _isColumnChanged = true;
10093 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10095 _cfgLocal.Width5 = lst.Columns[4].Width;
10096 _modifySettingLocal = true;
10097 _isColumnChanged = true;
10099 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10101 _cfgLocal.Width6 = lst.Columns[5].Width;
10102 _modifySettingLocal = true;
10103 _isColumnChanged = true;
10105 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10107 _cfgLocal.Width7 = lst.Columns[6].Width;
10108 _modifySettingLocal = true;
10109 _isColumnChanged = true;
10111 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10113 _cfgLocal.Width8 = lst.Columns[7].Width;
10114 _modifySettingLocal = true;
10115 _isColumnChanged = true;
10118 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10121 // SaveConfigsLocal();
10125 public string WebBrowser_GetSelectionText(ref WebBrowser ComponentInstance)
10127 //発言詳細で「選択文字列をコピー」を行う
10128 //WebBrowserコンポーネントのインスタンスを渡す
10129 Type typ = ComponentInstance.ActiveXInstance.GetType();
10130 object _SelObj = typ.InvokeMember("selection", BindingFlags.GetProperty, null, ComponentInstance.Document.DomDocument, null);
10131 object _objRange = _SelObj.GetType().InvokeMember("createRange", BindingFlags.InvokeMethod, null, _SelObj, null);
10132 return (string)_objRange.GetType().InvokeMember("text", BindingFlags.GetProperty, null, _objRange, null);
10135 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10138 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10141 Clipboard.SetDataObject(_selText, false, 5, 100);
10143 catch (Exception ex)
10145 MessageBox.Show(ex.Message);
10149 private void doSearchToolStrip(string url)
10151 //発言詳細で「選択文字列で検索」(選択文字列取得)
10152 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10154 if (_selText != null)
10156 if (url == Properties.Resources.SearchItem4Url)
10159 AddNewTabForSearch(_selText);
10163 string tmp = string.Format(url, Uri.EscapeUriString(_selText));
10168 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10171 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10174 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10176 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10179 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10181 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10184 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10186 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10189 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10193 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10194 foreach (Match m in mc)
10196 if (m.Groups["url"].Value == this._postBrowserStatusText)
10198 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10204 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10206 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10208 catch (Exception ex)
10210 MessageBox.Show(ex.Message);
10214 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10216 // URLコピーの項目の表示/非表示
10217 if (PostBrowser.StatusText.StartsWith("http"))
10219 this._postBrowserStatusText = PostBrowser.StatusText;
10220 string name = GetUserId();
10221 UrlCopyContextMenuItem.Enabled = true;
10224 FollowContextMenuItem.Enabled = true;
10225 RemoveContextMenuItem.Enabled = true;
10226 FriendshipContextMenuItem.Enabled = true;
10227 ShowUserStatusContextMenuItem.Enabled = true;
10228 SearchPostsDetailToolStripMenuItem.Enabled = true;
10229 IdFilterAddMenuItem.Enabled = true;
10230 ListManageUserContextToolStripMenuItem.Enabled = true;
10231 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10235 FollowContextMenuItem.Enabled = false;
10236 RemoveContextMenuItem.Enabled = false;
10237 FriendshipContextMenuItem.Enabled = false;
10238 ShowUserStatusContextMenuItem.Enabled = false;
10239 SearchPostsDetailToolStripMenuItem.Enabled = false;
10240 IdFilterAddMenuItem.Enabled = false;
10241 ListManageUserContextToolStripMenuItem.Enabled = false;
10242 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10245 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10246 UseHashtagMenuItem.Enabled = true;
10248 UseHashtagMenuItem.Enabled = false;
10252 this._postBrowserStatusText = "";
10253 UrlCopyContextMenuItem.Enabled = false;
10254 FollowContextMenuItem.Enabled = false;
10255 RemoveContextMenuItem.Enabled = false;
10256 FriendshipContextMenuItem.Enabled = false;
10257 ShowUserStatusContextMenuItem.Enabled = false;
10258 SearchPostsDetailToolStripMenuItem.Enabled = false;
10259 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10260 UseHashtagMenuItem.Enabled = false;
10261 IdFilterAddMenuItem.Enabled = false;
10262 ListManageUserContextToolStripMenuItem.Enabled = false;
10264 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10265 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10266 if (_selText == null)
10268 SelectionSearchContextMenuItem.Enabled = false;
10269 SelectionCopyContextMenuItem.Enabled = false;
10270 SelectionTranslationToolStripMenuItem.Enabled = false;
10274 SelectionSearchContextMenuItem.Enabled = true;
10275 SelectionCopyContextMenuItem.Enabled = true;
10276 SelectionTranslationToolStripMenuItem.Enabled = true;
10278 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10279 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10280 bool fAllFlag = false;
10281 foreach (Match mu in ma)
10283 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10289 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10291 if (_curPost == null)
10292 TranslationToolStripMenuItem.Enabled = false;
10294 TranslationToolStripMenuItem.Enabled = true;
10299 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10301 //発言詳細の選択文字列で現在のタブを検索
10302 string _selText = WebBrowser_GetSelectionText(ref PostBrowser);
10304 if (_selText != null)
10306 var searchOptions = new SearchWordDialog.SearchOptions(
10307 SearchWordDialog.SearchType.Timeline,
10310 caseSensitive: false,
10313 this.SearchDialog.ResultOptions = searchOptions;
10316 searchOptions.Query,
10317 searchOptions.CaseSensitive,
10318 searchOptions.UseRegex,
10319 SEARCHTYPE.NextSearch);
10323 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10325 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10326 _modifySettingLocal = true;
10329 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10331 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10333 SelectMedia_DragDrop(e);
10335 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10337 var url = GetUrlFromDataObject(e.Data);
10340 if (url.Item2 == null)
10341 appendText = url.Item1;
10343 appendText = url.Item2 + " " + url.Item1;
10345 if (this.StatusText.TextLength == 0)
10346 this.StatusText.Text = appendText;
10348 this.StatusText.Text += " " + appendText;
10350 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10352 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10353 if (data != null) StatusText.Text += data;
10358 /// IDataObject から URL とタイトルの対を取得します
10361 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10363 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10364 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10365 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10367 if (data.GetDataPresent("text/x-moz-url"))
10369 // Firefox, Google Chrome で利用可能
10370 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10372 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10374 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10375 if (lines.Length < 2)
10376 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10378 return new Tuple<string, string>(lines[0], lines[1]);
10381 else if (data.GetDataPresent("IESiteModeToUrl"))
10383 // Internet Exproler 用
10384 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10386 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10388 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10389 if (lines.Length < 2)
10390 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10392 return new Tuple<string, string>(lines[0], lines[1]);
10395 else if (data.GetDataPresent("UniformResourceLocatorW"))
10399 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10401 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10402 return new Tuple<string, string>(url, null);
10406 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10409 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10411 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10413 SelectMedia_DragEnter(e);
10417 private void TweenMain_DragOver(object sender, DragEventArgs e)
10419 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10421 SelectMedia_DragOver(e);
10423 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10425 e.Effect = DragDropEffects.Copy;
10427 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10429 e.Effect = DragDropEffects.Copy;
10433 e.Effect = DragDropEffects.None;
10437 public bool IsNetworkAvailable()
10440 nw = MyCommon.IsNetworkAvailable();
10441 _myStatusOnline = nw;
10445 public Task OpenUriAsync(string UriString)
10447 return Task.Run(() =>
10449 string myPath = UriString;
10453 var configBrowserPath = this._cfgLocal.BrowserPath;
10454 if (!string.IsNullOrEmpty(configBrowserPath))
10456 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10458 int sep = configBrowserPath.IndexOf("\"", 2);
10459 string browserPath = configBrowserPath.Substring(1, sep - 1);
10461 if (sep < configBrowserPath.Length - 1)
10463 arg = configBrowserPath.Substring(sep + 1);
10465 myPath = arg + " " + myPath;
10466 System.Diagnostics.Process.Start(browserPath, myPath);
10470 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10475 System.Diagnostics.Process.Start(myPath);
10480 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10485 private void ListTabSelect(TabPage _tab)
10489 this.PurgeListViewItemCache();
10492 _curList = (DetailsListView)_tab.Tag;
10493 if (_curList.SelectedIndices.Count > 0)
10495 _curItemIndex = _curList.SelectedIndices[0];
10496 _curPost = GetCurTabPost(_curItemIndex);
10500 _curItemIndex = -1;
10504 _anchorPost = null;
10505 _anchorFlag = false;
10509 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10513 for (int i = 0; i < _curList.Columns.Count; i++)
10515 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10520 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10522 ListTabSelect(e.TabPage);
10525 private void SelectListItem(DetailsListView LView, int Index)
10528 Rectangle bnd = new Rectangle();
10530 var item = LView.FocusedItem;
10539 LView.SelectedIndices.Clear();
10541 while (LView.SelectedIndices.Count > 0);
10542 item = LView.Items[Index];
10543 item.Selected = true;
10544 item.Focused = true;
10546 if (flg) LView.Invalidate(bnd);
10549 private void SelectListItem(DetailsListView LView , int[] Index, int[] FocusedIndex)
10552 Rectangle bnd = new Rectangle();
10554 var item = LView.FocusedItem;
10562 if (Index != null && !(Index.Length == 1 && Index[0] == -1))
10566 LView.SelectedIndices.Clear();
10568 while (LView.SelectedIndices.Count > 0);
10569 foreach (int idx in Index)
10571 if (idx > -1 && LView.VirtualListSize > idx)
10573 LView.SelectedIndices.Add(idx);
10574 if (fIdx == -1) fIdx = idx;
10578 if (FocusedIndex[1] > -1 && LView.VirtualListSize > FocusedIndex[1])
10580 LView.SelectionMark = FocusedIndex[1];
10582 if (FocusedIndex[0] > -1 && LView.VirtualListSize > FocusedIndex[0])
10584 LView.Items[FocusedIndex[0]].Focused = true;
10586 else if (fIdx > -1)
10588 LView.Items[fIdx].Focused = true;
10591 if (flg) LView.Invalidate(bnd);
10594 private void RunAsync(GetWorkerArg args)
10596 BackgroundWorker bw = null;
10597 if (args.type != MyCommon.WORKERTYPE.Follower)
10599 for (int i = 0; i < _bw.Length; i++)
10601 if (_bw[i] != null && !_bw[i].IsBusy)
10609 for (int i = 0; i < _bw.Length; i++)
10611 if (_bw[i] == null)
10613 _bw[i] = new BackgroundWorker();
10615 bw.WorkerReportsProgress = true;
10616 bw.WorkerSupportsCancellation = true;
10617 bw.DoWork += GetTimelineWorker_DoWork;
10618 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10619 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10627 if (_bwFollower == null)
10629 _bwFollower = new BackgroundWorker();
10631 bw.WorkerReportsProgress = true;
10632 bw.WorkerSupportsCancellation = true;
10633 bw.DoWork += GetTimelineWorker_DoWork;
10634 bw.ProgressChanged += GetTimelineWorker_ProgressChanged;
10635 bw.RunWorkerCompleted += GetTimelineWorker_RunWorkerCompleted;
10639 if (_bwFollower.IsBusy == false)
10643 if (bw == null) return;
10645 bw.RunWorkerAsync(args);
10648 private void StartUserStream()
10650 tw.NewPostFromStream += tw_NewPostFromStream;
10651 tw.UserStreamStarted += tw_UserStreamStarted;
10652 tw.UserStreamStopped += tw_UserStreamStopped;
10653 tw.PostDeleted += tw_PostDeleted;
10654 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10656 MenuItemUserStream.Text = "&UserStream ■";
10657 MenuItemUserStream.Enabled = true;
10658 StopToolStripMenuItem.Text = "&Start";
10659 StopToolStripMenuItem.Enabled = true;
10660 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
10663 private async void TweenMain_Shown(object sender, EventArgs e)
10667 PostBrowser.Url = new Uri("about:blank");
10668 PostBrowser.DocumentText = ""; //発言詳細部初期化
10674 NotifyIcon1.Visible = true;
10676 if (this.IsNetworkAvailable())
10678 this.RefreshMuteUserIdsAsync();
10679 GetTimeline(MyCommon.WORKERTYPE.BlockIds, 0, "");
10680 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10681 if (this._cfgCommon.StartupFollowers)
10683 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10685 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10687 _waitTimeline = true;
10688 GetTimeline(MyCommon.WORKERTYPE.Timeline, 1, "");
10690 GetTimeline(MyCommon.WORKERTYPE.Reply, 1, "");
10692 GetTimeline(MyCommon.WORKERTYPE.DirectMessegeRcv, 1, "");
10693 if (this._cfgCommon.GetFav)
10696 GetTimeline(MyCommon.WORKERTYPE.Favorites, 1, "");
10698 _waitPubSearch = true;
10699 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, ""); //tabname="":全タブ
10700 _waitUserTimeline = true;
10701 GetTimeline(MyCommon.WORKERTYPE.UserTimeline, 1, ""); //tabname="":全タブ
10703 GetTimeline(MyCommon.WORKERTYPE.List, 1, ""); //tabname="":全タブ
10706 while (this.IsInitialRead())
10708 await Task.Delay(5000);
10711 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10713 if (MyCommon._endingFlag)
10717 if (MyCommon._endingFlag) return;
10719 if (ApplicationSettings.VersionInfoUrl != null)
10721 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10722 if (this._cfgCommon.StartupVersion)
10723 await this.CheckNewVersion(true);
10727 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10728 this.VerUpMenuItem.Enabled = false;
10729 this.VerUpMenuItem.Available = false;
10730 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10734 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10735 GetTimeline(MyCommon.WORKERTYPE.Follower, 0, "");
10738 if (!tw.GetNoRetweetSuccess)
10739 GetTimeline(MyCommon.WORKERTYPE.NoRetweetIds, 0, "");
10742 if (SettingDialog.TwitterConfiguration.PhotoSizeLimit == 0)
10743 GetTimeline(MyCommon.WORKERTYPE.Configuration, 0, "");
10745 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10746 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10748 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10749 SettingStripMenuItem_Click(null, null);
10756 TimerTimeline.Enabled = true;
10759 private bool IsInitialRead()
10761 return _waitTimeline || _waitReply || _waitDm || _waitFav || _waitPubSearch || _waitUserTimeline || _waitLists;
10764 private void doGetFollowersMenu()
10766 GetTimeline(MyCommon.WORKERTYPE.Follower, 1, "");
10767 DispSelectedPost(true);
10770 private void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10772 doGetFollowersMenu();
10775 private void doReTweetUnofficial()
10778 if (this.ExistCurrentPost)
10780 if (_curPost.IsDm ||
10781 !StatusText.Enabled) return;
10783 if (_curPost.IsProtect)
10785 MessageBox.Show("Protected.");
10788 string rtdata = _curPost.Text;
10789 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10791 this._reply_to_id = null;
10792 this._reply_to_name = null;
10794 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
10796 StatusText.SelectionStart = 0;
10797 StatusText.Focus();
10801 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10803 doReTweetUnofficial();
10806 private void doReTweetOfficial(bool isConfirm)
10809 if (this.ExistCurrentPost)
10811 if (_curPost.IsProtect)
10813 MessageBox.Show("Protected.");
10814 _DoFavRetweetFlags = false;
10817 if (_curList.SelectedIndices.Count > 15)
10819 MessageBox.Show(Properties.Resources.RetweetLimitText);
10820 _DoFavRetweetFlags = false;
10823 else if (_curList.SelectedIndices.Count > 1)
10825 string QuestionText = Properties.Resources.RetweetQuestion2;
10826 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10827 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10829 case DialogResult.Cancel:
10830 case DialogResult.No:
10831 _DoFavRetweetFlags = false;
10837 if (_curPost.IsDm || _curPost.IsMe)
10839 _DoFavRetweetFlags = false;
10842 if (!this._cfgCommon.RetweetNoConfirm)
10844 string Questiontext = Properties.Resources.RetweetQuestion1;
10845 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10846 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10848 _DoFavRetweetFlags = false;
10853 GetWorkerArg args = new GetWorkerArg();
10854 args.ids = new List<long>();
10855 args.sIds = new List<long>();
10856 args.tName = _curTab.Text;
10857 args.type = MyCommon.WORKERTYPE.Retweet;
10858 foreach (int idx in _curList.SelectedIndices)
10860 PostClass post = GetCurTabPost(idx);
10861 if (!post.IsMe && !post.IsProtect && !post.IsDm) args.ids.Add(post.StatusId);
10867 private void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
10869 doReTweetOfficial(true);
10872 private void FavoritesRetweetOriginal()
10874 if (!this.ExistCurrentPost) return;
10875 _DoFavRetweetFlags = true;
10876 doReTweetOfficial(true);
10877 if (_DoFavRetweetFlags)
10879 _DoFavRetweetFlags = false;
10880 FavoriteChange(true, false);
10884 private void FavoritesRetweetUnofficial()
10886 if (this.ExistCurrentPost && !_curPost.IsDm)
10888 _DoFavRetweetFlags = true;
10889 FavoriteChange(true);
10890 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10892 _DoFavRetweetFlags = false;
10893 doReTweetUnofficial();
10899 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10901 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10902 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10903 /// <returns>復元されたツイート本文</returns>
10904 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10906 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10909 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10911 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10913 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10917 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10919 statusHtml = statusHtml.Replace("<br>", " ");
10921 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10922 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10923 statusHtml = statusHtml.Replace(" ", " ");
10925 return WebUtility.HtmlDecode(statusHtml);
10928 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10930 if (_curPost != null)
10931 DispSelectedPost(true);
10934 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10936 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10937 DebugModeToolStripMenuItem.Visible = true;
10939 DebugModeToolStripMenuItem.Visible = false;
10942 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10944 SettingDialog.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10947 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10949 ToolStripMenuItemUrlAutoShorten.Checked = SettingDialog.UrlConvertAuto;
10952 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10954 if (TraceOutToolStripMenuItem.Checked)
10955 MyCommon.TraceFlag = true;
10957 MyCommon.TraceFlag = false;
10960 private void TweenMain_Deactivate(object sender, EventArgs e)
10962 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10963 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10966 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10968 if (string.IsNullOrEmpty(_rclickTabName)) return;
10969 TabRename(ref _rclickTabName);
10972 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10974 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10977 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10979 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10983 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
10985 e.Result = tw.GetInfoApi();
10988 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10990 StringBuilder tmp = new StringBuilder();
10992 using (FormInfo dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
10996 var result = (TwitterApiStatus)dlg.Result;
10998 if (result == null)
11000 var accessLevel = result.AccessLevel;
11001 var timelineLimit = result.AccessLimit["/statuses/home_timeline"];
11002 var mediaLimit = result.MediaUploadLimit;
11004 tmp.AppendLine(Properties.Resources.ApiInfo1 + timelineLimit.AccessLimitCount);
11005 tmp.AppendLine(Properties.Resources.ApiInfo2 + timelineLimit.AccessLimitRemain);
11006 tmp.AppendLine(Properties.Resources.ApiInfo3 + timelineLimit.AccessLimitResetDate);
11007 tmp.AppendLine(Properties.Resources.ApiInfo7 + (tw.UserStreamEnabled ? Properties.Resources.Enable : Properties.Resources.Disable));
11010 tmp.AppendLine(Properties.Resources.ApiInfo8 + accessLevel);
11011 SetStatusLabelUrl();
11014 tmp.AppendLine(Properties.Resources.ApiInfo9 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitCount.ToString()));
11015 tmp.AppendLine(Properties.Resources.ApiInfo10 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitRemain.ToString()));
11016 tmp.AppendLine(Properties.Resources.ApiInfo11 + (mediaLimit == null ? Properties.Resources.ApiInfo91 : mediaLimit.AccessLimitResetDate.ToString()));
11020 tmp.Append(Properties.Resources.ApiInfo5);
11024 MessageBox.Show(tmp.ToString(), Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11027 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11030 if (_curPost != null) id = _curPost.ScreenName;
11034 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11036 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11037 e.Result = arg.tw.PostFollowCommand(arg.id);
11040 private void FollowCommand(string id)
11042 using (InputTabName inputName = new InputTabName())
11044 inputName.FormTitle = "Follow";
11045 inputName.FormDescription = Properties.Resources.FRMessage1;
11046 inputName.TabName = id;
11047 if (inputName.ShowDialog() == DialogResult.OK &&
11048 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11050 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11052 arg.id = inputName.TabName.Trim();
11053 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11054 FollowCommand_DoWork,
11058 _info.ShowDialog();
11059 string ret = (string)_info.Result;
11060 if (!string.IsNullOrEmpty(ret))
11061 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11063 MessageBox.Show(Properties.Resources.FRMessage3);
11069 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11072 if (_curPost != null) id = _curPost.ScreenName;
11073 RemoveCommand(id, false);
11076 private class FollowRemoveCommandArgs
11082 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11084 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11085 e.Result = arg.tw.PostRemoveCommand(arg.id);
11088 private void RemoveCommand(string id, bool skipInput)
11090 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11095 using (InputTabName inputName = new InputTabName())
11097 inputName.FormTitle = "Unfollow";
11098 inputName.FormDescription = Properties.Resources.FRMessage1;
11099 inputName.TabName = id;
11100 if (inputName.ShowDialog() == DialogResult.OK &&
11101 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11104 arg.id = inputName.TabName.Trim();
11113 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11114 RemoveCommand_DoWork,
11118 _info.ShowDialog();
11119 string ret = (string)_info.Result;
11120 if (!string.IsNullOrEmpty(ret))
11121 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11123 MessageBox.Show(Properties.Resources.FRMessage3);
11127 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11130 if (_curPost != null)
11131 id = _curPost.ScreenName;
11133 ShowFriendship(id);
11136 private class ShowFriendshipArgs
11139 public class FriendshipInfo
11141 public string id = "";
11142 public bool isFollowing = false;
11143 public bool isFollowed = false;
11144 public FriendshipInfo(string id)
11149 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11152 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11154 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11155 string result = "";
11156 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11158 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11159 if (!string.IsNullOrEmpty(rt))
11161 if (string.IsNullOrEmpty(result)) result = rt;
11167 private void ShowFriendship(string id)
11169 ShowFriendshipArgs args = new ShowFriendshipArgs();
11171 using (InputTabName inputName = new InputTabName())
11173 inputName.FormTitle = "Show Friendships";
11174 inputName.FormDescription = Properties.Resources.FRMessage1;
11175 inputName.TabName = id;
11176 if (inputName.ShowDialog() == DialogResult.OK &&
11177 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11180 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11181 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11182 ShowFriendship_DoWork,
11186 _info.ShowDialog();
11187 ret = (string)_info.Result;
11189 string result = "";
11190 if (string.IsNullOrEmpty(ret))
11192 if (args.ids[0].isFollowing)
11194 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11198 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11200 if (args.ids[0].isFollowed)
11202 result += Properties.Resources.GetFriendshipInfo3;
11206 result += Properties.Resources.GetFriendshipInfo4;
11208 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11214 MessageBox.Show(result);
11219 private void ShowFriendship(string[] ids)
11221 foreach (string id in ids)
11224 ShowFriendshipArgs args = new ShowFriendshipArgs();
11226 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11227 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11228 ShowFriendship_DoWork,
11232 _info.ShowDialog();
11233 ret = (string)_info.Result;
11235 string result = "";
11236 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11238 if (string.IsNullOrEmpty(ret))
11241 if (fInfo.isFollowing)
11243 ff += Properties.Resources.GetFriendshipInfo1;
11247 ff += Properties.Resources.GetFriendshipInfo2;
11250 ff += System.Environment.NewLine + " ";
11251 if (fInfo.isFollowed)
11253 ff += Properties.Resources.GetFriendshipInfo3;
11257 ff += Properties.Resources.GetFriendshipInfo4;
11259 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11260 if (fInfo.isFollowing)
11262 if (MessageBox.Show(
11263 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11264 MessageBoxButtons.YesNo,
11265 MessageBoxIcon.Question,
11266 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11268 RemoveCommand(fInfo.id, true);
11273 MessageBox.Show(result);
11278 MessageBox.Show(ret);
11283 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11285 doShowUserStatus(tw.Username, false);
11286 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11288 // doShowUserStatus(tw.Username, false);
11292 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11297 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11298 // URLから切り出した文字列を渡す
11300 public bool IsTwitterId(string name)
11302 if (SettingDialog.TwitterConfiguration.NonUsernamePaths == null || SettingDialog.TwitterConfiguration.NonUsernamePaths.Length == 0)
11303 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11305 return !SettingDialog.TwitterConfiguration.NonUsernamePaths.Contains(name.ToLower());
11308 private string GetUserId()
11310 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11311 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11312 return m.Result("${ScreenName}");
11317 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11319 string name = GetUserId();
11320 if (name != null) FollowCommand(name);
11323 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11325 string name = GetUserId();
11326 if (name != null) RemoveCommand(name, false);
11329 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11331 string name = GetUserId();
11332 if (name != null) ShowFriendship(name);
11335 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11337 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11338 List<string> ids = new List<string>();
11339 foreach (Match mu in ma)
11341 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11343 ids.Add(mu.Result("${ScreenName}"));
11346 ShowFriendship(ids.ToArray());
11349 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11351 string name = GetUserId();
11352 if (name != null) ShowUserStatus(name);
11355 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11357 string name = GetUserId();
11358 if (name != null) AddNewTabForUserTimeline(name);
11361 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11363 string name = GetUserId();
11364 if (name != null) AddNewTabForSearch("@" + name);
11367 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11369 _modifySettingCommon = true;
11372 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11374 _modifySettingCommon = true;
11377 private void doQuote()
11381 if (this.ExistCurrentPost)
11383 if (_curPost.IsDm ||
11384 !StatusText.Enabled) return;
11386 if (_curPost.IsProtect)
11388 MessageBox.Show("Protected.");
11391 string rtdata = _curPost.Text;
11392 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11394 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11395 if (_curPost.RetweetedId == null)
11397 _reply_to_id = _curPost.StatusId;
11401 _reply_to_id = _curPost.RetweetedId.Value;
11403 _reply_to_name = _curPost.ScreenName;
11405 StatusText.SelectionStart = 0;
11406 StatusText.Focus();
11410 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11415 private void SearchButton_Click(object sender, EventArgs e)
11418 Control pnl = ((Control)sender).Parent;
11419 if (pnl == null) return;
11420 string tbName = pnl.Parent.Text;
11421 TabClass tb = _statuses.Tabs[tbName];
11422 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11423 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11424 cmb.Text = cmb.Text.Trim();
11425 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11426 bool Quote = false;
11427 StringBuilder buf = new StringBuilder();
11428 char[] c = cmb.Text.ToCharArray();
11429 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11431 if (cnt > cmb.Text.Length - 4)
11433 buf.Append(cmb.Text.Substring(cnt));
11442 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11444 buf.Append(" OR ");
11449 buf.Append(c[cnt]);
11451 cmb.Text = buf.ToString();
11453 tb.SearchWords = cmb.Text;
11454 tb.SearchLang = cmbLang.Text;
11455 if (string.IsNullOrEmpty(cmb.Text))
11457 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11461 if (tb.IsQueryChanged())
11463 int idx = ((ComboBox)pnl.Controls["comboSearch"]).Items.IndexOf(tb.SearchWords);
11464 if (idx > -1) ((ComboBox)pnl.Controls["comboSearch"]).Items.RemoveAt(idx);
11465 ((ComboBox)pnl.Controls["comboSearch"]).Items.Insert(0, tb.SearchWords);
11466 cmb.Text = tb.SearchWords;
11468 DetailsListView lst = (DetailsListView)pnl.Parent.Tag;
11469 this.PurgeListViewItemCache();
11470 lst.VirtualListSize = 0;
11471 _statuses.ClearTabIds(tbName);
11472 SaveConfigsTabs(); //検索条件の保存
11475 GetTimeline(MyCommon.WORKERTYPE.PublicSearch, 1, tbName);
11476 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11479 private void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11485 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11487 if (_statuses.RemovedTab.Count == 0)
11489 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11494 TabClass tb = _statuses.RemovedTab.Pop();
11495 if (tb.TabType == MyCommon.TabUsageType.Related)
11497 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11498 if (relatedTab != null)
11500 // 関連発言なら既存のタブを置き換える
11501 tb.TabName = relatedTab.TabName;
11502 this.ClearTab(tb.TabName, false);
11503 _statuses.Tabs[tb.TabName] = tb;
11504 for (int i = 0; i < ListTab.TabPages.Count; i++)
11506 if (tb.TabName == ListTab.TabPages[i].Text)
11508 ListTab.SelectedIndex = i;
11509 ListTabSelect(ListTab.TabPages[i]);
11516 const string TabName = "Related Tweets";
11517 string renamed = TabName;
11518 for (int i = 2; i <= 100; i++)
11520 if (!_statuses.ContainsTab(renamed)) break;
11521 renamed = TabName + i.ToString();
11523 tb.TabName = renamed;
11524 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11525 _statuses.Tabs.Add(renamed, tb); // 後に
11526 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11527 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11532 string renamed = tb.TabName;
11533 for (int i = 1; i < int.MaxValue; i++)
11535 if (!_statuses.ContainsTab(renamed)) break;
11536 renamed = tb.TabName + "(" + i.ToString() + ")";
11538 tb.TabName = renamed;
11539 _statuses.Tabs.Add(renamed, tb); // 先に
11540 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11541 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11542 ListTabSelect(ListTab.TabPages[ListTab.TabPages.Count - 1]);
11548 private void doMoveToRTHome()
11550 if (_curList.SelectedIndices.Count > 0)
11552 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11553 if (post.RetweetedId != null)
11555 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11560 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11565 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11567 string name = GetUserId();
11573 if (_curList.SelectedIndices.Count == 0) return;
11576 if (!SelectTab(out tabName)) return;
11580 MoveOrCopy(ref mv, ref mk);
11582 PostFilterRule fc = new PostFilterRule();
11583 fc.FilterName = name;
11584 fc.UseNameField = true;
11585 fc.MoveMatches = mv;
11586 fc.MarkMatches = mk;
11587 fc.UseRegex = false;
11588 fc.FilterByUrl = false;
11589 _statuses.Tabs[tabName].AddFilter(fc);
11591 this.ApplyPostFilters();
11596 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11600 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11602 if (menuItem.Owner == this.ContextMenuPostBrowser)
11604 user = GetUserId();
11605 if (user == null) return;
11607 else if (this._curPost != null)
11609 user = this._curPost.ScreenName;
11616 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11618 string res = this.tw.GetListsApi();
11620 if (!string.IsNullOrEmpty(res))
11622 MessageBox.Show("Failed to get lists. (" + res + ")");
11627 using (MyLists listSelectForm = new MyLists(user, this.tw))
11629 listSelectForm.ShowDialog(this);
11633 private void SearchControls_Enter(object sender, EventArgs e)
11635 Control pnl = (Control)sender;
11636 foreach (Control ctl in pnl.Controls)
11638 ctl.TabStop = true;
11642 private void SearchControls_Leave(object sender, EventArgs e)
11644 Control pnl = (Control)sender;
11645 foreach (Control ctl in pnl.Controls)
11647 ctl.TabStop = false;
11651 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
11653 if (ListTab.SelectedTab != null)
11655 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
11656 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
11660 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
11662 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
11665 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
11666 HashStripSplitButton.Text = HashMgr.UseHash;
11667 HashToggleMenuItem.Checked = true;
11668 HashToggleToolStripMenuItem.Checked = true;
11670 _modifySettingCommon = true;
11674 private void StatusLabel_DoubleClick(object sender, EventArgs e)
11676 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
11679 private void HashManageMenuItem_Click(object sender, EventArgs e)
11681 DialogResult rslt = DialogResult.Cancel;
11684 rslt = HashMgr.ShowDialog();
11690 this.TopMost = this._cfgCommon.AlwaysTop;
11691 if (rslt == DialogResult.Cancel) return;
11692 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11694 HashStripSplitButton.Text = HashMgr.UseHash;
11695 HashToggleMenuItem.Checked = true;
11696 HashToggleToolStripMenuItem.Checked = true;
11700 HashStripSplitButton.Text = "#[-]";
11701 HashToggleMenuItem.Checked = false;
11702 HashToggleToolStripMenuItem.Checked = false;
11704 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
11706 // int sidx = StatusText.SelectionStart;
11707 // string hash = HashMgr.UseHash + " ";
11710 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
11711 // hash = " " + hash;
11713 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
11714 // sidx += hash.Length;
11715 // StatusText.SelectionStart = sidx;
11716 // StatusText.Focus();
11718 _modifySettingCommon = true;
11719 this.StatusText_TextChanged(null, null);
11722 private void HashToggleMenuItem_Click(object sender, EventArgs e)
11724 HashMgr.ToggleHash();
11725 if (!string.IsNullOrEmpty(HashMgr.UseHash))
11727 HashStripSplitButton.Text = HashMgr.UseHash;
11728 HashToggleMenuItem.Checked = true;
11729 HashToggleToolStripMenuItem.Checked = true;
11733 HashStripSplitButton.Text = "#[-]";
11734 HashToggleMenuItem.Checked = false;
11735 HashToggleToolStripMenuItem.Checked = false;
11737 _modifySettingCommon = true;
11738 this.StatusText_TextChanged(null, null);
11741 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
11743 HashToggleMenuItem_Click(null, null);
11746 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
11748 if (ListTab.SelectedTab == null) return;
11749 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
11750 if (!this.ExistCurrentPost)
11752 this.ReplyOpMenuItem.Enabled = false;
11753 this.ReplyAllOpMenuItem.Enabled = false;
11754 this.DmOpMenuItem.Enabled = false;
11755 this.ShowProfMenuItem.Enabled = false;
11756 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
11757 this.ListManageMenuItem.Enabled = false;
11758 this.OpenFavOpMenuItem.Enabled = false;
11759 this.CreateTabRuleOpMenuItem.Enabled = false;
11760 this.CreateIdRuleOpMenuItem.Enabled = false;
11761 this.ReadOpMenuItem.Enabled = false;
11762 this.UnreadOpMenuItem.Enabled = false;
11766 this.ReplyOpMenuItem.Enabled = true;
11767 this.ReplyAllOpMenuItem.Enabled = true;
11768 this.DmOpMenuItem.Enabled = true;
11769 this.ShowProfMenuItem.Enabled = true;
11770 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
11771 this.ListManageMenuItem.Enabled = true;
11772 this.OpenFavOpMenuItem.Enabled = true;
11773 this.CreateTabRuleOpMenuItem.Enabled = true;
11774 this.CreateIdRuleOpMenuItem.Enabled = true;
11775 this.ReadOpMenuItem.Enabled = true;
11776 this.UnreadOpMenuItem.Enabled = true;
11779 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11781 this.FavOpMenuItem.Enabled = false;
11782 this.UnFavOpMenuItem.Enabled = false;
11783 this.OpenStatusOpMenuItem.Enabled = false;
11784 this.OpenFavotterOpMenuItem.Enabled = false;
11785 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11786 this.RtOpMenuItem.Enabled = false;
11787 this.RtUnOpMenuItem.Enabled = false;
11788 this.QtOpMenuItem.Enabled = false;
11789 this.FavoriteRetweetMenuItem.Enabled = false;
11790 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11791 if (this.ExistCurrentPost && _curPost.IsDm) this.DelOpMenuItem.Enabled = true;
11795 this.FavOpMenuItem.Enabled = true;
11796 this.UnFavOpMenuItem.Enabled = true;
11797 this.OpenStatusOpMenuItem.Enabled = true;
11798 this.OpenFavotterOpMenuItem.Enabled = true;
11799 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11803 this.RtOpMenuItem.Enabled = false;
11804 this.FavoriteRetweetMenuItem.Enabled = false;
11805 this.DelOpMenuItem.Enabled = true;
11809 this.DelOpMenuItem.Enabled = false;
11810 if (_curPost.IsProtect)
11812 this.RtOpMenuItem.Enabled = false;
11813 this.RtUnOpMenuItem.Enabled = false;
11814 this.QtOpMenuItem.Enabled = false;
11815 this.FavoriteRetweetMenuItem.Enabled = false;
11816 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11820 this.RtOpMenuItem.Enabled = true;
11821 this.RtUnOpMenuItem.Enabled = true;
11822 this.QtOpMenuItem.Enabled = true;
11823 this.FavoriteRetweetMenuItem.Enabled = true;
11824 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11829 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11831 this.RefreshPrevOpMenuItem.Enabled = true;
11835 this.RefreshPrevOpMenuItem.Enabled = false;
11837 if (!this.ExistCurrentPost
11838 || _curPost.InReplyToStatusId == null)
11840 OpenRepSourceOpMenuItem.Enabled = false;
11844 OpenRepSourceOpMenuItem.Enabled = true;
11846 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11848 OpenRterHomeMenuItem.Enabled = false;
11852 OpenRterHomeMenuItem.Enabled = true;
11856 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11858 ContextMenuTabProperty_Opening(sender, null);
11861 public Twitter TwitterInstance
11866 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11868 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
11870 _mySpDis3 = SplitContainer3.SplitterDistance;
11871 _modifySettingLocal = true;
11875 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11877 if (_statuses.RemovedTab.Count == 0)
11879 UndoRemoveTabMenuItem.Enabled = false;
11883 UndoRemoveTabMenuItem.Enabled = true;
11885 if (ListTab.SelectedTab != null)
11887 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11888 PublicSearchQueryMenuItem.Enabled = true;
11890 PublicSearchQueryMenuItem.Enabled = false;
11894 PublicSearchQueryMenuItem.Enabled = false;
11896 if (!this.ExistCurrentPost)
11898 this.CopySTOTMenuItem.Enabled = false;
11899 this.CopyURLMenuItem.Enabled = false;
11900 this.CopyUserIdStripMenuItem.Enabled = false;
11904 this.CopySTOTMenuItem.Enabled = true;
11905 this.CopyURLMenuItem.Enabled = true;
11906 this.CopyUserIdStripMenuItem.Enabled = true;
11907 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11908 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11912 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11914 SetNotifyIconText();
11917 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11920 if (_curPost != null)
11922 id = _curPost.ScreenName;
11924 ShowUserStatus(id);
11927 private class GetUserInfoArgs
11931 public TwitterUser user;
11934 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
11936 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
11937 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
11940 private void doShowUserStatus(string id, bool ShowInputDialog)
11942 TwitterUser user = null;
11943 GetUserInfoArgs args = new GetUserInfoArgs();
11944 if (ShowInputDialog)
11946 using (InputTabName inputName = new InputTabName())
11948 inputName.FormTitle = "Show UserStatus";
11949 inputName.FormDescription = Properties.Resources.FRMessage1;
11950 inputName.TabName = id;
11951 if (inputName.ShowDialog() == DialogResult.OK &&
11952 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11954 id = inputName.TabName.Trim();
11958 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
11959 GetUserInfo_DoWork,
11963 _info.ShowDialog();
11964 string ret = (string)_info.Result;
11965 if (string.IsNullOrEmpty(ret))
11966 doShowUserStatus(args.user);
11968 MessageBox.Show(ret);
11978 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
11979 GetUserInfo_DoWork,
11983 _info.ShowDialog();
11984 string ret = (string)_info.Result;
11985 if (string.IsNullOrEmpty(ret))
11987 doShowUserStatus(args.user);
11991 MessageBox.Show(ret);
11997 private async void doShowUserStatus(TwitterUser user)
11999 using (var userDialog = new UserInfoDialog(this, this.tw))
12001 var showUserTask = userDialog.ShowUserAsync(user);
12002 userDialog.ShowDialog(this);
12005 this.BringToFront();
12007 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12008 await showUserTask;
12012 private void ShowUserStatus(string id, bool ShowInputDialog)
12014 doShowUserStatus(id, ShowInputDialog);
12017 private void ShowUserStatus(string id)
12019 doShowUserStatus(id, true);
12022 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12024 if (NameLabel.Tag != null)
12026 string id = (string)NameLabel.Tag;
12027 if (id != tw.Username)
12034 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12036 if (NameLabel.Tag != null)
12038 string id = (string)NameLabel.Tag;
12039 if (id != tw.Username)
12041 RemoveCommand(id, false);
12046 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12048 if (NameLabel.Tag != null)
12050 string id = (string)NameLabel.Tag;
12051 if (id != tw.Username)
12053 ShowFriendship(id);
12058 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12060 if (NameLabel.Tag != null)
12062 string id = (string)NameLabel.Tag;
12063 ShowUserStatus(id, false);
12067 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12069 if (NameLabel.Tag != null)
12071 string id = (string)NameLabel.Tag;
12072 AddNewTabForUserTimeline(id);
12076 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12078 if (NameLabel.Tag != null)
12080 string id = (string)NameLabel.Tag;
12081 AddNewTabForSearch("@" + id);
12085 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12087 if (_curPost != null)
12089 ShowUserStatus(_curPost.ScreenName, false);
12093 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12098 if (_curPost.RetweetedId != null)
12100 statusid = _curPost.RetweetedId.Value;
12104 statusid = _curPost.StatusId;
12106 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12108 e.Result = counter;
12111 private void RtCountMenuItem_Click(object sender, EventArgs e)
12113 if (this.ExistCurrentPost)
12115 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12116 GetRetweet_DoWork))
12118 int retweet_count = 0;
12121 _info.ShowDialog();
12122 retweet_count = (int)_info.Result;
12123 if (retweet_count < 0)
12125 MessageBox.Show(Properties.Resources.RtCountText2);
12129 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12135 private HookGlobalHotkey _hookGlobalHotkey;
12138 _hookGlobalHotkey = new HookGlobalHotkey(this);
12140 // この呼び出しは、Windows フォーム デザイナで必要です。
12141 InitializeComponent();
12143 // InitializeComponent() 呼び出しの後で初期化を追加します。
12145 this.SettingDialog.IntervalChanged += this.TimerInterval_Changed;
12146 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12147 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12148 this.gh.NotifyClicked += GrowlHelper_Callback;
12150 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12151 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12153 this._apiGauge = new ToolStripAPIGauge();
12154 this._apiGauge.BorderSides = ToolStripStatusLabelBorderSides.Right;
12155 this.StatusStrip1.Items.Insert(2, this._apiGauge);
12157 this.ImageSelector.Visible = false;
12158 this.ImageSelector.Enabled = false;
12159 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12161 this.ReplaceAppName();
12164 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12166 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12169 this.Visible = false;
12171 else if (Form.ActiveForm == null)
12173 this.Visible = true;
12174 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12176 this.BringToFront();
12177 this.StatusText.Focus();
12181 private void UserPicture_MouseEnter(object sender, EventArgs e)
12183 this.UserPicture.Cursor = Cursors.Hand;
12186 private void UserPicture_MouseLeave(object sender, EventArgs e)
12188 this.UserPicture.Cursor = Cursors.Default;
12191 private void UserPicture_DoubleClick(object sender, EventArgs e)
12193 if (NameLabel.Tag != null)
12195 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12199 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12201 this.MultiLineMenuItem.PerformClick();
12204 public PostClass CurPost
12206 get { return _curPost; }
12210 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12212 if (ImageSelector.Visible)
12213 ImageSelector.EndSelection();
12215 ImageSelector.BeginSelection();
12218 private void SelectMedia_DragEnter(DragEventArgs e)
12220 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12222 e.Effect = DragDropEffects.Copy;
12225 e.Effect = DragDropEffects.None;
12228 private void SelectMedia_DragOver(DragEventArgs e)
12233 private void SelectMedia_DragDrop(DragEventArgs e)
12236 this.BringToFront();
12237 ImageSelector.BeginSelection(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0]);
12238 StatusText.Focus();
12241 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12243 TimelinePanel.Visible = false;
12244 TimelinePanel.Enabled = false;
12247 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12249 TimelinePanel.Visible = true;
12250 TimelinePanel.Enabled = true;
12251 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12254 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12256 this.AllowDrop = false;
12259 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12261 this.AllowDrop = true;
12264 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12266 if (ImageSelector.Visible)
12268 _modifySettingCommon = true;
12269 SaveConfigsAll(true);
12271 if (ImageSelector.ServiceName.Equals("Twitter"))
12272 this.StatusText_TextChanged(null, null);
12276 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12278 this.StatusText_TextChanged(null, null);
12282 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12284 using (ListManage form = new ListManage(tw))
12286 form.ShowDialog(this);
12290 public bool ModifySettingCommon
12292 set { _modifySettingCommon = value; }
12295 public bool ModifySettingLocal
12297 set { _modifySettingLocal = value; }
12300 public bool ModifySettingAtId
12302 set { _modifySettingAtId = value; }
12305 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12307 string link = (string)SourceLinkLabel.Tag;
12308 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12310 OpenUriAsync(link);
12314 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12316 string link = (string)SourceLinkLabel.Tag;
12317 if (!string.IsNullOrEmpty(link))
12319 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12323 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12325 SetStatusLabelUrl();
12328 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12330 if (this.ExistCurrentPost && !_curPost.IsDm)
12331 RtCountMenuItem.Enabled = true;
12333 RtCountMenuItem.Enabled = false;
12335 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12336 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12338 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12341 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12346 private void CopyUserId()
12348 if (_curPost == null) return;
12349 string clstr = _curPost.ScreenName;
12352 Clipboard.SetDataObject(clstr, false, 5, 100);
12354 catch (Exception ex)
12356 MessageBox.Show(ex.Message);
12360 private void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e) // Handles ShowRelatedStatusesMenuItem.Click, ShowRelatedStatusesMenuItem2.Click
12362 if (this.ExistCurrentPost && !_curPost.IsDm)
12366 this.OpenRelatedTab(this._curPost);
12368 catch (TabException ex)
12370 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12376 /// 指定されたツイートに対する関連発言タブを開きます
12378 /// <param name="post">表示する対象となるツイート</param>
12379 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12380 private void OpenRelatedTab(PostClass post)
12382 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12385 if (tabRelated == null)
12387 tabName = this._statuses.MakeTabName("Related Tweets");
12389 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12390 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12392 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12393 tabRelated.UnreadManage = false;
12394 tabRelated.Notify = false;
12398 tabName = tabRelated.TabName;
12401 tabRelated.RelationTargetPost = post;
12402 this.ClearTab(tabName, false);
12404 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12406 var tabPage = this.ListTab.TabPages[i];
12407 if (tabName == tabPage.Text)
12409 this.ListTab.SelectedIndex = i;
12410 this.ListTabSelect(tabPage);
12415 this.GetTimeline(MyCommon.WORKERTYPE.Related, 1, tabName);
12418 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12420 StringBuilder buf = new StringBuilder();
12421 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12422 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12423 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12424 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12425 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12428 private void tw_UserIdChanged()
12430 this._modifySettingCommon = true;
12433 #region "Userstream"
12434 private bool _isActiveUserstream = false;
12436 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12440 if (InvokeRequired && !IsDisposed)
12442 Invoke((Action) (() =>
12444 _statuses.RemovePostReserve(e.StatusId);
12445 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12447 this.PurgeListViewItemCache();
12448 ((DetailsListView)_curTab.Tag).Update();
12449 if (_curPost != null && _curPost.StatusId == e.StatusId) DispSelectedPost(true);
12455 catch (ObjectDisposedException)
12459 catch (InvalidOperationException)
12465 private void tw_NewPostFromStream(object sender, EventArgs e)
12467 if (this._cfgCommon.ReadOldPosts)
12469 _statuses.SetRead(); //新着時未読クリア
12472 int rsltAddCount = _statuses.DistributePosts();
12475 DateTime tm = DateTime.Now;
12476 if (_tlTimestamps.ContainsKey(tm))
12478 _tlTimestamps[tm] += rsltAddCount;
12482 _tlTimestamps.Add(tm, rsltAddCount);
12484 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12485 List<DateTime> keys = new List<DateTime>();
12487 foreach (DateTime key in _tlTimestamps.Keys)
12489 if (key.CompareTo(oneHour) < 0)
12492 _tlCount += _tlTimestamps[key];
12494 foreach (DateTime key in keys)
12496 _tlTimestamps.Remove(key);
12500 //Static DateTime before = Now;
12501 //if (before.Subtract(Now).Seconds > -5) return;
12505 if (this._cfgCommon.UserstreamPeriod > 0) return;
12509 if (InvokeRequired && !IsDisposed)
12511 Invoke(new Action<bool>(RefreshTimeline), true);
12515 catch (ObjectDisposedException)
12519 catch (InvalidOperationException)
12525 private void tw_UserStreamStarted(object sender, EventArgs e)
12527 this._isActiveUserstream = true;
12530 if (InvokeRequired && !IsDisposed)
12532 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12536 catch (ObjectDisposedException)
12540 catch (InvalidOperationException)
12545 MenuItemUserStream.Text = "&UserStream ▶";
12546 MenuItemUserStream.Enabled = true;
12547 StopToolStripMenuItem.Text = "&Stop";
12548 StopToolStripMenuItem.Enabled = true;
12550 StatusLabel.Text = "UserStream Started.";
12553 private void tw_UserStreamStopped(object sender, EventArgs e)
12555 this._isActiveUserstream = false;
12558 if (InvokeRequired && !IsDisposed)
12560 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12564 catch (ObjectDisposedException)
12568 catch (InvalidOperationException)
12573 MenuItemUserStream.Text = "&UserStream ■";
12574 MenuItemUserStream.Enabled = true;
12575 StopToolStripMenuItem.Text = "&Start";
12576 StopToolStripMenuItem.Enabled = true;
12578 StatusLabel.Text = "UserStream Stopped.";
12581 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12585 if (InvokeRequired && !IsDisposed)
12587 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12591 catch (ObjectDisposedException)
12595 catch (InvalidOperationException)
12599 var ev = e.EventData;
12600 StatusLabel.Text = "Event: " + ev.Event;
12601 //if (ev.Event == "favorite")
12603 // NotifyFavorite(ev);
12606 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12608 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12610 this.PurgeListViewItemCache();
12611 ((DetailsListView)_curTab.Tag).Update();
12613 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12615 RemovePostFromFavTab(new long[] {ev.Id});
12620 private void NotifyEvent(Twitter.FormattedEvent ev)
12623 if (BalloonRequired(ev))
12625 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12626 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12627 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12628 StringBuilder title = new StringBuilder();
12629 if (this._cfgCommon.DispUsername)
12631 title.Append(tw.Username);
12632 title.Append(" - ");
12638 title.Append(Application.ProductName);
12639 title.Append(" [");
12640 title.Append(ev.Event.ToUpper());
12641 title.Append("] by ");
12642 if (!string.IsNullOrEmpty(ev.Username))
12644 title.Append(ev.Username.ToString());
12648 //title.Append("");
12651 if (!string.IsNullOrEmpty(ev.Target))
12653 //NotifyIcon1.BalloonTipText = ev.Target;
12658 //NotifyIcon1.BalloonTipText = " ";
12661 //NotifyIcon1.ShowBalloonTip(500);
12662 if (this._cfgCommon.IsUseNotifyGrowl)
12664 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
12665 ev.Id.ToString(), title.ToString(), text);
12669 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
12670 NotifyIcon1.BalloonTipTitle = title.ToString();
12671 NotifyIcon1.BalloonTipText = text;
12672 NotifyIcon1.ShowBalloonTip(500);
12677 string snd = SettingDialog.EventSoundFile;
12678 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
12680 if ((ev.Eventtype & SettingDialog.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
12684 string dir = Application.StartupPath;
12685 if (Directory.Exists(Path.Combine(dir, "Sounds")))
12687 dir = Path.Combine(dir, "Sounds");
12689 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
12701 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
12703 MenuItemUserStream.Enabled = false;
12704 if (StopRefreshAllMenuItem.Checked)
12706 StopRefreshAllMenuItem.Checked = false;
12709 if (this._isActiveUserstream)
12711 tw.StopUserStream();
12715 tw.StartUserStream();
12719 private static string inputTrack = "";
12721 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
12723 if (TrackToolStripMenuItem.Checked)
12725 using (InputTabName inputForm = new InputTabName())
12727 inputForm.TabName = inputTrack;
12728 inputForm.FormTitle = "Input track word";
12729 inputForm.FormDescription = "Track word";
12730 if (inputForm.ShowDialog() != DialogResult.OK)
12732 TrackToolStripMenuItem.Checked = false;
12735 inputTrack = inputForm.TabName.Trim();
12737 if (!inputTrack.Equals(tw.TrackWord))
12739 tw.TrackWord = inputTrack;
12740 this._modifySettingCommon = true;
12741 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
12742 tw.ReconnectUserStream();
12748 tw.ReconnectUserStream();
12750 this._modifySettingCommon = true;
12753 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
12755 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
12756 this._modifySettingCommon = true;
12757 tw.ReconnectUserStream();
12760 private void EventViewerMenuItem_Click(object sender, EventArgs e)
12762 if (evtDialog == null || evtDialog.IsDisposed)
12765 evtDialog = new EventViewerDialog();
12766 evtDialog.Owner = this;
12768 Point pos = evtDialog.Location;
12769 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
12770 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
12771 evtDialog.Location = pos;
12773 evtDialog.EventSource = tw.StoredEvent;
12774 if (!evtDialog.Visible)
12776 evtDialog.Show(this);
12780 evtDialog.Activate();
12782 this.TopMost = this._cfgCommon.AlwaysTop;
12786 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
12788 MyCommon._endingFlag = true;
12792 Application.Restart();
12796 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
12800 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
12802 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
12805 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
12807 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
12810 private async Task doTranslation(string str)
12812 if (string.IsNullOrEmpty(str))
12815 var bing = new Bing();
12818 var translatedText = await bing.TranslateAsync(str,
12820 langTo: this.SettingDialog.TranslateLanguage);
12822 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
12824 catch (HttpRequestException e)
12826 this.StatusLabel.Text = "Err:" + e.Message;
12830 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
12832 if (!this.ExistCurrentPost)
12835 await this.doTranslation(this._curPost.TextFromApi);
12838 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
12840 var text = this.WebBrowser_GetSelectionText(ref this.PostBrowser);
12841 await this.doTranslation(text);
12844 private bool ExistCurrentPost
12848 if (_curPost == null) return false;
12849 if (_curPost.IsDeleted) return false;
12854 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12856 ShowUserTimeline();
12859 public bool FavEventChangeUnread
12861 get { return SettingDialog.FavEventUnread; }
12864 private string GetUserIdFromCurPostOrInput(string caption)
12867 if (_curPost != null)
12869 id = _curPost.ScreenName;
12871 using (InputTabName inputName = new InputTabName())
12873 inputName.FormTitle = caption;
12874 inputName.FormDescription = Properties.Resources.FRMessage1;
12875 inputName.TabName = id;
12876 if (inputName.ShowDialog() == DialogResult.OK &&
12877 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12879 id = inputName.TabName.Trim();
12889 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
12891 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
12892 if (!string.IsNullOrEmpty(id))
12894 AddNewTabForUserTimeline(id);
12898 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
12900 string id = GetUserIdFromCurPostOrInput("Show Favstar");
12901 if (!string.IsNullOrEmpty(id))
12903 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
12907 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
12909 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12912 private void TimelineRefreshEnableChange(bool isEnable)
12916 tw.StartUserStream();
12920 tw.StopUserStream();
12922 TimerTimeline.Enabled = isEnable;
12925 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12927 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12930 private void OpenUserAppointUrl()
12932 if (SettingDialog.UserAppointUrl != null)
12934 if (SettingDialog.UserAppointUrl.Contains("{ID}") || SettingDialog.UserAppointUrl.Contains("{STATUS}"))
12936 if (_curPost != null)
12938 string xUrl = SettingDialog.UserAppointUrl;
12939 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12940 if (_curPost.RetweetedId != null)
12942 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
12946 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
12948 OpenUriAsync(xUrl);
12953 OpenUriAsync(SettingDialog.UserAppointUrl);
12958 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12960 OpenUserAppointUrl();
12963 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
12965 string selText = SourceLinkLabel.Text;
12968 Clipboard.SetDataObject(selText, false, 5, 100);
12970 catch (Exception ex)
12972 MessageBox.Show(ex.Message);
12976 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
12978 string selText = (string)SourceLinkLabel.Tag;
12981 Clipboard.SetDataObject(selText, false, 5, 100);
12983 catch (Exception ex)
12985 MessageBox.Show(ex.Message);
12989 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
12991 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
12993 SourceCopyMenuItem.Enabled = false;
12994 SourceUrlCopyMenuItem.Enabled = false;
12998 SourceCopyMenuItem.Enabled = true;
12999 SourceUrlCopyMenuItem.Enabled = true;
13003 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13005 if (Form.ActiveForm == null)
13007 this.BeginInvoke((Action) (() =>
13009 this.Visible = true;
13010 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13012 this.BringToFront();
13013 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13015 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13019 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13025 private void ReplaceAppName()
13027 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13028 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13031 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13033 this.SplitContainer3.Panel2Collapsed = false;
13035 // PreviewDistance が起動のたびに広がっていく問題の回避策
13036 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13037 // None で開いた後に設定するようにする
13038 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13039 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13042 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13044 this.OpenThumbnailPicture(e.Thumbnail);
13047 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13049 this.OpenUriAsync(e.ImageUrl);
13052 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13054 this.OpenUriAsync(Uri.EscapeUriString(thumbnail.ImageUrl));
13057 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13059 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13062 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13064 if (e.KeyCode == Keys.Space)
13066 this.JumpUnreadMenuItem_Click(null, null);
13068 e.SuppressKeyPress = true;
13072 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13074 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13075 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13076 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13077 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13078 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13080 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13083 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13085 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13088 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13090 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13093 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13095 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13098 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13100 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13103 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13105 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13108 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13110 if (this._cfgCommon.IconSize == iconSize) return;
13112 var oldIconCol = _iconCol;
13114 this._cfgCommon.IconSize = iconSize;
13115 ApplyListViewIconSize(iconSize);
13117 if (_iconCol != oldIconCol)
13119 foreach (TabPage tp in ListTab.TabPages)
13121 ResetColumns((DetailsListView)tp.Tag);
13125 if (_curList != null) _curList.Refresh();
13127 _modifySettingCommon = true;
13130 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13132 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13133 if (this._cfgCommon.SortOrderLock == state) return;
13135 this._cfgCommon.SortOrderLock = state;
13137 _modifySettingCommon = true;