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(); //ロック用
75 private const string detailHtmlFormatHeaderMono =
76 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
77 + "<style type=\"text/css\"><!-- "
78 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
79 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
80 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em;} "
82 + "</head><body style=\"margin:0px; background-color:rgb(%BG_COLOR%);\"><pre>";
83 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
84 private const string detailHtmlFormatHeaderColor =
85 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
86 + "<style type=\"text/css\"><!-- "
87 + "p {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
88 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
89 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em;} "
91 + "</head><body style=\"margin:0px; background-color:rgb(%BG_COLOR%);\"><p><span style=\"vertical-align:text-bottom\">";
92 private const string detailHtmlFormatFooterColor = "</span></p></body></html>";
93 private string detailHtmlFormatHeader;
94 private string detailHtmlFormatFooter;
96 private bool _myStatusError = false;
97 private bool _myStatusOnline = false;
98 private bool soundfileListup = false;
99 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
102 //private SettingToConfig _cfg; //旧
103 private SettingLocal _cfgLocal;
104 private SettingCommon _cfgCommon;
105 private bool _modifySettingLocal = false;
106 private bool _modifySettingCommon = false;
107 private bool _modifySettingAtId = false;
110 private Twitter tw = new Twitter();
113 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
116 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
117 private OpenURL UrlDialog = new OpenURL();
118 public AtIdSupplement AtIdSupl; //@id補助
119 public AtIdSupplement HashSupl; //Hashtag補助
120 public HashtagManage HashMgr;
121 private EventViewerDialog evtDialog;
124 private Font _fntUnread; //未読用フォント
125 private Color _clUnread; //未読用文字色
126 private Font _fntReaded; //既読用フォント
127 private Color _clReaded; //既読用文字色
128 private Color _clFav; //Fav用文字色
129 private Color _clOWL; //片思い用文字色
130 private Color _clRetweet; //Retweet用文字色
131 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
132 private Font _fntDetail; //発言詳細部用フォント
133 private Color _clDetail; //発言詳細部用色
134 private Color _clDetailLink; //発言詳細部用リンク文字色
135 private Color _clDetailBackcolor; //発言詳細部用背景色
136 private Color _clSelf; //自分の発言用背景色
137 private Color _clAtSelf; //自分宛返信用背景色
138 private Color _clTarget; //選択発言者の他の発言用背景色
139 private Color _clAtTarget; //選択発言中の返信先用背景色
140 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
141 private Color _clAtTo; //選択発言の唯一@先
142 private Color _clListBackcolor; //リスト部通常発言背景色
143 private Color _clInputBackcolor; //入力欄背景色
144 private Color _clInputFont; //入力欄文字色
145 private Font _fntInputFont; //入力欄フォント
146 private ImageCache IconCache; //アイコン画像リスト
147 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
148 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
149 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
150 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
151 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
152 private Icon MainIcon; //Main.ico 画面左上のアイコン
153 private Icon ReplyIcon; //5g
154 private Icon ReplyIconBlink; //6g
156 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
158 private PostClass _anchorPost;
159 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
161 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
162 private int _hisIdx; //発言履歴カレントインデックス
164 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
165 private long? _reply_to_id; // リプライ先のステータスID 0の場合はリプライではない 注:複数あてのものはリプライではない
166 private string _reply_to_name; // リプライ先ステータスの書き込み者の名前
169 private List<DateTime> _postTimestamps = new List<DateTime>();
170 private List<DateTime> _favTimestamps = new List<DateTime>();
171 private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
172 private int _tlCount;
175 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
176 private SolidBrush _brsBackColorMine;
177 private SolidBrush _brsBackColorAt;
178 private SolidBrush _brsBackColorYou;
179 private SolidBrush _brsBackColorAtYou;
180 private SolidBrush _brsBackColorAtFromTarget;
181 private SolidBrush _brsBackColorAtTo;
182 private SolidBrush _brsBackColorNone;
183 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
184 private StringFormat sfTab = new StringFormat();
186 //////////////////////////////////////////////////////////////////////////////////////////////////////////
187 private TabInformations _statuses;
189 // ListViewItem のキャッシュ関連
190 private int _itemCacheIndex;
191 private ListViewItem[] _itemCache;
192 private PostClass[] _postCache;
193 private ReaderWriterLockSlim itemCacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
195 private TabPage _curTab;
196 private int _curItemIndex;
197 private DetailsListView _curList;
198 private PostClass _curPost;
199 private bool _isColumnChanged = false;
201 private const int MAX_WORKER_THREADS = 20;
202 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
203 private CancellationTokenSource workerCts = new CancellationTokenSource();
205 private int UnreadCounter = -1;
206 private int UnreadAtCounter = -1;
208 private string[] ColumnOrgText = new string[9];
209 private string[] ColumnText = new string[9];
211 private bool _DoFavRetweetFlags = false;
212 private bool osResumed = false;
214 //////////////////////////////////////////////////////////////////////////////////////////////////////////
215 private string _postBrowserStatusText = "";
217 private bool _colorize = false;
219 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
221 private ImageListViewItem displayItem;
223 private string recommendedStatusFooter;
226 private struct urlUndo
228 public string Before;
232 private List<urlUndo> urlUndoBuffer = null;
234 private struct ReplyChain
236 public long OriginalId;
237 public long InReplyToId;
238 public TabPage OriginalTab;
240 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
242 this.OriginalId = originalId;
243 this.InReplyToId = inReplyToId;
244 this.OriginalTab = originalTab;
248 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
249 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
252 private enum SEARCHTYPE
259 private class PostingStatus
261 public string status = "";
262 public long? inReplyToId = null;
263 public string inReplyToName = null;
264 public string imageService = ""; //画像投稿サービス名
265 public string[] imagePath = null;
266 public PostingStatus()
269 public PostingStatus(string status, long? replyToId, string replyToName)
271 this.status = status;
272 this.inReplyToId = replyToId;
273 this.inReplyToName = replyToName;
277 private void TweenMain_Activated(object sender, EventArgs e)
279 //画面がアクティブになったら、発言欄の背景色戻す
280 if (StatusText.Focused)
282 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
286 private bool disposed = false;
289 /// 使用中のリソースをすべてクリーンアップします。
291 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
292 protected override void Dispose(bool disposing)
294 base.Dispose(disposing);
301 if (this.components != null)
302 this.components.Dispose();
305 SearchDialog.Dispose();
307 if (NIconAt != null) NIconAt.Dispose();
308 if (NIconAtRed != null) NIconAtRed.Dispose();
309 if (NIconAtSmoke != null) NIconAtSmoke.Dispose();
310 foreach (var iconRefresh in this.NIconRefresh)
312 if (iconRefresh != null)
313 iconRefresh.Dispose();
315 if (TabIcon != null) TabIcon.Dispose();
316 if (MainIcon != null) MainIcon.Dispose();
317 if (ReplyIcon != null) ReplyIcon.Dispose();
318 if (ReplyIconBlink != null) ReplyIconBlink.Dispose();
319 _listViewImageList.Dispose();
320 _brsHighLight.Dispose();
321 if (_brsBackColorMine != null) _brsBackColorMine.Dispose();
322 if (_brsBackColorAt != null) _brsBackColorAt.Dispose();
323 if (_brsBackColorYou != null) _brsBackColorYou.Dispose();
324 if (_brsBackColorAtYou != null) _brsBackColorAtYou.Dispose();
325 if (_brsBackColorAtFromTarget != null) _brsBackColorAtFromTarget.Dispose();
326 if (_brsBackColorAtTo != null) _brsBackColorAtTo.Dispose();
327 if (_brsBackColorNone != null) _brsBackColorNone.Dispose();
328 if (_brsDeactiveSelection != null) _brsDeactiveSelection.Dispose();
332 this.workerCts.Cancel();
334 if (IconCache != null)
336 this.IconCache.CancelAsync();
337 this.IconCache.Dispose();
340 if (this.thumbnailTokenSource != null)
341 this.thumbnailTokenSource.Dispose();
343 this.itemCacheLock.Dispose();
345 this._hookGlobalHotkey.Dispose();
348 // 終了時にRemoveHandlerしておかないとメモリリークする
349 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
350 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
352 this.disposed = true;
355 private void LoadIcons()
357 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
358 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
361 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
364 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
367 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
370 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
372 // タスクトレイ: オフライン時アイコン
373 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
375 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
376 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
377 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
379 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
380 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
381 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
382 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
383 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
385 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
387 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
388 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
389 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
390 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
391 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
393 if (iconReply != null && iconReplyBlink != null)
395 this.ReplyIcon = iconReply;
396 this.ReplyIconBlink = iconReplyBlink;
400 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
401 this.ReplyIconBlink = this.NIconAt;
404 if (iconRefresh1 == null)
406 this.NIconRefresh = new[] {
407 Properties.Resources.Refresh, Properties.Resources.Refresh2,
408 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
411 else if (iconRefresh2 == null)
413 this.NIconRefresh = new[] { iconRefresh1 };
415 else if (iconRefresh3 == null)
417 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
419 else if (iconRefresh4 == null)
421 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
423 else // iconRefresh1 から iconRefresh4 まで全て揃っている
425 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
429 private Icon LoadIcon(string filePath)
431 if (!File.Exists(filePath))
436 return new Icon(filePath);
444 private void InitColumns(ListView list, bool startup)
446 ColumnHeader _colHd1 = new ColumnHeader(); //アイコン
447 ColumnHeader _colHd2 = new ColumnHeader(); //ニックネーム
448 ColumnHeader _colHd3 = new ColumnHeader(); //本文
449 ColumnHeader _colHd4 = new ColumnHeader(); //日付
450 ColumnHeader _colHd5 = new ColumnHeader(); //ユーザID
451 ColumnHeader _colHd6 = new ColumnHeader(); //未読
452 ColumnHeader _colHd7 = new ColumnHeader(); //マーク&プロテクト
453 ColumnHeader _colHd8 = new ColumnHeader(); //ソース
457 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd2, _colHd3, _colHd4, _colHd5, _colHd6, _colHd7, _colHd8 });
461 list.Columns.AddRange(new ColumnHeader[] { _colHd1, _colHd3 });
465 _colHd1.Text = ColumnText[0];
467 _colHd2.Text = ColumnText[1];
469 _colHd3.Text = ColumnText[2];
471 _colHd4.Text = ColumnText[3];
473 _colHd5.Text = ColumnText[4];
475 _colHd6.Text = ColumnText[5];
477 _colHd7.Text = ColumnText[6];
479 _colHd8.Text = ColumnText[7];
482 int[] dispOrder = new int[8];
485 for (int i = 0; i < _curList.Columns.Count; i++)
487 for (int j = 0; j < _curList.Columns.Count; j++)
489 if (_curList.Columns[j].DisplayIndex == i)
496 for (int i = 0; i < _curList.Columns.Count; i++)
498 list.Columns[i].Width = _curList.Columns[i].Width;
499 list.Columns[dispOrder[i]].DisplayIndex = i;
504 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
508 list.Columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
509 list.Columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
510 list.Columns[0].DisplayIndex = 0;
511 list.Columns[1].DisplayIndex = 1;
515 for (int i = 0; i <= 7; i++)
517 if (_cfgLocal.DisplayIndex1 == i)
519 else if (_cfgLocal.DisplayIndex2 == i)
521 else if (_cfgLocal.DisplayIndex3 == i)
523 else if (_cfgLocal.DisplayIndex4 == i)
525 else if (_cfgLocal.DisplayIndex5 == i)
527 else if (_cfgLocal.DisplayIndex6 == i)
529 else if (_cfgLocal.DisplayIndex7 == i)
531 else if (_cfgLocal.DisplayIndex8 == i)
534 list.Columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
535 list.Columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
536 list.Columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
537 list.Columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
538 list.Columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
539 list.Columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
540 list.Columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
541 list.Columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
542 for (int i = 0; i <= 7; i++)
544 list.Columns[dispOrder[i]].DisplayIndex = i;
550 private void InitColumnText()
553 ColumnText[1] = Properties.Resources.AddNewTabText2;
554 ColumnText[2] = Properties.Resources.AddNewTabText3;
555 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
556 ColumnText[4] = Properties.Resources.AddNewTabText5;
559 ColumnText[7] = "Source";
561 ColumnOrgText[0] = "";
562 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
563 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
564 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
565 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
566 ColumnOrgText[5] = "";
567 ColumnOrgText[6] = "";
568 ColumnOrgText[7] = "Source";
571 switch (_statuses.SortMode)
573 case ComparerMode.Nickname: //ニックネーム
576 case ComparerMode.Data: //本文
579 case ComparerMode.Id: //時刻=発言Id
582 case ComparerMode.Name: //名前
585 case ComparerMode.Source: //Source
592 if (_statuses.SortOrder == SortOrder.Descending)
594 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
595 ColumnText[2] = ColumnOrgText[2] + "▾";
599 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
600 ColumnText[2] = ColumnOrgText[2] + "▴";
605 if (_statuses.SortOrder == SortOrder.Descending)
607 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
608 ColumnText[c] = ColumnOrgText[c] + "▾";
612 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
613 ColumnText[c] = ColumnOrgText[c] + "▴";
618 private void InitializeTraceFrag()
621 TraceOutToolStripMenuItem.Checked = true;
622 MyCommon.TraceFlag = true;
624 if (!MyCommon.FileVersion.EndsWith("0"))
626 TraceOutToolStripMenuItem.Checked = true;
627 MyCommon.TraceFlag = true;
631 private void TweenMain_Load(object sender, EventArgs e)
633 _ignoreConfigSave = true;
634 this.Visible = false;
636 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
638 new InternetSecurityManager(PostBrowser);
639 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
641 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
642 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
644 if (MyApplication.StartupOptions.ContainsKey("d"))
645 MyCommon.TraceFlag = true;
647 Regex.CacheSize = 100;
649 InitializeTraceFrag();
650 LoadIcons(); // アイコン読み込み
653 _statuses = TabInformations.GetInstance();
656 this.Icon = MainIcon; //メインフォーム(TweenMain)
657 NotifyIcon1.Icon = NIconAt; //タスクトレイ
658 TabImage.Images.Add(TabIcon); //タブ見出し
660 SearchDialog.Owner = this;
661 UrlDialog.Owner = this;
663 _history.Add(new PostingStatus());
666 _reply_to_name = null;
668 //<<<<<<<<<設定関連>>>>>>>>>
675 // 現在の DPI と設定保存時の DPI との比を取得する
676 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
679 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
680 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
683 _fntUnread = _cfgLocal.FontUnread;
684 _clUnread = _cfgLocal.ColorUnread;
685 _fntReaded = _cfgLocal.FontRead;
686 _clReaded = _cfgLocal.ColorRead;
687 _clFav = _cfgLocal.ColorFav;
688 _clOWL = _cfgLocal.ColorOWL;
689 _clRetweet = _cfgLocal.ColorRetweet;
690 _fntDetail = _cfgLocal.FontDetail;
691 _clDetail = _cfgLocal.ColorDetail;
692 _clDetailLink = _cfgLocal.ColorDetailLink;
693 _clDetailBackcolor = _cfgLocal.ColorDetailBackcolor;
694 _clSelf = _cfgLocal.ColorSelf;
695 _clAtSelf = _cfgLocal.ColorAtSelf;
696 _clTarget = _cfgLocal.ColorTarget;
697 _clAtTarget = _cfgLocal.ColorAtTarget;
698 _clAtFromTarget = _cfgLocal.ColorAtFromTarget;
699 _clAtTo = _cfgLocal.ColorAtTo;
700 _clListBackcolor = _cfgLocal.ColorListBackcolor;
701 _clInputBackcolor = _cfgLocal.ColorInputBackcolor;
702 _clInputFont = _cfgLocal.ColorInputFont;
703 _fntInputFont = _cfgLocal.FontInputFont;
705 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
706 if (fontUIGlobal != null)
708 OTBaseForm.GlobalFont = fontUIGlobal;
709 this.Font = fontUIGlobal;
712 // StringFormatオブジェクトへの事前設定
713 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
714 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
715 //sf.FormatFlags = StringFormatFlags.LineLimit; //
716 sfTab.Alignment = StringAlignment.Center;
717 sfTab.LineAlignment = StringAlignment.Center;
720 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
722 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
723 this._cfgCommon.TimelinePeriod = 15;
725 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
726 this._cfgCommon.ReplyPeriod = 15;
728 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
729 this._cfgCommon.DMPeriod = 15;
731 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
732 this._cfgCommon.PubSearchPeriod = 30;
734 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
735 this._cfgCommon.UserTimelinePeriod = 15;
737 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
738 this._cfgCommon.ListsPeriod = 15;
741 if (this._cfgCommon.CountApi < 20 || this._cfgCommon.CountApi > 200)
742 this._cfgCommon.CountApi = 60;
743 if (this._cfgCommon.CountApiReply < 20 || this._cfgCommon.CountApiReply > 200)
744 this._cfgCommon.CountApiReply = 40;
746 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
749 if (string.IsNullOrEmpty(_cfgCommon.Token)) _cfgCommon.UserName = "";
750 tw.Initialize(_cfgCommon.Token, _cfgCommon.TokenSecret, _cfgCommon.UserName, _cfgCommon.UserId);
752 //新着取得時のリストスクロールをするか。trueならスクロールしない
753 ListLockMenuItem.Checked = _cfgCommon.ListLock;
754 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
756 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
757 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
759 //廃止サービスが選択されていた場合bit.lyへ読み替え
760 if (_cfgCommon.AutoShortUrlFirst < 0)
761 _cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
763 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
765 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
766 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
768 //Regex statregex = new Regex("^0*");
769 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
772 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
773 HashMgr = new HashtagManage(HashSupl,
774 _cfgCommon.HashTags.ToArray(),
775 _cfgCommon.HashSelected,
776 _cfgCommon.HashIsPermanent,
777 _cfgCommon.HashIsHead,
778 _cfgCommon.HashIsNotAddToAtReply);
779 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
783 Networking.Initialize();
786 this.IconCache = new ImageCache();
788 bool saveRequired = false;
789 bool firstRun = false;
791 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
792 if (string.IsNullOrEmpty(tw.Username))
797 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
798 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
799 string.IsNullOrEmpty(tw.Username))
801 Application.Exit(); //強制終了
807 _fntUnread = this._cfgLocal.FontUnread;
808 _clUnread = this._cfgLocal.ColorUnread;
809 _fntReaded = this._cfgLocal.FontRead;
810 _clReaded = this._cfgLocal.ColorRead;
811 _clFav = this._cfgLocal.ColorFav;
812 _clOWL = this._cfgLocal.ColorOWL;
813 _clRetweet = this._cfgLocal.ColorRetweet;
814 _fntDetail = this._cfgLocal.FontDetail;
815 _clDetail = this._cfgLocal.ColorDetail;
816 _clDetailLink = this._cfgLocal.ColorDetailLink;
817 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
818 _clSelf = this._cfgLocal.ColorSelf;
819 _clAtSelf = this._cfgLocal.ColorAtSelf;
820 _clTarget = this._cfgLocal.ColorTarget;
821 _clAtTarget = this._cfgLocal.ColorAtTarget;
822 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
823 _clAtTo = this._cfgLocal.ColorAtTo;
824 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
825 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
826 _clInputFont = this._cfgLocal.ColorInputFont;
827 _fntInputFont = this._cfgLocal.FontInputFont;
830 _brsBackColorMine = new SolidBrush(_clSelf);
831 _brsBackColorAt = new SolidBrush(_clAtSelf);
832 _brsBackColorYou = new SolidBrush(_clTarget);
833 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
834 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
835 _brsBackColorAtTo = new SolidBrush(_clAtTo);
836 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
837 _brsBackColorNone = new SolidBrush(_clListBackcolor);
839 InitDetailHtmlFormat();
841 if (this._cfgCommon.HotkeyEnabled)
844 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
845 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
846 modKey |= HookGlobalHotkey.ModKeys.Alt;
847 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
848 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
849 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
850 modKey |= HookGlobalHotkey.ModKeys.Shift;
851 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
852 modKey |= HookGlobalHotkey.ModKeys.Win;
854 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
858 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
859 Networking.SetWebProxy(this._cfgLocal.ProxyType,
860 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
861 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
864 //プロキシ設定等の通信まわりの初期化が済んでから処理する
865 ThumbnailGenerator.InitializeGenerator();
867 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
868 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
869 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
871 Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
872 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
873 this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
875 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
876 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
877 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
878 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
879 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
880 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
881 tw.TrackWord = _cfgCommon.TrackWord;
882 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
883 tw.AllAtReply = _cfgCommon.AllAtReply;
884 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
887 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
890 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
891 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
892 _myLoc = _cfgLocal.FormLocation;
894 if (this.WindowState != FormWindowState.Minimized)
896 this.DesktopLocation = _cfgLocal.FormLocation;
897 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
898 bool outOfScreen = true;
899 if (Screen.AllScreens.Length == 1) //ハングするとの報告
901 foreach (Screen scr in Screen.AllScreens)
903 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
911 this.DesktopLocation = new Point(0, 0);
912 _myLoc = this.DesktopLocation;
916 this.TopMost = this._cfgCommon.AlwaysTop;
917 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
918 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
919 if (_cfgLocal.PreviewDistance == -1)
921 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
922 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
923 _cfgLocal.PreviewDistance = _mySpDis3;
927 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
929 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
930 //this.Tween_ClientSizeChanged(this, null);
931 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
932 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
934 StatusText.Font = _fntInputFont;
935 StatusText.ForeColor = _clInputFont;
937 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
938 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
939 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
941 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
942 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
944 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
945 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
947 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
948 if (this._cfgCommon.UnreadManage == false)
950 ReadedStripMenuItem.Enabled = false;
951 UnreadStripMenuItem.Enabled = false;
954 if (this._cfgCommon.IsUseNotifyGrowl)
958 TimerTimeline.AutoReset = true;
959 TimerTimeline.SynchronizingObject = this;
961 TimerTimeline.Interval = 1000;
962 TimerTimeline.Enabled = true;
965 TimerRefreshIcon.Interval = 200;
966 TimerRefreshIcon.Enabled = true;
969 StatusLabel.Text = "";
970 StatusLabel.AutoToolTip = false;
971 StatusLabel.ToolTipText = "";
973 lblLen.Text = GetRestStatusCount(true, false).ToString();
975 ////////////////////////////////////////////////////////////////////////////////
976 _statuses.SortOrder = (SortOrder)_cfgCommon.SortOrder;
977 var mode = ComparerMode.Id;
978 switch (_cfgCommon.SortColumn)
980 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
984 mode = ComparerMode.Id; //Idソートに読み替え
987 mode = ComparerMode.Nickname;
990 mode = ComparerMode.Data;
993 mode = ComparerMode.Id;
996 mode = ComparerMode.Name;
999 mode = ComparerMode.Source;
1002 _statuses.SortMode = mode;
1003 ////////////////////////////////////////////////////////////////////////////////
1005 ApplyListViewIconSize(this._cfgCommon.IconSize);
1007 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1008 StatusLabelUrl.Text = ""; //画面左下のリンク先URL表示部を初期化
1009 NameLabel.Text = ""; //発言詳細部名前ラベル初期化
1010 DateTimeLabel.Text = ""; //発言詳細部日時ラベル初期化
1011 SourceLinkLabel.Text = ""; //Source部分初期化
1013 //<<<<<<<<タブ関連>>>>>>>
1014 //デフォルトタブの存在チェック、ない場合には追加
1015 if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1018 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1020 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1024 tab.TabType = MyCommon.TabUsageType.Home;
1027 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1030 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1032 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1036 tab.TabType = MyCommon.TabUsageType.Mentions;
1039 if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1042 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1044 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1048 tab.TabType = MyCommon.TabUsageType.DirectMessage;
1051 if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1054 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1056 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1060 tab.TabType = MyCommon.TabUsageType.Favorites;
1063 if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1066 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1068 _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1072 tab.TabType = MyCommon.TabUsageType.Mute;
1076 foreach (var tab in _statuses.Tabs.Values)
1079 if (tab.TabType == MyCommon.TabUsageType.Mute)
1082 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1084 tab.TabType = MyCommon.TabUsageType.UserDefined;
1086 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1087 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1090 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1091 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1092 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1093 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1095 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1097 this.Visible = true;
1099 _curTab = ListTab.SelectedTab;
1101 _curList = (DetailsListView)_curTab.Tag;
1102 SetMainWindowTitle();
1103 SetNotifyIconText();
1105 if (this._cfgCommon.TabIconDisp)
1107 ListTab.DrawMode = TabDrawMode.Normal;
1111 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1112 ListTab.DrawItem += ListTab_DrawItem;
1113 ListTab.ImageList = null;
1116 _ignoreConfigSave = false;
1117 this.TweenMain_Resize(null, null);
1118 if (saveRequired) SaveConfigsAll(false);
1121 tw.VerifyCredentials();
1123 foreach (var ua in this._cfgCommon.UserAccounts)
1125 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1127 ua.UserId = tw.UserId;
1134 // 初回起動時だけ右下のメニューを目立たせる
1135 HashStripSplitButton.ShowDropDown();
1142 private void InitDetailHtmlFormat()
1144 if (this._cfgCommon.IsMonospace)
1146 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1147 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1151 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1152 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1155 detailHtmlFormatHeader = detailHtmlFormatHeader
1156 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1157 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1158 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1159 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1160 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1163 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1168 txt = ListTab.TabPages[e.Index].Text;
1175 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1176 if (e.State == DrawItemState.Selected)
1178 e.DrawFocusRectangle();
1183 if (_statuses.Tabs[txt].UnreadCount > 0)
1186 fore = System.Drawing.SystemBrushes.ControlText;
1190 fore = System.Drawing.SystemBrushes.ControlText;
1192 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1195 private void LoadConfig()
1197 _cfgCommon = SettingCommon.Load();
1198 SettingCommon.Instance = this._cfgCommon;
1199 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1201 _cfgCommon.UserAccounts = new List<UserAccount>();
1202 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1204 UserAccount account = new UserAccount();
1205 account.Username = _cfgCommon.UserName;
1206 account.UserId = _cfgCommon.UserId;
1207 account.Token = _cfgCommon.Token;
1208 account.TokenSecret = _cfgCommon.TokenSecret;
1210 _cfgCommon.UserAccounts.Add(account);
1214 _cfgLocal = SettingLocal.Load();
1216 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1217 if (_cfgLocal.ScaleDimension.IsEmpty)
1218 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1220 List<TabClass> tabs = SettingTabs.Load().Tabs;
1221 foreach (TabClass tb in tabs)
1225 tb.FilterModified = false;
1226 _statuses.Tabs.Add(tb.TabName, tb);
1230 tb.TabName = _statuses.GetUniqueTabName();
1231 _statuses.Tabs.Add(tb.TabName, tb);
1234 if (_statuses.Tabs.Count == 0)
1236 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1237 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1238 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1239 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1243 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1245 if (!TimerTimeline.Enabled) return;
1249 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1251 private static int homeCounter = 0;
1252 private static int mentionCounter = 0;
1253 private static int dmCounter = 0;
1254 private static int pubSearchCounter = 0;
1255 private static int userTimelineCounter = 0;
1256 private static int listsCounter = 0;
1257 private static int usCounter = 0;
1258 private static int ResumeWait = 0;
1259 private static int refreshFollowers = 0;
1261 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1263 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1264 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1265 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1266 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1267 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1268 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1269 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1270 Interlocked.Increment(ref refreshFollowers);
1272 var refreshTasks = new List<Task>();
1275 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1277 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1278 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1279 refreshTasks.Add(this.GetHomeTimelineAsync());
1280 ResetTimers.Timeline = false;
1282 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1284 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1285 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1286 refreshTasks.Add(this.GetReplyAsync());
1287 ResetTimers.Reply = false;
1289 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1291 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1292 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1293 refreshTasks.Add(this.GetDirectMessagesAsync());
1294 ResetTimers.DirectMessage = false;
1296 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1298 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1299 if (!ResetTimers.PublicSearch)
1300 refreshTasks.Add(this.GetPublicSearchAllAsync());
1301 ResetTimers.PublicSearch = false;
1303 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1305 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1306 if (!ResetTimers.UserTimeline)
1307 refreshTasks.Add(this.GetUserTimelineAllAsync());
1308 ResetTimers.UserTimeline = false;
1310 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1312 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1313 if (!ResetTimers.Lists)
1314 refreshTasks.Add(this.GetListTimelineAllAsync());
1315 ResetTimers.Lists = false;
1317 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1319 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1320 if (this._isActiveUserstream) RefreshTimeline(true);
1321 ResetTimers.UserStream = false;
1323 if (refreshFollowers > 6 * 3600)
1325 Interlocked.Exchange(ref refreshFollowers, 0);
1326 refreshTasks.AddRange(new[]
1328 this.doGetFollowersMenu(),
1329 this.RefreshNoRetweetIdsAsync(),
1330 this.RefreshTwitterConfigurationAsync(),
1335 Interlocked.Increment(ref ResumeWait);
1336 if (ResumeWait > 30)
1339 Interlocked.Exchange(ref ResumeWait, 0);
1340 refreshTasks.AddRange(new[]
1342 this.GetHomeTimelineAsync(),
1343 this.GetReplyAsync(),
1344 this.GetDirectMessagesAsync(),
1345 this.GetPublicSearchAllAsync(),
1346 this.GetUserTimelineAllAsync(),
1347 this.GetListTimelineAllAsync(),
1348 this.doGetFollowersMenu(),
1349 this.RefreshTwitterConfigurationAsync(),
1354 await Task.WhenAll(refreshTasks);
1357 private void RefreshTimeline(bool isUserStream)
1359 if (isUserStream) this.RefreshTasktrayIcon(true);
1361 int smode = -1; //-1:制御しない,-2:最新へ,その他:topitem使用
1362 long topId = GetScrollPos(ref smode);
1363 int befCnt = _curList.VirtualListSize;
1366 var selId = new Dictionary<string, long[]>();
1367 var focusedId = new Dictionary<string, Tuple<long, long>>();
1368 SaveSelectedStatus(selId, focusedId);
1371 int dmCount = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount;
1374 PostClass[] notifyPosts = null;
1375 string soundFile = "";
1377 bool isMention = false;
1378 bool isDelete = false;
1379 addCount = _statuses.SubmitUpdate(ref soundFile, ref notifyPosts, ref isMention, ref isDelete, isUserStream);
1381 if (MyCommon._endingFlag) return;
1386 foreach (TabPage tab in ListTab.TabPages)
1388 DetailsListView lst = (DetailsListView)tab.Tag;
1389 TabClass tabInfo = _statuses.Tabs[tab.Text];
1390 using (ControlTransaction.Update(lst))
1392 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1394 if (lst.Equals(_curList))
1396 this.PurgeListViewItemCache();
1400 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1407 // status_id から ListView 上のインデックスに変換
1408 var selectedIndices = selId[tab.Text] != null
1409 ? tabInfo.IndexOf(selId[tab.Text]).Where(x => x != -1).ToArray()
1411 var focusedIndex = tabInfo.IndexOf(focusedId[tab.Text].Item1);
1412 var selectionMarkIndex = tabInfo.IndexOf(focusedId[tab.Text].Item2);
1414 this.SelectListItem(lst, selectedIndices, focusedIndex, selectionMarkIndex);
1417 if (tabInfo.UnreadCount > 0)
1418 if (this._cfgCommon.TabIconDisp)
1419 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1421 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1425 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1434 if (befCnt != _curList.VirtualListSize)
1440 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(0);
1444 if (_curList.VirtualListSize > 0) _curList.EnsureVisible(_curList.VirtualListSize - 1);
1451 if (_curList.VirtualListSize > 0 && _statuses.Tabs[_curTab.Text].IndexOf(topId) > -1)
1453 _curList.EnsureVisible(_curList.VirtualListSize - 1);
1454 _curList.EnsureVisible(_statuses.Tabs[_curTab.Text].IndexOf(topId));
1460 catch (Exception ex)
1462 ex.Data["Msg"] = "Ref2";
1468 NotifyNewPosts(notifyPosts,
1471 isMention || dmCount != _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).AllCount);
1473 SetMainWindowTitle();
1474 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1476 HashSupl.AddRangeItem(tw.GetHashList());
1480 private long GetScrollPos(ref int smode)
1483 if (_curList != null && _curTab != null && _curList.VirtualListSize > 0)
1485 if (_statuses.SortMode == ComparerMode.Id)
1487 if (_statuses.SortOrder == SortOrder.Ascending)
1490 if (ListLockMenuItem.Checked)
1495 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1500 //最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1502 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1); //一番下
1503 if (_item == null) _item = _curList.Items[_curList.VirtualListSize - 1];
1504 if (_item.Index == _curList.VirtualListSize - 1)
1511 //if (_curList.TopItem != null) topId = _statuses.GetId(_curTab.Text, _curList.TopItem.Index);
1519 if (ListLockMenuItem.Checked)
1522 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1527 //最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1530 _item = _curList.GetItemAt(0, 10); //一番上
1531 if (_item == null) _item = _curList.Items[0];
1532 if (_item.Index == 0)
1538 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1547 if (_curList.TopItem != null) topId = _statuses.Tabs[_curTab.Text].GetId(_curList.TopItem.Index);
1558 private void SaveSelectedStatus(Dictionary<string, long[]> selId, Dictionary<string, Tuple<long, long>> focusedIdDict)
1560 if (MyCommon._endingFlag) return;
1561 foreach (TabPage tab in ListTab.TabPages)
1563 var lst = (DetailsListView)tab.Tag;
1564 var tabInfo = _statuses.Tabs[tab.Text];
1565 if (lst.SelectedIndices.Count > 0 && lst.SelectedIndices.Count < 61)
1567 selId.Add(tab.Text, tabInfo.GetId(lst.SelectedIndices));
1571 selId.Add(tab.Text, null);
1574 var focusedItem = lst.FocusedItem;
1575 var focusedId = focusedItem != null ? tabInfo.GetId(focusedItem.Index) : -2;
1577 var selectionMarkIndex = lst.SelectionMark;
1578 var selectionMarkId = selectionMarkIndex != -1 ? tabInfo.GetId(selectionMarkIndex) : -2;
1580 focusedIdDict[tab.Text] = Tuple.Create(focusedId, selectionMarkId);
1585 private bool BalloonRequired()
1587 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1588 ev.Eventtype = MyCommon.EVENTTYPE.None;
1590 return BalloonRequired(ev);
1593 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1595 return this._cfgCommon.EventNotifyEnabled && (type & this._cfgCommon.EventNotifyFlag) != 0 || type == MyCommon.EVENTTYPE.None;
1598 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1600 return (ev.Eventtype & this._cfgCommon.IsMyEventNotifyFlag) != 0 ? true : !ev.IsMe;
1603 private bool BalloonRequired(Twitter.FormattedEvent ev)
1606 IsEventNotifyAsEventType(ev.Eventtype) && IsMyEventNotityAsEventType(ev) &&
1607 (NewPostPopMenuItem.Checked || (this._cfgCommon.ForceEventNotify && ev.Eventtype != MyCommon.EVENTTYPE.None)) &&
1611 this._cfgCommon.LimitBalloon &&
1613 this.WindowState == FormWindowState.Minimized ||
1615 Form.ActiveForm == null
1618 !this._cfgCommon.LimitBalloon
1621 !NativeMethods.IsScreenSaverRunning())
1631 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1633 if (notifyPosts != null &&
1634 notifyPosts.Length > 0 &&
1635 this._cfgCommon.ReadOwnPost &&
1636 notifyPosts.All((post) => { return post.UserId == tw.UserId || post.ScreenName == tw.Username; }))
1642 if (BalloonRequired())
1644 if (notifyPosts != null && notifyPosts.Length > 0)
1646 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1647 if (this._cfgCommon.IsUseNotifyGrowl)
1649 StringBuilder sb = new StringBuilder();
1653 foreach (PostClass post in notifyPosts)
1655 if (!(notifyPosts.Length > 3))
1661 if (post.IsReply && !post.IsExcludeReply) reply = true;
1662 if (post.IsDm) dm = true;
1663 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1664 switch (this._cfgCommon.NameBalloon)
1666 case MyCommon.NameBalloonEnum.UserID:
1667 sb.Append(post.ScreenName).Append(" : ");
1669 case MyCommon.NameBalloonEnum.NickName:
1670 sb.Append(post.Nickname).Append(" : ");
1673 sb.Append(post.TextFromApi);
1674 if (notifyPosts.Length > 3)
1676 if (notifyPosts.Last() != post) continue;
1679 StringBuilder title = new StringBuilder();
1680 GrowlHelper.NotifyType nt;
1681 if (this._cfgCommon.DispUsername)
1683 title.Append(tw.Username);
1684 title.Append(" - ");
1692 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1693 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1694 title.Append(Application.ProductName);
1695 title.Append(" [DM] ");
1696 title.Append(Properties.Resources.RefreshDirectMessageText1);
1698 title.Append(addCount);
1699 title.Append(Properties.Resources.RefreshDirectMessageText2);
1700 nt = GrowlHelper.NotifyType.DirectMessage;
1704 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1705 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1706 title.Append(Application.ProductName);
1707 title.Append(" [Reply!] ");
1708 title.Append(Properties.Resources.RefreshTimelineText1);
1710 title.Append(addCount);
1711 title.Append(Properties.Resources.RefreshTimelineText2);
1712 nt = GrowlHelper.NotifyType.Reply;
1716 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1717 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1718 title.Append(Application.ProductName);
1720 title.Append(Properties.Resources.RefreshTimelineText1);
1722 title.Append(addCount);
1723 title.Append(Properties.Resources.RefreshTimelineText2);
1724 nt = GrowlHelper.NotifyType.Notify;
1726 string bText = sb.ToString();
1727 if (string.IsNullOrEmpty(bText)) return;
1729 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1730 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1735 StringBuilder sb = new StringBuilder();
1738 foreach (PostClass post in notifyPosts)
1740 if (post.IsReply && !post.IsExcludeReply) reply = true;
1741 if (post.IsDm) dm = true;
1742 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1743 switch (this._cfgCommon.NameBalloon)
1745 case MyCommon.NameBalloonEnum.UserID:
1746 sb.Append(post.ScreenName).Append(" : ");
1748 case MyCommon.NameBalloonEnum.NickName:
1749 sb.Append(post.Nickname).Append(" : ");
1752 sb.Append(post.TextFromApi);
1755 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1756 StringBuilder title = new StringBuilder();
1758 if (this._cfgCommon.DispUsername)
1760 title.Append(tw.Username);
1761 title.Append(" - ");
1769 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1770 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1771 ntIcon = ToolTipIcon.Warning;
1772 title.Append(Application.ProductName);
1773 title.Append(" [DM] ");
1774 title.Append(Properties.Resources.RefreshDirectMessageText1);
1776 title.Append(addCount);
1777 title.Append(Properties.Resources.RefreshDirectMessageText2);
1781 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1782 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1783 ntIcon = ToolTipIcon.Warning;
1784 title.Append(Application.ProductName);
1785 title.Append(" [Reply!] ");
1786 title.Append(Properties.Resources.RefreshTimelineText1);
1788 title.Append(addCount);
1789 title.Append(Properties.Resources.RefreshTimelineText2);
1793 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1794 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1795 ntIcon = ToolTipIcon.Info;
1796 title.Append(Application.ProductName);
1798 title.Append(Properties.Resources.RefreshTimelineText1);
1800 title.Append(addCount);
1801 title.Append(Properties.Resources.RefreshTimelineText2);
1803 string bText = sb.ToString();
1804 if (string.IsNullOrEmpty(bText)) return;
1805 //NotifyIcon1.BalloonTipText = sb.ToString();
1806 //NotifyIcon1.ShowBalloonTip(500);
1807 NotifyIcon1.BalloonTipTitle = title.ToString();
1808 NotifyIcon1.BalloonTipText = bText;
1809 NotifyIcon1.BalloonTipIcon = ntIcon;
1810 NotifyIcon1.ShowBalloonTip(500);
1816 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1820 string dir = Application.StartupPath;
1821 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1823 dir = Path.Combine(dir, "Sounds");
1825 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1835 //mentions新着時に画面ブリンク
1836 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1838 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1842 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1844 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1846 _curItemIndex = _curList.SelectedIndices[0];
1847 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1851 _curPost = GetCurTabPost(_curItemIndex);
1853 catch (ArgumentException)
1858 this.PushSelectPostChain();
1860 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1862 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1868 private void ChangeCacheStyleRead(bool Read, int Index)
1870 var tabInfo = _statuses.Tabs[_curTab.Text];
1871 //Read:true=既読 false=未読
1872 //未読管理していなかったら既読として扱う
1873 if (!tabInfo.UnreadManage ||
1874 !this._cfgCommon.UnreadManage) Read = true;
1877 ListViewItem itm = null;
1878 PostClass post = null;
1880 this.TryGetListViewItemCache(Index, out itm, out post);
1882 // キャッシュに含まれていないアイテムは対象外
1886 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1889 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1896 Item.SubItems[5].Text = "";
1901 Item.SubItems[5].Text = "★";
1907 else if (Post.RetweetedId != null)
1909 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1911 else if (Read || !this._cfgCommon.UseUnreadStyle)
1916 if (DList == null || Item.Index == -1)
1918 Item.ForeColor = cl;
1919 if (this._cfgCommon.UseUnreadStyle)
1925 if (this._cfgCommon.UseUnreadStyle)
1926 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1928 DList.ChangeItemForeColor(Item.Index, cl);
1929 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1933 private void ColorizeList()
1935 //Index:更新対象のListviewItem.Index。Colorを返す。
1936 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1939 _post = _anchorPost;
1943 if (_post == null) return;
1945 var itemColors = new Color[] { };
1948 this.itemCacheLock.EnterReadLock();
1951 if (this._itemCache == null) return;
1954 from i in Enumerable.Range(0, this._itemCache.Length)
1955 select this.JudgeColor(_post, this._postCache[i]);
1957 itemColors = query.ToArray();
1958 itemIndex = _itemCacheIndex;
1960 finally { this.itemCacheLock.ExitReadLock(); }
1962 if (itemIndex < 0) return;
1964 foreach (var backColor in itemColors)
1966 // この処理中に MyList_CacheVirtualItems が呼ばれることがあるため、
1967 // 同一スレッド内での二重ロックを避けるためにロックの外で実行する必要がある
1968 _curList.ChangeItemBackColor(itemIndex++, backColor);
1972 private void ColorizeList(ListViewItem Item, int Index)
1974 //Index:更新対象のListviewItem.Index。Colorを返す。
1975 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
1978 _post = _anchorPost;
1982 PostClass tPost = GetCurTabPost(Index);
1984 if (_post == null) return;
1986 if (Item.Index == -1)
1987 Item.BackColor = JudgeColor(_post, tPost);
1989 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
1992 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
1995 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
1998 else if (TargetPost.IsMe)
2001 else if (TargetPost.IsReply)
2004 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2006 cl = _clAtFromTarget;
2007 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2010 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2015 cl = _clListBackcolor;
2020 private async void PostButton_Click(object sender, EventArgs e)
2022 if (StatusText.Text.Trim().Length == 0)
2024 if (!ImageSelector.Enabled)
2031 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2033 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2035 MessageBoxButtons.YesNoCancel,
2036 MessageBoxIcon.Question);
2039 case DialogResult.Yes:
2040 StatusText.Text = "";
2041 await this.doReTweetOfficial(false);
2043 case DialogResult.Cancel:
2048 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
2050 if (this._cfgCommon.Nicoms)
2052 StatusText.SelectionStart = StatusText.Text.Length;
2053 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2055 //if (SettingDialog.UrlConvertAuto)
2057 // StatusText.SelectionStart = StatusText.Text.Length;
2058 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2060 //else if (SettingDialog.Nicoms)
2062 // StatusText.SelectionStart = StatusText.Text.Length;
2063 // UrlConvert(UrlConverter.Nicoms);
2065 StatusText.SelectionStart = StatusText.Text.Length;
2066 CheckReplyTo(StatusText.Text);
2069 int adjustCount = 0;
2070 string tmpStatus = StatusText.Text.Trim();
2071 if (ToolStripMenuItemApiCommandEvasion.Checked)
2074 if (Regex.IsMatch(tmpStatus,
2075 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2076 RegexOptions.IgnoreCase)
2077 && tmpStatus.EndsWith(" .") == false) adjustCount += 2;
2080 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2083 adjustCount += Regex.Matches(tmpStatus, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+").Count;
2086 bool isCutOff = false;
2087 bool isRemoveFooter = MyCommon.IsKeyDown(Keys.Shift);
2088 if (StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
2090 //複数行でEnter投稿の場合、Ctrlも押されていたらフッタ付加しない
2091 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2093 if (this._cfgCommon.PostShiftEnter)
2095 isRemoveFooter = MyCommon.IsKeyDown(Keys.Control);
2097 if (!isRemoveFooter && (StatusText.Text.Contains("RT @") || StatusText.Text.Contains("QT @")))
2099 isRemoveFooter = true;
2101 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2103 if (MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
2106 //if (!SettingDialog.UrlConvertAuto) UrlConvertAutoToolStripMenuItem_Click(null, null);
2107 if (GetRestStatusCount(false, !isRemoveFooter) - adjustCount < 0)
2109 isRemoveFooter = true;
2120 if (StatusText.Text.StartsWith("D ") || StatusText.Text.StartsWith("d "))
2128 if (HashMgr.IsNotAddToAtReply)
2130 if (!string.IsNullOrEmpty(HashMgr.UseHash) && _reply_to_id == null && string.IsNullOrEmpty(_reply_to_name))
2133 header = HashMgr.UseHash + " ";
2135 footer = " " + HashMgr.UseHash;
2140 if (!string.IsNullOrEmpty(HashMgr.UseHash))
2143 header = HashMgr.UseHash + " ";
2145 footer = " " + HashMgr.UseHash;
2148 if (!isRemoveFooter)
2150 if (this._cfgLocal.UseRecommendStatus)
2153 footer += this.recommendedStatusFooter;
2155 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
2157 // テキストボックスに入力されている文字列を使用する
2158 footer += " " + this._cfgLocal.StatusText.Trim();
2163 var status = new PostingStatus();
2164 status.status = header + StatusText.Text + footer;
2166 if (ToolStripMenuItemApiCommandEvasion.Checked)
2169 if (Regex.IsMatch(status.status,
2170 @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)",
2171 RegexOptions.IgnoreCase)
2172 && status.status.EndsWith(" .") == false) status.status += " .";
2175 if (ToolStripMenuItemUrlMultibyteSplit.Checked)
2178 Match mc2 = Regex.Match(status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+");
2179 if (mc2.Success) status.status = Regex.Replace(status.status, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
2182 if (IdeographicSpaceToSpaceToolStripMenuItem.Checked)
2184 // 文中の全角スペースを半角スペース1個にする
2185 status.status = status.status.Replace(" ", " ");
2188 if (isCutOff && status.status.Length > 140)
2190 status.status = status.status.Substring(0, 140);
2191 string AtId = @"(@|@)[a-z0-9_/]+$";
2192 string HashTag = @"(^|[^0-9A-Z&\/\?]+)(#|#)([0-9A-Z_]*[A-Z_]+)$";
2193 string Url = @"https?:\/\/[a-z0-9!\*'\(\);:&=\+\$\/%#\[\]\-_\.,~?]+$"; //簡易判定
2194 string pattern = string.Format("({0})|({1})|({2})", AtId, HashTag, Url);
2195 Match mc = Regex.Match(status.status, pattern, RegexOptions.IgnoreCase);
2198 //さらに@ID、ハッシュタグ、URLと推測される文字列をカットする
2199 status.status = status.status.Substring(0, 140 - mc.Value.Length);
2201 if (MessageBox.Show(status.status, "Post or Cancel?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
2204 status.inReplyToId = _reply_to_id;
2205 status.inReplyToName = _reply_to_name;
2206 if (ImageSelector.Visible)
2209 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.imagePath))
2213 _reply_to_id = null;
2214 _reply_to_name = null;
2215 StatusText.Text = "";
2216 _history.Add(new PostingStatus());
2217 _hisIdx = _history.Count - 1;
2218 if (!ToolStripFocusLockMenuItem.Checked)
2219 ((Control)ListTab.SelectedTab.Tag).Focus();
2220 urlUndoBuffer = null;
2221 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2224 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2226 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2227 await this.OpenUriAsync(tmp);
2230 await this.PostMessageAsync(status);
2233 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2235 MyCommon._endingFlag = true;
2239 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2241 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2243 //_endingFlag=false:フォームの×ボタン
2245 this.Visible = false;
2249 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2250 _ignoreConfigSave = true;
2251 MyCommon._endingFlag = true;
2252 TimerTimeline.Enabled = false;
2253 TimerRefreshIcon.Enabled = false;
2257 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2259 this.Visible = true;
2260 if (this.WindowState == FormWindowState.Minimized)
2262 this.WindowState = FormWindowState.Normal;
2265 this.BringToFront();
2268 private static int errorCount = 0;
2270 private static bool CheckAccountValid()
2272 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2278 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2287 private Task GetHomeTimelineAsync()
2289 return this.GetHomeTimelineAsync(loadMore: false);
2292 private async Task GetHomeTimelineAsync(bool loadMore)
2294 await this.workerSemaphore.WaitAsync();
2298 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2300 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2302 catch (WebApiException ex)
2304 this._myStatusError = true;
2305 this.StatusLabel.Text = ex.Message;
2309 this.workerSemaphore.Release();
2313 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2315 if (ct.IsCancellationRequested)
2318 if (!CheckAccountValid())
2319 throw new WebApiException("Auth error. Check your account");
2322 if (!this._cfgCommon.UnreadManage)
2325 read = this._initial && this._cfgCommon.Read;
2327 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5 +
2328 (loadMore ? "-1" : "1") +
2329 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2331 await Task.Run(() =>
2333 var err = this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2335 if (!string.IsNullOrEmpty(err))
2336 throw new WebApiException(err);
2339 if (this._cfgCommon.ReadOldPosts)
2340 this._statuses.SetReadHomeTab();
2342 var addCount = this._statuses.DistributePosts();
2346 lock (this._syncObject)
2348 var tm = DateTime.Now;
2349 if (this._tlTimestamps.ContainsKey(tm))
2350 this._tlTimestamps[tm] += addCount;
2352 this._tlTimestamps[tm] = addCount;
2354 var removeKeys = new List<DateTime>();
2355 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2358 foreach (var pair in this._tlTimestamps)
2360 if (pair.Key < oneHour)
2361 removeKeys.Add(pair.Key);
2363 this._tlCount += pair.Value;
2366 foreach (var key in removeKeys)
2367 this._tlTimestamps.Remove(key);
2372 if (ct.IsCancellationRequested)
2375 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2377 this.RefreshTimeline(false);
2380 private Task GetReplyAsync()
2382 return this.GetReplyAsync(loadMore: false);
2385 private async Task GetReplyAsync(bool loadMore)
2387 await this.workerSemaphore.WaitAsync();
2391 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2393 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2395 catch (WebApiException ex)
2397 this._myStatusError = true;
2398 this.StatusLabel.Text = ex.Message;
2402 this.workerSemaphore.Release();
2406 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2408 if (ct.IsCancellationRequested)
2411 if (!CheckAccountValid())
2412 throw new WebApiException("Auth error. Check your account");
2415 if (!this._cfgCommon.UnreadManage)
2418 read = this._initial && this._cfgCommon.Read;
2420 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4 +
2421 (loadMore ? "-1" : "1") +
2422 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2424 await Task.Run(() =>
2426 var err = this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2428 if (!string.IsNullOrEmpty(err))
2429 throw new WebApiException(err);
2431 this._statuses.DistributePosts();
2434 if (ct.IsCancellationRequested)
2437 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2439 this.RefreshTimeline(false);
2442 private Task GetDirectMessagesAsync()
2444 return this.GetDirectMessagesAsync(loadMore: false);
2447 private async Task GetDirectMessagesAsync(bool loadMore)
2449 await this.workerSemaphore.WaitAsync();
2453 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2455 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2457 catch (WebApiException ex)
2459 this._myStatusError = true;
2460 this.StatusLabel.Text = ex.Message;
2464 this.workerSemaphore.Release();
2468 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2470 if (ct.IsCancellationRequested)
2473 if (!CheckAccountValid())
2474 throw new WebApiException("Auth error. Check your account");
2477 if (!this._cfgCommon.UnreadManage)
2480 read = this._initial && this._cfgCommon.Read;
2482 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8 +
2483 (loadMore ? "-1" : "1") +
2484 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText6);
2486 await Task.Run(() =>
2488 var err = this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2489 if (!string.IsNullOrEmpty(err))
2490 throw new WebApiException(err);
2492 var err2 = this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2493 if (!string.IsNullOrEmpty(err2))
2494 throw new WebApiException(err2);
2496 this._statuses.DistributePosts();
2499 if (ct.IsCancellationRequested)
2502 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2504 this.RefreshTimeline(false);
2507 private Task GetFavoritesAsync()
2509 return this.GetFavoritesAsync(loadMore: false);
2512 private async Task GetFavoritesAsync(bool loadMore)
2514 await this.workerSemaphore.WaitAsync();
2518 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2520 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2522 catch (WebApiException ex)
2524 this._myStatusError = true;
2525 this.StatusLabel.Text = ex.Message;
2529 this.workerSemaphore.Release();
2533 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2535 if (ct.IsCancellationRequested)
2538 if (!CheckAccountValid())
2539 throw new WebApiException("Auth error. Check your account");
2542 if (!this._cfgCommon.UnreadManage)
2545 read = this._initial && this._cfgCommon.Read;
2547 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2549 await Task.Run(() =>
2551 var err = this.tw.GetFavoritesApi(read, MyCommon.WORKERTYPE.Favorites, loadMore);
2553 if (!string.IsNullOrEmpty(err))
2554 throw new WebApiException(err);
2556 this._statuses.DistributePosts();
2559 if (ct.IsCancellationRequested)
2562 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2564 this.RefreshTimeline(false);
2567 private Task GetPublicSearchAllAsync()
2569 return this.GetPublicSearchAsync(null, loadMore: false);
2572 private Task GetPublicSearchAsync(TabClass tab)
2574 return this.GetPublicSearchAsync(tab, loadMore: false);
2577 private async Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2579 await this.workerSemaphore.WaitAsync();
2583 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2585 var tabs = tab != null
2586 ? new[] { tab }.AsEnumerable()
2587 : this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2589 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2591 catch (WebApiException ex)
2593 this._myStatusError = true;
2594 this.StatusLabel.Text = ex.Message;
2598 this.workerSemaphore.Release();
2602 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2604 if (ct.IsCancellationRequested)
2607 if (!CheckAccountValid())
2608 throw new WebApiException("Auth error. Check your account");
2611 if (!this._cfgCommon.UnreadManage)
2614 read = this._initial && this._cfgCommon.Read;
2616 p.Report("Search refreshing...");
2618 await Task.Run(() =>
2620 foreach (var tab in tabs)
2622 if (string.IsNullOrEmpty(tab.SearchWords))
2625 var err = this.tw.GetSearch(read, tab, false);
2626 if (!string.IsNullOrEmpty(err))
2627 throw new WebApiException(err);
2631 var err2 = this.tw.GetSearch(read, tab, true);
2632 if (!string.IsNullOrEmpty(err2))
2633 throw new WebApiException(err2);
2637 this._statuses.DistributePosts();
2640 if (ct.IsCancellationRequested)
2643 p.Report("Search refreshed");
2645 this.RefreshTimeline(false);
2648 private Task GetUserTimelineAllAsync()
2650 return this.GetUserTimelineAsync(null, loadMore: false);
2653 private Task GetUserTimelineAsync(TabClass tab)
2655 return this.GetUserTimelineAsync(tab, loadMore: false);
2658 private async Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2660 await this.workerSemaphore.WaitAsync();
2664 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2666 var tabs = tab != null
2667 ? new[] { tab }.AsEnumerable()
2668 : this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2670 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2672 catch (WebApiException ex)
2674 this._myStatusError = true;
2675 this.StatusLabel.Text = ex.Message;
2679 this.workerSemaphore.Release();
2683 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2685 if (ct.IsCancellationRequested)
2688 if (!CheckAccountValid())
2689 throw new WebApiException("Auth error. Check your account");
2692 if (!this._cfgCommon.UnreadManage)
2695 read = this._initial && this._cfgCommon.Read;
2697 p.Report("UserTimeline refreshing...");
2699 await Task.Run(() =>
2702 if (this._cfgCommon.UseAdditionalCount)
2703 count = this._cfgCommon.UserTimelineCountApi;
2705 foreach (var tab in tabs)
2707 if (string.IsNullOrEmpty(tab.User))
2710 var err = this.tw.GetUserTimelineApi(read, count, tab.User, tab, loadMore);
2711 if (!string.IsNullOrEmpty(err))
2712 throw new WebApiException(err);
2715 this._statuses.DistributePosts();
2718 if (ct.IsCancellationRequested)
2721 p.Report("UserTimeline refreshed");
2723 this.RefreshTimeline(false);
2726 private Task GetListTimelineAllAsync()
2728 return this.GetListTimelineAsync(null, loadMore: false);
2731 private Task GetListTimelineAsync(TabClass tab)
2733 return this.GetListTimelineAsync(tab, loadMore: false);
2736 private async Task GetListTimelineAsync(TabClass tab, bool loadMore)
2738 await this.workerSemaphore.WaitAsync();
2742 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2744 var tabs = tab != null
2745 ? new[] { tab }.AsEnumerable()
2746 : this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2748 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2750 catch (WebApiException ex)
2752 this._myStatusError = true;
2753 this.StatusLabel.Text = ex.Message;
2757 this.workerSemaphore.Release();
2761 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2763 if (ct.IsCancellationRequested)
2766 if (!CheckAccountValid())
2767 throw new WebApiException("Auth error. Check your account");
2770 if (!this._cfgCommon.UnreadManage)
2773 read = this._initial && this._cfgCommon.Read;
2775 p.Report("List refreshing...");
2777 await Task.Run(() =>
2779 foreach (var tab in tabs)
2781 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2784 var err = this.tw.GetListStatus(read, tab, loadMore, this._initial);
2785 if (!string.IsNullOrEmpty(err))
2786 throw new WebApiException(err);
2789 this._statuses.DistributePosts();
2792 if (ct.IsCancellationRequested)
2795 p.Report("List refreshed");
2797 this.RefreshTimeline(false);
2800 private async Task GetRelatedTweetsAsync(TabClass tab)
2802 await this.workerSemaphore.WaitAsync();
2806 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2808 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2810 catch (WebApiException ex)
2812 this._myStatusError = true;
2813 this.StatusLabel.Text = ex.Message;
2817 this.workerSemaphore.Release();
2821 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2823 if (ct.IsCancellationRequested)
2826 if (!CheckAccountValid())
2827 throw new WebApiException("Auth error. Check your account");
2830 if (!this._cfgCommon.UnreadManage)
2833 read = this._initial && this._cfgCommon.Read;
2835 p.Report("Related refreshing...");
2837 await Task.Run(() =>
2839 var err = this.tw.GetRelatedResult(read, tab);
2840 if (!string.IsNullOrEmpty(err))
2841 throw new WebApiException(err);
2843 this._statuses.DistributePosts();
2846 if (ct.IsCancellationRequested)
2849 p.Report("Related refreshed");
2851 this.RefreshTimeline(false);
2853 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2854 .FirstOrDefault(x => x.Text == tab.TabName);
2856 if (tabPage != null)
2858 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2860 var listView = (DetailsListView)tabPage.Tag;
2861 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2863 if (index != -1 && index < listView.Items.Count)
2865 listView.SelectedIndices.Add(index);
2866 listView.Items[index].Focused = true;
2871 private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2873 await this.workerSemaphore.WaitAsync();
2877 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2879 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2881 catch (WebApiException ex)
2883 this._myStatusError = true;
2884 this.StatusLabel.Text = ex.Message;
2888 this.workerSemaphore.Release();
2892 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2894 if (ct.IsCancellationRequested)
2897 if (!CheckAccountValid())
2898 throw new WebApiException("Auth error. Check your account");
2900 var successIds = new List<long>();
2902 await Task.Run(() =>
2906 var failedCount = 0;
2908 foreach (var statusId in statusIds)
2912 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15 +
2913 allCount + "/" + statusIds.Count +
2914 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText16 +
2917 var post = tab.Posts[statusId];
2922 var err = this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2924 if (!string.IsNullOrEmpty(err))
2930 successIds.Add(statusId);
2931 post.IsFav = true; // リスト再描画必要
2933 this._favTimestamps.Add(DateTime.Now);
2936 if (this._statuses.ContainsKey(statusId))
2938 var postTl = this._statuses[statusId];
2939 postTl.IsFav = true;
2941 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2942 favTab.Add(statusId, postTl.IsRead, false);
2945 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2946 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2948 if (tb.Contains(statusId))
2949 tb.Posts[statusId].IsFav = true;
2954 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2955 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2957 if (this._favTimestamps[i] < oneHour)
2958 this._favTimestamps.RemoveAt(i);
2961 this._statuses.DistributePosts();
2964 if (ct.IsCancellationRequested)
2967 this.RefreshTimeline(false);
2969 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2971 using (ControlTransaction.Update(this._curList))
2973 foreach (var statusId in successIds)
2975 var idx = tab.IndexOf(statusId);
2979 var post = tab.Posts[statusId];
2980 this.ChangeCacheStyleRead(post.IsRead, idx);
2984 if (successIds.Contains(this._curPost.StatusId))
2985 this.DispSelectedPost(true); // 選択アイテム再表示
2989 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2991 await this.workerSemaphore.WaitAsync();
2995 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2997 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2999 catch (WebApiException ex)
3001 this._myStatusError = true;
3002 this.StatusLabel.Text = ex.Message;
3006 this.workerSemaphore.Release();
3010 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
3012 if (ct.IsCancellationRequested)
3015 if (!CheckAccountValid())
3016 throw new WebApiException("Auth error. Check your account");
3018 var successIds = new List<long>();
3020 await Task.Run(() =>
3024 var failedCount = 0;
3025 foreach (var statusId in statusIds)
3029 var post = tab.Posts[statusId];
3031 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17 +
3032 allCount + "/" + statusIds.Count +
3033 Properties.Resources.GetTimelineWorker_RunWorkerCompletedText18 +
3039 var err = this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
3041 if (!string.IsNullOrEmpty(err))
3047 successIds.Add(statusId);
3048 post.IsFav = false; // リスト再描画必要
3050 if (this._statuses.ContainsKey(statusId))
3052 this._statuses[statusId].IsFav = false;
3055 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3056 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3058 if (tb.Contains(statusId))
3059 tb.Posts[statusId].IsFav = false;
3064 if (ct.IsCancellationRequested)
3067 this.RemovePostFromFavTab(successIds.ToArray());
3069 this.RefreshTimeline(false);
3071 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3073 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3079 using (ControlTransaction.Update(this._curList))
3081 foreach (var statusId in successIds)
3083 var idx = tab.IndexOf(statusId);
3087 var post = tab.Posts[statusId];
3088 this.ChangeCacheStyleRead(post.IsRead, idx);
3092 if (successIds.Contains(this._curPost.StatusId))
3093 this.DispSelectedPost(true); // 選択アイテム再表示
3098 private async Task PostMessageAsync(PostingStatus status)
3100 await this.workerSemaphore.WaitAsync();
3104 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3106 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3108 catch (WebApiException ex)
3110 this._myStatusError = true;
3111 this.StatusLabel.Text = ex.Message;
3115 this.workerSemaphore.Release();
3119 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3121 if (ct.IsCancellationRequested)
3124 if (!CheckAccountValid())
3125 throw new WebApiException("Auth error. Check your account");
3127 p.Report("Posting...");
3133 await Task.Run(async () =>
3135 if (status.imagePath == null || status.imagePath.Length == 0 || string.IsNullOrEmpty(status.imagePath[0]))
3137 var err = this.tw.PostStatus(status.status, status.inReplyToId);
3138 if (!string.IsNullOrEmpty(err))
3139 throw new WebApiException(err);
3143 var service = ImageSelector.GetService(status.imageService);
3144 await service.PostStatusAsync(status.status, status.inReplyToId, status.imagePath)
3145 .ConfigureAwait(false);
3149 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3151 catch (WebApiException ex)
3153 // 処理は中断せずエラーの表示のみ行う
3154 errMsg = ex.Message;
3156 this._myStatusError = true;
3159 if (ct.IsCancellationRequested)
3162 if (!string.IsNullOrEmpty(errMsg) &&
3163 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3164 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3166 var ret = MessageBox.Show(
3168 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3169 "\"" + status.status + "\"" + Environment.NewLine +
3171 Properties.Resources.StatusUpdateFailed1,
3172 Properties.Resources.StatusUpdateFailed2),
3173 "Failed to update status",
3174 MessageBoxButtons.RetryCancel,
3175 MessageBoxIcon.Question);
3177 if (ret == DialogResult.Retry)
3179 await this.PostMessageAsync(status);
3183 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3184 if (this.ToolStripFocusLockMenuItem.Checked)
3185 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3190 this._postTimestamps.Add(DateTime.Now);
3192 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3193 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3195 if (this._postTimestamps[i] < oneHour)
3196 this._postTimestamps.RemoveAt(i);
3199 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3201 this.HashMgr.ClearHashtag();
3202 this.HashStripSplitButton.Text = "#[-]";
3203 this.HashToggleMenuItem.Checked = false;
3204 this.HashToggleToolStripMenuItem.Checked = false;
3207 this.SetMainWindowTitle();
3209 if (this._cfgCommon.PostAndGet)
3211 if (this._isActiveUserstream)
3212 this.RefreshTimeline(true);
3214 await this.GetHomeTimelineAsync();
3218 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3220 await this.workerSemaphore.WaitAsync();
3224 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3226 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3228 catch (WebApiException ex)
3230 this._myStatusError = true;
3231 this.StatusLabel.Text = ex.Message;
3235 this.workerSemaphore.Release();
3239 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3241 if (ct.IsCancellationRequested)
3244 if (!CheckAccountValid())
3245 throw new WebApiException("Auth error. Check your account");
3248 if (!this._cfgCommon.UnreadManage)
3251 read = this._initial && this._cfgCommon.Read;
3253 p.Report("Posting...");
3255 await Task.Run(() =>
3257 foreach (var statusId in statusIds)
3259 var err = this.tw.PostRetweet(statusId, read);
3260 if (!string.IsNullOrEmpty(err))
3261 throw new WebApiException(err);
3265 if (ct.IsCancellationRequested)
3268 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3270 this._postTimestamps.Add(DateTime.Now);
3272 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3273 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3275 if (this._postTimestamps[i] < oneHour)
3276 this._postTimestamps.RemoveAt(i);
3279 if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3280 await this.GetHomeTimelineAsync();
3283 private async Task RefreshFollowerIdsAsync()
3285 await this.workerSemaphore.WaitAsync();
3288 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3290 await Task.Run(() => tw.RefreshFollowerIds());
3292 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3294 this.RefreshTimeline(false);
3295 this.PurgeListViewItemCache();
3296 if (this._curList != null)
3297 this._curList.Refresh();
3299 catch (WebApiException ex)
3301 this.StatusLabel.Text = ex.Message;
3305 this.workerSemaphore.Release();
3309 private async Task RefreshNoRetweetIdsAsync()
3311 await this.workerSemaphore.WaitAsync();
3314 await Task.Run(() => tw.RefreshNoRetweetIds());
3316 this.StatusLabel.Text = "NoRetweetIds refreshed";
3318 catch (WebApiException ex)
3320 this.StatusLabel.Text = ex.Message;
3324 this.workerSemaphore.Release();
3328 private async Task RefreshBlockIdsAsync()
3330 await this.workerSemaphore.WaitAsync();
3333 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3335 await Task.Run(() => tw.RefreshBlockIds());
3337 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3339 catch (WebApiException ex)
3341 this.StatusLabel.Text = ex.Message;
3345 this.workerSemaphore.Release();
3349 private async Task RefreshTwitterConfigurationAsync()
3351 await this.workerSemaphore.WaitAsync();
3354 await Task.Run(() => tw.RefreshConfiguration());
3356 if (this.tw.Configuration.PhotoSizeLimit != 0)
3358 foreach (var service in this.ImageSelector.GetServices())
3360 service.UpdateTwitterConfiguration(this.tw.Configuration);
3364 this.PurgeListViewItemCache();
3366 if (this._curList != null)
3367 this._curList.Refresh();
3369 catch (WebApiException ex)
3371 this.StatusLabel.Text = ex.Message;
3375 this.workerSemaphore.Release();
3379 private async Task RefreshMuteUserIdsAsync()
3381 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3385 await tw.RefreshMuteUserIdsAsync();
3387 catch (WebApiException ex)
3389 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3393 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3396 private void RemovePostFromFavTab(Int64[] ids)
3398 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3399 string favTabName = favTab.TabName;
3401 if (_curTab.Text.Equals(favTabName))
3403 if (_curList.FocusedItem != null)
3404 fidx = _curList.FocusedItem.Index;
3405 else if (_curList.TopItem != null)
3406 fidx = _curList.TopItem.Index;
3411 foreach (long i in ids)
3415 _statuses.RemoveFavPost(i);
3422 if (_curTab != null && _curTab.Text.Equals(favTabName))
3424 this.PurgeListViewItemCache();
3426 //_curItemIndex = -1;
3428 foreach (TabPage tp in ListTab.TabPages)
3430 if (tp.Text == favTabName)
3432 ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3436 if (_curTab.Text.Equals(favTabName))
3440 _curList.SelectedIndices.Clear();
3442 while (_curList.SelectedIndices.Count > 0);
3444 if (favTab.AllCount > 0)
3446 if (favTab.AllCount - 1 > fidx && fidx > -1)
3448 _curList.SelectedIndices.Add(fidx);
3452 _curList.SelectedIndices.Add(favTab.AllCount - 1);
3454 if (_curList.SelectedIndices.Count > 0)
3456 _curList.EnsureVisible(_curList.SelectedIndices[0]);
3457 _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3463 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3465 if (e.Button == MouseButtons.Left)
3467 this.Visible = true;
3468 if (this.WindowState == FormWindowState.Minimized)
3470 this.WindowState = _formWindowState;
3473 this.BringToFront();
3477 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3479 switch (this._cfgCommon.ListDoubleClickAction)
3482 MakeReplyOrDirectStatus();
3485 await this.FavoriteChange(true);
3488 if (_curPost != null)
3489 ShowUserStatus(_curPost.ScreenName, false);
3495 ShowRelatedStatusesMenuItem_Click(null, null);
3498 MoveToHomeToolStripMenuItem_Click(null, null);
3501 StatusOpenMenuItem_Click(null, null);
3509 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3511 await this.FavoriteChange(true);
3514 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3516 await this.FavoriteChange(false);
3520 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3522 await this.FavoritesRetweetOriginal();
3525 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3527 await this.FavoritesRetweetUnofficial();
3530 private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3533 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3536 //trueでFavAdd,falseでFavRemove
3537 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3538 || !this.ExistCurrentPost) return;
3541 if (_curList.SelectedIndices.Count > 250 && FavAdd)
3543 MessageBox.Show(Properties.Resources.FavoriteLimitCountText);
3544 _DoFavRetweetFlags = false;
3547 else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3551 string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3552 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3553 if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3554 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3556 _DoFavRetweetFlags = false;
3562 if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3563 MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3570 var statusIds = new List<long>();
3571 foreach (int idx in _curList.SelectedIndices)
3573 PostClass post = GetCurTabPost(idx);
3577 statusIds.Add(post.StatusId);
3582 statusIds.Add(post.StatusId);
3585 if (statusIds.Count == 0)
3588 StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3590 StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3596 await this.FavAddAsync(statusIds, tab);
3598 await this.FavRemoveAsync(statusIds, tab);
3601 private PostClass GetCurTabPost(int Index)
3603 this.itemCacheLock.EnterReadLock();
3606 if (_postCache != null && Index >= _itemCacheIndex && Index < _itemCacheIndex + _postCache.Length)
3607 return _postCache[Index - _itemCacheIndex];
3609 finally { this.itemCacheLock.ExitReadLock(); }
3611 return _statuses.Tabs[_curTab.Text][Index];
3615 private void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3617 if (_curList.SelectedIndices.Count > 0)
3618 OpenUriAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3619 else if (_curList.SelectedIndices.Count == 0)
3620 OpenUriAsync(MyCommon.TwitterUrl);
3623 private void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3625 if (_curList.SelectedIndices.Count > 0)
3626 OpenUriAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3629 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3631 if ((!_initialLayout) && this.Visible)
3633 if (this.WindowState == FormWindowState.Normal)
3635 _mySize = this.ClientSize;
3636 _mySpDis = this.SplitContainer1.SplitterDistance;
3637 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3638 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3639 _modifySettingLocal = true;
3644 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3646 if (this._cfgCommon.SortOrderLock) return;
3647 var mode = ComparerMode.Id;
3650 mode = ComparerMode.Id;
3658 case 6: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
3662 mode = ComparerMode.Nickname;
3665 mode = ComparerMode.Data;
3668 mode = ComparerMode.Id;
3671 mode = ComparerMode.Name;
3674 mode = ComparerMode.Source;
3678 _statuses.ToggleSortOrder(mode);
3681 DetailsListView list = (DetailsListView)sender;
3684 list.Columns[0].Text = ColumnOrgText[0];
3685 list.Columns[1].Text = ColumnText[2];
3689 for (int i = 0; i <= 7; i++)
3691 list.Columns[i].Text = ColumnOrgText[i];
3693 list.Columns[e.Column].Text = ColumnText[e.Column];
3696 this.PurgeListViewItemCache();
3698 if (_statuses.Tabs[_curTab.Text].AllCount > 0 && _curPost != null)
3700 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_curPost.StatusId);
3703 SelectListItem(_curList, idx);
3704 _curList.EnsureVisible(idx);
3708 _modifySettingCommon = true;
3711 private void TweenMain_LocationChanged(object sender, EventArgs e)
3713 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3715 _myLoc = this.DesktopLocation;
3716 _modifySettingLocal = true;
3720 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3722 if (ListTab.SelectedTab == null) return;
3723 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3724 if (!this.ExistCurrentPost)
3726 ReplyStripMenuItem.Enabled = false;
3727 ReplyAllStripMenuItem.Enabled = false;
3728 DMStripMenuItem.Enabled = false;
3729 ShowProfileMenuItem.Enabled = false;
3730 ShowUserTimelineContextMenuItem.Enabled = false;
3731 ListManageUserContextToolStripMenuItem2.Enabled = false;
3732 MoveToFavToolStripMenuItem.Enabled = false;
3733 TabMenuItem.Enabled = false;
3734 IDRuleMenuItem.Enabled = false;
3735 SourceRuleMenuItem.Enabled = false;
3736 ReadedStripMenuItem.Enabled = false;
3737 UnreadStripMenuItem.Enabled = false;
3741 ShowProfileMenuItem.Enabled = true;
3742 ListManageUserContextToolStripMenuItem2.Enabled = true;
3743 ReplyStripMenuItem.Enabled = true;
3744 ReplyAllStripMenuItem.Enabled = true;
3745 DMStripMenuItem.Enabled = true;
3746 ShowUserTimelineContextMenuItem.Enabled = true;
3747 MoveToFavToolStripMenuItem.Enabled = true;
3748 TabMenuItem.Enabled = true;
3749 IDRuleMenuItem.Enabled = true;
3750 SourceRuleMenuItem.Enabled = true;
3751 ReadedStripMenuItem.Enabled = true;
3752 UnreadStripMenuItem.Enabled = true;
3754 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3756 FavAddToolStripMenuItem.Enabled = false;
3757 FavRemoveToolStripMenuItem.Enabled = false;
3758 StatusOpenMenuItem.Enabled = false;
3759 FavorareMenuItem.Enabled = false;
3760 ShowRelatedStatusesMenuItem.Enabled = false;
3762 ReTweetStripMenuItem.Enabled = false;
3763 ReTweetOriginalStripMenuItem.Enabled = false;
3764 QuoteStripMenuItem.Enabled = false;
3765 FavoriteRetweetContextMenu.Enabled = false;
3766 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3770 FavAddToolStripMenuItem.Enabled = true;
3771 FavRemoveToolStripMenuItem.Enabled = true;
3772 StatusOpenMenuItem.Enabled = true;
3773 FavorareMenuItem.Enabled = true;
3774 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3778 ReTweetOriginalStripMenuItem.Enabled = false;
3779 FavoriteRetweetContextMenu.Enabled = false;
3783 if (_curPost.IsProtect)
3785 ReTweetOriginalStripMenuItem.Enabled = false;
3786 ReTweetStripMenuItem.Enabled = false;
3787 QuoteStripMenuItem.Enabled = false;
3788 FavoriteRetweetContextMenu.Enabled = false;
3789 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3793 ReTweetOriginalStripMenuItem.Enabled = true;
3794 ReTweetStripMenuItem.Enabled = true;
3795 QuoteStripMenuItem.Enabled = true;
3796 FavoriteRetweetContextMenu.Enabled = true;
3797 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3801 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3803 // RefreshMoreStripMenuItem.Enabled = true;
3807 // RefreshMoreStripMenuItem.Enabled = false;
3809 if (!this.ExistCurrentPost
3810 || _curPost.InReplyToStatusId == null)
3812 RepliedStatusOpenMenuItem.Enabled = false;
3816 RepliedStatusOpenMenuItem.Enabled = true;
3818 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3820 MoveToRTHomeMenuItem.Enabled = false;
3824 MoveToRTHomeMenuItem.Enabled = true;
3827 if (this.ExistCurrentPost)
3829 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3830 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3831 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3833 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3837 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3839 MakeReplyOrDirectStatus(false, true);
3842 private void DMStripMenuItem_Click(object sender, EventArgs e)
3844 MakeReplyOrDirectStatus(false, false);
3847 private void doStatusDelete()
3849 if (this._curTab == null || this._curList == null)
3852 if (this._curList.SelectedIndices.Count == 0)
3855 var posts = this._curList.SelectedIndices.Cast<int>()
3856 .Select(x => this.GetCurTabPost(x))
3859 // 選択されたツイートの中に削除可能なものが一つでもあるか
3860 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3863 var ret = MessageBox.Show(this,
3864 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3865 Properties.Resources.DeleteStripMenuItem_ClickText2,
3866 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3868 if (ret != DialogResult.OK)
3872 if (this._curList.FocusedItem != null)
3873 focusedIndex = this._curList.FocusedItem.Index;
3874 else if (this._curList.TopItem != null)
3875 focusedIndex = this._curList.TopItem.Index;
3879 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3881 string lastError = null;
3882 foreach (var post in posts)
3884 if (!post.CanDeleteBy(this.tw.UserId))
3890 err = this.tw.RemoveDirectMessage(post.StatusId, post);
3894 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3895 // 他人に RT された自分のツイート
3896 err = this.tw.RemoveStatus(post.RetweetedId.Value);
3898 // 自分のツイート or 自分が RT したツイート
3899 err = this.tw.RemoveStatus(post.StatusId);
3902 if (!string.IsNullOrEmpty(err))
3908 this._statuses.RemovePost(post.StatusId);
3911 if (lastError == null)
3912 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3914 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3916 this.PurgeListViewItemCache();
3917 this._curPost = null;
3918 this._curItemIndex = -1;
3920 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3922 var listView = (DetailsListView)tabPage.Tag;
3923 var tab = this._statuses.Tabs[tabPage.Text];
3925 using (ControlTransaction.Update(listView))
3927 listView.VirtualListSize = tab.AllCount;
3929 if (tabPage == this._curTab)
3931 listView.SelectedIndices.Clear();
3933 if (tab.AllCount != 0)
3936 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3937 selectedIndex = focusedIndex;
3939 selectedIndex = tab.AllCount - 1;
3941 listView.SelectedIndices.Add(selectedIndex);
3942 listView.EnsureVisible(selectedIndex);
3943 listView.FocusedItem = listView.Items[selectedIndex];
3948 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3950 if (tabPage.ImageIndex == 0)
3951 tabPage.ImageIndex = -1; // タブアイコン
3955 if (!this._cfgCommon.TabIconDisp)
3956 this.ListTab.Refresh();
3960 private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3965 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3967 using (ControlTransaction.Update(this._curList))
3969 foreach (int idx in _curList.SelectedIndices)
3971 var post = this._statuses.Tabs[this._curTab.Text][idx];
3972 this._statuses.SetReadAllTab(post.StatusId, read: true);
3973 ChangeCacheStyleRead(true, idx);
3977 foreach (TabPage tb in ListTab.TabPages)
3979 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3981 if (this._cfgCommon.TabIconDisp)
3983 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3987 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3990 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3992 using (ControlTransaction.Update(this._curList))
3994 foreach (int idx in _curList.SelectedIndices)
3996 var post = this._statuses.Tabs[this._curTab.Text][idx];
3997 this._statuses.SetReadAllTab(post.StatusId, read: false);
3998 ChangeCacheStyleRead(false, idx);
4002 foreach (TabPage tb in ListTab.TabPages)
4004 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4006 if (this._cfgCommon.TabIconDisp)
4008 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4012 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4015 private void RefreshStripMenuItem_Click(object sender, EventArgs e)
4020 private void DoRefresh()
4022 if (_curTab != null)
4025 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4028 switch (_statuses.Tabs[_curTab.Text].TabType)
4030 case MyCommon.TabUsageType.Mentions:
4031 this.GetReplyAsync();
4033 case MyCommon.TabUsageType.DirectMessage:
4034 this.GetDirectMessagesAsync();
4036 case MyCommon.TabUsageType.Favorites:
4037 this.GetFavoritesAsync();
4039 //case MyCommon.TabUsageType.Profile:
4041 case MyCommon.TabUsageType.PublicSearch:
4043 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4044 this.GetPublicSearchAsync(tab);
4046 case MyCommon.TabUsageType.UserTimeline:
4047 this.GetUserTimelineAsync(tab);
4049 case MyCommon.TabUsageType.Lists:
4051 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4052 this.GetListTimelineAsync(tab);
4055 this.GetHomeTimelineAsync();
4061 this.GetHomeTimelineAsync();
4065 private async Task DoRefreshMore()
4068 if (_curTab != null)
4071 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4074 switch (_statuses.Tabs[_curTab.Text].TabType)
4076 case MyCommon.TabUsageType.Mentions:
4077 await this.GetReplyAsync(loadMore: true);
4079 case MyCommon.TabUsageType.DirectMessage:
4080 await this.GetDirectMessagesAsync(loadMore: true);
4082 case MyCommon.TabUsageType.Favorites:
4083 await this.GetFavoritesAsync(loadMore: true);
4085 case MyCommon.TabUsageType.Profile:
4088 case MyCommon.TabUsageType.PublicSearch:
4090 if (string.IsNullOrEmpty(tab.SearchWords)) return;
4091 await this.GetPublicSearchAsync(tab, loadMore: true);
4093 case MyCommon.TabUsageType.UserTimeline:
4094 await this.GetUserTimelineAsync(tab, loadMore: true);
4096 case MyCommon.TabUsageType.Lists:
4098 if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4099 await this.GetListTimelineAsync(tab, loadMore: true);
4102 await this.GetHomeTimelineAsync(loadMore: true);
4108 await this.GetHomeTimelineAsync(loadMore: true);
4112 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4114 DialogResult result = DialogResult.Abort;
4116 using (var settingDialog = new AppendSettingDialog())
4118 settingDialog.Icon = this.MainIcon;
4119 settingDialog.Owner = this;
4120 settingDialog.ShowInTaskbar = showTaskbarIcon;
4121 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4123 settingDialog.tw = this.tw;
4124 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4128 result = settingDialog.ShowDialog(this);
4132 return DialogResult.Abort;
4135 if (result == DialogResult.OK)
4139 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4147 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4150 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4152 var oldIconSz = this._cfgCommon.IconSize;
4154 if (ShowSettingDialog() == DialogResult.OK)
4158 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4159 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4160 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4161 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4162 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4163 HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4165 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4166 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4167 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4168 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4170 ImageSelector.Reset(tw, this.tw.Configuration);
4174 if (this._cfgCommon.TabIconDisp)
4176 ListTab.DrawItem -= ListTab_DrawItem;
4177 ListTab.DrawMode = TabDrawMode.Normal;
4178 ListTab.ImageList = this.TabImage;
4182 ListTab.DrawItem -= ListTab_DrawItem;
4183 ListTab.DrawItem += ListTab_DrawItem;
4184 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4185 ListTab.ImageList = null;
4188 catch (Exception ex)
4190 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4191 ex.Data["IsTerminatePermission"] = false;
4197 if (!this._cfgCommon.UnreadManage)
4199 ReadedStripMenuItem.Enabled = false;
4200 UnreadStripMenuItem.Enabled = false;
4201 if (this._cfgCommon.TabIconDisp)
4203 foreach (TabPage myTab in ListTab.TabPages)
4205 myTab.ImageIndex = -1;
4211 ReadedStripMenuItem.Enabled = true;
4212 UnreadStripMenuItem.Enabled = true;
4215 catch (Exception ex)
4217 ex.Data["Instance"] = "ListTab(UnreadManage)";
4218 ex.Data["IsTerminatePermission"] = false;
4225 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4227 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4228 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4229 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4231 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4232 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4233 _fntUnread = this._cfgLocal.FontUnread;
4234 _clUnread = this._cfgLocal.ColorUnread;
4235 _fntReaded = this._cfgLocal.FontRead;
4236 _clReaded = this._cfgLocal.ColorRead;
4237 _clFav = this._cfgLocal.ColorFav;
4238 _clOWL = this._cfgLocal.ColorOWL;
4239 _clRetweet = this._cfgLocal.ColorRetweet;
4240 _fntDetail = this._cfgLocal.FontDetail;
4241 _clDetail = this._cfgLocal.ColorDetail;
4242 _clDetailLink = this._cfgLocal.ColorDetailLink;
4243 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4244 _clSelf = this._cfgLocal.ColorSelf;
4245 _clAtSelf = this._cfgLocal.ColorAtSelf;
4246 _clTarget = this._cfgLocal.ColorTarget;
4247 _clAtTarget = this._cfgLocal.ColorAtTarget;
4248 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4249 _clAtTo = this._cfgLocal.ColorAtTo;
4250 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4251 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4252 _clInputFont = this._cfgLocal.ColorInputFont;
4253 _fntInputFont = this._cfgLocal.FontInputFont;
4254 _brsBackColorMine.Dispose();
4255 _brsBackColorAt.Dispose();
4256 _brsBackColorYou.Dispose();
4257 _brsBackColorAtYou.Dispose();
4258 _brsBackColorAtFromTarget.Dispose();
4259 _brsBackColorAtTo.Dispose();
4260 _brsBackColorNone.Dispose();
4261 _brsBackColorMine = new SolidBrush(_clSelf);
4262 _brsBackColorAt = new SolidBrush(_clAtSelf);
4263 _brsBackColorYou = new SolidBrush(_clTarget);
4264 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4265 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4266 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4267 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4271 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4272 StatusText.Font = _fntInputFont;
4273 StatusText.ForeColor = _clInputFont;
4275 catch (Exception ex)
4277 MessageBox.Show(ex.Message);
4282 InitDetailHtmlFormat();
4284 catch (Exception ex)
4286 ex.Data["Instance"] = "Font";
4287 ex.Data["IsTerminatePermission"] = false;
4293 foreach (TabPage tb in ListTab.TabPages)
4295 if (this._cfgCommon.TabIconDisp)
4297 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4304 catch (Exception ex)
4306 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4307 ex.Data["IsTerminatePermission"] = false;
4313 var oldIconCol = _iconCol;
4315 if (this._cfgCommon.IconSize != oldIconSz)
4316 ApplyListViewIconSize(this._cfgCommon.IconSize);
4318 foreach (TabPage tp in ListTab.TabPages)
4320 DetailsListView lst = (DetailsListView)tp.Tag;
4322 using (ControlTransaction.Update(lst))
4324 lst.GridLines = this._cfgCommon.ShowGrid;
4325 lst.Font = _fntReaded;
4326 lst.BackColor = _clListBackcolor;
4328 if (_iconCol != oldIconCol)
4333 catch (Exception ex)
4335 ex.Data["Instance"] = "ListView(IconSize)";
4336 ex.Data["IsTerminatePermission"] = false;
4340 SetMainWindowTitle();
4341 SetNotifyIconText();
4343 this.PurgeListViewItemCache();
4344 if (_curList != null) _curList.Refresh();
4347 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4348 if (this._cfgCommon.HotkeyEnabled)
4350 ///グローバルホットキーの登録。設定で変更可能にするかも
4351 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4352 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4353 modKey |= HookGlobalHotkey.ModKeys.Alt;
4354 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4355 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4356 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4357 modKey |= HookGlobalHotkey.ModKeys.Shift;
4358 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4359 modKey |= HookGlobalHotkey.ModKeys.Win;
4361 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4364 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4367 StatusText_TextChanged(null, null);
4376 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4377 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4380 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4382 this.TopMost = this._cfgCommon.AlwaysTop;
4383 SaveConfigsAll(false);
4385 if (tw.Username != oldUser.Username)
4386 await this.doGetFollowersMenu();
4392 private void SetTabAlignment()
4394 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4395 if (ListTab.Alignment == newAlignment) return;
4398 var selId = new Dictionary<string, long[]>();
4399 var focusedId = new Dictionary<string, Tuple<long, long>>();
4400 SaveSelectedStatus(selId, focusedId);
4402 ListTab.Alignment = newAlignment;
4405 foreach (TabPage tab in ListTab.TabPages)
4407 DetailsListView lst = (DetailsListView)tab.Tag;
4408 TabClass tabInfo = _statuses.Tabs[tab.Text];
4409 using (ControlTransaction.Update(lst))
4411 // status_id から ListView 上のインデックスに変換
4412 var selectedIndices = selId[tab.Text] != null
4413 ? tabInfo.IndexOf(selId[tab.Text]).Where(x => x != -1).ToArray()
4415 var focusedIndex = tabInfo.IndexOf(focusedId[tab.Text].Item1);
4416 var selectionMarkIndex = tabInfo.IndexOf(focusedId[tab.Text].Item2);
4418 this.SelectListItem(lst, selectedIndices, focusedIndex, selectionMarkIndex);
4423 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4429 case MyCommon.IconSizes.IconNone:
4432 case MyCommon.IconSizes.Icon16:
4435 case MyCommon.IconSizes.Icon24:
4438 case MyCommon.IconSizes.Icon48:
4441 case MyCommon.IconSizes.Icon48_2:
4449 // ディスプレイの DPI 設定を考慮したサイズを設定する
4450 _listViewImageList.ImageSize = new Size(
4452 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4456 _listViewImageList.ImageSize = new Size(1, 1);
4460 private void ResetColumns(DetailsListView list)
4462 using (ControlTransaction.Update(list))
4463 using (ControlTransaction.Layout(list, false))
4466 list.ColumnClick -= MyList_ColumnClick;
4467 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4468 list.ColumnReordered -= MyList_ColumnReordered;
4469 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4471 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4472 list.Columns.Clear();
4473 cols.ForEach(col => col.Dispose());
4476 InitColumns(list, true);
4478 list.ColumnClick += MyList_ColumnClick;
4479 list.DrawColumnHeader += MyList_DrawColumnHeader;
4480 list.ColumnReordered += MyList_ColumnReordered;
4481 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4485 private void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4487 if (e.Url.AbsoluteUri != "about:blank")
4490 OpenUriAsync(e.Url.OriginalString);
4494 private void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4496 if (e.Url.Scheme == "data")
4498 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4500 else if (e.Url.AbsoluteUri != "about:blank")
4504 if (e.Url.AbsoluteUri.StartsWith("http://twitter.com/search?q=%23") ||
4505 e.Url.AbsoluteUri.StartsWith("https://twitter.com/search?q=%23"))
4508 string urlStr = Uri.UnescapeDataString(e.Url.AbsoluteUri);
4509 int i = urlStr.IndexOf('#');
4510 if (i == -1) return;
4512 string hash = urlStr.Substring(i);
4513 HashSupl.AddItem(hash);
4514 HashMgr.AddHashToHistory(hash.Trim(), false);
4515 AddNewTabForSearch(hash);
4520 Match m = Regex.Match(e.Url.AbsoluteUri, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
4521 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
4523 // Ctrlを押しながらリンクをクリックした場合は設定と逆の動作をする
4524 if (this._cfgCommon.OpenUserTimeline)
4526 if (MyCommon.IsKeyDown(Keys.Control))
4527 OpenUriAsync(e.Url.OriginalString);
4529 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4533 if (MyCommon.IsKeyDown(Keys.Control))
4534 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
4536 OpenUriAsync(e.Url.OriginalString);
4541 OpenUriAsync(e.Url.OriginalString);
4547 public void AddNewTabForSearch(string searchWord)
4549 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4550 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4552 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4554 foreach (TabPage tp in ListTab.TabPages)
4556 if (tb.TabName == tp.Text)
4558 ListTab.SelectedTab = tp;
4565 string tabName = searchWord;
4566 for (int i = 0; i <= 100; i++)
4568 if (_statuses.ContainsTab(tabName))
4574 _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4575 AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4577 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4579 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4580 cmb.Items.Add(searchWord);
4581 cmb.Text = searchWord;
4584 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4587 private void ShowUserTimeline()
4589 if (!this.ExistCurrentPost) return;
4590 AddNewTabForUserTimeline(_curPost.ScreenName);
4593 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4595 if (e.KeyCode == Keys.Escape)
4597 TabPage relTp = ListTab.SelectedTab;
4598 RemoveSpecifiedTab(relTp.Text, false);
4600 e.SuppressKeyPress = true;
4604 public void AddNewTabForUserTimeline(string user)
4606 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4607 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4609 if (tb.User == user)
4611 foreach (TabPage tp in ListTab.TabPages)
4613 if (tb.TabName == tp.Text)
4615 ListTab.SelectedTab = tp;
4622 string tabName = "user:" + user;
4623 while (_statuses.ContainsTab(tabName))
4628 _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4629 var tab = this._statuses.Tabs[tabName];
4631 AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4633 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4636 this.GetUserTimelineAsync(tab);
4639 public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4642 foreach (TabPage tb in ListTab.TabPages)
4644 if (tb.Text == tabName) return false;
4648 if (tabName == Properties.Resources.AddNewTabText1) return false;
4653 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4654 tabType == MyCommon.TabUsageType.Favorites ||
4655 tabType == MyCommon.TabUsageType.Home ||
4656 tabType == MyCommon.TabUsageType.Mentions ||
4657 tabType == MyCommon.TabUsageType.Related)
4659 if (_statuses.GetTabByType(tabType) != null) return false;
4663 TabPage _tabPage = new TabPage();
4664 DetailsListView _listCustom = new DetailsListView();
4666 int cnt = ListTab.TabPages.Count;
4668 ///ToDo:Create and set controls follow tabtypes
4670 using (ControlTransaction.Update(_listCustom))
4671 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4672 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4673 using (ControlTransaction.Layout(this.SplitContainer1, false))
4674 using (ControlTransaction.Layout(this.ListTab, false))
4675 using (ControlTransaction.Layout(this))
4676 using (ControlTransaction.Layout(_tabPage, false))
4680 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4682 label = new Label();
4683 label.Dock = DockStyle.Top;
4684 label.Name = "labelUser";
4685 if (tabType == MyCommon.TabUsageType.Lists)
4687 label.Text = listInfo.ToString();
4691 label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4693 label.TextAlign = ContentAlignment.MiddleLeft;
4694 using (ComboBox tmpComboBox = new ComboBox())
4696 label.Height = tmpComboBox.Height;
4698 _tabPage.Controls.Add(label);
4703 if (tabType == MyCommon.TabUsageType.PublicSearch)
4707 Label lbl = new Label();
4708 ComboBox cmb = new ComboBox();
4709 Button btn = new Button();
4710 ComboBox cmbLang = new ComboBox();
4712 pnl.SuspendLayout();
4714 pnl.Controls.Add(cmb);
4715 pnl.Controls.Add(cmbLang);
4716 pnl.Controls.Add(btn);
4717 pnl.Controls.Add(lbl);
4718 pnl.Name = "panelSearch";
4719 pnl.Dock = DockStyle.Top;
4720 pnl.Height = cmb.Height;
4721 pnl.Enter += SearchControls_Enter;
4722 pnl.Leave += SearchControls_Leave;
4725 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4726 cmb.Dock = DockStyle.Fill;
4727 cmb.Name = "comboSearch";
4728 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4729 cmb.ImeMode = ImeMode.NoControl;
4730 cmb.TabStop = false;
4731 cmb.AutoCompleteMode = AutoCompleteMode.None;
4732 cmb.KeyDown += SearchComboBox_KeyDown;
4734 if (_statuses.ContainsTab(tabName))
4736 cmb.Items.Add(_statuses.Tabs[tabName].SearchWords);
4737 cmb.Text = _statuses.Tabs[tabName].SearchWords;
4741 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4742 cmbLang.Dock = DockStyle.Right;
4744 cmbLang.Name = "comboLang";
4745 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4746 cmbLang.TabStop = false;
4747 cmbLang.Items.Add("");
4748 cmbLang.Items.Add("ja");
4749 cmbLang.Items.Add("en");
4750 cmbLang.Items.Add("ar");
4751 cmbLang.Items.Add("da");
4752 cmbLang.Items.Add("nl");
4753 cmbLang.Items.Add("fa");
4754 cmbLang.Items.Add("fi");
4755 cmbLang.Items.Add("fr");
4756 cmbLang.Items.Add("de");
4757 cmbLang.Items.Add("hu");
4758 cmbLang.Items.Add("is");
4759 cmbLang.Items.Add("it");
4760 cmbLang.Items.Add("no");
4761 cmbLang.Items.Add("pl");
4762 cmbLang.Items.Add("pt");
4763 cmbLang.Items.Add("ru");
4764 cmbLang.Items.Add("es");
4765 cmbLang.Items.Add("sv");
4766 cmbLang.Items.Add("th");
4767 if (_statuses.ContainsTab(tabName)) cmbLang.Text = _statuses.Tabs[tabName].SearchLang;
4769 lbl.Text = "Search(C-S-f)";
4770 lbl.Name = "label1";
4771 lbl.Dock = DockStyle.Left;
4773 lbl.Height = cmb.Height;
4774 lbl.TextAlign = ContentAlignment.MiddleLeft;
4776 btn.Text = "Search";
4777 btn.Name = "buttonSearch";
4778 btn.UseVisualStyleBackColor = true;
4779 btn.Dock = DockStyle.Right;
4780 btn.TabStop = false;
4781 btn.Click += SearchButton_Click;
4784 this.ListTab.Controls.Add(_tabPage);
4785 _tabPage.Controls.Add(_listCustom);
4787 if (tabType == MyCommon.TabUsageType.PublicSearch) _tabPage.Controls.Add(pnl);
4788 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists) _tabPage.Controls.Add(label);
4790 _tabPage.Location = new Point(4, 4);
4791 _tabPage.Name = "CTab" + cnt.ToString();
4792 _tabPage.Size = new Size(380, 260);
4793 _tabPage.TabIndex = 2 + cnt;
4794 _tabPage.Text = tabName;
4795 _tabPage.UseVisualStyleBackColor = true;
4797 _listCustom.AllowColumnReorder = true;
4798 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4799 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4800 _listCustom.Dock = DockStyle.Fill;
4801 _listCustom.FullRowSelect = true;
4802 _listCustom.HideSelection = false;
4803 _listCustom.Location = new Point(0, 0);
4804 _listCustom.Margin = new Padding(0);
4805 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4806 _listCustom.ShowItemToolTips = true;
4807 _listCustom.Size = new Size(380, 260);
4808 _listCustom.UseCompatibleStateImageBehavior = false;
4809 _listCustom.View = View.Details;
4810 _listCustom.OwnerDraw = true;
4811 _listCustom.VirtualMode = true;
4812 _listCustom.Font = _fntReaded;
4813 _listCustom.BackColor = _clListBackcolor;
4815 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4816 _listCustom.AllowDrop = true;
4818 _listCustom.SmallImageList = _listViewImageList;
4820 InitColumns(_listCustom, startup);
4822 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4823 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4824 _listCustom.ColumnClick += MyList_ColumnClick;
4825 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4826 _listCustom.DragDrop += TweenMain_DragDrop;
4827 _listCustom.DragEnter += TweenMain_DragEnter;
4828 _listCustom.DragOver += TweenMain_DragOver;
4829 _listCustom.DrawItem += MyList_DrawItem;
4830 _listCustom.MouseClick += MyList_MouseClick;
4831 _listCustom.ColumnReordered += MyList_ColumnReordered;
4832 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4833 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4834 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4835 _listCustom.DrawSubItem += MyList_DrawSubItem;
4836 _listCustom.HScrolled += MyList_HScrolled;
4838 if (tabType == MyCommon.TabUsageType.PublicSearch) pnl.ResumeLayout(false);
4841 _tabPage.Tag = _listCustom;
4845 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4847 var tabInfo = _statuses.GetTabByName(TabName);
4848 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4852 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4853 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4854 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4860 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4861 if (_tabPage == null) return false;
4863 SetListProperty(); //他のタブに列幅等を反映
4866 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4867 _tabPage.Tag = null;
4869 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4870 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4871 using (ControlTransaction.Layout(this.SplitContainer1, false))
4872 using (ControlTransaction.Layout(this.ListTab, false))
4873 using (ControlTransaction.Layout(this))
4874 using (ControlTransaction.Layout(_tabPage, false))
4876 if (this.ListTab.SelectedTab == _tabPage)
4878 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4879 this._beforeSelectedTab = null;
4881 this.ListTab.Controls.Remove(_tabPage);
4884 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4886 using (Control label = _tabPage.Controls["labelUser"])
4888 _tabPage.Controls.Remove(label);
4891 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4893 using (Control pnl = _tabPage.Controls["panelSearch"])
4895 pnl.Enter -= SearchControls_Enter;
4896 pnl.Leave -= SearchControls_Leave;
4897 _tabPage.Controls.Remove(pnl);
4899 foreach (Control ctrl in pnl.Controls)
4901 if (ctrl.Name == "buttonSearch")
4903 ctrl.Click -= SearchButton_Click;
4905 else if (ctrl.Name == "comboSearch")
4907 ctrl.KeyDown -= SearchComboBox_KeyDown;
4909 pnl.Controls.Remove(ctrl);
4915 _tabPage.Controls.Remove(_listCustom);
4917 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4918 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4919 _listCustom.ColumnClick -= MyList_ColumnClick;
4920 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4921 _listCustom.DragDrop -= TweenMain_DragDrop;
4922 _listCustom.DragEnter -= TweenMain_DragEnter;
4923 _listCustom.DragOver -= TweenMain_DragOver;
4924 _listCustom.DrawItem -= MyList_DrawItem;
4925 _listCustom.MouseClick -= MyList_MouseClick;
4926 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4927 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4928 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4929 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4930 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4931 _listCustom.HScrolled -= MyList_HScrolled;
4933 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4934 _listCustom.Columns.Clear();
4935 cols.ForEach(col => col.Dispose());
4938 _listCustom.ContextMenuStrip = null;
4939 _listCustom.ColumnHeaderContextMenuStrip = null;
4940 _listCustom.Font = null;
4942 _listCustom.SmallImageList = null;
4943 _listCustom.ListViewItemSorter = null;
4946 if (_curTab.Equals(_tabPage))
4953 this.PurgeListViewItemCache();
4957 _listCustom.Dispose();
4958 _statuses.RemoveTab(TabName);
4960 foreach (TabPage tp in ListTab.TabPages)
4962 DetailsListView lst = (DetailsListView)tp.Tag;
4963 var count = _statuses.Tabs[tp.Text].AllCount;
4964 if (lst.VirtualListSize != count)
4966 lst.VirtualListSize = count;
4973 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4975 this.PurgeListViewItemCache();
4976 _beforeSelectedTab = e.TabPage;
4979 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4983 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4986 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4987 if (!dragEnableRectangle.Contains(e.Location))
4989 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4990 tn = ListTab.SelectedTab.Text;
4993 if (string.IsNullOrEmpty(tn)) return;
4995 foreach (TabPage tb in ListTab.TabPages)
4999 ListTab.DoDragDrop(tb, DragDropEffects.All);
5009 Point cpos = new Point(e.X, e.Y);
5010 for (int i = 0; i < ListTab.TabPages.Count; i++)
5012 Rectangle rect = ListTab.GetTabRect(i);
5013 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
5014 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
5016 _rclickTabName = ListTab.TabPages[i].Text;
5022 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
5024 //_curList.Refresh();
5026 SetMainWindowTitle();
5027 SetStatusLabelUrl();
5028 SetApiStatusLabel();
5029 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
5030 TabMenuControl(ListTab.SelectedTab.Text);
5031 this.PushSelectPostChain();
5034 private void SetListProperty()
5036 //削除などで見つからない場合は処理せず
5037 if (_curList == null) return;
5038 if (!_isColumnChanged) return;
5040 int[] dispOrder = new int[_curList.Columns.Count];
5041 for (int i = 0; i < _curList.Columns.Count; i++)
5043 for (int j = 0; j < _curList.Columns.Count; j++)
5045 if (_curList.Columns[j].DisplayIndex == i)
5054 foreach (TabPage tb in ListTab.TabPages)
5056 if (!tb.Equals(_curTab))
5058 if (tb.Tag != null && tb.Controls.Count > 0)
5060 DetailsListView lst = (DetailsListView)tb.Tag;
5061 for (int i = 0; i < lst.Columns.Count; i++)
5063 lst.Columns[dispOrder[i]].DisplayIndex = i;
5064 lst.Columns[i].Width = _curList.Columns[i].Width;
5070 _isColumnChanged = false;
5073 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5077 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5078 || PostBrowser.StatusText.StartsWith("data"))
5080 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5082 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5084 SetStatusLabelUrl();
5092 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5094 if (e.KeyChar == '@')
5096 if (!this._cfgCommon.UseAtIdSupplement) return;
5098 int cnt = AtIdSupl.ItemCount;
5099 ShowSuplDialog(StatusText, AtIdSupl);
5100 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
5103 else if (e.KeyChar == '#')
5105 if (!this._cfgCommon.UseHashSupplement) return;
5106 ShowSuplDialog(StatusText, HashSupl);
5111 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5113 ShowSuplDialog(owner, dialog, 0, "");
5116 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5118 ShowSuplDialog(owner, dialog, offset, "");
5121 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5123 dialog.StartsWith = startswith;
5130 dialog.ShowDialog();
5132 this.TopMost = this._cfgCommon.AlwaysTop;
5133 int selStart = owner.SelectionStart;
5136 if (dialog.DialogResult == DialogResult.OK)
5138 if (!string.IsNullOrEmpty(dialog.inputText))
5142 fHalf = owner.Text.Substring(0, selStart - offset);
5144 if (selStart < owner.Text.Length)
5146 eHalf = owner.Text.Substring(selStart);
5148 owner.Text = fHalf + dialog.inputText + eHalf;
5149 owner.SelectionStart = selStart + dialog.inputText.Length;
5156 fHalf = owner.Text.Substring(0, selStart);
5158 if (selStart < owner.Text.Length)
5160 eHalf = owner.Text.Substring(selStart);
5162 owner.Text = fHalf + eHalf;
5165 owner.SelectionStart = selStart;
5171 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5174 if (!e.Alt && !e.Control && !e.Shift)
5176 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5178 bool isSpace = false;
5179 foreach (char c in StatusText.Text.ToCharArray())
5181 if (c == ' ' || c == ' ')
5194 StatusText.Text = "";
5195 JumpUnreadMenuItem_Click(null, null);
5199 this.StatusText_TextChanged(null, null);
5202 private void StatusText_TextChanged(object sender, EventArgs e)
5205 int pLen = GetRestStatusCount(true, false);
5206 lblLen.Text = pLen.ToString();
5209 StatusText.ForeColor = Color.Red;
5213 StatusText.ForeColor = _clInputFont;
5215 if (string.IsNullOrEmpty(StatusText.Text))
5217 _reply_to_id = null;
5218 _reply_to_name = null;
5222 private int GetRestStatusCount(bool isAuto, bool isAddFooter)
5225 var statusText = this.StatusText.Text;
5226 statusText = statusText.Replace("\r\n", "\n");
5228 int pLen = 140 - statusText.Length;
5229 if (this.NotifyIcon1 == null || !this.NotifyIcon1.Visible) return pLen;
5230 if ((isAuto && !MyCommon.IsKeyDown(Keys.Control) && this._cfgCommon.PostShiftEnter) ||
5231 (isAuto && !MyCommon.IsKeyDown(Keys.Shift) && !this._cfgCommon.PostShiftEnter) ||
5232 (!isAuto && isAddFooter))
5234 if (this._cfgLocal.UseRecommendStatus)
5235 pLen -= this.recommendedStatusFooter.Length;
5236 else if (this._cfgLocal.StatusText.Length > 0)
5237 pLen -= this._cfgLocal.StatusText.Length + 1;
5239 if (!string.IsNullOrEmpty(HashMgr.UseHash))
5241 pLen -= HashMgr.UseHash.Length + 1;
5243 //foreach (Match m in Regex.Matches(statusText, "https?:\/\/[-_.!~*//()a-zA-Z0-9;\/?:\@&=+\$,%#^]+"))
5245 // pLen += m.Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5247 foreach (Match m in Regex.Matches(statusText, Twitter.rgUrl, RegexOptions.IgnoreCase))
5249 string before = m.Result("${before}");
5250 string url = m.Result("${url}");
5251 string protocol = m.Result("${protocol}");
5252 string domain = m.Result("${domain}");
5253 string path = m.Result("${path}");
5254 if (protocol.Length == 0)
5256 if (Regex.IsMatch(before, Twitter.url_invalid_without_protocol_preceding_chars))
5261 bool last_url_invalid_match = false;
5262 string lasturl = null;
5263 foreach (Match mm in Regex.Matches(domain, Twitter.url_valid_ascii_domain, RegexOptions.IgnoreCase))
5265 lasturl = mm.ToString();
5266 last_url_invalid_match = Regex.IsMatch(lasturl, Twitter.url_invalid_short_domain, RegexOptions.IgnoreCase);
5267 if (!last_url_invalid_match)
5269 pLen += lasturl.Length - this.tw.Configuration.ShortUrlLength;
5273 if (path.Length != 0)
5275 if (last_url_invalid_match)
5277 pLen += lasturl.Length - this.tw.Configuration.ShortUrlLength;
5279 pLen += path.Length;
5284 int shortUrlLength = protocol == "https://"
5285 ? this.tw.Configuration.ShortUrlLengthHttps
5286 : this.tw.Configuration.ShortUrlLength;
5288 pLen += url.Length - shortUrlLength;
5291 //if (m.Result("${url}").Length > SettingDialog.TwitterConfiguration.ShortUrlLength)
5293 // pLen += m.Result("${url}").Length - SettingDialog.TwitterConfiguration.ShortUrlLength;
5296 if (ImageSelector.Visible && !string.IsNullOrEmpty(ImageSelector.ServiceName))
5298 pLen -= this.tw.Configuration.CharactersReservedPerMedia;
5303 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5305 this.itemCacheLock.EnterUpgradeableReadLock();
5308 if (_curList.Equals(sender))
5310 if (_itemCache != null &&
5311 e.StartIndex >= _itemCacheIndex &&
5312 e.EndIndex < _itemCacheIndex + _itemCache.Length)
5314 //If the newly requested cache is a subset of the old cache,
5315 //no need to rebuild everything, so do nothing.
5319 //Now we need to rebuild the cache.
5320 CreateCache(e.StartIndex, e.EndIndex);
5323 finally { this.itemCacheLock.ExitUpgradeableReadLock(); }
5326 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5328 ListViewItem item = null;
5329 PostClass cacheItemPost = null;
5331 if (_curList.Equals(sender))
5332 this.TryGetListViewItemCache(e.ItemIndex, out item, out cacheItemPost);
5336 //A cache miss, so create a new ListViewItem and pass it back.
5337 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5340 item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5345 string[] sitem = {"", "", "", "", "", "", "", ""};
5346 item = new ImageListViewItem(sitem);
5353 private void CreateCache(int StartIndex, int EndIndex)
5355 this.itemCacheLock.EnterWriteLock();
5358 var tabInfo = _statuses.Tabs[_curTab.Text];
5360 //キャッシュ要求(要求範囲±30を作成)
5362 if (StartIndex < 0) StartIndex = 0;
5364 if (EndIndex >= tabInfo.AllCount) EndIndex = tabInfo.AllCount - 1;
5365 _postCache = tabInfo[StartIndex, EndIndex]; //配列で取得
5366 _itemCacheIndex = StartIndex;
5368 _itemCache = new ListViewItem[0] {};
5369 Array.Resize(ref _itemCache, _postCache.Length);
5371 for (int i = 0; i < _postCache.Length; i++)
5373 _itemCache[i] = CreateItem(_curTab, _postCache[i], StartIndex + i);
5378 //キャッシュ要求が実データとずれるため(イベントの遅延?)
5380 _itemCacheIndex = -1;
5383 finally { this.itemCacheLock.ExitWriteLock(); }
5387 /// DetailsListView のための ListViewItem のキャッシュを消去する
5389 private void PurgeListViewItemCache()
5391 this.itemCacheLock.EnterWriteLock();
5394 this._itemCache = null;
5395 this._itemCacheIndex = -1;
5396 this._postCache = null;
5398 finally { this.itemCacheLock.ExitWriteLock(); }
5401 private bool TryGetListViewItemCache(int index, out ListViewItem item, out PostClass post)
5403 this.itemCacheLock.EnterReadLock();
5406 if (this._itemCache != null && index >= this._itemCacheIndex && index < this._itemCacheIndex + this._itemCache.Length)
5408 item = this._itemCache[index - _itemCacheIndex];
5409 post = this._postCache[index - _itemCacheIndex];
5413 finally { this.itemCacheLock.ExitReadLock(); }
5420 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5422 StringBuilder mk = new StringBuilder();
5423 //if (Post.IsDeleted) mk.Append("×");
5424 //if (Post.IsMark) mk.Append("♪");
5425 //if (Post.IsProtect) mk.Append("Ю");
5426 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5427 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5428 ImageListViewItem itm;
5429 if (Post.RetweetedId == null)
5431 string[] sitem= {"",
5433 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5434 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5439 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5443 string[] sitem = {"",
5445 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5446 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5447 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5451 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5453 itm.StateIndex = Post.StateIndex;
5455 bool read = Post.IsRead;
5456 //未読管理していなかったら既読として扱う
5457 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5458 ChangeItemStyleRead(read, itm, Post, null);
5459 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5464 /// 全てのタブの振り分けルールを反映し直します
5466 private void ApplyPostFilters()
5468 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5470 this.PurgeListViewItemCache();
5471 this._curPost = null;
5472 this._curItemIndex = -1;
5473 this._statuses.FilterAll();
5475 foreach (TabPage tabPage in this.ListTab.TabPages)
5477 var tab = this._statuses.Tabs[tabPage.Text];
5479 var listview = (DetailsListView)tabPage.Tag;
5480 using (ControlTransaction.Update(listview))
5482 listview.VirtualListSize = tab.AllCount;
5485 if (this._cfgCommon.TabIconDisp)
5487 if (tab.UnreadCount > 0)
5488 tabPage.ImageIndex = 0;
5490 tabPage.ImageIndex = -1;
5494 if (!this._cfgCommon.TabIconDisp)
5495 this.ListTab.Refresh();
5497 SetMainWindowTitle();
5498 SetStatusLabelUrl();
5502 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5504 e.DrawDefault = true;
5507 private void MyList_HScrolled(object sender, EventArgs e)
5509 DetailsListView listView = (DetailsListView)sender;
5513 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5515 if (e.State == 0) return;
5516 e.DrawDefault = false;
5518 SolidBrush brs2 = null;
5519 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5521 if (e.Item.BackColor == _clSelf)
5522 brs2 = _brsBackColorMine;
5523 else if (e.Item.BackColor == _clAtSelf)
5524 brs2 = _brsBackColorAt;
5525 else if (e.Item.BackColor == _clTarget)
5526 brs2 = _brsBackColorYou;
5527 else if (e.Item.BackColor == _clAtTarget)
5528 brs2 = _brsBackColorAtYou;
5529 else if (e.Item.BackColor == _clAtFromTarget)
5530 brs2 = _brsBackColorAtFromTarget;
5531 else if (e.Item.BackColor == _clAtTo)
5532 brs2 = _brsBackColorAtTo;
5534 brs2 = _brsBackColorNone;
5539 if (((Control)sender).Focused)
5540 brs2 = _brsHighLight;
5542 brs2 = _brsDeactiveSelection;
5544 e.Graphics.FillRectangle(brs2, e.Bounds);
5545 e.DrawFocusRectangle();
5546 this.DrawListViewItemIcon(e);
5549 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5551 if (e.ItemState == 0) return;
5553 if (e.ColumnIndex > 0)
5556 RectangleF rct = e.Bounds;
5557 rct.Width = e.Header.Width;
5558 int fontHeight = e.Item.Font.Height;
5561 rct.Y += fontHeight;
5562 rct.Height -= fontHeight;
5566 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5568 //if (heightDiff > fontHeight * 0.7)
5570 // rct.Height += fontHeight;
5571 // drawLineCount += 1;
5574 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5575 if (!_iconCol && drawLineCount <= 1)
5577 //rct.Inflate(0, heightDiff / -2);
5578 //rct.Height += fontHeight / 2;
5580 else if (heightDiff < fontHeight * 0.7)
5582 //最終行が70%以上欠けていたら、最終行は表示しない
5583 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5584 rct.Height = (fontHeight * drawLineCount) - 1;
5591 //if (!_iconCol && drawLineCount > 1)
5593 // rct.Y += fontHeight * 0.2;
5594 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5599 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5600 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5605 Rectangle rctB = e.Bounds;
5606 rctB.Width = e.Header.Width;
5607 rctB.Height = fontHeight;
5609 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5611 TextRenderer.DrawText(e.Graphics,
5612 e.Item.SubItems[2].Text,
5614 Rectangle.Round(rct),
5616 TextFormatFlags.WordBreak |
5617 TextFormatFlags.EndEllipsis |
5618 TextFormatFlags.GlyphOverhangPadding |
5619 TextFormatFlags.NoPrefix);
5620 TextRenderer.DrawText(e.Graphics,
5621 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 + "]",
5625 TextFormatFlags.SingleLine |
5626 TextFormatFlags.EndEllipsis |
5627 TextFormatFlags.GlyphOverhangPadding |
5628 TextFormatFlags.NoPrefix);
5631 else if (drawLineCount == 1)
5633 TextRenderer.DrawText(e.Graphics,
5636 Rectangle.Round(rct),
5638 TextFormatFlags.SingleLine |
5639 TextFormatFlags.EndEllipsis |
5640 TextFormatFlags.GlyphOverhangPadding |
5641 TextFormatFlags.NoPrefix |
5642 TextFormatFlags.VerticalCenter);
5646 TextRenderer.DrawText(e.Graphics,
5649 Rectangle.Round(rct),
5651 TextFormatFlags.WordBreak |
5652 TextFormatFlags.EndEllipsis |
5653 TextFormatFlags.GlyphOverhangPadding |
5654 TextFormatFlags.NoPrefix);
5656 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5661 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5663 if (_iconSz == 0) return;
5665 ImageListViewItem item = (ImageListViewItem)e.Item;
5667 //e.Bounds.Leftが常に0を指すから自前で計算
5668 Rectangle itemRect = item.Bounds;
5669 var col0 = e.Item.ListView.Columns[0];
5670 itemRect.Width = col0.Width;
5672 if (col0.DisplayIndex > 0)
5674 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5676 if (clm.DisplayIndex < col0.DisplayIndex)
5677 itemRect.X += clm.Width;
5681 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5682 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5683 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5686 var img = item.Image;
5689 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5690 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5692 if (iconRect.Width > 0)
5694 e.Graphics.FillRectangle(Brushes.White, iconRect);
5695 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5698 e.Graphics.DrawImage(img.Image, iconRect);
5700 catch (ArgumentException)
5702 item.RefreshImageAsync();
5708 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5709 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5711 item.GetImageAsync();
5714 if (item.StateIndex > -1)
5716 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5717 if (stateRect.Width > 0)
5719 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5720 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5721 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5726 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5728 base.ScaleControl(factor, specified);
5730 ScaleChildControl(this.TabImage, factor);
5732 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5733 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5735 foreach (var listview in listviews)
5737 ScaleChildControl(listview, factor);
5741 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5743 // ImageListViewItem item = (ImageListViewItem)e.Item;
5744 // if (item.StateImageIndex > -1)
5746 // ////e.Bounds.Leftが常に0を指すから自前で計算
5747 // //Rectangle itemRect = item.Bounds;
5748 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5750 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5752 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5754 // // itemRect.X += clm.Width;
5758 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5759 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5761 // if (rct.Width > 0)
5763 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5764 // //e.Graphics.FillRectangle(Brushes.White, rct);
5765 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5766 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5771 private void DoTabSearch(string _word,
5781 if (_curList.VirtualListSize == 0)
5783 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5786 if (_curList.SelectedIndices.Count > 0)
5788 cidx = _curList.SelectedIndices[0];
5790 toIdx = _curList.VirtualListSize;
5794 case SEARCHTYPE.DialogSearch: //ダイアログからの検索
5795 if (_curList.SelectedIndices.Count > 0)
5796 cidx = _curList.SelectedIndices[0];
5800 case SEARCHTYPE.NextSearch: //次を検索
5801 if (_curList.SelectedIndices.Count > 0)
5803 cidx = _curList.SelectedIndices[0] + 1;
5804 if (cidx > toIdx) cidx = toIdx;
5811 case SEARCHTYPE.PrevSearch: //前を検索
5812 if (_curList.SelectedIndices.Count > 0)
5814 cidx = _curList.SelectedIndices[0] - 1;
5815 if (cidx < 0) cidx = 0;
5826 RegexOptions regOpt = RegexOptions.None;
5827 StringComparison fndOpt = StringComparison.Ordinal;
5830 regOpt = RegexOptions.IgnoreCase;
5831 fndOpt = StringComparison.OrdinalIgnoreCase;
5842 _search = new Regex(_word, regOpt);
5843 for (int idx = cidx; idx != toIdx; idx += stp)
5848 post = _statuses.Tabs[_curTab.Text][idx];
5854 if (_search.IsMatch(post.Nickname)
5855 || _search.IsMatch(post.TextFromApi)
5856 || _search.IsMatch(post.ScreenName))
5858 SelectListItem(_curList, idx);
5859 _curList.EnsureVisible(idx);
5864 catch (ArgumentException)
5866 MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5873 for (int idx = cidx; idx != toIdx; idx += stp)
5878 post = _statuses.Tabs[_curTab.Text][idx];
5884 if (post.Nickname.IndexOf(_word, fndOpt) > -1
5885 || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5886 || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5888 SelectListItem(_curList, idx);
5889 _curList.EnsureVisible(idx);
5899 case SEARCHTYPE.DialogSearch:
5900 case SEARCHTYPE.NextSearch:
5904 case SEARCHTYPE.PrevSearch:
5906 cidx = _curList.VirtualListSize - 1;
5913 catch (ArgumentOutOfRangeException)
5916 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5919 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5922 this.ShowSearchDialog();
5925 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5927 var previousSearch = this.SearchDialog.ResultOptions;
5928 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5930 this.SearchDialog.Reset();
5931 this.ShowSearchDialog();
5937 previousSearch.Query,
5938 previousSearch.CaseSensitive,
5939 previousSearch.UseRegex,
5940 SEARCHTYPE.NextSearch);
5943 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5945 var previousSearch = this.SearchDialog.ResultOptions;
5946 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5948 this.SearchDialog.Reset();
5949 this.ShowSearchDialog();
5955 previousSearch.Query,
5956 previousSearch.CaseSensitive,
5957 previousSearch.UseRegex,
5958 SEARCHTYPE.PrevSearch);
5962 /// 検索ダイアログを表示し、検索を実行します
5964 private void ShowSearchDialog()
5966 // Recentタブの検索時以外では「新規タブに表示」ボタンを無効化する
5967 if (this._statuses.Tabs[this._curTab.Text].TabType == MyCommon.TabUsageType.Home)
5968 this.SearchDialog.DisableNewTabButton = false;
5970 this.SearchDialog.DisableNewTabButton = true;
5972 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5974 this.TopMost = this._cfgCommon.AlwaysTop;
5977 this.TopMost = this._cfgCommon.AlwaysTop;
5979 var searchOptions = this.SearchDialog.ResultOptions;
5980 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5982 if (searchOptions.NewTab)
5984 var tabName = searchOptions.Query;
5988 tabName = this._statuses.MakeTabName(tabName);
5990 catch (TabException ex)
5992 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5995 this.AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined);
5996 this._statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null);
5998 var filter = new PostFilterRule
6000 FilterBody = new[] { searchOptions.Query },
6001 UseRegex = searchOptions.UseRegex,
6002 CaseSensitive = searchOptions.CaseSensitive,
6004 this._statuses.Tabs[tabName].AddFilter(filter);
6006 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
6007 .First(x => x.Text == tabName);
6009 this.ListTab.SelectedTab = tabPage;
6011 this.ApplyPostFilters();
6012 this.SaveConfigsTabs();
6017 searchOptions.Query,
6018 searchOptions.CaseSensitive,
6019 searchOptions.UseRegex,
6020 SEARCHTYPE.DialogSearch);
6023 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
6025 this.AddNewTabForSearch(searchOptions.Query);
6029 private void AboutMenuItem_Click(object sender, EventArgs e)
6031 using (TweenAboutBox about = new TweenAboutBox())
6033 about.ShowDialog(this);
6035 this.TopMost = this._cfgCommon.AlwaysTop;
6038 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
6040 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
6042 DetailsListView lst = null;
6044 if (ImageSelector.Enabled)
6048 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
6051 idx = _statuses.Tabs[ListTab.TabPages[i].Text].OldestUnreadIndex;
6054 ListTab.SelectedIndex = i;
6055 lst = (DetailsListView)ListTab.TabPages[i].Tag;
6056 //_curTab = ListTab.TabPages[i];
6061 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
6062 if (idx == -1 && bgnIdx > 0)
6064 for (int i = 0; i < bgnIdx; i++)
6066 idx = _statuses.Tabs[ListTab.TabPages[i].Text].OldestUnreadIndex;
6069 ListTab.SelectedIndex = i;
6070 lst = (DetailsListView)ListTab.TabPages[i].Tag;
6071 //_curTab = ListTab.TabPages[i];
6077 //全部調べたが未読見つからず→先頭タブの最新発言へ
6080 ListTab.SelectedIndex = 0;
6081 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6082 //_curTab = ListTab.TabPages[0];
6083 if (_statuses.SortOrder == SortOrder.Ascending)
6084 idx = lst.VirtualListSize - 1;
6089 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6091 SelectListItem(lst, idx);
6092 if (_statuses.SortMode == ComparerMode.Id)
6094 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6095 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6101 lst.EnsureVisible(idx);
6106 lst.EnsureVisible(idx);
6112 private void StatusOpenMenuItem_Click(object sender, EventArgs e)
6114 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6116 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6117 OpenUriAsync(MyCommon.GetStatusUrl(post));
6121 private void FavorareMenuItem_Click(object sender, EventArgs e)
6123 if (_curList.SelectedIndices.Count > 0)
6125 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6126 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6130 private async void VerUpMenuItem_Click(object sender, EventArgs e)
6132 await this.CheckNewVersion(false);
6135 private void RunTweenUp()
6137 ProcessStartInfo pinfo = new ProcessStartInfo();
6138 pinfo.UseShellExecute = true;
6139 pinfo.WorkingDirectory = MyCommon.settingPath;
6140 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6141 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6144 Process.Start(pinfo);
6148 MessageBox.Show("Failed to execute TweenUp3.exe.");
6152 public class VersionInfo
6154 public Version Version { get; set; }
6155 public Uri DownloadUri { get; set; }
6156 public string ReleaseNote { get; set; }
6160 /// OpenTween の最新バージョンの情報を取得します
6162 public async Task<VersionInfo> GetVersionInfoAsync()
6164 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6165 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6167 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6168 .ConfigureAwait(false);
6170 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6171 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6173 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6174 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6176 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6178 return new VersionInfo
6180 Version = Version.Parse(msgHeader[0]),
6181 DownloadUri = new Uri(msgHeader[1]),
6182 ReleaseNote = msgBody,
6186 private async Task CheckNewVersion(bool startup = false)
6188 if (ApplicationSettings.VersionInfoUrl == null)
6189 return; // 更新チェック無効化
6193 var versionInfo = await this.GetVersionInfoAsync();
6195 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6200 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6201 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6202 msgtext = MyCommon.ReplaceAppName(msgtext);
6204 MessageBox.Show(msgtext,
6205 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6206 MessageBoxButtons.OK, MessageBoxIcon.Information);
6211 using (var dialog = new UpdateDialog())
6213 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6214 MyCommon.GetReadableVersion(versionInfo.Version));
6215 dialog.DetailsText = versionInfo.ReleaseNote;
6217 if (dialog.ShowDialog(this) == DialogResult.Yes)
6219 await this.OpenUriAsync(versionInfo.DownloadUri.OriginalString);
6225 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6228 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6229 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6230 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6235 private void Colorize()
6239 //件数関連の場合、タイトル即時書き換え
6240 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6241 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6242 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6243 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6245 SetMainWindowTitle();
6247 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6248 foreach (TabPage tb in ListTab.TabPages)
6250 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6252 if (this._cfgCommon.TabIconDisp)
6254 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6258 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6261 public string createDetailHtml(string orgdata)
6263 if (this._cfgLocal.UseTwemoji)
6264 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6266 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6269 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6271 if (sender.Equals(displayItem))
6273 this.ClearUserPicture();
6275 var img = displayItem.Image;
6279 img = await img.CloneAsync();
6281 UserPicture.Image = img;
6285 UserPicture.ShowErrorImage();
6290 private void DispSelectedPost()
6292 DispSelectedPost(false);
6295 private PostClass displayPost = new PostClass();
6298 /// サムネイルの表示処理を表すタスク
6300 private Task thumbnailTask = null;
6303 /// サムネイル表示に使用する CancellationToken の生成元
6305 private CancellationTokenSource thumbnailTokenSource = null;
6307 private void DispSelectedPost(bool forceupdate)
6309 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6312 var oldDisplayPost = this.displayPost;
6313 this.displayPost = this._curPost;
6315 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6318 if (displayItem != null)
6320 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6323 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6324 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6326 using (ControlTransaction.Update(this.TableLayoutPanel1))
6328 var sourceText = "";
6329 string sourceUrl = null;
6332 var mc = Regex.Match(_curPost.SourceHtml, "<a href=\"(?<sourceurl>.+?)\"");
6335 var src = mc.Groups["sourceurl"].Value;
6336 if (Regex.IsMatch(src, "^https?://"))
6339 sourceUrl = "https://twitter.com/" + src;
6342 if (_curPost.Source != null)
6343 sourceText = _curPost.Source;
6345 SourceLinkLabel.Text = sourceText;
6346 SourceLinkLabel.Tag = sourceUrl;
6347 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6353 nameText = "DM FROM <- ";
6355 nameText = "DM TO -> ";
6361 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6362 if (_curPost.RetweetedId != null)
6363 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6365 NameLabel.Text = nameText;
6366 NameLabel.Tag = _curPost.ScreenName;
6368 var nameForeColor = SystemColors.ControlText;
6369 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6370 nameForeColor = this._clOWL;
6371 if (_curPost.RetweetedId != null)
6372 nameForeColor = this._clRetweet;
6374 nameForeColor = this._clFav;
6375 NameLabel.ForeColor = nameForeColor;
6377 this.ClearUserPicture();
6379 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6381 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6384 UserPicture.Image = image != null ? image.Clone() : null;
6388 UserPicture.ShowErrorImage();
6392 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6394 if (DumpPostClassToolStripMenuItem.Checked)
6396 StringBuilder sb = new StringBuilder(512);
6398 sb.Append("-----Start PostClass Dump<br>");
6399 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6400 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6401 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6402 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6403 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6404 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6405 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6406 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6407 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6408 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6409 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6410 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6411 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6412 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6413 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6415 foreach (string nm in _curPost.ReplyToList)
6417 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6420 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6421 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6422 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6423 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6424 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6425 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6426 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6427 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6428 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6429 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6430 sb.AppendFormat("SearchTabName : {0}<br>", _curPost.RelTabName);
6432 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6433 if (_curPost.Media.Count > 0)
6435 for (int i = 0; i < _curPost.Media.Count; i++)
6437 var info = _curPost.Media[i];
6438 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6439 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6442 sb.Append("-----End PostClass Dump<br>");
6444 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6448 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6449 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6450 if (_curPost.StatusId != oldDisplayPost.StatusId)
6452 this.PostBrowser.DocumentText =
6453 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6455 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6457 this.SplitContainer3.Panel2Collapsed = true;
6459 if (this._cfgCommon.PreviewEnable)
6461 if (this.thumbnailTokenSource != null)
6463 var oldTokenSource = this.thumbnailTokenSource;
6465 var cancelTask = Task.Run(() => oldTokenSource.Cancel());
6467 Task.WhenAll(this.thumbnailTask, cancelTask)
6468 .ContinueWith(_ => oldTokenSource.Dispose(), TaskScheduler.Default);
6471 this.thumbnailTokenSource = new CancellationTokenSource();
6473 var token = this.thumbnailTokenSource.Token;
6474 this.thumbnailTask = this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token);
6481 private void MatomeMenuItem_Click(object sender, EventArgs e)
6483 OpenApplicationWebsite();
6486 private void OpenApplicationWebsite()
6488 OpenUriAsync(ApplicationSettings.WebsiteUrl);
6491 private void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6493 OpenUriAsync(ApplicationSettings.ShortcutKeyUrl);
6496 private void ListTab_KeyDown(object sender, KeyEventArgs e)
6498 if (ListTab.SelectedTab != null)
6500 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6502 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6503 if (pnl.Controls["comboSearch"].Focused ||
6504 pnl.Controls["comboLang"].Focused ||
6505 pnl.Controls["buttonSearch"].Focused) return;
6507 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
6508 if (State == ModifierState.NotFlags) return;
6509 if (State != ModifierState.None) _anchorFlag = false;
6510 if (CommonKeyDown(e.KeyCode, FocusedControl.ListTab, State))
6513 e.SuppressKeyPress = true;
6518 private ModifierState GetModifierState(bool sControl, bool sShift, bool sAlt)
6520 ModifierState state = ModifierState.None;
6521 if (sControl) state = state | ModifierState.Ctrl;
6522 if (sShift) state = state | ModifierState.Shift;
6523 if (sAlt) state = state | ModifierState.Alt;
6528 private enum ModifierState
6540 //PostBrowser = 102,
6544 private enum FocusedControl : int
6552 private bool CommonKeyDown(Keys KeyCode, FocusedControl Focused, ModifierState Modifier)
6554 //リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6555 if (Focused == FocusedControl.ListTab)
6557 if (Modifier == (ModifierState.Ctrl | ModifierState.Shift) ||
6558 Modifier == ModifierState.Ctrl ||
6559 Modifier == ModifierState.None ||
6560 Modifier == ModifierState.Shift)
6562 if (KeyCode == Keys.J)
6564 SendKeys.Send("{DOWN}");
6567 else if (KeyCode == Keys.K)
6569 SendKeys.Send("{UP}");
6573 if (Modifier == ModifierState.Shift ||
6574 Modifier == ModifierState.None)
6576 if (KeyCode == Keys.F)
6578 SendKeys.Send("{PGDN}");
6581 else if (KeyCode == Keys.B)
6583 SendKeys.Send("{PGUP}");
6592 case ModifierState.None:
6597 OpenApplicationWebsite();
6600 MenuItemSearchNext_Click(null, null);
6606 this.GetReplyAsync();
6609 this.GetDirectMessagesAsync();
6612 if (Focused != FocusedControl.StatusText)
6618 case Keys.ProcessKey:
6619 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6620 JumpUnreadMenuItem_Click(null, null);
6623 if (Focused == FocusedControl.ListTab) _anchorFlag = false;
6624 ShowRelatedStatusesMenuItem_Click(null, null);
6628 if (Focused == FocusedControl.ListTab)
6641 case Keys.OemPeriod:
6645 if (this.StatusText.Enabled) this.StatusText.Focus();
6648 MakeReplyOrDirectStatus();
6655 _anchorFlag = false;
6675 // ] in_reply_to参照元へ戻る
6676 GoInReplyToPostTree();
6679 // [ in_reply_toへジャンプ
6680 GoBackInReplyToPostTree();
6683 if (ListTab.SelectedTab != null)
6685 MyCommon.TabUsageType tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6686 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch)
6688 TabPage relTp = ListTab.SelectedTab;
6689 RemoveSpecifiedTab(relTp.Text, false);
6697 else if (Focused == FocusedControl.PostBrowser)
6704 //スクロールを発生させるため、true を返す
6709 case ModifierState.Ctrl:
6714 MakeReplyOrDirectStatus(false, true);
6720 MakeReplyOrDirectStatus(false, false);
6723 FavoriteChange(true);
6726 doRepliedStatusOpen();
6732 ReadedStripMenuItem_Click(null, null);
6735 HashManageMenuItem_Click(null, null);
6738 UrlConvertAutoToolStripMenuItem_Click(null, null);
6741 if (Focused != FocusedControl.PostBrowser)
6743 MultiLineMenuItem_Click(null, null);
6748 MenuItemSubSearch_Click(null, null);
6755 MoveToHomeToolStripMenuItem_Click(null, null);
6759 MoveToFavToolStripMenuItem_Click(null, null);
6763 StatusOpenMenuItem_Click(null, null);
6767 OpenURLMenuItem_Click(null, null);
6771 if (Focused == FocusedControl.ListTab)
6778 return false; //スルーする
6796 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6797 int tabNo = KeyCode - Keys.D1;
6798 if (ListTab.TabPages.Count < tabNo)
6800 ListTab.SelectedIndex = tabNo;
6803 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
6807 else if (Focused == FocusedControl.StatusText)
6813 StatusText.SelectAll();
6817 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6819 _history[_hisIdx] = new PostingStatus(StatusText.Text, _reply_to_id, _reply_to_name);
6821 if (KeyCode == Keys.Up)
6824 if (_hisIdx < 0) _hisIdx = 0;
6829 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6831 StatusText.Text = _history[_hisIdx].status;
6832 _reply_to_id = _history[_hisIdx].inReplyToId;
6833 _reply_to_name = _history[_hisIdx].inReplyToName;
6834 StatusText.SelectionStart = StatusText.Text.Length;
6838 if (ListTab.SelectedIndex == 0)
6840 ListTab.SelectedIndex = ListTab.TabCount - 1;
6844 ListTab.SelectedIndex -= 1;
6850 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6852 ListTab.SelectedIndex = 0;
6856 ListTab.SelectedIndex += 1;
6864 //フォーカスPostBrowserもしくは関係なし
6868 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6869 MultiLineMenuItem_Click(null, null);
6874 case ModifierState.Shift:
6879 MenuItemSearchPrev_Click(null, null);
6885 this.GetReplyAsync(loadMore: true);
6888 this.GetDirectMessagesAsync(loadMore: true);
6892 if (Focused != FocusedControl.StatusText)
6894 if (KeyCode == Keys.R)
6901 if (Focused == FocusedControl.ListTab)
6921 GoBackInReplyToPostTree(true, false);
6924 GoBackInReplyToPostTree(true, true);
6928 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6933 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6937 this.GoBackSelectPostChain();
6942 case ModifierState.Alt:
6946 doReTweetOfficial(true);
6949 if (_curPost != null)
6951 doShowUserStatus(_curPost.ScreenName, false);
6956 ScrollDownPostBrowser(false);
6959 ScrollDownPostBrowser(true);
6962 PageDownPostBrowser(false);
6965 PageDownPostBrowser(true);
6968 if (Focused == FocusedControl.ListTab)
6970 // 別タブの同じ書き込みへ(ALT+←/→)
6971 if (KeyCode == Keys.Right)
6973 GoSamePostToAnotherTab(false);
6976 else if (KeyCode == Keys.Left)
6978 GoSamePostToAnotherTab(true);
6983 case ModifierState.Ctrl | ModifierState.Shift:
6987 MakeReplyOrDirectStatus(false, true, true);
6993 if (ListTab.SelectedTab != null)
6995 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6997 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
7003 FavoriteChange(false);
7006 UnreadStripMenuItem_Click(null, null);
7009 HashToggleMenuItem_Click(null, null);
7012 ImageSelectMenuItem_Click(null, null);
7018 FavorareMenuItem_Click(null, null);
7021 if (Focused == FocusedControl.StatusText)
7027 if (_curList != null && _curList.VirtualListSize != 0 &&
7028 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
7030 idx = _curList.SelectedIndices[0] - 1;
7031 SelectListItem(_curList, idx);
7032 _curList.EnsureVisible(idx);
7037 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
7038 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
7040 idx = _curList.SelectedIndices[0] + 1;
7041 SelectListItem(_curList, idx);
7042 _curList.EnsureVisible(idx);
7047 if (StatusText.SelectionStart > 0)
7049 int endidx = StatusText.SelectionStart - 1;
7050 string startstr = "";
7051 bool pressed = false;
7052 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
7054 char c = StatusText.Text[i];
7055 if (Char.IsLetterOrDigit(c) || c == '_')
7062 startstr = StatusText.Text.Substring(i + 1, endidx - i);
7063 int cnt = AtIdSupl.ItemCount;
7064 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
7065 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
7070 startstr = StatusText.Text.Substring(i + 1, endidx - i);
7071 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
7083 else if (Focused == FocusedControl.ListTab)
7085 DetailsListView lst = (DetailsListView)ListTab.SelectedTab.Tag;
7097 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7098 int colNo = KeyCode - Keys.D1;
7099 if (lst.Columns.Count < colNo) return false;
7100 col = lst.Columns.Cast<ColumnHeader>().Where((x) => { return x.DisplayIndex == colNo; }).FirstOrDefault();
7101 if (col == null) return false;
7102 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
7105 col = lst.Columns.Cast<ColumnHeader>().OrderByDescending((x) => { return x.DisplayIndex; }).First();
7106 MyList_ColumnClick(lst, new ColumnClickEventArgs(col.Index));
7111 case ModifierState.Ctrl | ModifierState.Alt:
7112 if (KeyCode == Keys.S)
7114 FavoritesRetweetOriginal();
7117 else if (KeyCode == Keys.R)
7119 FavoritesRetweetUnofficial();
7122 else if (KeyCode == Keys.H)
7124 OpenUserAppointUrl();
7128 case ModifierState.Alt | ModifierState.Shift:
7129 if (Focused == FocusedControl.PostBrowser)
7131 if (KeyCode == Keys.R)
7132 doReTweetUnofficial();
7133 else if (KeyCode == Keys.C)
7140 if (!this.ExistCurrentPost) return false;
7141 doTranslation(_curPost.TextFromApi);
7144 doReTweetUnofficial();
7150 this.tweetThumbnail1.ScrollUp();
7153 this.tweetThumbnail1.ScrollDown();
7156 if (Focused == FocusedControl.ListTab && KeyCode == Keys.Enter)
7158 if (!this.SplitContainer3.Panel2Collapsed)
7160 OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail);
7170 private void ScrollDownPostBrowser(bool forward)
7172 var doc = PostBrowser.Document;
7173 if (doc == null) return;
7175 var tags = doc.GetElementsByTagName("html");
7179 tags[0].ScrollTop += this._fntDetail.Height;
7181 tags[0].ScrollTop -= this._fntDetail.Height;
7185 private void PageDownPostBrowser(bool forward)
7187 var doc = PostBrowser.Document;
7188 if (doc == null) return;
7190 var tags = doc.GetElementsByTagName("html");
7194 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7196 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7200 private void GoNextTab(bool forward)
7202 int idx = ListTab.SelectedIndex;
7206 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7211 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7213 ListTab.SelectedIndex = idx;
7216 private void CopyStot()
7219 StringBuilder sb = new StringBuilder();
7220 bool IsProtected = false;
7222 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7223 foreach (int idx in _curList.SelectedIndices)
7225 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7231 if (post.IsDeleted) continue;
7234 if (post.RetweetedId != null)
7235 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7237 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7241 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7246 MessageBox.Show(Properties.Resources.CopyStotText1);
7250 clstr = sb.ToString();
7253 Clipboard.SetDataObject(clstr, false, 5, 100);
7255 catch (Exception ex)
7257 MessageBox.Show(ex.Message);
7262 private void CopyIdUri()
7265 StringBuilder sb = new StringBuilder();
7266 if (this._curTab == null) return;
7267 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7268 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7269 foreach (int idx in _curList.SelectedIndices)
7271 var post = _statuses.Tabs[_curTab.Text][idx];
7272 sb.Append(MyCommon.GetStatusUrl(post));
7273 sb.Append(Environment.NewLine);
7277 clstr = sb.ToString();
7280 Clipboard.SetDataObject(clstr, false, 5, 100);
7282 catch (Exception ex)
7284 MessageBox.Show(ex.Message);
7289 private void GoFav(bool forward)
7291 if (_curList.VirtualListSize == 0) return;
7298 if (_curList.SelectedIndices.Count == 0)
7304 fIdx = _curList.SelectedIndices[0] + 1;
7305 if (fIdx > _curList.VirtualListSize - 1) return;
7307 toIdx = _curList.VirtualListSize;
7312 if (_curList.SelectedIndices.Count == 0)
7314 fIdx = _curList.VirtualListSize - 1;
7318 fIdx = _curList.SelectedIndices[0] - 1;
7319 if (fIdx < 0) return;
7325 for (int idx = fIdx; idx != toIdx; idx += stp)
7327 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7329 SelectListItem(_curList, idx);
7330 _curList.EnsureVisible(idx);
7336 private void GoSamePostToAnotherTab(bool left)
7338 if (_curList.VirtualListSize == 0) return;
7344 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7345 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7347 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7352 if (ListTab.SelectedIndex == 0)
7358 fIdx = ListTab.SelectedIndex - 1;
7366 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7372 fIdx = ListTab.SelectedIndex + 1;
7374 toIdx = ListTab.TabCount;
7379 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7381 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7382 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7384 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7386 ListTab.SelectedIndex = tabidx;
7387 SelectListItem(_curList, idx);
7388 _curList.EnsureVisible(idx);
7397 private void GoPost(bool forward)
7399 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7406 fIdx = _curList.SelectedIndices[0] + 1;
7407 if (fIdx > _curList.VirtualListSize - 1) return;
7408 toIdx = _curList.VirtualListSize;
7413 fIdx = _curList.SelectedIndices[0] - 1;
7414 if (fIdx < 0) return;
7420 if (_curPost.RetweetedId == null)
7422 name = _curPost.ScreenName;
7426 name = _curPost.RetweetedBy;
7428 for (int idx = fIdx; idx != toIdx; idx += stp)
7430 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7432 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7434 SelectListItem(_curList, idx);
7435 _curList.EnsureVisible(idx);
7441 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7443 SelectListItem(_curList, idx);
7444 _curList.EnsureVisible(idx);
7451 private void GoRelPost(bool forward)
7453 if (_curList.SelectedIndices.Count == 0) return;
7460 fIdx = _curList.SelectedIndices[0] + 1;
7461 if (fIdx > _curList.VirtualListSize - 1) return;
7462 toIdx = _curList.VirtualListSize;
7467 fIdx = _curList.SelectedIndices[0] - 1;
7468 if (fIdx < 0) return;
7475 if (_curPost == null) return;
7476 _anchorPost = _curPost;
7481 if (_anchorPost == null) return;
7484 for (int idx = fIdx; idx != toIdx; idx += stp)
7486 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7487 if (post.ScreenName == _anchorPost.ScreenName ||
7488 post.RetweetedBy == _anchorPost.ScreenName ||
7489 post.ScreenName == _anchorPost.RetweetedBy ||
7490 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7491 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7492 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7493 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7494 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7496 SelectListItem(_curList, idx);
7497 _curList.EnsureVisible(idx);
7503 private void GoAnchor()
7505 if (_anchorPost == null) return;
7506 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7507 if (idx == -1) return;
7509 SelectListItem(_curList, idx);
7510 _curList.EnsureVisible(idx);
7513 private void GoTopEnd(bool GoTop)
7515 if (_curList.VirtualListSize == 0)
7523 _item = _curList.GetItemAt(0, 25);
7531 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7533 idx = _curList.VirtualListSize - 1;
7537 SelectListItem(_curList, idx);
7540 private void GoMiddle()
7542 if (_curList.VirtualListSize == 0)
7550 _item = _curList.GetItemAt(0, 0);
7560 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7563 idx2 = _curList.VirtualListSize - 1;
7569 idx3 = (idx1 + idx2) / 2;
7571 SelectListItem(_curList, idx3);
7574 private void GoLast()
7576 if (_curList.VirtualListSize == 0) return;
7578 if (_statuses.SortOrder == SortOrder.Ascending)
7580 SelectListItem(_curList, _curList.VirtualListSize - 1);
7581 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7585 SelectListItem(_curList, 0);
7586 _curList.EnsureVisible(0);
7590 private void MoveTop()
7592 if (_curList.SelectedIndices.Count == 0) return;
7593 int idx = _curList.SelectedIndices[0];
7594 if (_statuses.SortOrder == SortOrder.Ascending)
7596 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7600 _curList.EnsureVisible(0);
7602 _curList.EnsureVisible(idx);
7605 private void GoInReplyToPostTree()
7607 if (_curPost == null) return;
7609 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7611 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7613 PostClass post = null;
7614 string r = tw.GetStatusApi(false, _curPost.StatusId, ref post);
7615 if (string.IsNullOrEmpty(r) && post != null)
7617 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7618 _curPost.InReplyToUser = post.InReplyToUser;
7619 _curPost.IsReply = post.IsReply;
7620 this.PurgeListViewItemCache();
7621 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7625 this.StatusLabel.Text = r;
7629 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7631 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7633 replyChains = new Stack<ReplyChain>();
7635 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7638 string inReplyToTabName;
7639 long inReplyToId = _curPost.InReplyToStatusId.Value;
7640 string inReplyToUser = _curPost.InReplyToUser;
7641 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7643 var inReplyToPosts = from tab in _statuses.Tabs.Values
7644 orderby tab != curTabClass
7645 from post in tab.Posts.Values
7646 where post.StatusId == inReplyToId
7647 let index = tab.IndexOf(post.StatusId)
7649 select new {Tab = tab, Index = index};
7653 var inReplyPost = inReplyToPosts.First();
7654 inReplyToTabName = inReplyPost.Tab.TabName;
7655 inReplyToIndex = inReplyPost.Index;
7657 catch (InvalidOperationException)
7659 PostClass post = null;
7660 string r = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value, ref post);
7661 if (string.IsNullOrEmpty(r) && post != null)
7664 _statuses.AddPost(post);
7665 _statuses.DistributePosts();
7666 //_statuses.SubmitUpdate(null, null, null, false);
7667 this.RefreshTimeline(false);
7670 var inReplyPost = inReplyToPosts.First();
7671 inReplyToTabName = inReplyPost.Tab.TabName;
7672 inReplyToIndex = inReplyPost.Index;
7674 catch (InvalidOperationException)
7676 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7682 this.StatusLabel.Text = r;
7683 OpenUriAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7688 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7689 DetailsListView listView = (DetailsListView)tabPage.Tag;
7691 if (_curTab != tabPage)
7693 this.ListTab.SelectTab(tabPage);
7696 this.SelectListItem(listView, inReplyToIndex);
7697 listView.EnsureVisible(inReplyToIndex);
7700 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7702 if (_curPost == null) return;
7704 TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7705 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7709 if (_curPost.InReplyToStatusId != null)
7711 var posts = from t in _statuses.Tabs
7712 from p in t.Value.Posts
7713 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7714 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7716 orderby isForward ? indexOf : indexOf * -1
7717 orderby t.Value != curTabClass
7718 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7721 var postList = posts.ToList();
7722 for (int i = postList.Count - 1; i >= 0; i--)
7725 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7727 postList.RemoveAt(index);
7730 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7731 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7732 if (post == null) post = postList.First();
7733 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7734 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7735 SelectListItem(listView, post.Index);
7736 listView.EnsureVisible(post.Index);
7738 catch (InvalidOperationException)
7746 if (replyChains == null || replyChains.Count < 1)
7748 var posts = from t in _statuses.Tabs
7749 from p in t.Value.Posts
7750 where p.Value.InReplyToStatusId == _curPost.StatusId
7751 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7754 orderby t.Value != curTabClass
7755 select new {Tab = t.Value, Index = indexOf};
7758 var post = posts.First();
7759 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7760 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7761 SelectListItem(listView, post.Index);
7762 listView.EnsureVisible(post.Index);
7764 catch (InvalidOperationException)
7771 ReplyChain chainHead = replyChains.Pop();
7772 if (chainHead.InReplyToId == _curPost.StatusId)
7774 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7783 ListTab.SelectTab(chainHead.OriginalTab);
7789 SelectListItem(_curList, idx);
7790 _curList.EnsureVisible(idx);
7796 this.GoBackInReplyToPostTree(parallel);
7802 private void GoBackSelectPostChain()
7804 if (this.selectPostChains.Count > 1)
7813 this.selectPostChains.Pop();
7814 var tabPostPair = this.selectPostChains.Peek();
7816 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7818 if (tabPostPair.Item2 != null)
7820 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7821 if (idx == -1) continue; //該当ポストが存在しないので無視
7824 tp = tabPostPair.Item1;
7826 this.selectPostChains.Pop();
7828 catch (InvalidOperationException)
7834 while (this.selectPostChains.Count > 1);
7839 //履歴が残り1つであればクリアしておく
7840 if (this.selectPostChains.Count == 1)
7841 this.selectPostChains.Clear();
7845 DetailsListView lst = (DetailsListView)tp.Tag;
7846 this.ListTab.SelectedTab = tp;
7849 SelectListItem(lst, idx);
7850 lst.EnsureVisible(idx);
7856 private void PushSelectPostChain()
7858 int count = this.selectPostChains.Count;
7861 var p = this.selectPostChains.Peek();
7862 if (p.Item1 == this._curTab)
7864 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7865 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7868 if (count >= 2500) TrimPostChain();
7869 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7872 private void TrimPostChain()
7874 if (this.selectPostChains.Count <= 2000) return;
7875 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7876 for (int i = 0; i < 2000; i++)
7878 p.Push(this.selectPostChains.Pop());
7880 this.selectPostChains.Clear();
7881 for (int i = 0; i < 2000; i++)
7883 this.selectPostChains.Push(p.Pop());
7887 private bool GoStatus(long statusId)
7889 if (statusId == 0) return false;
7890 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7892 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7894 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7895 ListTab.SelectedIndex = tabidx;
7896 SelectListItem(_curList, idx);
7897 _curList.EnsureVisible(idx);
7904 private bool GoDirectMessage(long statusId)
7906 if (statusId == 0) return false;
7907 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7909 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7911 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7912 ListTab.SelectedIndex = tabidx;
7913 SelectListItem(_curList, idx);
7914 _curList.EnsureVisible(idx);
7921 private void MyList_MouseClick(object sender, MouseEventArgs e)
7923 _anchorFlag = false;
7926 private void StatusText_Enter(object sender, EventArgs e)
7928 // フォーカスの戻り先を StatusText に設定
7929 this.Tag = StatusText;
7930 StatusText.BackColor = _clInputBackcolor;
7933 public Color InputBackColor
7935 get { return _clInputBackcolor; }
7936 set { _clInputBackcolor = value; }
7939 private void StatusText_Leave(object sender, EventArgs e)
7941 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7942 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7943 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7946 private void StatusText_KeyDown(object sender, KeyEventArgs e)
7948 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
7949 if (State == ModifierState.NotFlags) return;
7950 if (CommonKeyDown(e.KeyCode, FocusedControl.StatusText, State))
7953 e.SuppressKeyPress = true;
7956 this.StatusText_TextChanged(null, null);
7959 private void SaveConfigsAll(bool ifModified)
7963 SaveConfigsCommon();
7970 if (_modifySettingCommon) SaveConfigsCommon();
7971 if (_modifySettingLocal) SaveConfigsLocal();
7972 if (_modifySettingAtId) SaveConfigsAtId();
7976 private void SaveConfigsAtId()
7978 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7980 _modifySettingAtId = false;
7981 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7985 private void SaveConfigsCommon()
7987 if (_ignoreConfigSave) return;
7989 _modifySettingCommon = false;
7992 _cfgCommon.UserName = tw.Username;
7993 _cfgCommon.UserId = tw.UserId;
7994 _cfgCommon.Password = tw.Password;
7995 _cfgCommon.Token = tw.AccessToken;
7996 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7998 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7999 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
8001 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
8004 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
8005 switch (_statuses.SortMode)
8007 case ComparerMode.Nickname: //ニックネーム
8008 _cfgCommon.SortColumn = 1;
8010 case ComparerMode.Data: //本文
8011 _cfgCommon.SortColumn = 2;
8013 case ComparerMode.Id: //時刻=発言Id
8014 _cfgCommon.SortColumn = 3;
8016 case ComparerMode.Name: //名前
8017 _cfgCommon.SortColumn = 4;
8019 case ComparerMode.Source: //Source
8020 _cfgCommon.SortColumn = 7;
8024 _cfgCommon.HashTags = HashMgr.HashHistories;
8025 if (HashMgr.IsPermanent)
8027 _cfgCommon.HashSelected = HashMgr.UseHash;
8031 _cfgCommon.HashSelected = "";
8033 _cfgCommon.HashIsHead = HashMgr.IsHead;
8034 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
8035 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
8036 if (ToolStripFocusLockMenuItem != null &&
8037 ToolStripFocusLockMenuItem.IsDisposed == false)
8039 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
8041 _cfgCommon.TrackWord = tw.TrackWord;
8042 _cfgCommon.AllAtReply = tw.AllAtReply;
8043 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
8044 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
8050 private void SaveConfigsLocal()
8052 if (_ignoreConfigSave) return;
8055 _modifySettingLocal = false;
8056 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
8057 _cfgLocal.FormSize = _mySize;
8058 _cfgLocal.FormLocation = _myLoc;
8059 _cfgLocal.SplitterDistance = _mySpDis;
8060 _cfgLocal.PreviewDistance = _mySpDis3;
8061 _cfgLocal.StatusMultiline = StatusText.Multiline;
8062 _cfgLocal.StatusTextHeight = _mySpDis2;
8064 _cfgLocal.FontUnread = _fntUnread;
8065 _cfgLocal.ColorUnread = _clUnread;
8066 _cfgLocal.FontRead = _fntReaded;
8067 _cfgLocal.ColorRead = _clReaded;
8068 _cfgLocal.FontDetail = _fntDetail;
8069 _cfgLocal.ColorDetail = _clDetail;
8070 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
8071 _cfgLocal.ColorDetailLink = _clDetailLink;
8072 _cfgLocal.ColorFav = _clFav;
8073 _cfgLocal.ColorOWL = _clOWL;
8074 _cfgLocal.ColorRetweet = _clRetweet;
8075 _cfgLocal.ColorSelf = _clSelf;
8076 _cfgLocal.ColorAtSelf = _clAtSelf;
8077 _cfgLocal.ColorTarget = _clTarget;
8078 _cfgLocal.ColorAtTarget = _clAtTarget;
8079 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8080 _cfgLocal.ColorAtTo = _clAtTo;
8081 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8082 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8083 _cfgLocal.ColorInputFont = _clInputFont;
8084 _cfgLocal.FontInputFont = _fntInputFont;
8086 if (_ignoreConfigSave) return;
8091 private void SaveConfigsTabs()
8093 SettingTabs tabSetting = new SettingTabs();
8094 for (int i = 0; i < ListTab.TabPages.Count; i++)
8096 if (_statuses.Tabs[ListTab.TabPages[i].Text].TabType != MyCommon.TabUsageType.Related) tabSetting.Tabs.Add(_statuses.Tabs[ListTab.TabPages[i].Text]);
8098 tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8102 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8105 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8106 if (ret != DialogResult.OK)
8109 var match = Twitter.StatusUrlRegex.Match(inputText);
8112 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8113 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8117 var statusId = long.Parse(match.Groups["StatusId"].Value);
8119 var post = this._statuses[statusId];
8124 post = await Task.Run(() =>
8126 PostClass newPost = null;
8128 var err = this.tw.GetStatusApi(false, statusId, ref newPost);
8129 if (!string.IsNullOrEmpty(err))
8130 throw new WebApiException(err);
8135 catch (WebApiException ex)
8137 var message = ex.Message;
8138 MessageBox.Show(this, string.Format(Properties.Resources.OpenURL_LoadFailed, message),
8139 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8146 await this.OpenRelatedTab(post);
8148 catch (TabException ex)
8150 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8154 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8156 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8157 Properties.Resources.SaveLogMenuItem_ClickText2,
8158 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8159 if (rslt == DialogResult.Cancel) return;
8161 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8162 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8163 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8164 SaveFileDialog1.FilterIndex = 0;
8165 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8166 SaveFileDialog1.RestoreDirectory = true;
8168 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8170 if (!SaveFileDialog1.ValidateNames) return;
8171 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8173 if (rslt == DialogResult.Yes)
8176 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8178 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8179 string protect = "";
8180 if (post.IsProtect) protect = "Protect";
8181 sw.WriteLine(post.Nickname + "\t" +
8182 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8183 post.CreatedAt.ToString() + "\t" +
8184 post.ScreenName + "\t" +
8185 post.StatusId.ToString() + "\t" +
8186 post.ImageUrl + "\t" +
8187 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8193 foreach (int idx in _curList.SelectedIndices)
8195 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8196 string protect = "";
8197 if (post.IsProtect) protect = "Protect";
8198 sw.WriteLine(post.Nickname + "\t" +
8199 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8200 post.CreatedAt.ToString() + "\t" +
8201 post.ScreenName + "\t" +
8202 post.StatusId.ToString() + "\t" +
8203 post.ImageUrl + "\t" +
8204 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8210 this.TopMost = this._cfgCommon.AlwaysTop;
8213 private void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8215 ModifierState State = GetModifierState(e.Control, e.Shift, e.Alt);
8216 if (State == ModifierState.NotFlags) return;
8217 bool KeyRes = CommonKeyDown(e.KeyCode, FocusedControl.PostBrowser, State);
8220 e.IsInputKey = true;
8224 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8226 var shortcut = (Shortcut)e.KeyData;
8229 case Shortcut.CtrlA:
8230 case Shortcut.CtrlC:
8231 case Shortcut.CtrlIns:
8235 // その他のショートカットキーは無効にする
8236 e.IsInputKey = true;
8241 public bool TabRename(ref string tabName)
8244 string newTabText = null;
8245 using (InputTabName inputName = new InputTabName())
8247 inputName.TabName = tabName;
8248 inputName.ShowDialog();
8249 if (inputName.DialogResult == DialogResult.Cancel) return false;
8250 newTabText = inputName.TabName;
8252 this.TopMost = this._cfgCommon.AlwaysTop;
8253 if (!string.IsNullOrEmpty(newTabText))
8256 for (int i = 0; i < ListTab.TabCount; i++)
8258 if (ListTab.TabPages[i].Text == newTabText)
8260 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8261 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8266 for (int i = 0; i < ListTab.TabCount; i++)
8268 if (ListTab.TabPages[i].Text == tabName)
8270 ListTab.TabPages[i].Text = newTabText;
8274 _statuses.RenameTab(tabName, newTabText);
8276 SaveConfigsCommon();
8278 _rclickTabName = newTabText;
8279 tabName = newTabText;
8288 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8290 if (e.Button == MouseButtons.Middle)
8292 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8294 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8296 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8297 this.SaveConfigsTabs();
8304 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8306 string tn = ListTab.SelectedTab.Text;
8310 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8312 if (this._cfgCommon.TabMouseLock) return;
8313 Point cpos = new Point(e.X, e.Y);
8314 if (e.Button == MouseButtons.Left)
8316 for (int i = 0; i < ListTab.TabPages.Count; i++)
8318 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8321 _tabMouseDownPoint = e.Location;
8332 private void ListTab_DragEnter(object sender, DragEventArgs e)
8334 if (e.Data.GetDataPresent(typeof(TabPage)))
8335 e.Effect = DragDropEffects.Move;
8337 e.Effect = DragDropEffects.None;
8340 private void ListTab_DragDrop(object sender, DragEventArgs e)
8342 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8347 Point cpos = new Point(e.X, e.Y);
8348 Point spos = ListTab.PointToClient(cpos);
8350 for (i = 0; i < ListTab.TabPages.Count; i++)
8352 Rectangle rect = ListTab.GetTabRect(i);
8353 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8354 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8356 tn = ListTab.TabPages[i].Text;
8357 if (spos.X <= (rect.Left + rect.Right) / 2)
8366 //タブのないところにドロップ->最後尾へ移動
8367 if (string.IsNullOrEmpty(tn))
8369 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8371 i = ListTab.TabPages.Count - 1;
8374 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8375 if (tp.Text == tn) return;
8377 ReOrderTab(tp.Text, tn, bef);
8380 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8383 for (baseIndex = 0; baseIndex < ListTab.TabPages.Count; baseIndex++)
8385 if (ListTab.TabPages[baseIndex].Text == baseTabText) break;
8388 using (ControlTransaction.Layout(this.ListTab))
8391 for (int j = 0; j < ListTab.TabPages.Count; j++)
8393 if (ListTab.TabPages[j].Text == targetTabText)
8395 mTp = ListTab.TabPages[j];
8396 ListTab.TabPages.Remove(mTp);
8397 if (j < baseIndex) baseIndex -= 1;
8401 if (isBeforeBaseTab)
8402 ListTab.TabPages.Insert(baseIndex, mTp);
8404 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8410 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8412 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8413 //isReply:true=@,false=DM
8414 if (!StatusText.Enabled) return;
8415 if (_curList == null) return;
8416 if (_curTab == null) return;
8417 if (!this.ExistCurrentPost) return;
8419 // 複数あてリプライはReplyではなく通常ポスト
8420 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8421 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8422 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8424 if (_curList.SelectedIndices.Count > 0)
8427 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8430 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8433 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8434 StatusText.SelectionStart = StatusText.Text.Length;
8436 _reply_to_id = null;
8437 _reply_to_name = null;
8440 if (string.IsNullOrEmpty(StatusText.Text))
8444 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8445 StatusText.Text = "@" + _curPost.ScreenName + " ";
8446 if (_curPost.RetweetedId != null)
8448 _reply_to_id = _curPost.RetweetedId.Value;
8452 _reply_to_id = _curPost.StatusId;
8454 _reply_to_name = _curPost.ScreenName;
8462 //1件選んでEnter or DoubleClick
8463 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8465 if (_reply_to_id != null && _reply_to_name == _curPost.ScreenName)
8468 if (_curPost.RetweetedId != null)
8470 _reply_to_id = _curPost.RetweetedId.Value;
8474 _reply_to_id = _curPost.StatusId;
8476 _reply_to_name = _curPost.ScreenName;
8480 if (!StatusText.Text.StartsWith("@"))
8483 if (StatusText.Text.StartsWith(". "))
8486 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8487 _reply_to_id = null;
8488 _reply_to_name = null;
8493 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8494 if (_curPost.RetweetedId != null)
8496 _reply_to_id = _curPost.RetweetedId.Value;
8500 _reply_to_id = _curPost.StatusId;
8502 _reply_to_name = _curPost.ScreenName;
8509 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8510 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8511 _reply_to_id = null;
8512 _reply_to_name = null;
8517 //1件選んでCtrl-Rの場合(返信先操作せず)
8518 int sidx = StatusText.SelectionStart;
8519 string id = "@" + _curPost.ScreenName + " ";
8522 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8527 StatusText.Text = StatusText.Text.Insert(sidx, id);
8529 //if (StatusText.Text.StartsWith("@"))
8532 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8533 // sidx += 5 + _curPost.ScreenName.Length;
8538 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8539 // sidx += 3 + _curPost.ScreenName.Length;
8541 StatusText.SelectionStart = sidx;
8544 //_reply_to_name = null;
8552 if (!isAuto && !isReply) return;
8554 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8558 //Enter or DoubleClick
8560 string sTxt = StatusText.Text;
8561 if (!sTxt.StartsWith(". "))
8564 _reply_to_id = null;
8565 _reply_to_name = null;
8567 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8569 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8570 if (!sTxt.Contains("@" + post.ScreenName + " "))
8572 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8573 //sTxt = "@" + post.ScreenName + " " + sTxt;
8576 StatusText.Text = sTxt;
8581 if (_curList.SelectedIndices.Count > 1)
8586 int sidx = StatusText.SelectionStart;
8587 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8589 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8590 if (!ids.Contains("@" + post.ScreenName + " ") &&
8591 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8593 ids += "@" + post.ScreenName + " ";
8597 foreach (string nm in post.ReplyToList)
8599 if (!ids.Contains("@" + nm + " ") &&
8600 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8602 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8604 ids += "@" + m.Result("${id}") + " ";
8606 ids += "@" + nm + " ";
8611 if (ids.Length == 0) return;
8612 if (!StatusText.Text.StartsWith(". "))
8614 StatusText.Text = ". " + StatusText.Text;
8616 _reply_to_id = null;
8617 _reply_to_name = null;
8621 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8626 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8628 //if (StatusText.Text.StartsWith("@"))
8630 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8631 // sidx += 2 + ids.Length;
8635 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8636 // sidx += 1 + ids.Length;
8638 StatusText.SelectionStart = sidx;
8644 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8647 int sidx = StatusText.SelectionStart;
8648 PostClass post = _curPost;
8649 if (!ids.Contains("@" + post.ScreenName + " ") &&
8650 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8652 ids += "@" + post.ScreenName + " ";
8654 foreach (string nm in post.ReplyToList)
8656 if (!ids.Contains("@" + nm + " ") &&
8657 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8659 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8661 ids += "@" + m.Result("${id}") + " ";
8663 ids += "@" + nm + " ";
8666 if (!string.IsNullOrEmpty(post.RetweetedBy))
8668 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8669 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8671 ids += "@" + post.RetweetedBy + " ";
8674 if (ids.Length == 0) return;
8675 if (string.IsNullOrEmpty(StatusText.Text))
8678 StatusText.Text = ids;
8679 StatusText.SelectionStart = ids.Length;
8681 if (post.RetweetedId != null)
8683 _reply_to_id = post.RetweetedId.Value;
8687 _reply_to_id = post.StatusId;
8689 _reply_to_name = post.ScreenName;
8695 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8700 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8702 StatusText.SelectionStart = sidx;
8708 StatusText.SelectionStart = StatusText.Text.Length;
8713 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8718 private static int iconCnt = 0;
8719 private static int blinkCnt = 0;
8720 private static bool blink = false;
8721 private static bool idle = false;
8723 private void RefreshTasktrayIcon(bool forceRefresh)
8725 if (_colorize) Colorize();
8726 if (!TimerRefreshIcon.Enabled) return;
8727 //Static usCheckCnt As int = 0
8729 //Static iconDlListTopItem As ListViewItem = null
8731 if (forceRefresh) idle = false;
8733 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8734 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8736 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8738 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8744 //if (usCheckCnt > 300) //1min
8747 // if (!this.IsReceivedUserStream)
8749 // TraceOut("ReconnectUserStream");
8750 // tw.ReconnectUserStream();
8754 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8756 if (iconCnt >= this.NIconRefresh.Length)
8764 SaveConfigsAll(true);
8769 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8771 _myStatusError = false;
8775 TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8776 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8778 if (blinkCnt > 0) return;
8780 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8782 NotifyIcon1.Icon = ReplyIcon;
8786 NotifyIcon1.Icon = ReplyIconBlink;
8794 //優先度:エラー→オフライン→アイドル
8798 NotifyIcon1.Icon = NIconAtRed;
8801 if (_myStatusOnline)
8803 NotifyIcon1.Icon = NIconAt;
8807 NotifyIcon1.Icon = NIconAtSmoke;
8811 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
8814 this.RefreshTasktrayIcon(false);
8817 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8819 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8820 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8822 if (ListTab != null && ListTab.SelectedTab != null)
8823 _rclickTabName = ListTab.SelectedTab.Text;
8828 if (_statuses == null) return;
8829 if (_statuses.Tabs == null) return;
8831 TabClass tb = _statuses.Tabs[_rclickTabName];
8832 if (tb == null) return;
8834 NotifyDispMenuItem.Checked = tb.Notify;
8835 this.NotifyTbMenuItem.Checked = tb.Notify;
8837 soundfileListup = true;
8838 SoundFileComboBox.Items.Clear();
8839 this.SoundFileTbComboBox.Items.Clear();
8840 SoundFileComboBox.Items.Add("");
8841 this.SoundFileTbComboBox.Items.Add("");
8842 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8843 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8845 oDir = oDir.GetDirectories("Sounds")[0];
8847 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8849 SoundFileComboBox.Items.Add(oFile.Name);
8850 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8852 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8853 if (idx == -1) idx = 0;
8854 SoundFileComboBox.SelectedIndex = idx;
8855 this.SoundFileTbComboBox.SelectedIndex = idx;
8856 soundfileListup = false;
8857 UreadManageMenuItem.Checked = tb.UnreadManage;
8858 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8860 TabMenuControl(_rclickTabName);
8863 private void TabMenuControl(string tabName)
8865 var tabInfo = _statuses.GetTabByName(tabName);
8867 this.FilterEditMenuItem.Enabled = true;
8868 this.EditRuleTbMenuItem.Enabled = true;
8870 if (tabInfo.IsDefaultTabType)
8872 this.ProtectTabMenuItem.Enabled = false;
8873 this.ProtectTbMenuItem.Enabled = false;
8877 this.ProtectTabMenuItem.Enabled = true;
8878 this.ProtectTbMenuItem.Enabled = true;
8881 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8883 this.ProtectTabMenuItem.Checked = true;
8884 this.ProtectTbMenuItem.Checked = true;
8885 this.DeleteTabMenuItem.Enabled = false;
8886 this.DeleteTbMenuItem.Enabled = false;
8890 this.ProtectTabMenuItem.Checked = false;
8891 this.ProtectTbMenuItem.Checked = false;
8892 this.DeleteTabMenuItem.Enabled = true;
8893 this.DeleteTbMenuItem.Enabled = true;
8897 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8899 var checkState = ((ToolStripMenuItem)sender).Checked;
8902 this.ProtectTbMenuItem.Checked = checkState;
8903 this.ProtectTabMenuItem.Checked = checkState;
8906 this.DeleteTabMenuItem.Enabled = !checkState;
8907 this.DeleteTbMenuItem.Enabled = !checkState;
8909 if (string.IsNullOrEmpty(_rclickTabName)) return;
8910 _statuses.Tabs[_rclickTabName].Protected = checkState;
8915 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8917 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8918 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8920 if (string.IsNullOrEmpty(_rclickTabName)) return;
8921 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8926 public void ChangeTabUnreadManage(string tabName, bool isManage)
8929 for (idx = 0; idx < ListTab.TabCount; idx++)
8931 if (ListTab.TabPages[idx].Text == tabName) break;
8934 _statuses.Tabs[tabName].UnreadManage = isManage;
8935 if (this._cfgCommon.TabIconDisp)
8937 if (_statuses.Tabs[tabName].UnreadCount > 0)
8938 ListTab.TabPages[idx].ImageIndex = 0;
8940 ListTab.TabPages[idx].ImageIndex = -1;
8943 if (_curTab.Text == tabName)
8945 this.PurgeListViewItemCache();
8949 SetMainWindowTitle();
8950 SetStatusLabelUrl();
8951 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8954 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8956 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8957 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8959 if (string.IsNullOrEmpty(_rclickTabName)) return;
8961 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8966 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8968 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8970 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8975 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8977 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8979 RemoveSpecifiedTab(_rclickTabName, true);
8983 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8985 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8987 using (var fltDialog = new FilterDialog())
8989 fltDialog.Owner = this;
8990 fltDialog.SetCurrent(_rclickTabName);
8991 fltDialog.ShowDialog(this);
8993 this.TopMost = this._cfgCommon.AlwaysTop;
8995 this.ApplyPostFilters();
8999 private void AddTabMenuItem_Click(object sender, EventArgs e)
9001 string tabName = null;
9002 MyCommon.TabUsageType tabUsage;
9003 using (InputTabName inputName = new InputTabName())
9005 inputName.TabName = _statuses.GetUniqueTabName();
9006 inputName.IsShowUsage = true;
9007 inputName.ShowDialog();
9008 if (inputName.DialogResult == DialogResult.Cancel) return;
9009 tabName = inputName.TabName;
9010 tabUsage = inputName.Usage;
9012 this.TopMost = this._cfgCommon.AlwaysTop;
9013 if (!string.IsNullOrEmpty(tabName))
9016 ListElement list = null;
9017 if (tabUsage == MyCommon.TabUsageType.Lists)
9019 using (ListAvailable listAvail = new ListAvailable())
9021 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
9022 if (listAvail.SelectedList == null) return;
9023 list = listAvail.SelectedList;
9026 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
9028 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
9029 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9035 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
9037 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
9038 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
9040 if (tabUsage == MyCommon.TabUsageType.Lists)
9042 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
9043 var tab = this._statuses.Tabs[this._curTab.Text];
9044 this.GetListTimelineAsync(tab);
9050 private void TabMenuItem_Click(object sender, EventArgs e)
9052 using (var fltDialog = new FilterDialog())
9054 fltDialog.Owner = this;
9057 foreach (int idx in _curList.SelectedIndices)
9061 if (!SelectTab(out tabName)) return;
9063 fltDialog.SetCurrent(tabName);
9064 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
9066 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
9070 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
9072 fltDialog.ShowDialog(this);
9073 this.TopMost = this._cfgCommon.AlwaysTop;
9077 this.ApplyPostFilters();
9079 if (this.ListTab.SelectedTab != null &&
9080 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
9082 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
9086 protected override bool ProcessDialogKey(Keys keyData)
9088 //TextBox1でEnterを押してもビープ音が鳴らないようにする
9089 if ((keyData & Keys.KeyCode) == Keys.Enter)
9091 if (StatusText.Focused)
9093 bool _NewLine = false;
9096 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
9098 if (StatusText.Multiline)
9100 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9102 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
9106 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
9110 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
9112 if (StatusText.Multiline)
9114 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
9116 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
9120 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9126 if (StatusText.Multiline)
9128 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9130 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
9131 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9135 if (((keyData & Keys.Shift) == Keys.Shift) ||
9136 (((keyData & Keys.Control) != Keys.Control) &&
9137 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9143 int pos1 = StatusText.SelectionStart;
9144 if (StatusText.SelectionLength > 0)
9146 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9148 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9149 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9154 PostButton_Click(null, null);
9158 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9159 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9160 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9162 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9167 return base.ProcessDialogKey(keyData);
9170 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9172 MakeReplyOrDirectStatus(false, true, true);
9175 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9180 if (_curList.SelectedIndices.Count == 0) return;
9183 if (!SelectTab(out tabName)) return;
9187 MoveOrCopy(ref mv, ref mk);
9189 List<string> ids = new List<string>();
9190 foreach (int idx in _curList.SelectedIndices)
9192 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9193 if (!ids.Contains(post.ScreenName))
9195 PostFilterRule fc = new PostFilterRule();
9196 ids.Add(post.ScreenName);
9197 if (post.RetweetedId == null)
9199 fc.FilterName = post.ScreenName;
9203 fc.FilterName = post.RetweetedBy;
9205 fc.UseNameField = true;
9206 fc.MoveMatches = mv;
9207 fc.MarkMatches = mk;
9208 fc.UseRegex = false;
9209 fc.FilterByUrl = false;
9210 _statuses.Tabs[tabName].AddFilter(fc);
9215 List<string> atids = new List<string>();
9216 foreach (string id in ids)
9218 atids.Add("@" + id);
9220 int cnt = AtIdSupl.ItemCount;
9221 AtIdSupl.AddRangeItem(atids.ToArray());
9222 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9225 this.ApplyPostFilters();
9229 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9231 if (this._curList.SelectedIndices.Count == 0)
9234 // タブ選択ダイアログを表示(or追加)
9236 if (!this.SelectTab(out tabName))
9239 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9242 this.MoveOrCopy(ref mv, ref mk);
9244 var currentTab = this._statuses.Tabs[this._curTab.Text];
9245 var filterTab = this._statuses.Tabs[tabName];
9247 // 振り分けルールに追加するSource
9248 var sources = new HashSet<string>();
9250 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9252 var post = currentTab[idx];
9253 var filterSource = post.Source;
9255 if (sources.Add(filterSource))
9257 var filter = new PostFilterRule
9259 FilterSource = filterSource,
9263 FilterByUrl = false,
9265 filterTab.AddFilter(filter);
9269 this.ApplyPostFilters();
9270 this.SaveConfigsTabs();
9273 private bool SelectTab(out string tabName)
9280 using (var dialog = new TabsDialog(_statuses))
9282 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9284 var selectedTab = dialog.SelectedTab;
9285 tabName = selectedTab == null ? null : selectedTab.TabName;
9288 ListTab.SelectedTab.Focus();
9290 if (tabName == null)
9292 using (InputTabName inputName = new InputTabName())
9294 inputName.TabName = _statuses.GetUniqueTabName();
9295 inputName.ShowDialog();
9296 if (inputName.DialogResult == DialogResult.Cancel) return false;
9297 tabName = inputName.TabName;
9299 this.TopMost = this._cfgCommon.AlwaysTop;
9300 if (!string.IsNullOrEmpty(tabName))
9302 if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9304 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9305 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9323 private void MoveOrCopy(ref bool move, ref bool mark)
9327 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9328 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9336 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9337 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9343 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9348 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9353 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9355 if (StatusText.Focused)
9358 StatusText.SelectAll();
9362 // ListView上でのCtrl+A
9363 NativeMethods.SelectAllItems(this._curList);
9367 private void MoveMiddle()
9373 if (_curList.SelectedIndices.Count == 0) return;
9375 int idx = _curList.SelectedIndices[0];
9377 _item = _curList.GetItemAt(0, 25);
9383 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9385 idx2 = _curList.VirtualListSize - 1;
9389 idx -= Math.Abs(idx1 - idx2) / 2;
9390 if (idx < 0) idx = 0;
9392 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9393 _curList.EnsureVisible(idx);
9396 private void OpenURLMenuItem_Click(object sender, EventArgs e)
9398 if (PostBrowser.Document.Links.Count > 0)
9400 UrlDialog.ClearUrl();
9402 string openUrlStr = "";
9404 if (PostBrowser.Document.Links.Count == 1)
9409 urlStr = MyCommon.IDNEncode(PostBrowser.Document.Links[0].GetAttribute("href"));
9411 catch (ArgumentException)
9420 if (string.IsNullOrEmpty(urlStr)) return;
9421 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9425 foreach (HtmlElement linkElm in PostBrowser.Document.Links)
9428 string linkText = "";
9432 urlStr = linkElm.GetAttribute("title");
9433 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9434 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9435 linkText = linkElm.InnerText;
9437 catch (ArgumentException)
9446 if (string.IsNullOrEmpty(urlStr)) continue;
9447 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9451 if (UrlDialog.ShowDialog() == DialogResult.OK)
9453 openUrlStr = UrlDialog.SelectedUrl;
9460 this.TopMost = this._cfgCommon.AlwaysTop;
9462 if (string.IsNullOrEmpty(openUrlStr)) return;
9464 if (openUrlStr.StartsWith("http://twitter.com/search?q=") ||
9465 openUrlStr.StartsWith("https://twitter.com/search?q="))
9468 string urlStr = Uri.UnescapeDataString(openUrlStr);
9469 string hash = urlStr.Substring(urlStr.IndexOf("#"));
9470 HashSupl.AddItem(hash);
9471 HashMgr.AddHashToHistory(hash.Trim(), false);
9472 AddNewTabForSearch(hash);
9477 Match m = Regex.Match(openUrlStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9478 if (this._cfgCommon.OpenUserTimeline && m.Success && IsTwitterId(m.Result("${ScreenName}")))
9479 this.AddNewTabForUserTimeline(m.Result("${ScreenName}"));
9481 OpenUriAsync(openUrlStr);
9487 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9489 if (string.IsNullOrEmpty(_rclickTabName)) return;
9490 ClearTab(_rclickTabName, true);
9493 private void ClearTab(string tabName, bool showWarning)
9497 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9498 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9504 _statuses.ClearTabIds(tabName);
9505 if (ListTab.SelectedTab.Text == tabName)
9508 _anchorFlag = false;
9509 this.PurgeListViewItemCache();
9513 foreach (TabPage tb in ListTab.TabPages)
9515 if (tb.Text == tabName)
9518 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9522 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9524 SetMainWindowTitle();
9525 SetStatusLabelUrl();
9528 private static long followers = 0;
9530 private void SetMainWindowTitle()
9533 StringBuilder ttl = new StringBuilder(256);
9536 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9537 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9538 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9539 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9541 foreach (var tab in _statuses.Tabs.Values)
9543 ur += tab.UnreadCount;
9548 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9549 ttl.Append(Application.ProductName);
9551 switch (this._cfgCommon.DispLatestPost)
9553 case MyCommon.DispTitleEnum.Ver:
9554 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9556 case MyCommon.DispTitleEnum.Post:
9557 if (_history != null && _history.Count > 1)
9558 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9560 case MyCommon.DispTitleEnum.UnreadRepCount:
9561 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9563 case MyCommon.DispTitleEnum.UnreadAllCount:
9564 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9566 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9567 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9569 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9570 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9572 case MyCommon.DispTitleEnum.OwnStatus:
9573 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9574 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9580 this.Text = ttl.ToString();
9582 catch (AccessViolationException)
9584 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9588 private string GetStatusLabelText()
9591 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9592 if (_statuses == null) return "";
9593 TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9594 TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9595 if (tbRep == null || tbDm == null) return "";
9596 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9601 StringBuilder slbl = new StringBuilder(256);
9604 foreach (var tab in _statuses.Tabs.Values)
9606 ur += tab.UnreadCount;
9608 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9610 tur = tab.UnreadCount;
9621 UnreadAtCounter = urat;
9623 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9624 if (this._cfgCommon.TimelinePeriod == 0)
9626 slbl.Append(Properties.Resources.SetStatusLabelText2);
9630 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9632 return slbl.ToString();
9635 private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9639 if (this.InvokeRequired && !this.IsDisposed)
9641 this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9645 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9646 SetApiStatusLabel(endpointName);
9649 catch (ObjectDisposedException)
9653 catch (InvalidOperationException)
9659 private void SetApiStatusLabel(string endpointName = null)
9661 if (_curTab == null)
9663 this.toolStripApiGauge.ApiEndpoint = null;
9667 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9669 if (endpointName == null)
9674 case MyCommon.TabUsageType.Home:
9675 case MyCommon.TabUsageType.UserDefined:
9676 endpointName = "/statuses/home_timeline";
9679 case MyCommon.TabUsageType.Mentions:
9680 endpointName = "/statuses/mentions_timeline";
9683 case MyCommon.TabUsageType.Favorites:
9684 endpointName = "/favorites/list";
9687 case MyCommon.TabUsageType.DirectMessage:
9688 endpointName = "/direct_messages";
9691 case MyCommon.TabUsageType.UserTimeline:
9692 endpointName = "/statuses/user_timeline";
9695 case MyCommon.TabUsageType.Lists:
9696 endpointName = "/lists/statuses";
9699 case MyCommon.TabUsageType.PublicSearch:
9700 endpointName = "/search/tweets";
9703 case MyCommon.TabUsageType.Related:
9704 endpointName = "/statuses/show/:id";
9711 this.toolStripApiGauge.ApiEndpoint = endpointName;
9715 // 表示中のタブに関連する endpoint であれば更新
9718 switch (endpointName)
9720 case "/statuses/home_timeline":
9721 update = tabType == MyCommon.TabUsageType.Home ||
9722 tabType == MyCommon.TabUsageType.UserDefined;
9725 case "/statuses/mentions_timeline":
9726 update = tabType == MyCommon.TabUsageType.Mentions;
9729 case "/favorites/list":
9730 update = tabType == MyCommon.TabUsageType.Favorites;
9733 case "/direct_messages:":
9734 update = tabType == MyCommon.TabUsageType.DirectMessage;
9737 case "/statuses/user_timeline":
9738 update = tabType == MyCommon.TabUsageType.UserTimeline;
9741 case "/lists/statuses":
9742 update = tabType == MyCommon.TabUsageType.Lists;
9745 case "/search/tweets":
9746 update = tabType == MyCommon.TabUsageType.PublicSearch;
9749 case "/statuses/show/:id":
9750 update = tabType == MyCommon.TabUsageType.Related;
9759 this.toolStripApiGauge.ApiEndpoint = endpointName;
9765 private void SetStatusLabelUrl()
9767 StatusLabelUrl.Text = GetStatusLabelText();
9770 public void SetStatusLabel(string text)
9772 StatusLabel.Text = text;
9775 private static StringBuilder ur = new StringBuilder(64);
9777 private void SetNotifyIconText()
9779 // タスクトレイアイコンのツールチップテキスト書き換え
9781 ur.Remove(0, ur.Length);
9782 if (this._cfgCommon.DispUsername)
9784 ur.Append(tw.Username);
9787 ur.Append(Application.ProductName);
9789 ur.Append("(Debug Build)");
9791 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9794 ur.Append(UnreadCounter);
9796 ur.Append(UnreadAtCounter);
9799 NotifyIcon1.Text = ur.ToString();
9802 internal void CheckReplyTo(string StatusText)
9806 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9808 foreach (Match hm in m)
9810 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9812 hstr += "#" + hm.Result("$3") + " ";
9813 HashSupl.AddItem("#" + hm.Result("$3"));
9816 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9818 hstr += HashMgr.UseHash;
9820 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9822 // 本当にリプライ先指定すべきかどうかの判定
9823 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9825 if (this._cfgCommon.UseAtIdSupplement)
9827 int bCnt = AtIdSupl.ItemCount;
9828 foreach (Match mid in m)
9830 AtIdSupl.AddItem(mid.Result("${id}"));
9832 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9835 // リプライ先ステータスIDの指定がない場合は指定しない
9836 if (_reply_to_id == null) return;
9838 // リプライ先ユーザー名がない場合も指定しない
9839 if (string.IsNullOrEmpty(_reply_to_name))
9841 _reply_to_id = null;
9846 // 次の条件を満たす場合に in_reply_to_status_id 指定
9847 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9848 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9849 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9853 if (StatusText.StartsWith("@"))
9855 if (StatusText.StartsWith("@" + _reply_to_name)) return;
9859 foreach (Match mid in m)
9861 if (StatusText.Contains("QT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + _reply_to_name) return;
9866 _reply_to_id = null;
9867 _reply_to_name = null;
9871 private void TweenMain_Resize(object sender, EventArgs e)
9873 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9875 this.Visible = false;
9877 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9879 // 現在の DPI と設定保存時の DPI との比を取得する
9880 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9882 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9883 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9884 this.DesktopLocation = _cfgLocal.FormLocation;
9885 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9888 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9889 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9890 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9892 this.SplitContainer1.SplitterDistance = splitterDistance;
9896 StatusText.Multiline = _cfgLocal.StatusMultiline;
9897 if (StatusText.Multiline)
9899 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9900 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9901 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9903 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9905 StatusText.Height = statusTextHeight;
9909 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9911 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9915 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9916 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9918 this.SplitContainer3.SplitterDistance = previewDistance;
9920 _initialLayout = false;
9922 if (this.WindowState != FormWindowState.Minimized)
9924 _formWindowState = this.WindowState;
9928 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9930 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9931 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9932 if (PlaySoundMenuItem.Checked)
9934 this._cfgCommon.PlaySound = true;
9938 this._cfgCommon.PlaySound = false;
9940 _modifySettingCommon = true;
9943 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9945 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
9947 _mySpDis = SplitContainer1.SplitterDistance;
9948 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9949 _modifySettingLocal = true;
9953 private void doRepliedStatusOpen()
9955 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9957 if (MyCommon.IsKeyDown(Keys.Shift))
9959 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9962 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9964 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9965 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9969 foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9971 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9972 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9973 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9976 OpenUriAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9981 private void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9983 doRepliedStatusOpen();
9987 /// UserPicture.Image に設定されている画像を破棄します。
9989 private void ClearUserPicture()
9991 if (this.UserPicture.Image != null)
9993 var oldImage = this.UserPicture.Image;
9994 this.UserPicture.Image = null;
9999 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
10001 //発言詳細のアイコン右クリック時のメニュー制御
10002 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
10004 string name = _curPost.ImageUrl;
10005 if (name != null && name.Length > 0)
10007 int idx = name.LastIndexOf('/');
10010 name = Path.GetFileName(name.Substring(idx));
10011 if (name.Contains("_normal.") || name.EndsWith("_normal"))
10013 name = name.Replace("_normal", "");
10014 this.IconNameToolStripMenuItem.Text = name;
10015 this.IconNameToolStripMenuItem.Enabled = true;
10019 this.IconNameToolStripMenuItem.Enabled = false;
10020 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
10025 this.IconNameToolStripMenuItem.Enabled = false;
10026 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
10029 this.ReloadIconToolStripMenuItem.Enabled = true;
10031 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
10033 this.SaveIconPictureToolStripMenuItem.Enabled = true;
10037 this.SaveIconPictureToolStripMenuItem.Enabled = false;
10042 this.IconNameToolStripMenuItem.Enabled = false;
10043 this.ReloadIconToolStripMenuItem.Enabled = false;
10044 this.SaveIconPictureToolStripMenuItem.Enabled = false;
10045 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
10050 this.IconNameToolStripMenuItem.Enabled = false;
10051 this.ReloadIconToolStripMenuItem.Enabled = false;
10052 this.SaveIconPictureToolStripMenuItem.Enabled = false;
10053 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
10055 if (NameLabel.Tag != null)
10057 string id = (string)NameLabel.Tag;
10058 if (id == tw.Username)
10060 FollowToolStripMenuItem.Enabled = false;
10061 UnFollowToolStripMenuItem.Enabled = false;
10062 ShowFriendShipToolStripMenuItem.Enabled = false;
10063 ShowUserStatusToolStripMenuItem.Enabled = true;
10064 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
10065 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
10066 ListManageUserContextToolStripMenuItem3.Enabled = true;
10070 FollowToolStripMenuItem.Enabled = true;
10071 UnFollowToolStripMenuItem.Enabled = true;
10072 ShowFriendShipToolStripMenuItem.Enabled = true;
10073 ShowUserStatusToolStripMenuItem.Enabled = true;
10074 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
10075 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
10076 ListManageUserContextToolStripMenuItem3.Enabled = true;
10081 FollowToolStripMenuItem.Enabled = false;
10082 UnFollowToolStripMenuItem.Enabled = false;
10083 ShowFriendShipToolStripMenuItem.Enabled = false;
10084 ShowUserStatusToolStripMenuItem.Enabled = false;
10085 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
10086 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
10087 ListManageUserContextToolStripMenuItem3.Enabled = false;
10091 private void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
10093 if (_curPost == null) return;
10094 string name = _curPost.ImageUrl;
10095 OpenUriAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
10098 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
10100 if (this._curPost == null) return;
10102 await this.UserPicture.SetImageFromTask(async () =>
10104 var imageUrl = this._curPost.ImageUrl;
10106 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10107 .ConfigureAwait(false);
10109 return await image.CloneAsync()
10110 .ConfigureAwait(false);
10114 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10116 if (_curPost == null) return;
10117 string name = _curPost.ImageUrl;
10118 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10120 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10122 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10128 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10130 if (_curPost == null) return;
10131 string name = _curPost.ImageUrl;
10133 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10135 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10139 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10141 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10143 using (Graphics g = Graphics.FromImage(bmp2))
10145 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10146 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10148 bmp2.Save(this.SaveFileDialog1.FileName);
10154 //処理中にキャッシュアウトする可能性あり
10159 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10161 this.StatusText.Multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10162 MultiLineMenuItem.Checked = this.StatusText.Multiline;
10163 _modifySettingLocal = true;
10166 private void StatusText_MultilineChanged(object sender, EventArgs e)
10168 if (this.StatusText.Multiline)
10169 this.StatusText.ScrollBars = ScrollBars.Vertical;
10171 this.StatusText.ScrollBars = ScrollBars.None;
10173 _modifySettingLocal = true;
10176 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10179 StatusText.Multiline = MultiLineMenuItem.Checked;
10180 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10181 if (MultiLineMenuItem.Checked)
10183 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10184 SplitContainer2.SplitterDistance = 0;
10186 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10190 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10192 _modifySettingLocal = true;
10195 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10197 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10198 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10200 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10201 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10202 //Appendix A. Collected ABNF for URI
10203 //http://www.ietf.org/rfc/rfc3986.txt
10205 string result = "";
10207 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10209 if (StatusText.SelectionLength > 0)
10211 string tmp = StatusText.SelectedText;
10212 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10213 if (tmp.StartsWith("http"))
10215 // 文字列が選択されている場合はその文字列について処理
10217 //nico.ms使用、nicovideoにマッチしたら変換
10218 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10220 result = nicoms.Shorten(tmp);
10222 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10224 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10227 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10228 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10229 result = resultUri.AbsoluteUri;
10231 catch (WebApiException e)
10233 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10236 catch (UriFormatException e)
10238 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10247 if (!string.IsNullOrEmpty(result))
10249 urlUndo undotmp = new urlUndo();
10251 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10252 StatusText.SelectedText = result;
10255 undotmp.Before = tmp;
10256 undotmp.After = result;
10258 if (urlUndoBuffer == null)
10260 urlUndoBuffer = new List<urlUndo>();
10261 UrlUndoToolStripMenuItem.Enabled = true;
10264 urlUndoBuffer.Add(undotmp);
10270 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10271 @"(?<url>(?<protocol>https?://)" +
10272 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10273 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10274 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10275 // 正規表現にマッチしたURL文字列をtinyurl化
10276 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10278 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10279 string tmp = mt.Result("${url}");
10280 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10281 urlUndo undotmp = new urlUndo();
10284 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10286 //nico.ms使用、nicovideoにマッチしたら変換
10287 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10289 result = nicoms.Shorten(tmp);
10291 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10293 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10296 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10297 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10298 result = resultUri.AbsoluteUri;
10300 catch (HttpRequestException e)
10302 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10303 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10304 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10306 this.StatusLabel.Text = Converter_Type + ":" + message;
10309 catch (WebApiException e)
10311 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10314 catch (UriFormatException e)
10316 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10325 if (!string.IsNullOrEmpty(result))
10327 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10328 StatusText.SelectedText = result;
10330 undotmp.Before = mt.Result("${url}");
10331 undotmp.After = result;
10333 if (urlUndoBuffer == null)
10335 urlUndoBuffer = new List<urlUndo>();
10336 UrlUndoToolStripMenuItem.Enabled = true;
10339 urlUndoBuffer.Add(undotmp);
10347 private void doUrlUndo()
10349 if (urlUndoBuffer != null)
10351 string tmp = StatusText.Text;
10352 foreach (urlUndo data in urlUndoBuffer)
10354 tmp = tmp.Replace(data.After, data.Before);
10356 StatusText.Text = tmp;
10357 urlUndoBuffer = null;
10358 UrlUndoToolStripMenuItem.Enabled = false;
10359 StatusText.SelectionStart = 0;
10360 StatusText.SelectionLength = 0;
10364 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10366 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10369 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10371 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10374 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10376 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10379 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10381 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10384 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10386 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10388 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10389 Random rnd = new Random();
10390 // 前回使用した短縮URLサービス以外を選択する
10393 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10395 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10396 await UrlConvertAsync(svc);
10400 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10405 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10407 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10408 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10409 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10410 _modifySettingCommon = true;
10413 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10415 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10416 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10417 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10418 _modifySettingCommon = true;
10421 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10423 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10424 MenuStrip1.Tag = new Object();
10425 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10428 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10430 if (this.Tag != null) // 設定された戻り先へ遷移
10432 if (this.Tag == this.ListTab.SelectedTab)
10433 ((Control)this.ListTab.SelectedTab.Tag).Select();
10435 ((Control)this.Tag).Select();
10437 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10439 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10441 this.Tag = ListTab.SelectedTab.Tag;
10442 ((Control)this.Tag).Select();
10445 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10446 MenuStrip1.Tag = null;
10449 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10451 DetailsListView lst = (DetailsListView)sender;
10452 if (_cfgLocal == null) return;
10456 _cfgLocal.Width1 = lst.Columns[0].Width;
10457 _cfgLocal.Width3 = lst.Columns[1].Width;
10461 int[] darr = new int[lst.Columns.Count];
10462 for (int i = 0; i < lst.Columns.Count; i++)
10464 darr[lst.Columns[i].DisplayIndex] = i;
10466 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10468 for (int i = 0; i < lst.Columns.Count; i++)
10473 _cfgLocal.DisplayIndex1 = i;
10476 _cfgLocal.DisplayIndex2 = i;
10479 _cfgLocal.DisplayIndex3 = i;
10482 _cfgLocal.DisplayIndex4 = i;
10485 _cfgLocal.DisplayIndex5 = i;
10488 _cfgLocal.DisplayIndex6 = i;
10491 _cfgLocal.DisplayIndex7 = i;
10494 _cfgLocal.DisplayIndex8 = i;
10498 _cfgLocal.Width1 = lst.Columns[0].Width;
10499 _cfgLocal.Width2 = lst.Columns[1].Width;
10500 _cfgLocal.Width3 = lst.Columns[2].Width;
10501 _cfgLocal.Width4 = lst.Columns[3].Width;
10502 _cfgLocal.Width5 = lst.Columns[4].Width;
10503 _cfgLocal.Width6 = lst.Columns[5].Width;
10504 _cfgLocal.Width7 = lst.Columns[6].Width;
10505 _cfgLocal.Width8 = lst.Columns[7].Width;
10507 _modifySettingLocal = true;
10508 _isColumnChanged = true;
10511 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10513 DetailsListView lst = (DetailsListView)sender;
10514 if (_cfgLocal == null) return;
10517 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10519 _cfgLocal.Width1 = lst.Columns[0].Width;
10520 _modifySettingLocal = true;
10521 _isColumnChanged = true;
10523 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10525 _cfgLocal.Width3 = lst.Columns[1].Width;
10526 _modifySettingLocal = true;
10527 _isColumnChanged = true;
10532 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10534 _cfgLocal.Width1 = lst.Columns[0].Width;
10535 _modifySettingLocal = true;
10536 _isColumnChanged = true;
10538 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10540 _cfgLocal.Width2 = lst.Columns[1].Width;
10541 _modifySettingLocal = true;
10542 _isColumnChanged = true;
10544 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10546 _cfgLocal.Width3 = lst.Columns[2].Width;
10547 _modifySettingLocal = true;
10548 _isColumnChanged = true;
10550 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10552 _cfgLocal.Width4 = lst.Columns[3].Width;
10553 _modifySettingLocal = true;
10554 _isColumnChanged = true;
10556 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10558 _cfgLocal.Width5 = lst.Columns[4].Width;
10559 _modifySettingLocal = true;
10560 _isColumnChanged = true;
10562 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10564 _cfgLocal.Width6 = lst.Columns[5].Width;
10565 _modifySettingLocal = true;
10566 _isColumnChanged = true;
10568 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10570 _cfgLocal.Width7 = lst.Columns[6].Width;
10571 _modifySettingLocal = true;
10572 _isColumnChanged = true;
10574 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10576 _cfgLocal.Width8 = lst.Columns[7].Width;
10577 _modifySettingLocal = true;
10578 _isColumnChanged = true;
10581 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10584 // SaveConfigsLocal();
10588 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10591 string _selText = this.PostBrowser.GetSelectedText();
10594 Clipboard.SetDataObject(_selText, false, 5, 100);
10596 catch (Exception ex)
10598 MessageBox.Show(ex.Message);
10602 private void doSearchToolStrip(string url)
10604 //発言詳細で「選択文字列で検索」(選択文字列取得)
10605 string _selText = this.PostBrowser.GetSelectedText();
10607 if (_selText != null)
10609 if (url == Properties.Resources.SearchItem4Url)
10612 AddNewTabForSearch(_selText);
10616 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10621 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10624 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10627 private void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10629 doSearchToolStrip(Properties.Resources.SearchItem1Url);
10632 private void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10634 doSearchToolStrip(Properties.Resources.SearchItem2Url);
10637 private void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10639 doSearchToolStrip(Properties.Resources.SearchItem4Url);
10642 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10646 MatchCollection mc = Regex.Matches(this.PostBrowser.DocumentText, @"<a[^>]*href=""(?<url>" + this._postBrowserStatusText.Replace(".", @"\.") + @")""[^>]*title=""(?<title>https?://[^""]+)""", RegexOptions.IgnoreCase);
10647 foreach (Match m in mc)
10649 if (m.Groups["url"].Value == this._postBrowserStatusText)
10651 Clipboard.SetDataObject(m.Groups["title"].Value, false, 5, 100);
10657 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10659 //Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10661 catch (Exception ex)
10663 MessageBox.Show(ex.Message);
10667 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10669 // URLコピーの項目の表示/非表示
10670 if (PostBrowser.StatusText.StartsWith("http"))
10672 this._postBrowserStatusText = PostBrowser.StatusText;
10673 string name = GetUserId();
10674 UrlCopyContextMenuItem.Enabled = true;
10677 FollowContextMenuItem.Enabled = true;
10678 RemoveContextMenuItem.Enabled = true;
10679 FriendshipContextMenuItem.Enabled = true;
10680 ShowUserStatusContextMenuItem.Enabled = true;
10681 SearchPostsDetailToolStripMenuItem.Enabled = true;
10682 IdFilterAddMenuItem.Enabled = true;
10683 ListManageUserContextToolStripMenuItem.Enabled = true;
10684 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10688 FollowContextMenuItem.Enabled = false;
10689 RemoveContextMenuItem.Enabled = false;
10690 FriendshipContextMenuItem.Enabled = false;
10691 ShowUserStatusContextMenuItem.Enabled = false;
10692 SearchPostsDetailToolStripMenuItem.Enabled = false;
10693 IdFilterAddMenuItem.Enabled = false;
10694 ListManageUserContextToolStripMenuItem.Enabled = false;
10695 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10698 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10699 UseHashtagMenuItem.Enabled = true;
10701 UseHashtagMenuItem.Enabled = false;
10705 this._postBrowserStatusText = "";
10706 UrlCopyContextMenuItem.Enabled = false;
10707 FollowContextMenuItem.Enabled = false;
10708 RemoveContextMenuItem.Enabled = false;
10709 FriendshipContextMenuItem.Enabled = false;
10710 ShowUserStatusContextMenuItem.Enabled = false;
10711 SearchPostsDetailToolStripMenuItem.Enabled = false;
10712 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10713 UseHashtagMenuItem.Enabled = false;
10714 IdFilterAddMenuItem.Enabled = false;
10715 ListManageUserContextToolStripMenuItem.Enabled = false;
10717 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10718 string _selText = this.PostBrowser.GetSelectedText();
10719 if (_selText == null)
10721 SelectionSearchContextMenuItem.Enabled = false;
10722 SelectionCopyContextMenuItem.Enabled = false;
10723 SelectionTranslationToolStripMenuItem.Enabled = false;
10727 SelectionSearchContextMenuItem.Enabled = true;
10728 SelectionCopyContextMenuItem.Enabled = true;
10729 SelectionTranslationToolStripMenuItem.Enabled = true;
10731 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10732 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10733 bool fAllFlag = false;
10734 foreach (Match mu in ma)
10736 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10742 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10744 if (_curPost == null)
10745 TranslationToolStripMenuItem.Enabled = false;
10747 TranslationToolStripMenuItem.Enabled = true;
10752 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10754 //発言詳細の選択文字列で現在のタブを検索
10755 string _selText = this.PostBrowser.GetSelectedText();
10757 if (_selText != null)
10759 var searchOptions = new SearchWordDialog.SearchOptions(
10760 SearchWordDialog.SearchType.Timeline,
10763 caseSensitive: false,
10766 this.SearchDialog.ResultOptions = searchOptions;
10769 searchOptions.Query,
10770 searchOptions.CaseSensitive,
10771 searchOptions.UseRegex,
10772 SEARCHTYPE.NextSearch);
10776 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10778 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10779 _modifySettingLocal = true;
10782 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10784 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10786 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10788 SelectMedia_DragDrop(e);
10791 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10793 var url = GetUrlFromDataObject(e.Data);
10796 if (url.Item2 == null)
10797 appendText = url.Item1;
10799 appendText = url.Item2 + " " + url.Item1;
10801 if (this.StatusText.TextLength == 0)
10802 this.StatusText.Text = appendText;
10804 this.StatusText.Text += " " + appendText;
10806 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10808 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10810 this.StatusText.Text += text;
10812 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10814 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10815 if (data != null) StatusText.Text += data;
10820 /// IDataObject から URL とタイトルの対を取得します
10823 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10825 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10826 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10827 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10829 if (data.GetDataPresent("text/x-moz-url"))
10831 // Firefox, Google Chrome で利用可能
10832 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10834 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10836 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10837 if (lines.Length < 2)
10838 throw new ArgumentException("不正な text/x-moz-url フォーマットです", "data");
10840 return new Tuple<string, string>(lines[0], lines[1]);
10843 else if (data.GetDataPresent("IESiteModeToUrl"))
10845 // Internet Exproler 用
10846 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10848 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10850 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10851 if (lines.Length < 2)
10852 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", "data");
10854 return new Tuple<string, string>(lines[0], lines[1]);
10857 else if (data.GetDataPresent("UniformResourceLocatorW"))
10861 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10863 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10864 return new Tuple<string, string>(url, null);
10868 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10871 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10873 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10875 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10877 SelectMedia_DragEnter(e);
10881 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10883 e.Effect = DragDropEffects.Copy;
10886 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10888 e.Effect = DragDropEffects.Copy;
10891 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10893 e.Effect = DragDropEffects.Copy;
10897 e.Effect = DragDropEffects.None;
10900 private void TweenMain_DragOver(object sender, DragEventArgs e)
10904 public bool IsNetworkAvailable()
10907 nw = MyCommon.IsNetworkAvailable();
10908 _myStatusOnline = nw;
10912 public Task OpenUriAsync(string UriString)
10914 return Task.Run(() =>
10916 string myPath = UriString;
10920 var configBrowserPath = this._cfgLocal.BrowserPath;
10921 if (!string.IsNullOrEmpty(configBrowserPath))
10923 if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10925 int sep = configBrowserPath.IndexOf("\"", 2);
10926 string browserPath = configBrowserPath.Substring(1, sep - 1);
10928 if (sep < configBrowserPath.Length - 1)
10930 arg = configBrowserPath.Substring(sep + 1);
10932 myPath = arg + " " + myPath;
10933 System.Diagnostics.Process.Start(browserPath, myPath);
10937 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10942 System.Diagnostics.Process.Start(myPath);
10947 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10952 private void ListTabSelect(TabPage _tab)
10956 this.PurgeListViewItemCache();
10959 _curList = (DetailsListView)_tab.Tag;
10960 if (_curList.SelectedIndices.Count > 0)
10962 _curItemIndex = _curList.SelectedIndices[0];
10963 _curPost = GetCurTabPost(_curItemIndex);
10967 _curItemIndex = -1;
10971 _anchorPost = null;
10972 _anchorFlag = false;
10976 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10980 for (int i = 0; i < _curList.Columns.Count; i++)
10982 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10987 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10989 ListTabSelect(e.TabPage);
10992 private void SelectListItem(DetailsListView LView, int Index)
10995 Rectangle bnd = new Rectangle();
10997 var item = LView.FocusedItem;
11006 LView.SelectedIndices.Clear();
11008 while (LView.SelectedIndices.Count > 0);
11009 item = LView.Items[Index];
11010 item.Selected = true;
11011 item.Focused = true;
11013 if (flg) LView.Invalidate(bnd);
11016 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
11019 Rectangle bnd = new Rectangle();
11021 var item = LView.FocusedItem;
11032 LView.SelectedIndices.Clear();
11034 while (LView.SelectedIndices.Count > 0);
11035 LView.SelectItems(Index);
11037 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11039 LView.SelectionMark = selectionMarkIndex;
11041 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11043 LView.Items[focusedIndex].Focused = true;
11045 else if (Index != null && Index.Length != 0)
11047 LView.Items[Index.Last()].Focused = true;
11050 if (flg) LView.Invalidate(bnd);
11053 private void StartUserStream()
11055 tw.NewPostFromStream += tw_NewPostFromStream;
11056 tw.UserStreamStarted += tw_UserStreamStarted;
11057 tw.UserStreamStopped += tw_UserStreamStopped;
11058 tw.PostDeleted += tw_PostDeleted;
11059 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11061 MenuItemUserStream.Text = "&UserStream ■";
11062 MenuItemUserStream.Enabled = true;
11063 StopToolStripMenuItem.Text = "&Start";
11064 StopToolStripMenuItem.Enabled = true;
11065 if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11068 private async void TweenMain_Shown(object sender, EventArgs e)
11072 PostBrowser.Url = new Uri("about:blank");
11073 PostBrowser.DocumentText = ""; //発言詳細部初期化
11079 NotifyIcon1.Visible = true;
11081 if (this.IsNetworkAvailable())
11085 var loadTasks = new List<Task>
11087 this.RefreshMuteUserIdsAsync(),
11088 this.RefreshBlockIdsAsync(),
11089 this.RefreshNoRetweetIdsAsync(),
11090 this.RefreshTwitterConfigurationAsync(),
11091 this.GetHomeTimelineAsync(),
11092 this.GetReplyAsync(),
11093 this.GetDirectMessagesAsync(),
11094 this.GetPublicSearchAllAsync(),
11095 this.GetUserTimelineAllAsync(),
11096 this.GetListTimelineAllAsync(),
11099 if (this._cfgCommon.StartupFollowers)
11100 loadTasks.Add(this.RefreshFollowerIdsAsync());
11102 if (this._cfgCommon.GetFav)
11103 loadTasks.Add(this.GetFavoritesAsync());
11105 var allTasks = Task.WhenAll(loadTasks);
11110 var timeout = Task.Delay(5000);
11111 if (await Task.WhenAny(allTasks, timeout) != timeout)
11115 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11117 if (MyCommon._endingFlag)
11121 if (MyCommon._endingFlag) return;
11123 if (ApplicationSettings.VersionInfoUrl != null)
11125 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11126 if (this._cfgCommon.StartupVersion)
11127 await this.CheckNewVersion(true);
11131 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11132 this.VerUpMenuItem.Enabled = false;
11133 this.VerUpMenuItem.Available = false;
11134 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11137 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11138 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11140 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11141 SettingStripMenuItem_Click(null, null);
11145 var reloadTasks = new List<Task>();
11147 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11148 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11150 if (!tw.GetNoRetweetSuccess)
11151 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11153 if (this.tw.Configuration.PhotoSizeLimit == 0)
11154 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11156 await Task.WhenAll(reloadTasks);
11161 TimerTimeline.Enabled = true;
11164 private async Task doGetFollowersMenu()
11166 await this.RefreshFollowerIdsAsync();
11167 DispSelectedPost(true);
11170 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11172 await this.doGetFollowersMenu();
11175 private void doReTweetUnofficial()
11178 if (this.ExistCurrentPost)
11180 if (_curPost.IsDm ||
11181 !StatusText.Enabled) return;
11183 if (_curPost.IsProtect)
11185 MessageBox.Show("Protected.");
11188 string rtdata = _curPost.Text;
11189 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11191 this._reply_to_id = null;
11192 this._reply_to_name = null;
11194 StatusText.Text = "RT @" + _curPost.ScreenName + ": " + rtdata;
11196 StatusText.SelectionStart = 0;
11197 StatusText.Focus();
11201 private void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11203 doReTweetUnofficial();
11206 private async Task doReTweetOfficial(bool isConfirm)
11209 if (this.ExistCurrentPost)
11211 if (_curPost.IsProtect)
11213 MessageBox.Show("Protected.");
11214 _DoFavRetweetFlags = false;
11217 if (_curList.SelectedIndices.Count > 15)
11219 MessageBox.Show(Properties.Resources.RetweetLimitText);
11220 _DoFavRetweetFlags = false;
11223 else if (_curList.SelectedIndices.Count > 1)
11225 string QuestionText = Properties.Resources.RetweetQuestion2;
11226 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11227 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11229 case DialogResult.Cancel:
11230 case DialogResult.No:
11231 _DoFavRetweetFlags = false;
11237 if (_curPost.IsDm || _curPost.IsMe)
11239 _DoFavRetweetFlags = false;
11242 if (!this._cfgCommon.RetweetNoConfirm)
11244 string Questiontext = Properties.Resources.RetweetQuestion1;
11245 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11246 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11248 _DoFavRetweetFlags = false;
11254 var statusIds = new List<long>();
11255 foreach (int idx in _curList.SelectedIndices)
11257 PostClass post = GetCurTabPost(idx);
11258 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11259 statusIds.Add(post.StatusId);
11262 await this.RetweetAsync(statusIds);
11266 private async void ReTweetOriginalStripMenuItem_Click(object sender, EventArgs e)
11268 await this.doReTweetOfficial(true);
11271 private async Task FavoritesRetweetOriginal()
11273 if (!this.ExistCurrentPost) return;
11274 _DoFavRetweetFlags = true;
11275 await this.doReTweetOfficial(true);
11276 if (_DoFavRetweetFlags)
11278 _DoFavRetweetFlags = false;
11279 await this.FavoriteChange(true, false);
11283 private async Task FavoritesRetweetUnofficial()
11285 if (this.ExistCurrentPost && !_curPost.IsDm)
11287 _DoFavRetweetFlags = true;
11288 await this.FavoriteChange(true);
11289 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11291 _DoFavRetweetFlags = false;
11292 doReTweetUnofficial();
11298 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11300 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11301 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11302 /// <returns>復元されたツイート本文</returns>
11303 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11305 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11308 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11310 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11312 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11316 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11318 statusHtml = statusHtml.Replace("<br>", " ");
11320 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11321 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11322 statusHtml = statusHtml.Replace(" ", " ");
11324 return WebUtility.HtmlDecode(statusHtml);
11327 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11329 if (_curPost != null)
11330 DispSelectedPost(true);
11333 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11335 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11336 DebugModeToolStripMenuItem.Visible = true;
11338 DebugModeToolStripMenuItem.Visible = false;
11341 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11343 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11346 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11348 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11351 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11353 if (TraceOutToolStripMenuItem.Checked)
11354 MyCommon.TraceFlag = true;
11356 MyCommon.TraceFlag = false;
11359 private void TweenMain_Deactivate(object sender, EventArgs e)
11361 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11362 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11365 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11367 if (string.IsNullOrEmpty(_rclickTabName)) return;
11368 TabRename(ref _rclickTabName);
11371 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11373 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11376 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11378 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11382 private void GetApiInfo_Dowork(object sender, DoWorkEventArgs e)
11384 e.Result = tw.GetInfoApi();
11387 private void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11389 var result = false;
11391 using (var dlg = new FormInfo(this, Properties.Resources.ApiInfo6, GetApiInfo_Dowork))
11395 result = dlg.Result != null;
11400 using (var apiDlg = new ApiInfoDialog())
11402 apiDlg.ShowDialog();
11407 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11411 private void FollowCommandMenuItem_Click(object sender, EventArgs e)
11414 if (_curPost != null) id = _curPost.ScreenName;
11418 private void FollowCommand_DoWork(object sender, DoWorkEventArgs e)
11420 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11421 e.Result = arg.tw.PostFollowCommand(arg.id);
11424 private void FollowCommand(string id)
11426 using (InputTabName inputName = new InputTabName())
11428 inputName.FormTitle = "Follow";
11429 inputName.FormDescription = Properties.Resources.FRMessage1;
11430 inputName.TabName = id;
11431 if (inputName.ShowDialog() == DialogResult.OK &&
11432 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11434 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11436 arg.id = inputName.TabName.Trim();
11437 using (FormInfo _info = new FormInfo(this, Properties.Resources.FollowCommandText1,
11438 FollowCommand_DoWork,
11442 _info.ShowDialog();
11443 string ret = (string)_info.Result;
11444 if (!string.IsNullOrEmpty(ret))
11445 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11447 MessageBox.Show(Properties.Resources.FRMessage3);
11453 private void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11456 if (_curPost != null) id = _curPost.ScreenName;
11457 RemoveCommand(id, false);
11460 private class FollowRemoveCommandArgs
11466 private void RemoveCommand_DoWork(object sender , DoWorkEventArgs e)
11468 FollowRemoveCommandArgs arg = (FollowRemoveCommandArgs)e.Argument;
11469 e.Result = arg.tw.PostRemoveCommand(arg.id);
11472 private void RemoveCommand(string id, bool skipInput)
11474 FollowRemoveCommandArgs arg = new FollowRemoveCommandArgs();
11479 using (InputTabName inputName = new InputTabName())
11481 inputName.FormTitle = "Unfollow";
11482 inputName.FormDescription = Properties.Resources.FRMessage1;
11483 inputName.TabName = id;
11484 if (inputName.ShowDialog() == DialogResult.OK &&
11485 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11488 arg.id = inputName.TabName.Trim();
11497 using (FormInfo _info = new FormInfo(this, Properties.Resources.RemoveCommandText1,
11498 RemoveCommand_DoWork,
11502 _info.ShowDialog();
11503 string ret = (string)_info.Result;
11504 if (!string.IsNullOrEmpty(ret))
11505 MessageBox.Show(Properties.Resources.FRMessage2 + ret);
11507 MessageBox.Show(Properties.Resources.FRMessage3);
11511 private void FriendshipMenuItem_Click(object sender, EventArgs e)
11514 if (_curPost != null)
11515 id = _curPost.ScreenName;
11517 ShowFriendship(id);
11520 private class ShowFriendshipArgs
11523 public class FriendshipInfo
11525 public string id = "";
11526 public bool isFollowing = false;
11527 public bool isFollowed = false;
11528 public FriendshipInfo(string id)
11533 public List<FriendshipInfo> ids = new List<FriendshipInfo>();
11536 private void ShowFriendship_DoWork(object sender, DoWorkEventArgs e)
11538 ShowFriendshipArgs arg = (ShowFriendshipArgs)e.Argument;
11539 string result = "";
11540 foreach (ShowFriendshipArgs.FriendshipInfo fInfo in arg.ids)
11542 string rt = arg.tw.GetFriendshipInfo(fInfo.id, ref fInfo.isFollowing, ref fInfo.isFollowed);
11543 if (!string.IsNullOrEmpty(rt))
11545 if (string.IsNullOrEmpty(result)) result = rt;
11551 private void ShowFriendship(string id)
11553 ShowFriendshipArgs args = new ShowFriendshipArgs();
11555 using (InputTabName inputName = new InputTabName())
11557 inputName.FormTitle = "Show Friendships";
11558 inputName.FormDescription = Properties.Resources.FRMessage1;
11559 inputName.TabName = id;
11560 if (inputName.ShowDialog() == DialogResult.OK &&
11561 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11564 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(inputName.TabName.Trim()));
11565 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11566 ShowFriendship_DoWork,
11570 _info.ShowDialog();
11571 ret = (string)_info.Result;
11573 string result = "";
11574 if (string.IsNullOrEmpty(ret))
11576 if (args.ids[0].isFollowing)
11578 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11582 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11584 if (args.ids[0].isFollowed)
11586 result += Properties.Resources.GetFriendshipInfo3;
11590 result += Properties.Resources.GetFriendshipInfo4;
11592 result = args.ids[0].id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11598 MessageBox.Show(result);
11603 private void ShowFriendship(string[] ids)
11605 foreach (string id in ids)
11608 ShowFriendshipArgs args = new ShowFriendshipArgs();
11610 args.ids.Add(new ShowFriendshipArgs.FriendshipInfo(id.Trim()));
11611 using (FormInfo _info = new FormInfo(this, Properties.Resources.ShowFriendshipText1,
11612 ShowFriendship_DoWork,
11616 _info.ShowDialog();
11617 ret = (string)_info.Result;
11619 string result = "";
11620 ShowFriendshipArgs.FriendshipInfo fInfo = args.ids[0];
11622 if (string.IsNullOrEmpty(ret))
11625 if (fInfo.isFollowing)
11627 ff += Properties.Resources.GetFriendshipInfo1;
11631 ff += Properties.Resources.GetFriendshipInfo2;
11634 ff += System.Environment.NewLine + " ";
11635 if (fInfo.isFollowed)
11637 ff += Properties.Resources.GetFriendshipInfo3;
11641 ff += Properties.Resources.GetFriendshipInfo4;
11643 result += fInfo.id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11644 if (fInfo.isFollowing)
11646 if (MessageBox.Show(
11647 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11648 MessageBoxButtons.YesNo,
11649 MessageBoxIcon.Question,
11650 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11652 RemoveCommand(fInfo.id, true);
11657 MessageBox.Show(result);
11662 MessageBox.Show(ret);
11667 private void OwnStatusMenuItem_Click(object sender, EventArgs e)
11669 doShowUserStatus(tw.Username, false);
11670 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11672 // doShowUserStatus(tw.Username, false);
11676 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11681 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11682 // URLから切り出した文字列を渡す
11684 public bool IsTwitterId(string name)
11686 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11687 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11689 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11692 private string GetUserId()
11694 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11695 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11696 return m.Result("${ScreenName}");
11701 private void FollowContextMenuItem_Click(object sender, EventArgs e)
11703 string name = GetUserId();
11704 if (name != null) FollowCommand(name);
11707 private void RemoveContextMenuItem_Click(object sender, EventArgs e)
11709 string name = GetUserId();
11710 if (name != null) RemoveCommand(name, false);
11713 private void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11715 string name = GetUserId();
11716 if (name != null) ShowFriendship(name);
11719 private void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11721 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11722 List<string> ids = new List<string>();
11723 foreach (Match mu in ma)
11725 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11727 ids.Add(mu.Result("${ScreenName}"));
11730 ShowFriendship(ids.ToArray());
11733 private void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11735 string name = GetUserId();
11736 if (name != null) ShowUserStatus(name);
11739 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11741 string name = GetUserId();
11742 if (name != null) AddNewTabForUserTimeline(name);
11745 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11747 string name = GetUserId();
11748 if (name != null) AddNewTabForSearch("@" + name);
11751 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11753 _modifySettingCommon = true;
11756 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11758 _modifySettingCommon = true;
11761 private void doQuote()
11765 if (this.ExistCurrentPost)
11767 if (_curPost.IsDm ||
11768 !StatusText.Enabled) return;
11770 if (_curPost.IsProtect)
11772 MessageBox.Show("Protected.");
11775 string rtdata = _curPost.Text;
11776 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11778 StatusText.Text = " QT @" + _curPost.ScreenName + ": " + rtdata;
11779 if (_curPost.RetweetedId == null)
11781 _reply_to_id = _curPost.StatusId;
11785 _reply_to_id = _curPost.RetweetedId.Value;
11787 _reply_to_name = _curPost.ScreenName;
11789 StatusText.SelectionStart = 0;
11790 StatusText.Focus();
11794 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11799 private void SearchButton_Click(object sender, EventArgs e)
11802 Control pnl = ((Control)sender).Parent;
11803 if (pnl == null) return;
11804 string tbName = pnl.Parent.Text;
11805 TabClass tb = _statuses.Tabs[tbName];
11806 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11807 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11808 cmb.Text = cmb.Text.Trim();
11809 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11810 bool Quote = false;
11811 StringBuilder buf = new StringBuilder();
11812 char[] c = cmb.Text.ToCharArray();
11813 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11815 if (cnt > cmb.Text.Length - 4)
11817 buf.Append(cmb.Text.Substring(cnt));
11826 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11828 buf.Append(" OR ");
11833 buf.Append(c[cnt]);
11835 cmb.Text = buf.ToString();
11837 var listView = (DetailsListView)pnl.Parent.Tag;
11839 tb.SearchWords = cmb.Text;
11840 tb.SearchLang = cmbLang.Text;
11841 if (string.IsNullOrEmpty(cmb.Text))
11847 if (tb.IsSearchQueryChanged)
11849 int idx = cmb.Items.IndexOf(tb.SearchWords);
11850 if (idx > -1) cmb.Items.RemoveAt(idx);
11851 cmb.Items.Insert(0, tb.SearchWords);
11852 cmb.Text = tb.SearchWords;
11854 this.PurgeListViewItemCache();
11855 listView.VirtualListSize = 0;
11856 _statuses.ClearTabIds(tbName);
11857 SaveConfigsTabs(); //検索条件の保存
11860 this.GetPublicSearchAsync(tb);
11864 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11867 await this.DoRefreshMore();
11870 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11872 if (_statuses.RemovedTab.Count == 0)
11874 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11879 DetailsListView listView = null;
11881 TabClass tb = _statuses.RemovedTab.Pop();
11882 if (tb.TabType == MyCommon.TabUsageType.Related)
11884 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11885 if (relatedTab != null)
11887 // 関連発言なら既存のタブを置き換える
11888 tb.TabName = relatedTab.TabName;
11889 this.ClearTab(tb.TabName, false);
11890 _statuses.Tabs[tb.TabName] = tb;
11891 for (int i = 0; i < ListTab.TabPages.Count; i++)
11893 var tabPage = ListTab.TabPages[i];
11894 if (tb.TabName == tabPage.Text)
11896 listView = (DetailsListView)tabPage.Tag;
11897 ListTab.SelectedIndex = i;
11904 const string TabName = "Related Tweets";
11905 string renamed = TabName;
11906 for (int i = 2; i <= 100; i++)
11908 if (!_statuses.ContainsTab(renamed)) break;
11909 renamed = TabName + i.ToString();
11911 tb.TabName = renamed;
11912 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11913 _statuses.Tabs.Add(renamed, tb); // 後に
11915 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11916 listView = (DetailsListView)tabPage.Tag;
11917 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11922 string renamed = tb.TabName;
11923 for (int i = 1; i < int.MaxValue; i++)
11925 if (!_statuses.ContainsTab(renamed)) break;
11926 renamed = tb.TabName + "(" + i.ToString() + ")";
11928 tb.TabName = renamed;
11929 _statuses.Tabs.Add(renamed, tb); // 先に
11930 AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11932 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11933 listView = (DetailsListView)tabPage.Tag;
11934 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11938 if (listView != null)
11940 using (ControlTransaction.Update(listView))
11942 listView.VirtualListSize = tb.AllCount;
11948 private void doMoveToRTHome()
11950 if (_curList.SelectedIndices.Count > 0)
11952 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11953 if (post.RetweetedId != null)
11955 OpenUriAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11960 private void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11965 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11967 string name = GetUserId();
11973 if (_curList.SelectedIndices.Count == 0) return;
11976 if (!SelectTab(out tabName)) return;
11980 MoveOrCopy(ref mv, ref mk);
11982 PostFilterRule fc = new PostFilterRule();
11983 fc.FilterName = name;
11984 fc.UseNameField = true;
11985 fc.MoveMatches = mv;
11986 fc.MarkMatches = mk;
11987 fc.UseRegex = false;
11988 fc.FilterByUrl = false;
11989 _statuses.Tabs[tabName].AddFilter(fc);
11991 this.ApplyPostFilters();
11996 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
12000 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
12002 if (menuItem.Owner == this.ContextMenuPostBrowser)
12004 user = GetUserId();
12005 if (user == null) return;
12007 else if (this._curPost != null)
12009 user = this._curPost.ScreenName;
12016 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
12018 string res = this.tw.GetListsApi();
12020 if (!string.IsNullOrEmpty(res))
12022 MessageBox.Show("Failed to get lists. (" + res + ")");
12027 using (MyLists listSelectForm = new MyLists(user, this.tw))
12029 listSelectForm.ShowDialog(this);
12033 private void SearchControls_Enter(object sender, EventArgs e)
12035 Control pnl = (Control)sender;
12036 foreach (Control ctl in pnl.Controls)
12038 ctl.TabStop = true;
12042 private void SearchControls_Leave(object sender, EventArgs e)
12044 Control pnl = (Control)sender;
12045 foreach (Control ctl in pnl.Controls)
12047 ctl.TabStop = false;
12051 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12053 if (ListTab.SelectedTab != null)
12055 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12056 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12060 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12062 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12065 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12066 HashStripSplitButton.Text = HashMgr.UseHash;
12067 HashToggleMenuItem.Checked = true;
12068 HashToggleToolStripMenuItem.Checked = true;
12070 _modifySettingCommon = true;
12074 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12076 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12079 private void HashManageMenuItem_Click(object sender, EventArgs e)
12081 DialogResult rslt = DialogResult.Cancel;
12084 rslt = HashMgr.ShowDialog();
12090 this.TopMost = this._cfgCommon.AlwaysTop;
12091 if (rslt == DialogResult.Cancel) return;
12092 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12094 HashStripSplitButton.Text = HashMgr.UseHash;
12095 HashToggleMenuItem.Checked = true;
12096 HashToggleToolStripMenuItem.Checked = true;
12100 HashStripSplitButton.Text = "#[-]";
12101 HashToggleMenuItem.Checked = false;
12102 HashToggleToolStripMenuItem.Checked = false;
12104 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12106 // int sidx = StatusText.SelectionStart;
12107 // string hash = HashMgr.UseHash + " ";
12110 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12111 // hash = " " + hash;
12113 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12114 // sidx += hash.Length;
12115 // StatusText.SelectionStart = sidx;
12116 // StatusText.Focus();
12118 _modifySettingCommon = true;
12119 this.StatusText_TextChanged(null, null);
12122 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12124 HashMgr.ToggleHash();
12125 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12127 HashStripSplitButton.Text = HashMgr.UseHash;
12128 HashToggleMenuItem.Checked = true;
12129 HashToggleToolStripMenuItem.Checked = true;
12133 HashStripSplitButton.Text = "#[-]";
12134 HashToggleMenuItem.Checked = false;
12135 HashToggleToolStripMenuItem.Checked = false;
12137 _modifySettingCommon = true;
12138 this.StatusText_TextChanged(null, null);
12141 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12143 HashToggleMenuItem_Click(null, null);
12146 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12148 if (ListTab.SelectedTab == null) return;
12149 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12150 if (!this.ExistCurrentPost)
12152 this.ReplyOpMenuItem.Enabled = false;
12153 this.ReplyAllOpMenuItem.Enabled = false;
12154 this.DmOpMenuItem.Enabled = false;
12155 this.ShowProfMenuItem.Enabled = false;
12156 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12157 this.ListManageMenuItem.Enabled = false;
12158 this.OpenFavOpMenuItem.Enabled = false;
12159 this.CreateTabRuleOpMenuItem.Enabled = false;
12160 this.CreateIdRuleOpMenuItem.Enabled = false;
12161 this.CreateSourceRuleOpMenuItem.Enabled = false;
12162 this.ReadOpMenuItem.Enabled = false;
12163 this.UnreadOpMenuItem.Enabled = false;
12167 this.ReplyOpMenuItem.Enabled = true;
12168 this.ReplyAllOpMenuItem.Enabled = true;
12169 this.DmOpMenuItem.Enabled = true;
12170 this.ShowProfMenuItem.Enabled = true;
12171 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12172 this.ListManageMenuItem.Enabled = true;
12173 this.OpenFavOpMenuItem.Enabled = true;
12174 this.CreateTabRuleOpMenuItem.Enabled = true;
12175 this.CreateIdRuleOpMenuItem.Enabled = true;
12176 this.CreateSourceRuleOpMenuItem.Enabled = true;
12177 this.ReadOpMenuItem.Enabled = true;
12178 this.UnreadOpMenuItem.Enabled = true;
12181 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12183 this.FavOpMenuItem.Enabled = false;
12184 this.UnFavOpMenuItem.Enabled = false;
12185 this.OpenStatusOpMenuItem.Enabled = false;
12186 this.OpenFavotterOpMenuItem.Enabled = false;
12187 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12188 this.RtOpMenuItem.Enabled = false;
12189 this.RtUnOpMenuItem.Enabled = false;
12190 this.QtOpMenuItem.Enabled = false;
12191 this.FavoriteRetweetMenuItem.Enabled = false;
12192 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12196 this.FavOpMenuItem.Enabled = true;
12197 this.UnFavOpMenuItem.Enabled = true;
12198 this.OpenStatusOpMenuItem.Enabled = true;
12199 this.OpenFavotterOpMenuItem.Enabled = true;
12200 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12204 this.RtOpMenuItem.Enabled = false;
12205 this.FavoriteRetweetMenuItem.Enabled = false;
12209 if (_curPost.IsProtect)
12211 this.RtOpMenuItem.Enabled = false;
12212 this.RtUnOpMenuItem.Enabled = false;
12213 this.QtOpMenuItem.Enabled = false;
12214 this.FavoriteRetweetMenuItem.Enabled = false;
12215 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12219 this.RtOpMenuItem.Enabled = true;
12220 this.RtUnOpMenuItem.Enabled = true;
12221 this.QtOpMenuItem.Enabled = true;
12222 this.FavoriteRetweetMenuItem.Enabled = true;
12223 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12228 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12230 this.RefreshPrevOpMenuItem.Enabled = true;
12234 this.RefreshPrevOpMenuItem.Enabled = false;
12236 if (!this.ExistCurrentPost
12237 || _curPost.InReplyToStatusId == null)
12239 OpenRepSourceOpMenuItem.Enabled = false;
12243 OpenRepSourceOpMenuItem.Enabled = true;
12245 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12247 OpenRterHomeMenuItem.Enabled = false;
12251 OpenRterHomeMenuItem.Enabled = true;
12254 if (this.ExistCurrentPost)
12256 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12260 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12262 ContextMenuTabProperty_Opening(sender, null);
12265 public Twitter TwitterInstance
12270 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12272 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
12274 _mySpDis3 = SplitContainer3.SplitterDistance;
12275 _modifySettingLocal = true;
12279 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12281 if (_statuses.RemovedTab.Count == 0)
12283 UndoRemoveTabMenuItem.Enabled = false;
12287 UndoRemoveTabMenuItem.Enabled = true;
12289 if (ListTab.SelectedTab != null)
12291 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12292 PublicSearchQueryMenuItem.Enabled = true;
12294 PublicSearchQueryMenuItem.Enabled = false;
12298 PublicSearchQueryMenuItem.Enabled = false;
12300 if (!this.ExistCurrentPost)
12302 this.CopySTOTMenuItem.Enabled = false;
12303 this.CopyURLMenuItem.Enabled = false;
12304 this.CopyUserIdStripMenuItem.Enabled = false;
12308 this.CopySTOTMenuItem.Enabled = true;
12309 this.CopyURLMenuItem.Enabled = true;
12310 this.CopyUserIdStripMenuItem.Enabled = true;
12311 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12312 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12316 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12318 SetNotifyIconText();
12321 private void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12324 if (_curPost != null)
12326 id = _curPost.ScreenName;
12328 ShowUserStatus(id);
12331 private class GetUserInfoArgs
12335 public TwitterUser user;
12338 private void GetUserInfo_DoWork(object sender, DoWorkEventArgs e)
12340 GetUserInfoArgs args = (GetUserInfoArgs)e.Argument;
12341 e.Result = args.tw.GetUserInfo(args.id, ref args.user);
12344 private void doShowUserStatus(string id, bool ShowInputDialog)
12346 TwitterUser user = null;
12347 GetUserInfoArgs args = new GetUserInfoArgs();
12348 if (ShowInputDialog)
12350 using (InputTabName inputName = new InputTabName())
12352 inputName.FormTitle = "Show UserStatus";
12353 inputName.FormDescription = Properties.Resources.FRMessage1;
12354 inputName.TabName = id;
12355 if (inputName.ShowDialog() == DialogResult.OK &&
12356 !string.IsNullOrEmpty(inputName.TabName.Trim()))
12358 id = inputName.TabName.Trim();
12362 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12363 GetUserInfo_DoWork,
12367 _info.ShowDialog();
12368 string ret = (string)_info.Result;
12369 if (string.IsNullOrEmpty(ret))
12370 doShowUserStatus(args.user);
12372 MessageBox.Show(ret);
12382 using (FormInfo _info = new FormInfo(this, Properties.Resources.doShowUserStatusText1,
12383 GetUserInfo_DoWork,
12387 _info.ShowDialog();
12388 string ret = (string)_info.Result;
12389 if (string.IsNullOrEmpty(ret))
12391 doShowUserStatus(args.user);
12395 MessageBox.Show(ret);
12401 private async void doShowUserStatus(TwitterUser user)
12403 using (var userDialog = new UserInfoDialog(this, this.tw))
12405 var showUserTask = userDialog.ShowUserAsync(user);
12406 userDialog.ShowDialog(this);
12409 this.BringToFront();
12411 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12412 await showUserTask;
12416 private void ShowUserStatus(string id, bool ShowInputDialog)
12418 doShowUserStatus(id, ShowInputDialog);
12421 private void ShowUserStatus(string id)
12423 doShowUserStatus(id, true);
12426 private void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12428 if (NameLabel.Tag != null)
12430 string id = (string)NameLabel.Tag;
12431 if (id != tw.Username)
12438 private void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12440 if (NameLabel.Tag != null)
12442 string id = (string)NameLabel.Tag;
12443 if (id != tw.Username)
12445 RemoveCommand(id, false);
12450 private void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12452 if (NameLabel.Tag != null)
12454 string id = (string)NameLabel.Tag;
12455 if (id != tw.Username)
12457 ShowFriendship(id);
12462 private void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12464 if (NameLabel.Tag != null)
12466 string id = (string)NameLabel.Tag;
12467 ShowUserStatus(id, false);
12471 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12473 if (NameLabel.Tag != null)
12475 string id = (string)NameLabel.Tag;
12476 AddNewTabForUserTimeline(id);
12480 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12482 if (NameLabel.Tag != null)
12484 string id = (string)NameLabel.Tag;
12485 AddNewTabForSearch("@" + id);
12489 private void ShowProfileMenuItem_Click(object sender, EventArgs e)
12491 if (_curPost != null)
12493 ShowUserStatus(_curPost.ScreenName, false);
12497 private void GetRetweet_DoWork(object sender, DoWorkEventArgs e)
12502 if (_curPost.RetweetedId != null)
12504 statusid = _curPost.RetweetedId.Value;
12508 statusid = _curPost.StatusId;
12510 tw.GetStatus_Retweeted_Count(statusid, ref counter);
12512 e.Result = counter;
12515 private void RtCountMenuItem_Click(object sender, EventArgs e)
12517 if (this.ExistCurrentPost)
12519 using (FormInfo _info = new FormInfo(this, Properties.Resources.RtCountMenuItem_ClickText1,
12520 GetRetweet_DoWork))
12522 int retweet_count = 0;
12525 _info.ShowDialog();
12526 retweet_count = (int)_info.Result;
12527 if (retweet_count < 0)
12529 MessageBox.Show(Properties.Resources.RtCountText2);
12533 MessageBox.Show(retweet_count.ToString() + Properties.Resources.RtCountText1);
12539 private HookGlobalHotkey _hookGlobalHotkey;
12542 _hookGlobalHotkey = new HookGlobalHotkey(this);
12544 // この呼び出しは、Windows フォーム デザイナで必要です。
12545 InitializeComponent();
12547 // InitializeComponent() 呼び出しの後で初期化を追加します。
12549 if (!this.DesignMode)
12551 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12552 this.StatusText.Dock = DockStyle.Fill;
12555 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12556 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12557 this.gh.NotifyClicked += GrowlHelper_Callback;
12559 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12560 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12562 this.ImageSelector.Visible = false;
12563 this.ImageSelector.Enabled = false;
12564 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12566 this.ReplaceAppName();
12569 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12571 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12574 this.Visible = false;
12576 else if (Form.ActiveForm == null)
12578 this.Visible = true;
12579 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12581 this.BringToFront();
12582 this.StatusText.Focus();
12586 private void UserPicture_MouseEnter(object sender, EventArgs e)
12588 this.UserPicture.Cursor = Cursors.Hand;
12591 private void UserPicture_MouseLeave(object sender, EventArgs e)
12593 this.UserPicture.Cursor = Cursors.Default;
12596 private void UserPicture_DoubleClick(object sender, EventArgs e)
12598 if (NameLabel.Tag != null)
12600 OpenUriAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12604 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12606 this.MultiLineMenuItem.PerformClick();
12609 public PostClass CurPost
12611 get { return _curPost; }
12615 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12617 if (ImageSelector.Visible)
12618 ImageSelector.EndSelection();
12620 ImageSelector.BeginSelection();
12623 private void SelectMedia_DragEnter(DragEventArgs e)
12625 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12627 e.Effect = DragDropEffects.Copy;
12630 e.Effect = DragDropEffects.None;
12633 private void SelectMedia_DragDrop(DragEventArgs e)
12636 this.BringToFront();
12637 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12638 StatusText.Focus();
12641 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12643 TimelinePanel.Visible = false;
12644 TimelinePanel.Enabled = false;
12647 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12649 TimelinePanel.Visible = true;
12650 TimelinePanel.Enabled = true;
12651 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12654 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12656 this.AllowDrop = false;
12659 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12661 this.AllowDrop = true;
12664 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12666 if (ImageSelector.Visible)
12668 _modifySettingCommon = true;
12669 SaveConfigsAll(true);
12671 if (ImageSelector.ServiceName.Equals("Twitter"))
12672 this.StatusText_TextChanged(null, null);
12676 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12678 this.StatusText_TextChanged(null, null);
12682 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12684 using (ListManage form = new ListManage(tw))
12686 form.ShowDialog(this);
12690 public bool ModifySettingCommon
12692 set { _modifySettingCommon = value; }
12695 public bool ModifySettingLocal
12697 set { _modifySettingLocal = value; }
12700 public bool ModifySettingAtId
12702 set { _modifySettingAtId = value; }
12705 private void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12707 string link = (string)SourceLinkLabel.Tag;
12708 if (!string.IsNullOrEmpty(link) && e.Button == MouseButtons.Left)
12710 OpenUriAsync(link);
12714 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12716 string link = (string)SourceLinkLabel.Tag;
12717 if (!string.IsNullOrEmpty(link))
12719 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(link);
12723 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12725 SetStatusLabelUrl();
12728 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12730 if (this.ExistCurrentPost && !_curPost.IsDm)
12731 RtCountMenuItem.Enabled = true;
12733 RtCountMenuItem.Enabled = false;
12735 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12736 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12738 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12741 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12746 private void CopyUserId()
12748 if (_curPost == null) return;
12749 string clstr = _curPost.ScreenName;
12752 Clipboard.SetDataObject(clstr, false, 5, 100);
12754 catch (Exception ex)
12756 MessageBox.Show(ex.Message);
12760 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12762 if (this.ExistCurrentPost && !_curPost.IsDm)
12766 await this.OpenRelatedTab(this._curPost);
12768 catch (TabException ex)
12770 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12776 /// 指定されたツイートに対する関連発言タブを開きます
12778 /// <param name="post">表示する対象となるツイート</param>
12779 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12780 private async Task OpenRelatedTab(PostClass post)
12782 var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12785 if (tabRelated == null)
12787 tabName = this._statuses.MakeTabName("Related Tweets");
12789 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12790 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12792 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12793 tabRelated.UnreadManage = false;
12794 tabRelated.Notify = false;
12798 tabName = tabRelated.TabName;
12801 tabRelated.RelationTargetPost = post;
12802 this.ClearTab(tabName, false);
12804 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12806 var tabPage = this.ListTab.TabPages[i];
12807 if (tabName == tabPage.Text)
12809 this.ListTab.SelectedIndex = i;
12814 await this.GetRelatedTweetsAsync(tabRelated);
12817 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12819 StringBuilder buf = new StringBuilder();
12820 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12821 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12822 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12823 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12824 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12827 private void tw_UserIdChanged()
12829 this._modifySettingCommon = true;
12832 #region "Userstream"
12833 private bool _isActiveUserstream = false;
12835 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12839 if (InvokeRequired && !IsDisposed)
12841 Invoke((Action) (() =>
12843 _statuses.RemovePostReserve(e.StatusId);
12844 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12846 this.PurgeListViewItemCache();
12847 ((DetailsListView)_curTab.Tag).Update();
12848 if (_curPost != null && _curPost.StatusId == e.StatusId) DispSelectedPost(true);
12854 catch (ObjectDisposedException)
12858 catch (InvalidOperationException)
12864 private void tw_NewPostFromStream(object sender, EventArgs e)
12866 if (this._cfgCommon.ReadOldPosts)
12868 _statuses.SetReadHomeTab(); //新着時未読クリア
12871 int rsltAddCount = _statuses.DistributePosts();
12874 DateTime tm = DateTime.Now;
12875 if (_tlTimestamps.ContainsKey(tm))
12877 _tlTimestamps[tm] += rsltAddCount;
12881 _tlTimestamps.Add(tm, rsltAddCount);
12883 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12884 List<DateTime> keys = new List<DateTime>();
12886 foreach (DateTime key in _tlTimestamps.Keys)
12888 if (key.CompareTo(oneHour) < 0)
12891 _tlCount += _tlTimestamps[key];
12893 foreach (DateTime key in keys)
12895 _tlTimestamps.Remove(key);
12899 //Static DateTime before = Now;
12900 //if (before.Subtract(Now).Seconds > -5) return;
12904 if (this._cfgCommon.UserstreamPeriod > 0) return;
12908 if (InvokeRequired && !IsDisposed)
12910 Invoke(new Action<bool>(RefreshTimeline), true);
12914 catch (ObjectDisposedException)
12918 catch (InvalidOperationException)
12924 private void tw_UserStreamStarted(object sender, EventArgs e)
12926 this._isActiveUserstream = true;
12929 if (InvokeRequired && !IsDisposed)
12931 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12935 catch (ObjectDisposedException)
12939 catch (InvalidOperationException)
12944 MenuItemUserStream.Text = "&UserStream ▶";
12945 MenuItemUserStream.Enabled = true;
12946 StopToolStripMenuItem.Text = "&Stop";
12947 StopToolStripMenuItem.Enabled = true;
12949 StatusLabel.Text = "UserStream Started.";
12952 private void tw_UserStreamStopped(object sender, EventArgs e)
12954 this._isActiveUserstream = false;
12957 if (InvokeRequired && !IsDisposed)
12959 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12963 catch (ObjectDisposedException)
12967 catch (InvalidOperationException)
12972 MenuItemUserStream.Text = "&UserStream ■";
12973 MenuItemUserStream.Enabled = true;
12974 StopToolStripMenuItem.Text = "&Start";
12975 StopToolStripMenuItem.Enabled = true;
12977 StatusLabel.Text = "UserStream Stopped.";
12980 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12984 if (InvokeRequired && !IsDisposed)
12986 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12990 catch (ObjectDisposedException)
12994 catch (InvalidOperationException)
12998 var ev = e.EventData;
12999 StatusLabel.Text = "Event: " + ev.Event;
13000 //if (ev.Event == "favorite")
13002 // NotifyFavorite(ev);
13005 if (ev.Event == "favorite" || ev.Event == "unfavorite")
13007 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13009 this.PurgeListViewItemCache();
13010 ((DetailsListView)_curTab.Tag).Update();
13012 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13014 RemovePostFromFavTab(new long[] {ev.Id});
13019 private void NotifyEvent(Twitter.FormattedEvent ev)
13022 if (BalloonRequired(ev))
13024 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13025 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13026 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13027 StringBuilder title = new StringBuilder();
13028 if (this._cfgCommon.DispUsername)
13030 title.Append(tw.Username);
13031 title.Append(" - ");
13037 title.Append(Application.ProductName);
13038 title.Append(" [");
13039 title.Append(ev.Event.ToUpper());
13040 title.Append("] by ");
13041 if (!string.IsNullOrEmpty(ev.Username))
13043 title.Append(ev.Username.ToString());
13047 //title.Append("");
13050 if (!string.IsNullOrEmpty(ev.Target))
13052 //NotifyIcon1.BalloonTipText = ev.Target;
13057 //NotifyIcon1.BalloonTipText = " ";
13060 //NotifyIcon1.ShowBalloonTip(500);
13061 if (this._cfgCommon.IsUseNotifyGrowl)
13063 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13064 ev.Id.ToString(), title.ToString(), text);
13068 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13069 NotifyIcon1.BalloonTipTitle = title.ToString();
13070 NotifyIcon1.BalloonTipText = text;
13071 NotifyIcon1.ShowBalloonTip(500);
13076 string snd = this._cfgCommon.EventSoundFile;
13077 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13079 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13083 string dir = Application.StartupPath;
13084 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13086 dir = Path.Combine(dir, "Sounds");
13088 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13100 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13102 MenuItemUserStream.Enabled = false;
13103 if (StopRefreshAllMenuItem.Checked)
13105 StopRefreshAllMenuItem.Checked = false;
13108 if (this._isActiveUserstream)
13110 tw.StopUserStream();
13114 tw.StartUserStream();
13118 private static string inputTrack = "";
13120 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13122 if (TrackToolStripMenuItem.Checked)
13124 using (InputTabName inputForm = new InputTabName())
13126 inputForm.TabName = inputTrack;
13127 inputForm.FormTitle = "Input track word";
13128 inputForm.FormDescription = "Track word";
13129 if (inputForm.ShowDialog() != DialogResult.OK)
13131 TrackToolStripMenuItem.Checked = false;
13134 inputTrack = inputForm.TabName.Trim();
13136 if (!inputTrack.Equals(tw.TrackWord))
13138 tw.TrackWord = inputTrack;
13139 this._modifySettingCommon = true;
13140 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13141 tw.ReconnectUserStream();
13147 tw.ReconnectUserStream();
13149 this._modifySettingCommon = true;
13152 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13154 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13155 this._modifySettingCommon = true;
13156 tw.ReconnectUserStream();
13159 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13161 if (evtDialog == null || evtDialog.IsDisposed)
13164 evtDialog = new EventViewerDialog();
13165 evtDialog.Owner = this;
13167 Point pos = evtDialog.Location;
13168 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13169 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13170 evtDialog.Location = pos;
13172 evtDialog.EventSource = tw.StoredEvent;
13173 if (!evtDialog.Visible)
13175 evtDialog.Show(this);
13179 evtDialog.Activate();
13181 this.TopMost = this._cfgCommon.AlwaysTop;
13185 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13187 MyCommon._endingFlag = true;
13191 Application.Restart();
13195 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13199 private void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13201 if (!string.IsNullOrEmpty(tw.Username)) OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13204 private void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13206 OpenUriAsync(MyCommon.TwitterUrl + tw.Username);
13209 private async Task doTranslation(string str)
13211 if (string.IsNullOrEmpty(str))
13214 var bing = new Bing();
13217 var translatedText = await bing.TranslateAsync(str,
13219 langTo: this._cfgCommon.TranslateLanguage);
13221 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13223 catch (HttpRequestException e)
13225 this.StatusLabel.Text = "Err:" + e.Message;
13229 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13231 if (!this.ExistCurrentPost)
13234 await this.doTranslation(this._curPost.TextFromApi);
13237 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13239 var text = this.PostBrowser.GetSelectedText();
13240 await this.doTranslation(text);
13243 private bool ExistCurrentPost
13247 if (_curPost == null) return false;
13248 if (_curPost.IsDeleted) return false;
13253 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13255 ShowUserTimeline();
13258 private string GetUserIdFromCurPostOrInput(string caption)
13261 if (_curPost != null)
13263 id = _curPost.ScreenName;
13265 using (InputTabName inputName = new InputTabName())
13267 inputName.FormTitle = caption;
13268 inputName.FormDescription = Properties.Resources.FRMessage1;
13269 inputName.TabName = id;
13270 if (inputName.ShowDialog() == DialogResult.OK &&
13271 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13273 id = inputName.TabName.Trim();
13283 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13285 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13286 if (!string.IsNullOrEmpty(id))
13288 AddNewTabForUserTimeline(id);
13292 private void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13294 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13295 if (!string.IsNullOrEmpty(id))
13297 OpenUriAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13301 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13303 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13306 private void TimelineRefreshEnableChange(bool isEnable)
13310 tw.StartUserStream();
13314 tw.StopUserStream();
13316 TimerTimeline.Enabled = isEnable;
13319 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13321 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13324 private void OpenUserAppointUrl()
13326 if (this._cfgCommon.UserAppointUrl != null)
13328 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13330 if (_curPost != null)
13332 string xUrl = this._cfgCommon.UserAppointUrl;
13333 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13334 if (_curPost.RetweetedId != null)
13336 xUrl = xUrl.Replace("{STATUS}", _curPost.RetweetedId.ToString());
13340 xUrl = xUrl.Replace("{STATUS}", _curPost.StatusId.ToString());
13342 OpenUriAsync(xUrl);
13347 OpenUriAsync(this._cfgCommon.UserAppointUrl);
13352 private void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13354 OpenUserAppointUrl();
13357 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13359 string selText = SourceLinkLabel.Text;
13362 Clipboard.SetDataObject(selText, false, 5, 100);
13364 catch (Exception ex)
13366 MessageBox.Show(ex.Message);
13370 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13372 string selText = (string)SourceLinkLabel.Tag;
13375 Clipboard.SetDataObject(selText, false, 5, 100);
13377 catch (Exception ex)
13379 MessageBox.Show(ex.Message);
13383 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13385 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13387 SourceCopyMenuItem.Enabled = false;
13388 SourceUrlCopyMenuItem.Enabled = false;
13392 SourceCopyMenuItem.Enabled = true;
13393 SourceUrlCopyMenuItem.Enabled = true;
13397 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13399 if (Form.ActiveForm == null)
13401 this.BeginInvoke((Action) (() =>
13403 this.Visible = true;
13404 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13406 this.BringToFront();
13407 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13409 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13413 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13419 private void ReplaceAppName()
13421 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13422 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13425 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13427 this.SplitContainer3.Panel2Collapsed = false;
13429 // PreviewDistance が起動のたびに広がっていく問題の回避策
13430 // FixedPanel が Panel2 に設定された状態で Panel2 を開くと、初回だけ SplitterDistance が再計算されておかしくなるため、
13431 // None で開いた後に設定するようにする
13432 if (this.SplitContainer3.FixedPanel == FixedPanel.None)
13433 this.SplitContainer3.FixedPanel = FixedPanel.Panel2;
13436 private void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13438 this.OpenThumbnailPicture(e.Thumbnail);
13441 private void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13443 this.OpenUriAsync(e.ImageUrl);
13446 private void OpenThumbnailPicture(ThumbnailInfo thumbnail)
13448 var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13450 this.OpenUriAsync(url);
13453 private void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13455 this.OpenUriAsync(Twitter.ServiceAvailabilityStatusUrl);
13458 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13460 if (e.KeyCode == Keys.Space)
13462 this.JumpUnreadMenuItem_Click(null, null);
13464 e.SuppressKeyPress = true;
13468 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13470 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13471 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13472 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13473 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13474 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13476 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13479 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13481 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13484 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13486 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13489 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13491 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13494 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13496 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13499 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13501 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13504 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13506 if (this._cfgCommon.IconSize == iconSize) return;
13508 var oldIconCol = _iconCol;
13510 this._cfgCommon.IconSize = iconSize;
13511 ApplyListViewIconSize(iconSize);
13513 if (_iconCol != oldIconCol)
13515 foreach (TabPage tp in ListTab.TabPages)
13517 ResetColumns((DetailsListView)tp.Tag);
13521 if (_curList != null) _curList.Refresh();
13523 _modifySettingCommon = true;
13526 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13528 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13529 if (this._cfgCommon.SortOrderLock == state) return;
13531 this._cfgCommon.SortOrderLock = state;
13533 _modifySettingCommon = true;