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.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.Models;
53 using OpenTween.OpenTweenCustomControl;
54 using OpenTween.Thumbnail;
58 public partial class TweenMain : OTBaseForm
61 private Size _mySize; //画面サイズ
62 private Point _myLoc; //画面位置
63 private int _mySpDis; //区切り位置
64 private int _mySpDis2; //発言欄区切り位置
65 private int _mySpDis3; //プレビュー区切り位置
66 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
67 private bool _iconCol; //1列表示の時true(48サイズのとき)
70 private bool _initial; //true:起動時処理中
71 private bool _initialLayout = true;
72 private bool _ignoreConfigSave; //true:起動時処理中
73 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
74 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
75 private Point _tabMouseDownPoint;
76 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
77 private readonly object _syncObject = new object(); //ロック用
79 private const string detailHtmlFormatHeaderMono =
80 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
81 + "<style type=\"text/css\"><!-- "
82 + "body, p, pre {margin: 0;} "
83 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
84 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
85 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
86 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
87 + ".quote-tweet.reply {border-color: #f33;} "
88 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
90 + "</head><body><pre>";
91 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
92 private const string detailHtmlFormatHeaderColor =
93 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
94 + "<style type=\"text/css\"><!-- "
95 + "body, p, pre {margin: 0;} "
96 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
97 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
98 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
99 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
100 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
101 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
103 + "</head><body><p>";
104 private const string detailHtmlFormatFooterColor = "</p></body></html>";
105 private string detailHtmlFormatHeader;
106 private string detailHtmlFormatFooter;
108 private bool _myStatusError = false;
109 private bool _myStatusOnline = false;
110 private bool soundfileListup = false;
111 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
114 //private SettingToConfig _cfg; //旧
115 private SettingLocal _cfgLocal;
116 private SettingCommon _cfgCommon;
119 private TwitterApi twitterApi = new TwitterApi();
123 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
126 private SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
127 private OpenURL UrlDialog = new OpenURL();
128 public AtIdSupplement AtIdSupl; //@id補助
129 public AtIdSupplement HashSupl; //Hashtag補助
130 public HashtagManage HashMgr;
131 private EventViewerDialog evtDialog;
134 private Font _fntUnread; //未読用フォント
135 private Color _clUnread; //未読用文字色
136 private Font _fntReaded; //既読用フォント
137 private Color _clReaded; //既読用文字色
138 private Color _clFav; //Fav用文字色
139 private Color _clOWL; //片思い用文字色
140 private Color _clRetweet; //Retweet用文字色
141 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
142 private Font _fntDetail; //発言詳細部用フォント
143 private Color _clDetail; //発言詳細部用色
144 private Color _clDetailLink; //発言詳細部用リンク文字色
145 private Color _clDetailBackcolor; //発言詳細部用背景色
146 private Color _clSelf; //自分の発言用背景色
147 private Color _clAtSelf; //自分宛返信用背景色
148 private Color _clTarget; //選択発言者の他の発言用背景色
149 private Color _clAtTarget; //選択発言中の返信先用背景色
150 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
151 private Color _clAtTo; //選択発言の唯一@先
152 private Color _clListBackcolor; //リスト部通常発言背景色
153 private Color _clInputBackcolor; //入力欄背景色
154 private Color _clInputFont; //入力欄文字色
155 private Font _fntInputFont; //入力欄フォント
156 private ImageCache IconCache; //アイコン画像リスト
157 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
158 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
159 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
160 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
161 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
162 private Icon MainIcon; //Main.ico 画面左上のアイコン
163 private Icon ReplyIcon; //5g
164 private Icon ReplyIconBlink; //6g
166 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
168 private PostClass _anchorPost;
169 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
171 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
172 private int _hisIdx; //発言履歴カレントインデックス
174 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
175 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
178 private List<DateTime> _postTimestamps = new List<DateTime>();
179 private List<DateTime> _favTimestamps = new List<DateTime>();
180 private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
181 private int _tlCount;
184 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
185 private SolidBrush _brsBackColorMine;
186 private SolidBrush _brsBackColorAt;
187 private SolidBrush _brsBackColorYou;
188 private SolidBrush _brsBackColorAtYou;
189 private SolidBrush _brsBackColorAtFromTarget;
190 private SolidBrush _brsBackColorAtTo;
191 private SolidBrush _brsBackColorNone;
192 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
193 private StringFormat sfTab = new StringFormat();
195 //////////////////////////////////////////////////////////////////////////////////////////////////////////
196 private TabInformations _statuses;
199 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
202 /// キャッシュクリアのために null が代入されることがあるため、
203 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
204 /// 一旦ローカル変数に代入してから参照すること。
206 private ListViewItemCache _listItemCache = null;
208 internal class ListViewItemCache
210 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
211 public ListView TargetList { get; set; }
213 /// <summary>キャッシュする範囲の開始インデックス</summary>
214 public int StartIndex { get; set; }
216 /// <summary>キャッシュする範囲の終了インデックス</summary>
217 public int EndIndex { get; set; }
219 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
220 public ListViewItem[] ListItem { get; set; }
222 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
223 public PostClass[] Post { get; set; }
225 /// <summary>キャッシュされたアイテムの件数</summary>
227 => this.EndIndex - this.StartIndex + 1;
229 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool Contains(int index)
232 => index >= this.StartIndex && index <= this.EndIndex;
234 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
235 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
236 public bool IsSupersetOf(int rangeStart, int rangeEnd)
237 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
239 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
240 /// <returns>取得に成功すれば true、それ以外は false</returns>
241 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
243 if (this.Contains(index))
245 item = this.ListItem[index - this.StartIndex];
246 post = this.Post[index - this.StartIndex];
258 private TabPage _curTab;
259 private int _curItemIndex;
260 private DetailsListView _curList;
261 private PostClass _curPost;
262 private bool _isColumnChanged = false;
264 private const int MAX_WORKER_THREADS = 20;
265 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
266 private CancellationTokenSource workerCts = new CancellationTokenSource();
268 private int UnreadCounter = -1;
269 private int UnreadAtCounter = -1;
271 private string[] ColumnOrgText = new string[9];
272 private string[] ColumnText = new string[9];
274 private bool _DoFavRetweetFlags = false;
275 private bool osResumed = false;
277 //////////////////////////////////////////////////////////////////////////////////////////////////////////
278 private string _postBrowserStatusText = "";
280 private bool _colorize = false;
282 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
284 private ImageListViewItem displayItem;
286 private string recommendedStatusFooter;
289 private struct urlUndo
291 public string Before;
295 private List<urlUndo> urlUndoBuffer = null;
297 private struct ReplyChain
299 public long OriginalId;
300 public long InReplyToId;
301 public TabPage OriginalTab;
303 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
305 this.OriginalId = originalId;
306 this.InReplyToId = inReplyToId;
307 this.OriginalTab = originalTab;
311 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
312 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
315 private enum SEARCHTYPE
322 private class PostingStatus
324 public string status = "";
325 public long? inReplyToId = null;
326 public string inReplyToName = null;
327 public string imageService = ""; //画像投稿サービス名
328 public IMediaItem[] mediaItems = null;
329 public PostingStatus()
332 public PostingStatus(string status, long? replyToId, string replyToName)
334 this.status = status;
335 this.inReplyToId = replyToId;
336 this.inReplyToName = replyToName;
340 private void TweenMain_Activated(object sender, EventArgs e)
342 //画面がアクティブになったら、発言欄の背景色戻す
343 if (StatusText.Focused)
345 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
349 private bool disposed = false;
352 /// 使用中のリソースをすべてクリーンアップします。
354 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
355 protected override void Dispose(bool disposing)
357 base.Dispose(disposing);
364 this.components?.Dispose();
367 SearchDialog.Dispose();
370 NIconAtRed?.Dispose();
371 NIconAtSmoke?.Dispose();
372 foreach (var iconRefresh in this.NIconRefresh)
374 iconRefresh?.Dispose();
378 ReplyIcon?.Dispose();
379 ReplyIconBlink?.Dispose();
380 _listViewImageList.Dispose();
381 _brsHighLight.Dispose();
382 _brsBackColorMine?.Dispose();
383 _brsBackColorAt?.Dispose();
384 _brsBackColorYou?.Dispose();
385 _brsBackColorAtYou?.Dispose();
386 _brsBackColorAtFromTarget?.Dispose();
387 _brsBackColorAtTo?.Dispose();
388 _brsBackColorNone?.Dispose();
389 _brsDeactiveSelection?.Dispose();
393 this.workerCts.Cancel();
395 if (IconCache != null)
397 this.IconCache.CancelAsync();
398 this.IconCache.Dispose();
401 this.thumbnailTokenSource?.Dispose();
404 this.twitterApi.Dispose();
405 this._hookGlobalHotkey.Dispose();
408 // 終了時にRemoveHandlerしておかないとメモリリークする
409 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
410 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
412 this.disposed = true;
415 private void LoadIcons()
417 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
418 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
421 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
424 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
427 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
430 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
432 // タスクトレイ: オフライン時アイコン
433 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
435 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
436 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
437 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
439 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
440 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
441 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
442 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
443 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
445 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
447 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
448 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
449 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
450 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
451 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
453 if (iconReply != null && iconReplyBlink != null)
455 this.ReplyIcon = iconReply;
456 this.ReplyIconBlink = iconReplyBlink;
460 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
461 this.ReplyIconBlink = this.NIconAt;
464 if (iconRefresh1 == null)
466 this.NIconRefresh = new[] {
467 Properties.Resources.Refresh, Properties.Resources.Refresh2,
468 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
471 else if (iconRefresh2 == null)
473 this.NIconRefresh = new[] { iconRefresh1 };
475 else if (iconRefresh3 == null)
477 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
479 else if (iconRefresh4 == null)
481 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
483 else // iconRefresh1 から iconRefresh4 まで全て揃っている
485 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
489 private Icon LoadIcon(string filePath)
491 if (!File.Exists(filePath))
496 return new Icon(filePath);
504 private void InitColumns(ListView list, bool startup)
506 this.InitColumnText();
508 ColumnHeader[] columns = null;
515 new ColumnHeader(), // アイコン
516 new ColumnHeader(), // 本文
519 columns[0].Text = this.ColumnText[0];
520 columns[1].Text = this.ColumnText[2];
524 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
526 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
527 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
528 columns[0].DisplayIndex = 0;
529 columns[1].DisplayIndex = 1;
534 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
536 columns[idx].Width = curListColumn.Width;
537 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
546 new ColumnHeader(), // アイコン
547 new ColumnHeader(), // ニックネーム
548 new ColumnHeader(), // 本文
549 new ColumnHeader(), // 日付
550 new ColumnHeader(), // ユーザID
551 new ColumnHeader(), // 未読
552 new ColumnHeader(), // マーク&プロテクト
553 new ColumnHeader(), // ソース
556 foreach (var i in Enumerable.Range(0, columns.Length))
557 columns[i].Text = this.ColumnText[i];
561 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
563 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
564 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
565 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
566 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
567 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
568 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
569 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
570 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
572 var displayIndex = new[] {
573 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
574 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
575 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
576 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
579 foreach (var i in Enumerable.Range(0, displayIndex.Length))
581 columns[i].DisplayIndex = displayIndex[i];
587 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
589 columns[idx].Width = curListColumn.Width;
590 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
596 list.Columns.AddRange(columns);
604 foreach (var column in columns)
610 private void InitColumnText()
613 ColumnText[1] = Properties.Resources.AddNewTabText2;
614 ColumnText[2] = Properties.Resources.AddNewTabText3;
615 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
616 ColumnText[4] = Properties.Resources.AddNewTabText5;
619 ColumnText[7] = "Source";
621 ColumnOrgText[0] = "";
622 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
623 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
624 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
625 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
626 ColumnOrgText[5] = "";
627 ColumnOrgText[6] = "";
628 ColumnOrgText[7] = "Source";
631 switch (_statuses.SortMode)
633 case ComparerMode.Nickname: //ニックネーム
636 case ComparerMode.Data: //本文
639 case ComparerMode.Id: //時刻=発言Id
642 case ComparerMode.Name: //名前
645 case ComparerMode.Source: //Source
652 if (_statuses.SortOrder == SortOrder.Descending)
654 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
655 ColumnText[2] = ColumnOrgText[2] + "▾";
659 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
660 ColumnText[2] = ColumnOrgText[2] + "▴";
665 if (_statuses.SortOrder == SortOrder.Descending)
667 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
668 ColumnText[c] = ColumnOrgText[c] + "▾";
672 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
673 ColumnText[c] = ColumnOrgText[c] + "▴";
678 private void InitializeTraceFrag()
681 TraceOutToolStripMenuItem.Checked = true;
682 MyCommon.TraceFlag = true;
684 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
686 TraceOutToolStripMenuItem.Checked = true;
687 MyCommon.TraceFlag = true;
691 private void TweenMain_Load(object sender, EventArgs e)
693 _ignoreConfigSave = true;
694 this.Visible = false;
696 if (MyApplication.StartupOptions.ContainsKey("d"))
697 MyCommon.TraceFlag = true;
699 InitializeTraceFrag();
701 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
703 new InternetSecurityManager(PostBrowser);
704 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
706 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
707 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
709 Regex.CacheSize = 100;
712 _statuses = TabInformations.GetInstance();
716 this.Icon = MainIcon; //メインフォーム(TweenMain)
717 NotifyIcon1.Icon = NIconAt; //タスクトレイ
718 TabImage.Images.Add(TabIcon); //タブ見出し
720 //<<<<<<<<<設定関連>>>>>>>>>
724 // 現在の DPI と設定保存時の DPI との比を取得する
725 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
728 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
729 if (fontUIGlobal != null)
731 OTBaseForm.GlobalFont = fontUIGlobal;
732 this.Font = fontUIGlobal;
736 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
738 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
739 this._cfgCommon.TimelinePeriod = 15;
741 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
742 this._cfgCommon.ReplyPeriod = 15;
744 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
745 this._cfgCommon.DMPeriod = 15;
747 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
748 this._cfgCommon.PubSearchPeriod = 30;
750 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
751 this._cfgCommon.UserTimelinePeriod = 15;
753 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
754 this._cfgCommon.ListsPeriod = 15;
757 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
758 this._cfgCommon.CountApi = 60;
759 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
760 this._cfgCommon.CountApiReply = 40;
762 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
763 this._cfgCommon.MoreCountApi = 200;
764 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
765 this._cfgCommon.FirstCountApi = 100;
767 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
768 this._cfgCommon.FavoritesCountApi = 40;
769 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
770 this._cfgCommon.ListCountApi = 100;
771 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
772 this._cfgCommon.SearchCountApi = 100;
773 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
774 this._cfgCommon.UserTimelineCountApi = 20;
776 //廃止サービスが選択されていた場合ux.nuへ読み替え
777 if (this._cfgCommon.AutoShortUrlFirst < 0)
778 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
780 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
781 this.tw = new Twitter(this.twitterApi);
784 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
785 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
789 Networking.Initialize();
791 bool saveRequired = false;
792 bool firstRun = false;
794 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
795 if (string.IsNullOrEmpty(tw.Username))
800 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
801 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
802 string.IsNullOrEmpty(tw.Username))
804 Application.Exit(); //強制終了
810 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
811 Networking.SetWebProxy(this._cfgLocal.ProxyType,
812 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
813 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
814 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
816 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
817 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
818 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
819 tw.TrackWord = this._cfgCommon.TrackWord;
820 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
821 tw.AllAtReply = this._cfgCommon.AllAtReply;
822 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
823 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
824 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
825 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
827 // アクセストークンが有効であるか確認する
828 // ここが Twitter API への最初のアクセスになるようにすること
831 this.tw.VerifyCredentials();
833 catch (WebApiException ex)
835 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
836 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
840 //プロキシ設定等の通信まわりの初期化が済んでから処理する
841 ThumbnailGenerator.InitializeGenerator();
843 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
844 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
845 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
847 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
850 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
853 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
854 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
855 HashMgr = new HashtagManage(HashSupl,
856 _cfgCommon.HashTags.ToArray(),
857 _cfgCommon.HashSelected,
858 _cfgCommon.HashIsPermanent,
859 _cfgCommon.HashIsHead,
860 _cfgCommon.HashIsNotAddToAtReply);
861 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
864 this.IconCache = new ImageCache();
867 _fntUnread = this._cfgLocal.FontUnread;
868 _clUnread = this._cfgLocal.ColorUnread;
869 _fntReaded = this._cfgLocal.FontRead;
870 _clReaded = this._cfgLocal.ColorRead;
871 _clFav = this._cfgLocal.ColorFav;
872 _clOWL = this._cfgLocal.ColorOWL;
873 _clRetweet = this._cfgLocal.ColorRetweet;
874 _fntDetail = this._cfgLocal.FontDetail;
875 _clDetail = this._cfgLocal.ColorDetail;
876 _clDetailLink = this._cfgLocal.ColorDetailLink;
877 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
878 _clSelf = this._cfgLocal.ColorSelf;
879 _clAtSelf = this._cfgLocal.ColorAtSelf;
880 _clTarget = this._cfgLocal.ColorTarget;
881 _clAtTarget = this._cfgLocal.ColorAtTarget;
882 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
883 _clAtTo = this._cfgLocal.ColorAtTo;
884 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
885 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
886 _clInputFont = this._cfgLocal.ColorInputFont;
887 _fntInputFont = this._cfgLocal.FontInputFont;
889 _brsBackColorMine = new SolidBrush(_clSelf);
890 _brsBackColorAt = new SolidBrush(_clAtSelf);
891 _brsBackColorYou = new SolidBrush(_clTarget);
892 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
893 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
894 _brsBackColorAtTo = new SolidBrush(_clAtTo);
895 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
896 _brsBackColorNone = new SolidBrush(_clListBackcolor);
898 // StringFormatオブジェクトへの事前設定
899 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
900 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
901 //sf.FormatFlags = StringFormatFlags.LineLimit; //
902 sfTab.Alignment = StringAlignment.Center;
903 sfTab.LineAlignment = StringAlignment.Center;
905 InitDetailHtmlFormat();
907 //Regex statregex = new Regex("^0*");
908 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
910 _history.Add(new PostingStatus());
912 this.inReplyTo = null;
915 SearchDialog.Owner = this;
916 UrlDialog.Owner = this;
919 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
920 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
922 //新着取得時のリストスクロールをするか。trueならスクロールしない
923 ListLockMenuItem.Checked = _cfgCommon.ListLock;
924 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
926 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
927 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
929 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
930 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
933 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
934 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
935 _myLoc = _cfgLocal.FormLocation;
937 if (this.WindowState != FormWindowState.Minimized)
939 this.DesktopLocation = _cfgLocal.FormLocation;
940 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
941 bool outOfScreen = true;
942 if (Screen.AllScreens.Length == 1) //ハングするとの報告
944 foreach (Screen scr in Screen.AllScreens)
946 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
954 this.DesktopLocation = new Point(0, 0);
955 _myLoc = this.DesktopLocation;
959 this.TopMost = this._cfgCommon.AlwaysTop;
960 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
961 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
962 if (_cfgLocal.PreviewDistance == -1)
964 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
965 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
966 _cfgLocal.PreviewDistance = _mySpDis3;
970 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
972 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
973 //this.Tween_ClientSizeChanged(this, null);
974 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
975 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
977 StatusText.Font = _fntInputFont;
978 StatusText.ForeColor = _clInputFont;
980 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
981 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
982 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
984 // NameLabel のフォントを OTBaseForm.GlobalFont に変更
985 this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
987 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
988 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
990 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
991 if (this._cfgCommon.UnreadManage == false)
993 ReadedStripMenuItem.Enabled = false;
994 UnreadStripMenuItem.Enabled = false;
999 DateTimeLabel.Text = "";
1000 SourceLinkLabel.Text = "";
1002 //リンク先URL表示部の初期化(画面左下)
1003 StatusLabelUrl.Text = "";
1005 StatusLabel.Text = "";
1006 StatusLabel.AutoToolTip = false;
1007 StatusLabel.ToolTipText = "";
1009 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1011 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1012 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1013 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1014 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1016 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1017 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1018 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1019 this.SplitContainer2.Panel2.AccessibleName = "";
1021 ////////////////////////////////////////////////////////////////////////////////
1022 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1023 var mode = ComparerMode.Id;
1024 switch (_cfgCommon.SortColumn)
1026 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1030 mode = ComparerMode.Id; //Idソートに読み替え
1033 mode = ComparerMode.Nickname;
1036 mode = ComparerMode.Data;
1039 mode = ComparerMode.Id;
1042 mode = ComparerMode.Name;
1045 mode = ComparerMode.Source;
1048 _statuses.SetSortMode(mode, sortOrder);
1049 ////////////////////////////////////////////////////////////////////////////////
1051 ApplyListViewIconSize(this._cfgCommon.IconSize);
1053 //<<<<<<<<タブ関連>>>>>>>
1057 //デフォルトタブの存在チェック、ない場合には追加
1058 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1059 this._statuses.AddTab(new HomeTabModel());
1061 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1062 this._statuses.AddTab(new MentionsTabModel());
1064 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1065 this._statuses.AddTab(new DirectMessagesTabModel());
1067 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1068 this._statuses.AddTab(new FavoritesTabModel());
1070 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1071 this._statuses.AddTab(new MuteTabModel());
1073 foreach (var tab in _statuses.Tabs.Values)
1076 if (tab.TabType == MyCommon.TabUsageType.Mute)
1079 if (!AddNewTab(tab, startup: true))
1080 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1083 _curTab = ListTab.SelectedTab;
1085 _curList = (DetailsListView)_curTab.Tag;
1087 if (this._cfgCommon.TabIconDisp)
1089 ListTab.DrawMode = TabDrawMode.Normal;
1093 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1094 ListTab.DrawItem += ListTab_DrawItem;
1095 ListTab.ImageList = null;
1098 if (this._cfgCommon.HotkeyEnabled)
1101 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1102 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1103 modKey |= HookGlobalHotkey.ModKeys.Alt;
1104 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1105 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1106 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1107 modKey |= HookGlobalHotkey.ModKeys.Shift;
1108 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1109 modKey |= HookGlobalHotkey.ModKeys.Win;
1111 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1114 if (this._cfgCommon.IsUseNotifyGrowl)
1117 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1119 SetMainWindowTitle();
1120 SetNotifyIconText();
1122 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1124 this.Visible = true;
1128 TimerTimeline.AutoReset = true;
1129 TimerTimeline.SynchronizingObject = this;
1131 TimerTimeline.Interval = 1000;
1132 TimerTimeline.Enabled = true;
1134 TimerRefreshIcon.Interval = 200;
1135 TimerRefreshIcon.Enabled = true;
1137 _ignoreConfigSave = false;
1138 this.TweenMain_Resize(null, null);
1139 if (saveRequired) SaveConfigsAll(false);
1141 foreach (var ua in this._cfgCommon.UserAccounts)
1143 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1145 ua.UserId = tw.UserId;
1152 // 初回起動時だけ右下のメニューを目立たせる
1153 HashStripSplitButton.ShowDropDown();
1157 private void InitDetailHtmlFormat()
1159 if (this._cfgCommon.IsMonospace)
1161 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1162 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1166 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1167 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1170 detailHtmlFormatHeader = detailHtmlFormatHeader
1171 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1172 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1173 .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1174 .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1175 .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1176 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1179 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1184 txt = ListTab.TabPages[e.Index].Text;
1191 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1192 if (e.State == DrawItemState.Selected)
1194 e.DrawFocusRectangle();
1199 if (_statuses.Tabs[txt].UnreadCount > 0)
1202 fore = System.Drawing.SystemBrushes.ControlText;
1206 fore = System.Drawing.SystemBrushes.ControlText;
1208 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1211 private void LoadConfig()
1213 _cfgCommon = SettingCommon.Load();
1214 SettingCommon.Instance = this._cfgCommon;
1215 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1217 _cfgCommon.UserAccounts = new List<UserAccount>();
1218 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1220 UserAccount account = new UserAccount();
1221 account.Username = _cfgCommon.UserName;
1222 account.UserId = _cfgCommon.UserId;
1223 account.Token = _cfgCommon.Token;
1224 account.TokenSecret = _cfgCommon.TokenSecret;
1226 _cfgCommon.UserAccounts.Add(account);
1230 _cfgLocal = SettingLocal.Load();
1232 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1233 if (_cfgLocal.ScaleDimension.IsEmpty)
1234 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1236 var tabsSetting = SettingTabs.Load().Tabs;
1237 foreach (var tabSetting in tabsSetting)
1240 switch (tabSetting.TabType)
1242 case MyCommon.TabUsageType.Home:
1243 tab = new HomeTabModel(tabSetting.TabName);
1245 case MyCommon.TabUsageType.Mentions:
1246 tab = new MentionsTabModel(tabSetting.TabName);
1248 case MyCommon.TabUsageType.DirectMessage:
1249 tab = new DirectMessagesTabModel(tabSetting.TabName);
1251 case MyCommon.TabUsageType.Favorites:
1252 tab = new FavoritesTabModel(tabSetting.TabName);
1254 case MyCommon.TabUsageType.UserDefined:
1255 tab = new FilterTabModel(tabSetting.TabName);
1257 case MyCommon.TabUsageType.UserTimeline:
1258 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1260 case MyCommon.TabUsageType.PublicSearch:
1261 tab = new PublicSearchTabModel(tabSetting.TabName)
1263 SearchWords = tabSetting.SearchWords,
1264 SearchLang = tabSetting.SearchLang,
1267 case MyCommon.TabUsageType.Lists:
1268 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1270 case MyCommon.TabUsageType.Mute:
1271 tab = new MuteTabModel(tabSetting.TabName);
1277 tab.UnreadManage = tabSetting.UnreadManage;
1278 tab.Protected = tabSetting.Protected;
1279 tab.Notify = tabSetting.Notify;
1280 tab.SoundFile = tabSetting.SoundFile;
1282 if (tab.IsDistributableTabType)
1284 var filterTab = (FilterTabModel)tab;
1285 filterTab.FilterArray = tabSetting.FilterArray;
1286 filterTab.FilterModified = false;
1289 if (this._statuses.ContainsTab(tab.TabName))
1290 tab.TabName = this._statuses.MakeTabName("MyTab");
1292 this._statuses.AddTab(tab);
1294 if (_statuses.Tabs.Count == 0)
1296 _statuses.AddTab(new HomeTabModel());
1297 _statuses.AddTab(new MentionsTabModel());
1298 _statuses.AddTab(new DirectMessagesTabModel());
1299 _statuses.AddTab(new FavoritesTabModel());
1303 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1305 if (!TimerTimeline.Enabled) return;
1309 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1311 private static int homeCounter = 0;
1312 private static int mentionCounter = 0;
1313 private static int dmCounter = 0;
1314 private static int pubSearchCounter = 0;
1315 private static int userTimelineCounter = 0;
1316 private static int listsCounter = 0;
1317 private static int usCounter = 0;
1318 private static int ResumeWait = 0;
1319 private static int refreshFollowers = 0;
1321 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1323 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1324 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1325 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1326 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1327 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1328 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1329 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1330 Interlocked.Increment(ref refreshFollowers);
1332 var refreshTasks = new List<Task>();
1335 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1337 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1338 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1339 refreshTasks.Add(this.GetHomeTimelineAsync());
1340 ResetTimers.Timeline = false;
1342 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1344 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1345 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1346 refreshTasks.Add(this.GetReplyAsync());
1347 ResetTimers.Reply = false;
1349 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1351 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1352 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1353 refreshTasks.Add(this.GetDirectMessagesAsync());
1354 ResetTimers.DirectMessage = false;
1356 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1358 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1359 if (!ResetTimers.PublicSearch)
1360 refreshTasks.Add(this.GetPublicSearchAllAsync());
1361 ResetTimers.PublicSearch = false;
1363 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1365 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1366 if (!ResetTimers.UserTimeline)
1367 refreshTasks.Add(this.GetUserTimelineAllAsync());
1368 ResetTimers.UserTimeline = false;
1370 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1372 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1373 if (!ResetTimers.Lists)
1374 refreshTasks.Add(this.GetListTimelineAllAsync());
1375 ResetTimers.Lists = false;
1377 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1379 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1380 if (this.tw.UserStreamActive)
1381 this.RefreshTimeline();
1382 ResetTimers.UserStream = false;
1384 if (refreshFollowers > 6 * 3600)
1386 Interlocked.Exchange(ref refreshFollowers, 0);
1387 refreshTasks.AddRange(new[]
1389 this.doGetFollowersMenu(),
1390 this.RefreshNoRetweetIdsAsync(),
1391 this.RefreshTwitterConfigurationAsync(),
1396 Interlocked.Increment(ref ResumeWait);
1397 if (ResumeWait > 30)
1400 Interlocked.Exchange(ref ResumeWait, 0);
1401 refreshTasks.AddRange(new[]
1403 this.GetHomeTimelineAsync(),
1404 this.GetReplyAsync(),
1405 this.GetDirectMessagesAsync(),
1406 this.GetPublicSearchAllAsync(),
1407 this.GetUserTimelineAllAsync(),
1408 this.GetListTimelineAllAsync(),
1409 this.doGetFollowersMenu(),
1410 this.RefreshTwitterConfigurationAsync(),
1415 await Task.WhenAll(refreshTasks);
1418 private void RefreshTimeline()
1420 // 現在表示中のタブのスクロール位置を退避
1421 var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1423 // 各タブのリスト上の選択位置などを退避
1424 var listSelections = this.SaveListViewSelection();
1427 PostClass[] notifyPosts;
1430 bool newMentionOrDm;
1432 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1434 if (MyCommon._endingFlag) return;
1439 foreach (TabPage tab in ListTab.TabPages)
1441 DetailsListView lst = (DetailsListView)tab.Tag;
1442 TabModel tabInfo = _statuses.Tabs[tab.Text];
1443 if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1445 using (ControlTransaction.Update(lst))
1447 if (lst.Equals(_curList))
1449 this.PurgeListViewItemCache();
1453 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1461 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1464 if (tabInfo.UnreadCount > 0)
1465 if (this._cfgCommon.TabIconDisp)
1466 if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1468 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1472 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1477 this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1480 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1482 SetMainWindowTitle();
1483 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1485 HashSupl.AddRangeItem(tw.GetHashList());
1489 internal struct ListViewScroll
1491 public ScrollLockMode ScrollLockMode { get; set; }
1492 public long? TopItemStatusId { get; set; }
1495 internal enum ScrollLockMode
1497 /// <summary>固定しない</summary>
1500 /// <summary>最上部に固定する</summary>
1503 /// <summary>最下部に固定する</summary>
1506 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1511 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1513 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1515 var listScroll = new ListViewScroll
1517 ScrollLockMode = this.GetScrollLockMode(listView),
1520 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1522 var topItem = listView.TopItem;
1523 if (topItem != null)
1524 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1530 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1532 if (this._statuses.SortMode == ComparerMode.Id)
1534 if (this._statuses.SortOrder == SortOrder.Ascending)
1537 if (this.ListLockMenuItem.Checked)
1538 return ScrollLockMode.None;
1540 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1543 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1544 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1545 return ScrollLockMode.FixedToBottom;
1547 return ScrollLockMode.None;
1552 if (this.ListLockMenuItem.Checked)
1553 return ScrollLockMode.FixedToItem;
1555 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1556 var topItem = listView.TopItem;
1557 if (topItem == null || topItem.Index == 0)
1558 return ScrollLockMode.FixedToTop;
1560 return ScrollLockMode.FixedToItem;
1565 return ScrollLockMode.FixedToItem;
1569 internal struct ListViewSelection
1571 public long[] SelectedStatusIds { get; set; }
1572 public long? SelectionMarkStatusId { get; set; }
1573 public long? FocusedStatusId { get; set; }
1577 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1579 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1581 var listsDict = new Dictionary<string, ListViewSelection>();
1583 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1585 var listView = (DetailsListView)tabPage.Tag;
1586 var tab = _statuses.Tabs[tabPage.Text];
1588 ListViewSelection listStatus;
1589 if (listView.VirtualListSize != 0)
1591 listStatus = new ListViewSelection
1593 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1594 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1595 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1600 listStatus = new ListViewSelection
1602 SelectedStatusIds = new long[0],
1603 SelectionMarkStatusId = null,
1604 FocusedStatusId = null,
1608 listsDict[tab.TabName] = listStatus;
1614 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1616 var selectedIndices = listView.SelectedIndices;
1617 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1618 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1623 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1625 var focusedItem = listView.FocusedItem;
1627 return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1630 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1632 var selectionMarkIndex = listView.SelectionMark;
1634 return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1638 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1640 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1642 if (listView.VirtualListSize == 0)
1645 switch (listScroll.ScrollLockMode)
1647 case ScrollLockMode.FixedToTop:
1648 listView.EnsureVisible(0);
1650 case ScrollLockMode.FixedToBottom:
1651 listView.EnsureVisible(listView.VirtualListSize - 1);
1653 case ScrollLockMode.FixedToItem:
1654 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1656 listView.TopItem = listView.Items[topIndex];
1658 case ScrollLockMode.None:
1665 /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1667 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1669 // status_id から ListView 上のインデックスに変換
1670 int[] selectedIndices = null;
1671 if (listSelection.SelectedStatusIds != null)
1672 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1674 var focusedIndex = -1;
1675 if (listSelection.FocusedStatusId != null)
1676 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1678 var selectionMarkIndex = -1;
1679 if (listSelection.SelectionMarkStatusId != null)
1680 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1682 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1685 private bool BalloonRequired()
1687 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1688 ev.Eventtype = MyCommon.EVENTTYPE.None;
1690 return BalloonRequired(ev);
1693 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1695 if (type == MyCommon.EVENTTYPE.None)
1698 if (!this._cfgCommon.EventNotifyEnabled)
1701 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1704 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1709 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1712 private bool BalloonRequired(Twitter.FormattedEvent ev)
1717 if (NativeMethods.IsScreenSaverRunning())
1721 if (!this.NewPostPopMenuItem.Checked)
1723 // 「新着通知が無効でもイベントを通知する」にも該当しない
1724 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1728 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1729 if (this._cfgCommon.LimitBalloon)
1731 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1735 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1738 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1740 if (this._cfgCommon.ReadOwnPost)
1742 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1747 if (BalloonRequired())
1749 if (notifyPosts != null && notifyPosts.Length > 0)
1751 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1752 if (this._cfgCommon.IsUseNotifyGrowl)
1754 StringBuilder sb = new StringBuilder();
1758 foreach (PostClass post in notifyPosts)
1760 if (!(notifyPosts.Length > 3))
1766 if (post.IsReply && !post.IsExcludeReply) reply = true;
1767 if (post.IsDm) dm = true;
1768 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1769 switch (this._cfgCommon.NameBalloon)
1771 case MyCommon.NameBalloonEnum.UserID:
1772 sb.Append(post.ScreenName).Append(" : ");
1774 case MyCommon.NameBalloonEnum.NickName:
1775 sb.Append(post.Nickname).Append(" : ");
1778 sb.Append(post.TextFromApi);
1779 if (notifyPosts.Length > 3)
1781 if (notifyPosts.Last() != post) continue;
1784 StringBuilder title = new StringBuilder();
1785 GrowlHelper.NotifyType nt;
1786 if (this._cfgCommon.DispUsername)
1788 title.Append(tw.Username);
1789 title.Append(" - ");
1797 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1798 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1799 title.Append(Application.ProductName);
1800 title.Append(" [DM] ");
1801 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1802 nt = GrowlHelper.NotifyType.DirectMessage;
1806 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1807 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1808 title.Append(Application.ProductName);
1809 title.Append(" [Reply!] ");
1810 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1811 nt = GrowlHelper.NotifyType.Reply;
1815 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1816 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1817 title.Append(Application.ProductName);
1819 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1820 nt = GrowlHelper.NotifyType.Notify;
1822 string bText = sb.ToString();
1823 if (string.IsNullOrEmpty(bText)) return;
1825 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1826 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1831 StringBuilder sb = new StringBuilder();
1834 foreach (PostClass post in notifyPosts)
1836 if (post.IsReply && !post.IsExcludeReply) reply = true;
1837 if (post.IsDm) dm = true;
1838 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1839 switch (this._cfgCommon.NameBalloon)
1841 case MyCommon.NameBalloonEnum.UserID:
1842 sb.Append(post.ScreenName).Append(" : ");
1844 case MyCommon.NameBalloonEnum.NickName:
1845 sb.Append(post.Nickname).Append(" : ");
1848 sb.Append(post.TextFromApi);
1851 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1852 StringBuilder title = new StringBuilder();
1854 if (this._cfgCommon.DispUsername)
1856 title.Append(tw.Username);
1857 title.Append(" - ");
1865 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1866 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1867 ntIcon = ToolTipIcon.Warning;
1868 title.Append(Application.ProductName);
1869 title.Append(" [DM] ");
1870 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1874 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1875 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1876 ntIcon = ToolTipIcon.Warning;
1877 title.Append(Application.ProductName);
1878 title.Append(" [Reply!] ");
1879 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1883 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1884 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1885 ntIcon = ToolTipIcon.Info;
1886 title.Append(Application.ProductName);
1888 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1890 string bText = sb.ToString();
1891 if (string.IsNullOrEmpty(bText)) return;
1892 //NotifyIcon1.BalloonTipText = sb.ToString();
1893 //NotifyIcon1.ShowBalloonTip(500);
1894 NotifyIcon1.BalloonTipTitle = title.ToString();
1895 NotifyIcon1.BalloonTipText = bText;
1896 NotifyIcon1.BalloonTipIcon = ntIcon;
1897 NotifyIcon1.ShowBalloonTip(500);
1903 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1907 string dir = Application.StartupPath;
1908 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1910 dir = Path.Combine(dir, "Sounds");
1912 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1922 //mentions新着時に画面ブリンク
1923 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1925 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1929 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1931 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1933 _curItemIndex = _curList.SelectedIndices[0];
1934 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1938 this._curPost = GetCurTabPost(_curItemIndex);
1940 catch (ArgumentException)
1945 this.PushSelectPostChain();
1947 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1949 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1955 private void ChangeCacheStyleRead(bool Read, int Index)
1957 var tabInfo = _statuses.Tabs[_curTab.Text];
1958 //Read:true=既読 false=未読
1959 //未読管理していなかったら既読として扱う
1960 if (!tabInfo.UnreadManage ||
1961 !this._cfgCommon.UnreadManage) Read = true;
1963 var listCache = this._listItemCache;
1964 if (listCache == null)
1967 // キャッシュに含まれていないアイテムは対象外
1970 if (!listCache.TryGetValue(Index, out itm, out post))
1973 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1976 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1983 Item.SubItems[5].Text = "";
1988 Item.SubItems[5].Text = "★";
1994 else if (Post.RetweetedId != null)
1996 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1998 else if (Read || !this._cfgCommon.UseUnreadStyle)
2003 if (DList == null || Item.Index == -1)
2005 Item.ForeColor = cl;
2006 if (this._cfgCommon.UseUnreadStyle)
2012 if (this._cfgCommon.UseUnreadStyle)
2013 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2015 DList.ChangeItemForeColor(Item.Index, cl);
2016 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2020 private void ColorizeList()
2022 //Index:更新対象のListviewItem.Index。Colorを返す。
2023 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2026 _post = _anchorPost;
2030 if (_post == null) return;
2032 var listCache = this._listItemCache;
2033 if (listCache == null)
2036 var index = listCache.StartIndex;
2037 foreach (var cachedPost in listCache.Post)
2039 var backColor = this.JudgeColor(_post, cachedPost);
2040 this._curList.ChangeItemBackColor(index++, backColor);
2044 private void ColorizeList(ListViewItem Item, int Index)
2046 //Index:更新対象のListviewItem.Index。Colorを返す。
2047 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2050 _post = _anchorPost;
2054 PostClass tPost = GetCurTabPost(Index);
2056 if (_post == null) return;
2058 if (Item.Index == -1)
2059 Item.BackColor = JudgeColor(_post, tPost);
2061 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2064 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2067 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2070 else if (TargetPost.IsMe)
2073 else if (TargetPost.IsReply)
2076 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2078 cl = _clAtFromTarget;
2079 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2082 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2087 cl = _clListBackcolor;
2092 private async void PostButton_Click(object sender, EventArgs e)
2094 if (StatusText.Text.Trim().Length == 0)
2096 if (!ImageSelector.Enabled)
2098 await this.DoRefresh();
2103 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2105 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2107 MessageBoxButtons.YesNoCancel,
2108 MessageBoxIcon.Question);
2111 case DialogResult.Yes:
2112 StatusText.Text = "";
2113 await this.doReTweetOfficial(false);
2115 case DialogResult.Cancel:
2120 var inReplyToStatusId = this.inReplyTo?.Item1;
2121 var inReplyToScreenName = this.inReplyTo?.Item2;
2122 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2124 if (this._cfgCommon.Nicoms)
2126 StatusText.SelectionStart = StatusText.Text.Length;
2127 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2129 //if (SettingDialog.UrlConvertAuto)
2131 // StatusText.SelectionStart = StatusText.Text.Length;
2132 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2134 //else if (SettingDialog.Nicoms)
2136 // StatusText.SelectionStart = StatusText.Text.Length;
2137 // UrlConvert(UrlConverter.Nicoms);
2139 StatusText.SelectionStart = StatusText.Text.Length;
2140 CheckReplyTo(StatusText.Text);
2142 var statusText = this.FormatStatusText(this.StatusText.Text);
2144 if (this.GetRestStatusCount(statusText) < 0)
2146 // 文字数制限を超えているが強制的に投稿するか
2147 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2148 if (ret != DialogResult.OK)
2152 var status = new PostingStatus();
2153 status.status = statusText;
2155 status.inReplyToId = this.inReplyTo?.Item1;
2156 status.inReplyToName = this.inReplyTo?.Item2;
2157 if (ImageSelector.Visible)
2160 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2164 this.inReplyTo = null;
2165 StatusText.Text = "";
2166 _history.Add(new PostingStatus());
2167 _hisIdx = _history.Count - 1;
2168 if (!ToolStripFocusLockMenuItem.Checked)
2169 ((Control)ListTab.SelectedTab.Tag).Focus();
2170 urlUndoBuffer = null;
2171 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2174 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2176 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2177 await this.OpenUriInBrowserAsync(tmp);
2180 await this.PostMessageAsync(status);
2183 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2185 MyCommon._endingFlag = true;
2189 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2191 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2193 //_endingFlag=false:フォームの×ボタン
2195 this.Visible = false;
2199 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2200 _ignoreConfigSave = true;
2201 MyCommon._endingFlag = true;
2202 TimerTimeline.Enabled = false;
2203 TimerRefreshIcon.Enabled = false;
2207 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2209 this.Visible = true;
2210 if (this.WindowState == FormWindowState.Minimized)
2212 this.WindowState = FormWindowState.Normal;
2215 this.BringToFront();
2218 private static int errorCount = 0;
2220 private static bool CheckAccountValid()
2222 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2228 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2237 private Task GetHomeTimelineAsync()
2239 return this.GetHomeTimelineAsync(loadMore: false);
2242 private async Task GetHomeTimelineAsync(bool loadMore)
2244 await this.workerSemaphore.WaitAsync();
2248 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2250 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2252 catch (WebApiException ex)
2254 this._myStatusError = true;
2255 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2259 this.workerSemaphore.Release();
2263 private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2265 if (ct.IsCancellationRequested)
2268 if (!CheckAccountValid())
2269 throw new WebApiException("Auth error. Check your account");
2272 if (!this._cfgCommon.UnreadManage)
2275 read = this._initial && this._cfgCommon.Read;
2277 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2279 await Task.Run(async () =>
2281 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2282 .ConfigureAwait(false);
2285 if (this._cfgCommon.ReadOldPosts)
2286 this._statuses.SetReadHomeTab();
2288 var addCount = this._statuses.DistributePosts();
2291 this.UpdateTimelineSpeed(addCount);
2294 if (ct.IsCancellationRequested)
2297 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2299 this.RefreshTimeline();
2303 /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2305 /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2306 private void UpdateTimelineSpeed(int addCount)
2308 var now = DateTime.Now;
2309 this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2311 var removeKeys = new List<DateTime>();
2312 var oneHour = TimeSpan.FromHours(1);
2314 foreach (var pair in this._tlTimestamps)
2316 if (now - pair.Key > oneHour)
2317 removeKeys.Add(pair.Key);
2319 tlCount += pair.Value;
2321 Interlocked.Exchange(ref this._tlCount, tlCount);
2324 foreach (var key in removeKeys)
2325 this._tlTimestamps.TryRemove(key, out _);
2328 private Task GetReplyAsync()
2330 return this.GetReplyAsync(loadMore: false);
2333 private async Task GetReplyAsync(bool loadMore)
2335 await this.workerSemaphore.WaitAsync();
2339 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2341 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2343 catch (WebApiException ex)
2345 this._myStatusError = true;
2346 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2350 this.workerSemaphore.Release();
2354 private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2356 if (ct.IsCancellationRequested)
2359 if (!CheckAccountValid())
2360 throw new WebApiException("Auth error. Check your account");
2363 if (!this._cfgCommon.UnreadManage)
2366 read = this._initial && this._cfgCommon.Read;
2368 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2370 await Task.Run(async () =>
2372 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2373 .ConfigureAwait(false);
2375 this._statuses.DistributePosts();
2378 if (ct.IsCancellationRequested)
2381 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2383 this.RefreshTimeline();
2386 private Task GetDirectMessagesAsync()
2388 return this.GetDirectMessagesAsync(loadMore: false);
2391 private async Task GetDirectMessagesAsync(bool loadMore)
2393 await this.workerSemaphore.WaitAsync();
2397 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2399 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2401 catch (WebApiException ex)
2403 this._myStatusError = true;
2404 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2408 this.workerSemaphore.Release();
2412 private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2414 if (ct.IsCancellationRequested)
2417 if (!CheckAccountValid())
2418 throw new WebApiException("Auth error. Check your account");
2421 if (!this._cfgCommon.UnreadManage)
2424 read = this._initial && this._cfgCommon.Read;
2426 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2428 await Task.Run(async () =>
2430 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2431 .ConfigureAwait(false);
2432 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2433 .ConfigureAwait(false);
2435 this._statuses.DistributePosts();
2438 if (ct.IsCancellationRequested)
2441 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2443 this.RefreshTimeline();
2446 private Task GetFavoritesAsync()
2448 return this.GetFavoritesAsync(loadMore: false);
2451 private async Task GetFavoritesAsync(bool loadMore)
2453 await this.workerSemaphore.WaitAsync();
2457 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2459 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2461 catch (WebApiException ex)
2463 this._myStatusError = true;
2464 this.StatusLabel.Text = ex.Message;
2468 this.workerSemaphore.Release();
2472 private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2474 if (ct.IsCancellationRequested)
2477 if (!CheckAccountValid())
2478 throw new WebApiException("Auth error. Check your account");
2481 if (!this._cfgCommon.UnreadManage)
2484 read = this._initial && this._cfgCommon.Read;
2486 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2488 await Task.Run(async () =>
2490 await this.tw.GetFavoritesApi(read, loadMore)
2491 .ConfigureAwait(false);
2493 this._statuses.DistributePosts();
2496 if (ct.IsCancellationRequested)
2499 p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2501 this.RefreshTimeline();
2504 private Task GetPublicSearchAllAsync()
2506 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2508 return this.GetPublicSearchAsync(tabs, loadMore: false);
2511 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2513 return this.GetPublicSearchAsync(tab, loadMore: false);
2516 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2518 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2521 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2523 await this.workerSemaphore.WaitAsync();
2527 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2529 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2531 catch (WebApiException ex)
2533 this._myStatusError = true;
2534 this.StatusLabel.Text = ex.Message;
2538 this.workerSemaphore.Release();
2542 private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2544 if (ct.IsCancellationRequested)
2547 if (!CheckAccountValid())
2548 throw new WebApiException("Auth error. Check your account");
2551 if (!this._cfgCommon.UnreadManage)
2554 read = this._initial && this._cfgCommon.Read;
2556 p.Report("Search refreshing...");
2558 await Task.Run(async () =>
2560 WebApiException lastException = null;
2562 foreach (var tab in tabs)
2566 if (string.IsNullOrEmpty(tab.SearchWords))
2569 await this.tw.GetSearch(read, tab, false)
2570 .ConfigureAwait(false);
2573 await this.tw.GetSearch(read, tab, true)
2574 .ConfigureAwait(false);
2576 catch (WebApiException ex)
2582 this._statuses.DistributePosts();
2584 if (lastException != null)
2585 throw new WebApiException(lastException.Message, lastException);
2588 if (ct.IsCancellationRequested)
2591 p.Report("Search refreshed");
2593 this.RefreshTimeline();
2596 private Task GetUserTimelineAllAsync()
2598 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2600 return this.GetUserTimelineAsync(tabs, loadMore: false);
2603 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2605 return this.GetUserTimelineAsync(tab, loadMore: false);
2608 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2610 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2613 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2615 await this.workerSemaphore.WaitAsync();
2619 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2621 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2623 catch (WebApiException ex)
2625 this._myStatusError = true;
2626 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2630 this.workerSemaphore.Release();
2634 private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2636 if (ct.IsCancellationRequested)
2639 if (!CheckAccountValid())
2640 throw new WebApiException("Auth error. Check your account");
2643 if (!this._cfgCommon.UnreadManage)
2646 read = this._initial && this._cfgCommon.Read;
2648 p.Report("UserTimeline refreshing...");
2650 await Task.Run(async () =>
2652 WebApiException lastException = null;
2654 foreach (var tab in tabs)
2658 if (string.IsNullOrEmpty(tab.ScreenName))
2661 await this.tw.GetUserTimelineApi(read, tab.ScreenName, tab, loadMore)
2662 .ConfigureAwait(false);
2664 catch (WebApiException ex)
2670 this._statuses.DistributePosts();
2672 if (lastException != null)
2673 throw new WebApiException(lastException.Message, lastException);
2676 if (ct.IsCancellationRequested)
2679 p.Report("UserTimeline refreshed");
2681 this.RefreshTimeline();
2684 private Task GetListTimelineAllAsync()
2686 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2688 return this.GetListTimelineAsync(tabs, loadMore: false);
2691 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2693 return this.GetListTimelineAsync(tab, loadMore: false);
2696 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2698 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2701 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2703 await this.workerSemaphore.WaitAsync();
2707 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2709 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2711 catch (WebApiException ex)
2713 this._myStatusError = true;
2714 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2718 this.workerSemaphore.Release();
2722 private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2724 if (ct.IsCancellationRequested)
2727 if (!CheckAccountValid())
2728 throw new WebApiException("Auth error. Check your account");
2731 if (!this._cfgCommon.UnreadManage)
2734 read = this._initial && this._cfgCommon.Read;
2736 p.Report("List refreshing...");
2738 await Task.Run(async () =>
2740 WebApiException lastException = null;
2742 foreach (var tab in tabs)
2746 if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2749 await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2750 .ConfigureAwait(false);
2752 catch (WebApiException ex)
2758 this._statuses.DistributePosts();
2760 if (lastException != null)
2761 throw new WebApiException(lastException.Message, lastException);
2764 if (ct.IsCancellationRequested)
2767 p.Report("List refreshed");
2769 this.RefreshTimeline();
2772 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2774 await this.workerSemaphore.WaitAsync();
2778 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2780 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2782 catch (WebApiException ex)
2784 this._myStatusError = true;
2785 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2789 this.workerSemaphore.Release();
2793 private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, RelatedPostsTabModel tab)
2795 if (ct.IsCancellationRequested)
2798 if (!CheckAccountValid())
2799 throw new WebApiException("Auth error. Check your account");
2802 if (!this._cfgCommon.UnreadManage)
2805 read = this._initial && this._cfgCommon.Read;
2807 p.Report("Related refreshing...");
2809 await Task.Run(async () =>
2811 await this.tw.GetRelatedResult(read, tab)
2812 .ConfigureAwait(false);
2814 this._statuses.DistributePosts();
2817 if (ct.IsCancellationRequested)
2820 p.Report("Related refreshed");
2822 this.RefreshTimeline();
2824 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2825 .FirstOrDefault(x => x.Text == tab.TabName);
2827 if (tabPage != null)
2829 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2831 var listView = (DetailsListView)tabPage.Tag;
2832 var index = tab.IndexOf(tab.TargetPost.RetweetedId ?? tab.TargetPost.StatusId);
2834 if (index != -1 && index < listView.Items.Count)
2836 listView.SelectedIndices.Add(index);
2837 listView.Items[index].Focused = true;
2842 private async Task FavAddAsync(long statusId, TabModel tab)
2844 await this.workerSemaphore.WaitAsync();
2848 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2850 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2852 catch (WebApiException ex)
2854 this._myStatusError = true;
2855 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2859 this.workerSemaphore.Release();
2863 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2865 if (ct.IsCancellationRequested)
2868 if (!CheckAccountValid())
2869 throw new WebApiException("Auth error. Check your account");
2872 if (!tab.Posts.TryGetValue(statusId, out post))
2878 await Task.Run(async () =>
2880 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2884 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2886 .ConfigureAwait(false);
2888 if (this._cfgCommon.RestrictFavCheck)
2890 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2891 .ConfigureAwait(false);
2893 if (status.Favorited != true)
2894 throw new WebApiException("NG(Restricted?)");
2897 this._favTimestamps.Add(DateTime.Now);
2900 if (this._statuses.ContainsKey(statusId))
2902 var postTl = this._statuses[statusId];
2903 postTl.IsFav = true;
2905 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2906 favTab.AddPostQueue(postTl);
2909 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2910 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2912 if (tb.Contains(statusId))
2913 tb.Posts[statusId].IsFav = true;
2916 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2918 catch (WebApiException)
2920 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2925 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2926 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2928 if (this._favTimestamps[i] < oneHour)
2929 this._favTimestamps.RemoveAt(i);
2932 this._statuses.DistributePosts();
2935 if (ct.IsCancellationRequested)
2938 this.RefreshTimeline();
2940 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2942 using (ControlTransaction.Update(this._curList))
2944 var idx = tab.IndexOf(statusId);
2946 this.ChangeCacheStyleRead(post.IsRead, idx);
2949 if (statusId == this._curPost.StatusId)
2950 await this.DispSelectedPost(true); // 選択アイテム再表示
2954 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2956 await this.workerSemaphore.WaitAsync();
2960 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2962 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2964 catch (WebApiException ex)
2966 this._myStatusError = true;
2967 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2971 this.workerSemaphore.Release();
2975 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2977 if (ct.IsCancellationRequested)
2980 if (!CheckAccountValid())
2981 throw new WebApiException("Auth error. Check your account");
2983 var successIds = new List<long>();
2985 await Task.Run(async () =>
2989 var failedCount = 0;
2990 foreach (var statusId in statusIds)
2994 var post = tab.Posts[statusId];
2996 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3003 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3005 .ConfigureAwait(false);
3007 catch (WebApiException)
3013 successIds.Add(statusId);
3014 post.IsFav = false; // リスト再描画必要
3016 if (this._statuses.ContainsKey(statusId))
3018 this._statuses[statusId].IsFav = false;
3021 // 検索,リスト,UserTimeline,Relatedの各タブに反映
3022 foreach (var tb in this._statuses.GetTabsInnerStorageType())
3024 if (tb.Contains(statusId))
3025 tb.Posts[statusId].IsFav = false;
3030 if (ct.IsCancellationRequested)
3033 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3034 foreach (var statusId in successIds)
3036 // ツイートが削除された訳ではないので IsDeleted はセットしない
3037 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
3040 this.RefreshTimeline();
3042 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3044 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3050 using (ControlTransaction.Update(this._curList))
3052 foreach (var statusId in successIds)
3054 var idx = tab.IndexOf(statusId);
3058 var post = tab.Posts[statusId];
3059 this.ChangeCacheStyleRead(post.IsRead, idx);
3063 if (successIds.Contains(this._curPost.StatusId))
3064 await this.DispSelectedPost(true); // 選択アイテム再表示
3069 private async Task PostMessageAsync(PostingStatus status)
3071 await this.workerSemaphore.WaitAsync();
3075 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3077 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3079 catch (WebApiException ex)
3081 this._myStatusError = true;
3082 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
3086 this.workerSemaphore.Release();
3090 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3092 if (ct.IsCancellationRequested)
3095 if (!CheckAccountValid())
3096 throw new WebApiException("Auth error. Check your account");
3098 p.Report("Posting...");
3104 await Task.Run(async () =>
3106 if (status.mediaItems == null || status.mediaItems.Length == 0)
3108 await this.tw.PostStatus(status.status, status.inReplyToId)
3109 .ConfigureAwait(false);
3113 var service = ImageSelector.GetService(status.imageService);
3114 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3115 .ConfigureAwait(false);
3119 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3121 catch (WebApiException ex)
3123 // 処理は中断せずエラーの表示のみ行う
3124 errMsg = $"Err:{ex.Message}(PostMessage)";
3126 this._myStatusError = true;
3130 // 使い終わった MediaItem は破棄する
3131 if (status.mediaItems != null)
3133 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3135 disposableItem.Dispose();
3140 if (ct.IsCancellationRequested)
3143 if (!string.IsNullOrEmpty(errMsg) &&
3144 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3145 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3147 var ret = MessageBox.Show(
3149 "{0} ---> [ " + errMsg + " ]" + Environment.NewLine +
3150 "\"" + status.status + "\"" + Environment.NewLine +
3152 Properties.Resources.StatusUpdateFailed1,
3153 Properties.Resources.StatusUpdateFailed2),
3154 "Failed to update status",
3155 MessageBoxButtons.RetryCancel,
3156 MessageBoxIcon.Question);
3158 if (ret == DialogResult.Retry)
3160 await this.PostMessageAsync(status);
3164 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3165 if (this.ToolStripFocusLockMenuItem.Checked)
3166 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3171 this._postTimestamps.Add(DateTime.Now);
3173 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3174 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3176 if (this._postTimestamps[i] < oneHour)
3177 this._postTimestamps.RemoveAt(i);
3180 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3182 this.HashMgr.ClearHashtag();
3183 this.HashStripSplitButton.Text = "#[-]";
3184 this.HashToggleMenuItem.Checked = false;
3185 this.HashToggleToolStripMenuItem.Checked = false;
3188 this.SetMainWindowTitle();
3190 if (this._cfgCommon.PostAndGet)
3192 if (this.tw.UserStreamActive)
3193 this.RefreshTimeline();
3195 await this.GetHomeTimelineAsync();
3199 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3201 await this.workerSemaphore.WaitAsync();
3205 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3207 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3209 catch (WebApiException ex)
3211 this._myStatusError = true;
3212 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
3216 this.workerSemaphore.Release();
3220 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3222 if (ct.IsCancellationRequested)
3225 if (!CheckAccountValid())
3226 throw new WebApiException("Auth error. Check your account");
3229 if (!this._cfgCommon.UnreadManage)
3232 read = this._initial && this._cfgCommon.Read;
3234 p.Report("Posting...");
3236 var retweetTasks = from statusId in statusIds
3237 select this.tw.PostRetweet(statusId, read);
3239 await Task.WhenAll(retweetTasks)
3240 .ConfigureAwait(false);
3242 if (ct.IsCancellationRequested)
3245 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3247 this._postTimestamps.Add(DateTime.Now);
3249 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3250 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3252 if (this._postTimestamps[i] < oneHour)
3253 this._postTimestamps.RemoveAt(i);
3256 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
3257 await this.GetHomeTimelineAsync();
3260 private async Task RefreshFollowerIdsAsync()
3262 await this.workerSemaphore.WaitAsync();
3265 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3267 await this.tw.RefreshFollowerIds();
3269 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3271 this.RefreshTimeline();
3272 this.PurgeListViewItemCache();
3273 this._curList?.Refresh();
3275 catch (WebApiException ex)
3277 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
3281 this.workerSemaphore.Release();
3285 private async Task RefreshNoRetweetIdsAsync()
3287 await this.workerSemaphore.WaitAsync();
3290 await this.tw.RefreshNoRetweetIds();
3292 this.StatusLabel.Text = "NoRetweetIds refreshed";
3294 catch (WebApiException ex)
3296 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
3300 this.workerSemaphore.Release();
3304 private async Task RefreshBlockIdsAsync()
3306 await this.workerSemaphore.WaitAsync();
3309 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3311 await this.tw.RefreshBlockIds();
3313 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3315 catch (WebApiException ex)
3317 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
3321 this.workerSemaphore.Release();
3325 private async Task RefreshTwitterConfigurationAsync()
3327 await this.workerSemaphore.WaitAsync();
3330 await this.tw.RefreshConfiguration();
3332 if (this.tw.Configuration.PhotoSizeLimit != 0)
3334 foreach (var service in this.ImageSelector.GetServices())
3336 service.UpdateTwitterConfiguration(this.tw.Configuration);
3340 this.PurgeListViewItemCache();
3342 this._curList?.Refresh();
3344 catch (WebApiException ex)
3346 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3350 this.workerSemaphore.Release();
3354 private async Task RefreshMuteUserIdsAsync()
3356 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3360 await tw.RefreshMuteUserIdsAsync();
3362 catch (WebApiException ex)
3364 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3368 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3371 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3373 if (e.Button == MouseButtons.Left)
3375 this.Visible = true;
3376 if (this.WindowState == FormWindowState.Minimized)
3378 this.WindowState = _formWindowState;
3381 this.BringToFront();
3385 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3387 switch (this._cfgCommon.ListDoubleClickAction)
3390 MakeReplyOrDirectStatus();
3393 await this.FavoriteChange(true);
3396 if (_curPost != null)
3397 await this.ShowUserStatus(_curPost.ScreenName, false);
3403 ShowRelatedStatusesMenuItem_Click(null, null);
3406 MoveToHomeToolStripMenuItem_Click(null, null);
3409 StatusOpenMenuItem_Click(null, null);
3417 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3419 await this.FavoriteChange(true);
3422 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3424 await this.FavoriteChange(false);
3428 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3430 await this.FavoritesRetweetOfficial();
3433 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3435 await this.FavoritesRetweetUnofficial();
3438 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3441 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3444 //trueでFavAdd,falseでFavRemove
3445 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3446 || !this.ExistCurrentPost) return;
3448 if (this._curList.SelectedIndices.Count > 1)
3453 // https://support.twitter.com/articles/76915#favoriting
3454 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3455 _DoFavRetweetFlags = false;
3460 if (multiFavoriteChangeDialogEnable)
3462 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3463 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3464 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3466 if (confirm == DialogResult.Cancel)
3474 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3475 if (selectedPost.IsFav)
3477 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3481 await this.FavAddAsync(selectedPost.StatusId, tab);
3485 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3486 .Select(x => this.GetCurTabPost(x))
3487 .Where(x => x.IsFav);
3489 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3490 if (statusIds.Length == 0)
3492 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3496 await this.FavRemoveAsync(statusIds, tab);
3500 private PostClass GetCurTabPost(int Index)
3502 var listCache = this._listItemCache;
3503 if (listCache != null)
3507 if (listCache.TryGetValue(Index, out item, out post))
3511 return _statuses.Tabs[_curTab.Text][Index];
3514 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3516 if (_curList.SelectedIndices.Count > 0)
3517 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3518 else if (_curList.SelectedIndices.Count == 0)
3519 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3522 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3524 if (_curList.SelectedIndices.Count > 0)
3525 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3528 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3530 if ((!_initialLayout) && this.Visible)
3532 if (this.WindowState == FormWindowState.Normal)
3534 _mySize = this.ClientSize;
3535 _mySpDis = this.SplitContainer1.SplitterDistance;
3536 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3537 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3538 ModifySettingLocal = true;
3543 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3545 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3546 if (comparerMode == null)
3549 this.SetSortColumn(comparerMode.Value);
3553 /// 列インデックスからソートを行う ComparerMode を求める
3555 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3556 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3557 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3560 return ComparerMode.Id;
3562 switch (columnIndex)
3565 return ComparerMode.Nickname;
3567 return ComparerMode.Data;
3569 return ComparerMode.Id;
3571 return ComparerMode.Name;
3573 return ComparerMode.Source;
3575 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3581 /// 発言一覧の指定した位置の列でソートする
3583 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3584 private void SetSortColumnByDisplayIndex(int columnIndex)
3586 // 表示上の列の位置から ColumnHeader を求める
3587 var col = this._curList.Columns.Cast<ColumnHeader>()
3588 .Where(x => x.DisplayIndex == columnIndex)
3594 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3595 if (comparerMode == null)
3598 this.SetSortColumn(comparerMode.Value);
3602 /// 発言一覧の最後列の項目でソートする
3604 private void SetSortLastColumn()
3606 // 表示上の最後列にある ColumnHeader を求める
3607 var col = this._curList.Columns.Cast<ColumnHeader>()
3608 .OrderByDescending(x => x.DisplayIndex)
3611 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3612 if (comparerMode == null)
3615 this.SetSortColumn(comparerMode.Value);
3619 /// 発言一覧を指定された ComparerMode に基づいてソートする
3621 private void SetSortColumn(ComparerMode sortColumn)
3623 if (this._cfgCommon.SortOrderLock)
3626 this._statuses.ToggleSortOrder(sortColumn);
3627 this.InitColumnText();
3629 var list = this._curList;
3632 list.Columns[0].Text = this.ColumnText[0];
3633 list.Columns[1].Text = this.ColumnText[2];
3637 for (var i = 0; i <= 7; i++)
3639 list.Columns[i].Text = this.ColumnText[i];
3643 this.PurgeListViewItemCache();
3645 var tab = this._statuses.Tabs[this._curTab.Text];
3646 if (tab.AllCount > 0 && this._curPost != null)
3648 var idx = tab.IndexOf(this._curPost.StatusId);
3651 this.SelectListItem(list, idx);
3652 list.EnsureVisible(idx);
3657 this.ModifySettingCommon = true;
3660 private void TweenMain_LocationChanged(object sender, EventArgs e)
3662 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3664 _myLoc = this.DesktopLocation;
3665 ModifySettingLocal = true;
3669 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3671 if (ListTab.SelectedTab == null) return;
3672 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3673 if (!this.ExistCurrentPost)
3675 ReplyStripMenuItem.Enabled = false;
3676 ReplyAllStripMenuItem.Enabled = false;
3677 DMStripMenuItem.Enabled = false;
3678 ShowProfileMenuItem.Enabled = false;
3679 ShowUserTimelineContextMenuItem.Enabled = false;
3680 ListManageUserContextToolStripMenuItem2.Enabled = false;
3681 MoveToFavToolStripMenuItem.Enabled = false;
3682 TabMenuItem.Enabled = false;
3683 IDRuleMenuItem.Enabled = false;
3684 SourceRuleMenuItem.Enabled = false;
3685 ReadedStripMenuItem.Enabled = false;
3686 UnreadStripMenuItem.Enabled = false;
3690 ShowProfileMenuItem.Enabled = true;
3691 ListManageUserContextToolStripMenuItem2.Enabled = true;
3692 ReplyStripMenuItem.Enabled = true;
3693 ReplyAllStripMenuItem.Enabled = true;
3694 DMStripMenuItem.Enabled = true;
3695 ShowUserTimelineContextMenuItem.Enabled = true;
3696 MoveToFavToolStripMenuItem.Enabled = true;
3697 TabMenuItem.Enabled = true;
3698 IDRuleMenuItem.Enabled = true;
3699 SourceRuleMenuItem.Enabled = true;
3700 ReadedStripMenuItem.Enabled = true;
3701 UnreadStripMenuItem.Enabled = true;
3703 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3705 FavAddToolStripMenuItem.Enabled = false;
3706 FavRemoveToolStripMenuItem.Enabled = false;
3707 StatusOpenMenuItem.Enabled = false;
3708 FavorareMenuItem.Enabled = false;
3709 ShowRelatedStatusesMenuItem.Enabled = false;
3711 ReTweetStripMenuItem.Enabled = false;
3712 ReTweetUnofficialStripMenuItem.Enabled = false;
3713 QuoteStripMenuItem.Enabled = false;
3714 FavoriteRetweetContextMenu.Enabled = false;
3715 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3719 FavAddToolStripMenuItem.Enabled = true;
3720 FavRemoveToolStripMenuItem.Enabled = true;
3721 StatusOpenMenuItem.Enabled = true;
3722 FavorareMenuItem.Enabled = true;
3723 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3727 ReTweetStripMenuItem.Enabled = false; //公式RTは無効に
3728 ReTweetUnofficialStripMenuItem.Enabled = true;
3729 QuoteStripMenuItem.Enabled = true;
3730 FavoriteRetweetContextMenu.Enabled = false; //公式RTは無効に
3731 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3735 if (_curPost.IsProtect)
3737 ReTweetStripMenuItem.Enabled = false;
3738 ReTweetUnofficialStripMenuItem.Enabled = false;
3739 QuoteStripMenuItem.Enabled = false;
3740 FavoriteRetweetContextMenu.Enabled = false;
3741 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3745 ReTweetStripMenuItem.Enabled = true;
3746 ReTweetUnofficialStripMenuItem.Enabled = true;
3747 QuoteStripMenuItem.Enabled = true;
3748 FavoriteRetweetContextMenu.Enabled = true;
3749 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3753 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3755 // RefreshMoreStripMenuItem.Enabled = true;
3759 // RefreshMoreStripMenuItem.Enabled = false;
3761 if (!this.ExistCurrentPost
3762 || _curPost.InReplyToStatusId == null)
3764 RepliedStatusOpenMenuItem.Enabled = false;
3768 RepliedStatusOpenMenuItem.Enabled = true;
3770 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3772 MoveToRTHomeMenuItem.Enabled = false;
3776 MoveToRTHomeMenuItem.Enabled = true;
3779 if (this.ExistCurrentPost)
3781 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3782 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3783 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3785 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3789 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3791 MakeReplyOrDirectStatus(false, true);
3794 private void DMStripMenuItem_Click(object sender, EventArgs e)
3796 MakeReplyOrDirectStatus(false, false);
3799 private async Task doStatusDelete()
3801 if (this._curTab == null || this._curList == null)
3804 if (this._curList.SelectedIndices.Count == 0)
3807 var posts = this._curList.SelectedIndices.Cast<int>()
3808 .Select(x => this.GetCurTabPost(x))
3811 // 選択されたツイートの中に削除可能なものが一つでもあるか
3812 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3815 var ret = MessageBox.Show(this,
3816 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3817 Properties.Resources.DeleteStripMenuItem_ClickText2,
3818 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3820 if (ret != DialogResult.OK)
3823 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3825 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3827 Exception lastException = null;
3828 foreach (var post in posts)
3830 if (!post.CanDeleteBy(this.tw.UserId))
3837 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3842 if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3843 // 他人に RT された自分のツイート
3844 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3847 // 自分のツイート or 自分が RT したツイート
3848 await this.twitterApi.StatusesDestroy(post.StatusId)
3852 catch (WebApiException ex)
3858 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3861 if (lastException == null)
3862 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3864 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3866 this.PurgeListViewItemCache();
3867 this._curPost = null;
3868 this._curItemIndex = -1;
3870 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3872 var listView = (DetailsListView)tabPage.Tag;
3873 var tab = this._statuses.Tabs[tabPage.Text];
3875 using (ControlTransaction.Update(listView))
3877 listView.VirtualListSize = tab.AllCount;
3879 if (tabPage == this._curTab)
3881 listView.SelectedIndices.Clear();
3883 if (tab.AllCount != 0)
3886 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3887 selectedIndex = focusedIndex;
3889 selectedIndex = tab.AllCount - 1;
3891 listView.SelectedIndices.Add(selectedIndex);
3892 listView.EnsureVisible(selectedIndex);
3893 listView.FocusedItem = listView.Items[selectedIndex];
3898 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3900 if (tabPage.ImageIndex == 0)
3901 tabPage.ImageIndex = -1; // タブアイコン
3905 if (!this._cfgCommon.TabIconDisp)
3906 this.ListTab.Refresh();
3910 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3912 await this.doStatusDelete();
3915 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3917 using (ControlTransaction.Update(this._curList))
3919 foreach (int idx in _curList.SelectedIndices)
3921 var post = this._statuses.Tabs[this._curTab.Text][idx];
3922 this._statuses.SetReadAllTab(post.StatusId, read: true);
3923 ChangeCacheStyleRead(true, idx);
3927 foreach (TabPage tb in ListTab.TabPages)
3929 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3931 if (this._cfgCommon.TabIconDisp)
3933 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3937 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3940 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3942 using (ControlTransaction.Update(this._curList))
3944 foreach (int idx in _curList.SelectedIndices)
3946 var post = this._statuses.Tabs[this._curTab.Text][idx];
3947 this._statuses.SetReadAllTab(post.StatusId, read: false);
3948 ChangeCacheStyleRead(false, idx);
3952 foreach (TabPage tb in ListTab.TabPages)
3954 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3956 if (this._cfgCommon.TabIconDisp)
3958 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3962 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3965 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3967 await this.DoRefresh();
3970 private async Task DoRefresh()
3972 if (_curTab != null)
3975 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3978 switch (_statuses.Tabs[_curTab.Text].TabType)
3980 case MyCommon.TabUsageType.Mentions:
3981 await this.GetReplyAsync();
3983 case MyCommon.TabUsageType.DirectMessage:
3984 await this.GetDirectMessagesAsync();
3986 case MyCommon.TabUsageType.Favorites:
3987 await this.GetFavoritesAsync();
3989 //case MyCommon.TabUsageType.Profile:
3991 case MyCommon.TabUsageType.PublicSearch:
3992 var searchTab = (PublicSearchTabModel)tab;
3993 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3994 await this.GetPublicSearchAsync(searchTab);
3996 case MyCommon.TabUsageType.UserTimeline:
3997 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3999 case MyCommon.TabUsageType.Lists:
4000 var listTab = (ListTimelineTabModel)tab;
4001 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
4002 await this.GetListTimelineAsync(listTab);
4005 await this.GetHomeTimelineAsync();
4011 await this.GetHomeTimelineAsync();
4015 private async Task DoRefreshMore()
4018 if (_curTab != null)
4021 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4024 switch (_statuses.Tabs[_curTab.Text].TabType)
4026 case MyCommon.TabUsageType.Mentions:
4027 await this.GetReplyAsync(loadMore: true);
4029 case MyCommon.TabUsageType.DirectMessage:
4030 await this.GetDirectMessagesAsync(loadMore: true);
4032 case MyCommon.TabUsageType.Favorites:
4033 await this.GetFavoritesAsync(loadMore: true);
4035 case MyCommon.TabUsageType.Profile:
4038 case MyCommon.TabUsageType.PublicSearch:
4039 var searchTab = (PublicSearchTabModel)tab;
4040 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
4041 await this.GetPublicSearchAsync(searchTab, loadMore: true);
4043 case MyCommon.TabUsageType.UserTimeline:
4044 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
4046 case MyCommon.TabUsageType.Lists:
4047 var listTab = (ListTimelineTabModel)tab;
4048 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
4049 await this.GetListTimelineAsync(listTab, loadMore: true);
4052 await this.GetHomeTimelineAsync(loadMore: true);
4058 await this.GetHomeTimelineAsync(loadMore: true);
4062 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4064 DialogResult result = DialogResult.Abort;
4066 using (var settingDialog = new AppendSettingDialog())
4068 settingDialog.Icon = this.MainIcon;
4069 settingDialog.Owner = this;
4070 settingDialog.ShowInTaskbar = showTaskbarIcon;
4071 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4073 settingDialog.tw = this.tw;
4074 settingDialog.twitterApi = this.twitterApi;
4076 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4080 result = settingDialog.ShowDialog(this);
4084 return DialogResult.Abort;
4087 if (result == DialogResult.OK)
4091 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4099 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4102 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4104 var oldIconSz = this._cfgCommon.IconSize;
4106 if (ShowSettingDialog() == DialogResult.OK)
4110 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4111 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4112 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4113 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4114 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4115 TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
4117 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4118 Networking.SetWebProxy(this._cfgLocal.ProxyType,
4119 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4120 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4121 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4123 ImageSelector.Reset(tw, this.tw.Configuration);
4127 if (this._cfgCommon.TabIconDisp)
4129 ListTab.DrawItem -= ListTab_DrawItem;
4130 ListTab.DrawMode = TabDrawMode.Normal;
4131 ListTab.ImageList = this.TabImage;
4135 ListTab.DrawItem -= ListTab_DrawItem;
4136 ListTab.DrawItem += ListTab_DrawItem;
4137 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4138 ListTab.ImageList = null;
4141 catch (Exception ex)
4143 ex.Data["Instance"] = "ListTab(TabIconDisp)";
4144 ex.Data["IsTerminatePermission"] = false;
4150 if (!this._cfgCommon.UnreadManage)
4152 ReadedStripMenuItem.Enabled = false;
4153 UnreadStripMenuItem.Enabled = false;
4154 if (this._cfgCommon.TabIconDisp)
4156 foreach (TabPage myTab in ListTab.TabPages)
4158 myTab.ImageIndex = -1;
4164 ReadedStripMenuItem.Enabled = true;
4165 UnreadStripMenuItem.Enabled = true;
4168 catch (Exception ex)
4170 ex.Data["Instance"] = "ListTab(UnreadManage)";
4171 ex.Data["IsTerminatePermission"] = false;
4178 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4180 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4181 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4182 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4184 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4185 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4186 _fntUnread = this._cfgLocal.FontUnread;
4187 _clUnread = this._cfgLocal.ColorUnread;
4188 _fntReaded = this._cfgLocal.FontRead;
4189 _clReaded = this._cfgLocal.ColorRead;
4190 _clFav = this._cfgLocal.ColorFav;
4191 _clOWL = this._cfgLocal.ColorOWL;
4192 _clRetweet = this._cfgLocal.ColorRetweet;
4193 _fntDetail = this._cfgLocal.FontDetail;
4194 _clDetail = this._cfgLocal.ColorDetail;
4195 _clDetailLink = this._cfgLocal.ColorDetailLink;
4196 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4197 _clSelf = this._cfgLocal.ColorSelf;
4198 _clAtSelf = this._cfgLocal.ColorAtSelf;
4199 _clTarget = this._cfgLocal.ColorTarget;
4200 _clAtTarget = this._cfgLocal.ColorAtTarget;
4201 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4202 _clAtTo = this._cfgLocal.ColorAtTo;
4203 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4204 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4205 _clInputFont = this._cfgLocal.ColorInputFont;
4206 _fntInputFont = this._cfgLocal.FontInputFont;
4207 _brsBackColorMine.Dispose();
4208 _brsBackColorAt.Dispose();
4209 _brsBackColorYou.Dispose();
4210 _brsBackColorAtYou.Dispose();
4211 _brsBackColorAtFromTarget.Dispose();
4212 _brsBackColorAtTo.Dispose();
4213 _brsBackColorNone.Dispose();
4214 _brsBackColorMine = new SolidBrush(_clSelf);
4215 _brsBackColorAt = new SolidBrush(_clAtSelf);
4216 _brsBackColorYou = new SolidBrush(_clTarget);
4217 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4218 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4219 _brsBackColorAtTo = new SolidBrush(_clAtTo);
4220 _brsBackColorNone = new SolidBrush(_clListBackcolor);
4224 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4225 StatusText.Font = _fntInputFont;
4226 StatusText.ForeColor = _clInputFont;
4228 catch (Exception ex)
4230 MessageBox.Show(ex.Message);
4235 InitDetailHtmlFormat();
4237 catch (Exception ex)
4239 ex.Data["Instance"] = "Font";
4240 ex.Data["IsTerminatePermission"] = false;
4246 foreach (TabPage tb in ListTab.TabPages)
4248 if (this._cfgCommon.TabIconDisp)
4250 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4257 catch (Exception ex)
4259 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4260 ex.Data["IsTerminatePermission"] = false;
4266 var oldIconCol = _iconCol;
4268 if (this._cfgCommon.IconSize != oldIconSz)
4269 ApplyListViewIconSize(this._cfgCommon.IconSize);
4271 foreach (TabPage tp in ListTab.TabPages)
4273 DetailsListView lst = (DetailsListView)tp.Tag;
4275 using (ControlTransaction.Update(lst))
4277 lst.GridLines = this._cfgCommon.ShowGrid;
4278 lst.Font = _fntReaded;
4279 lst.BackColor = _clListBackcolor;
4281 if (_iconCol != oldIconCol)
4286 catch (Exception ex)
4288 ex.Data["Instance"] = "ListView(IconSize)";
4289 ex.Data["IsTerminatePermission"] = false;
4293 SetMainWindowTitle();
4294 SetNotifyIconText();
4296 this.PurgeListViewItemCache();
4297 _curList?.Refresh();
4300 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4301 if (this._cfgCommon.HotkeyEnabled)
4303 ///グローバルホットキーの登録。設定で変更可能にするかも
4304 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4305 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4306 modKey |= HookGlobalHotkey.ModKeys.Alt;
4307 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4308 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4309 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4310 modKey |= HookGlobalHotkey.ModKeys.Shift;
4311 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4312 modKey |= HookGlobalHotkey.ModKeys.Win;
4314 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4317 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4320 StatusText_TextChanged(null, null);
4329 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4330 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4333 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4335 this.TopMost = this._cfgCommon.AlwaysTop;
4336 SaveConfigsAll(false);
4338 if (tw.Username != oldUser.Username)
4339 await this.doGetFollowersMenu();
4345 private void SetTabAlignment()
4347 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4348 if (ListTab.Alignment == newAlignment) return;
4350 // 各タブのリスト上の選択位置などを退避
4351 var listSelections = this.SaveListViewSelection();
4353 ListTab.Alignment = newAlignment;
4355 foreach (TabPage tab in ListTab.TabPages)
4357 DetailsListView lst = (DetailsListView)tab.Tag;
4358 TabModel tabInfo = _statuses.Tabs[tab.Text];
4359 using (ControlTransaction.Update(lst))
4362 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4367 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4373 case MyCommon.IconSizes.IconNone:
4376 case MyCommon.IconSizes.Icon16:
4379 case MyCommon.IconSizes.Icon24:
4382 case MyCommon.IconSizes.Icon48:
4385 case MyCommon.IconSizes.Icon48_2:
4393 // ディスプレイの DPI 設定を考慮したサイズを設定する
4394 _listViewImageList.ImageSize = new Size(
4396 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4400 _listViewImageList.ImageSize = new Size(1, 1);
4404 private void ResetColumns(DetailsListView list)
4406 using (ControlTransaction.Update(list))
4407 using (ControlTransaction.Layout(list, false))
4410 list.ColumnClick -= MyList_ColumnClick;
4411 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4412 list.ColumnReordered -= MyList_ColumnReordered;
4413 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4415 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4416 list.Columns.Clear();
4417 cols.ForEach(col => col.Dispose());
4420 InitColumns(list, true);
4422 list.ColumnClick += MyList_ColumnClick;
4423 list.DrawColumnHeader += MyList_DrawColumnHeader;
4424 list.ColumnReordered += MyList_ColumnReordered;
4425 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4429 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4431 if (e.Url.AbsoluteUri != "about:blank")
4433 await this.DispSelectedPost();
4434 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4438 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4440 if (e.Url.Scheme == "data")
4442 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4444 else if (e.Url.AbsoluteUri != "about:blank")
4447 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4448 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4452 public void AddNewTabForSearch(string searchWord)
4454 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4455 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4457 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4459 foreach (TabPage tp in ListTab.TabPages)
4461 if (tb.TabName == tp.Text)
4463 ListTab.SelectedTab = tp;
4470 string tabName = searchWord;
4471 for (int i = 0; i <= 100; i++)
4473 if (_statuses.ContainsTab(tabName))
4479 var tab = new PublicSearchTabModel(tabName);
4480 _statuses.AddTab(tab);
4481 AddNewTab(tab, startup: false);
4483 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4485 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4486 cmb.Items.Add(searchWord);
4487 cmb.Text = searchWord;
4490 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4493 private void ShowUserTimeline()
4495 if (!this.ExistCurrentPost) return;
4496 AddNewTabForUserTimeline(_curPost.ScreenName);
4499 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4501 if (e.KeyCode == Keys.Escape)
4503 TabPage relTp = ListTab.SelectedTab;
4504 RemoveSpecifiedTab(relTp.Text, false);
4506 e.SuppressKeyPress = true;
4510 public void AddNewTabForUserTimeline(string user)
4512 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4513 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4515 if (tb.ScreenName == user)
4517 foreach (TabPage tp in ListTab.TabPages)
4519 if (tb.TabName == tp.Text)
4521 ListTab.SelectedTab = tp;
4528 string tabName = "user:" + user;
4529 while (_statuses.ContainsTab(tabName))
4534 var tab = new UserTimelineTabModel(tabName, user);
4535 this._statuses.AddTab(tab);
4536 this.AddNewTab(tab, startup: false);
4538 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4541 this.GetUserTimelineAsync(tab);
4544 public bool AddNewTab(TabModel tab, bool startup)
4547 foreach (TabPage tb in ListTab.TabPages)
4549 if (tb.Text == tab.TabName) return false;
4553 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4558 if (tab.IsDefaultTabType || tab.TabType == MyCommon.TabUsageType.Related)
4560 if (_statuses.GetTabByType(tab.TabType) != null) return false;
4564 var _tabPage = new TabPage();
4565 var _listCustom = new DetailsListView();
4567 int cnt = ListTab.TabPages.Count;
4569 ///ToDo:Create and set controls follow tabtypes
4571 using (ControlTransaction.Update(_listCustom))
4572 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4573 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4574 using (ControlTransaction.Layout(this.SplitContainer1, false))
4575 using (ControlTransaction.Layout(this.ListTab, false))
4576 using (ControlTransaction.Layout(this))
4577 using (ControlTransaction.Layout(_tabPage, false))
4579 _tabPage.Controls.Add(_listCustom);
4582 var userTab = tab as UserTimelineTabModel;
4583 var listTab = tab as ListTimelineTabModel;
4584 var searchTab = tab as PublicSearchTabModel;
4586 if (userTab != null || listTab != null)
4588 var label = new Label();
4589 label.Dock = DockStyle.Top;
4590 label.Name = "labelUser";
4593 if (listTab != null)
4595 label.Text = listTab.ListInfo.ToString();
4597 else if (userTab != null)
4599 label.Text = userTab.ScreenName + "'s Timeline";
4601 label.TextAlign = ContentAlignment.MiddleLeft;
4602 using (ComboBox tmpComboBox = new ComboBox())
4604 label.Height = tmpComboBox.Height;
4606 _tabPage.Controls.Add(label);
4609 else if (searchTab != null)
4611 var pnl = new Panel();
4613 var lbl = new Label();
4614 var cmb = new ComboBox();
4615 var btn = new Button();
4616 var cmbLang = new ComboBox();
4618 using (ControlTransaction.Layout(pnl, false))
4620 pnl.Controls.Add(cmb);
4621 pnl.Controls.Add(cmbLang);
4622 pnl.Controls.Add(btn);
4623 pnl.Controls.Add(lbl);
4624 pnl.Name = "panelSearch";
4626 pnl.Dock = DockStyle.Top;
4627 pnl.Height = cmb.Height;
4628 pnl.Enter += SearchControls_Enter;
4629 pnl.Leave += SearchControls_Leave;
4632 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4633 cmb.Dock = DockStyle.Fill;
4634 cmb.Name = "comboSearch";
4635 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4636 cmb.ImeMode = ImeMode.NoControl;
4637 cmb.TabStop = false;
4639 cmb.AutoCompleteMode = AutoCompleteMode.None;
4640 cmb.KeyDown += SearchComboBox_KeyDown;
4643 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4644 cmbLang.Dock = DockStyle.Right;
4646 cmbLang.Name = "comboLang";
4647 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4648 cmbLang.TabStop = false;
4649 cmbLang.TabIndex = 2;
4650 cmbLang.Items.Add("");
4651 cmbLang.Items.Add("ja");
4652 cmbLang.Items.Add("en");
4653 cmbLang.Items.Add("ar");
4654 cmbLang.Items.Add("da");
4655 cmbLang.Items.Add("nl");
4656 cmbLang.Items.Add("fa");
4657 cmbLang.Items.Add("fi");
4658 cmbLang.Items.Add("fr");
4659 cmbLang.Items.Add("de");
4660 cmbLang.Items.Add("hu");
4661 cmbLang.Items.Add("is");
4662 cmbLang.Items.Add("it");
4663 cmbLang.Items.Add("no");
4664 cmbLang.Items.Add("pl");
4665 cmbLang.Items.Add("pt");
4666 cmbLang.Items.Add("ru");
4667 cmbLang.Items.Add("es");
4668 cmbLang.Items.Add("sv");
4669 cmbLang.Items.Add("th");
4671 lbl.Text = "Search(C-S-f)";
4672 lbl.Name = "label1";
4673 lbl.Dock = DockStyle.Left;
4675 lbl.Height = cmb.Height;
4676 lbl.TextAlign = ContentAlignment.MiddleLeft;
4679 btn.Text = "Search";
4680 btn.Name = "buttonSearch";
4681 btn.UseVisualStyleBackColor = true;
4682 btn.Dock = DockStyle.Right;
4683 btn.TabStop = false;
4685 btn.Click += SearchButton_Click;
4687 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4689 cmb.Items.Add(searchTab.SearchWords);
4690 cmb.Text = searchTab.SearchWords;
4693 cmbLang.Text = searchTab.SearchLang;
4695 _tabPage.Controls.Add(pnl);
4699 _tabPage.Tag = _listCustom;
4700 this.ListTab.Controls.Add(_tabPage);
4702 _tabPage.Location = new Point(4, 4);
4703 _tabPage.Name = "CTab" + cnt.ToString();
4704 _tabPage.Size = new Size(380, 260);
4705 _tabPage.TabIndex = 2 + cnt;
4706 _tabPage.Text = tab.TabName;
4707 _tabPage.UseVisualStyleBackColor = true;
4708 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4710 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4711 _listCustom.TabIndex = 1;
4712 _listCustom.AllowColumnReorder = true;
4713 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4714 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4715 _listCustom.Dock = DockStyle.Fill;
4716 _listCustom.FullRowSelect = true;
4717 _listCustom.HideSelection = false;
4718 _listCustom.Location = new Point(0, 0);
4719 _listCustom.Margin = new Padding(0);
4720 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4721 _listCustom.ShowItemToolTips = true;
4722 _listCustom.Size = new Size(380, 260);
4723 _listCustom.UseCompatibleStateImageBehavior = false;
4724 _listCustom.View = View.Details;
4725 _listCustom.OwnerDraw = true;
4726 _listCustom.VirtualMode = true;
4727 _listCustom.Font = _fntReaded;
4728 _listCustom.BackColor = _clListBackcolor;
4730 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4731 _listCustom.AllowDrop = true;
4733 _listCustom.SmallImageList = _listViewImageList;
4735 InitColumns(_listCustom, startup);
4737 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4738 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4739 _listCustom.ColumnClick += MyList_ColumnClick;
4740 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4741 _listCustom.DragDrop += TweenMain_DragDrop;
4742 _listCustom.DragEnter += TweenMain_DragEnter;
4743 _listCustom.DragOver += TweenMain_DragOver;
4744 _listCustom.DrawItem += MyList_DrawItem;
4745 _listCustom.MouseClick += MyList_MouseClick;
4746 _listCustom.ColumnReordered += MyList_ColumnReordered;
4747 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4748 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4749 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4750 _listCustom.DrawSubItem += MyList_DrawSubItem;
4751 _listCustom.HScrolled += MyList_HScrolled;
4757 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4759 var tabInfo = _statuses.GetTabByName(TabName);
4760 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4764 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4765 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4766 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4772 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4773 if (_tabPage == null) return false;
4775 SetListProperty(); //他のタブに列幅等を反映
4778 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4779 _tabPage.Tag = null;
4781 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4782 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4783 using (ControlTransaction.Layout(this.SplitContainer1, false))
4784 using (ControlTransaction.Layout(this.ListTab, false))
4785 using (ControlTransaction.Layout(this))
4786 using (ControlTransaction.Layout(_tabPage, false))
4788 if (this.ListTab.SelectedTab == _tabPage)
4790 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4791 this._beforeSelectedTab = null;
4793 this.ListTab.Controls.Remove(_tabPage);
4796 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4798 using (Control label = _tabPage.Controls["labelUser"])
4800 _tabPage.Controls.Remove(label);
4803 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4805 using (Control pnl = _tabPage.Controls["panelSearch"])
4807 pnl.Enter -= SearchControls_Enter;
4808 pnl.Leave -= SearchControls_Leave;
4809 _tabPage.Controls.Remove(pnl);
4811 foreach (Control ctrl in pnl.Controls)
4813 if (ctrl.Name == "buttonSearch")
4815 ctrl.Click -= SearchButton_Click;
4817 else if (ctrl.Name == "comboSearch")
4819 ctrl.KeyDown -= SearchComboBox_KeyDown;
4821 pnl.Controls.Remove(ctrl);
4827 _tabPage.Controls.Remove(_listCustom);
4829 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4830 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4831 _listCustom.ColumnClick -= MyList_ColumnClick;
4832 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4833 _listCustom.DragDrop -= TweenMain_DragDrop;
4834 _listCustom.DragEnter -= TweenMain_DragEnter;
4835 _listCustom.DragOver -= TweenMain_DragOver;
4836 _listCustom.DrawItem -= MyList_DrawItem;
4837 _listCustom.MouseClick -= MyList_MouseClick;
4838 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4839 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4840 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4841 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4842 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4843 _listCustom.HScrolled -= MyList_HScrolled;
4845 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4846 _listCustom.Columns.Clear();
4847 cols.ForEach(col => col.Dispose());
4850 _listCustom.ContextMenuStrip = null;
4851 _listCustom.ColumnHeaderContextMenuStrip = null;
4852 _listCustom.Font = null;
4854 _listCustom.SmallImageList = null;
4855 _listCustom.ListViewItemSorter = null;
4858 if (_curTab.Equals(_tabPage))
4865 this.PurgeListViewItemCache();
4869 _listCustom.Dispose();
4870 _statuses.RemoveTab(TabName);
4872 foreach (TabPage tp in ListTab.TabPages)
4874 DetailsListView lst = (DetailsListView)tp.Tag;
4875 var count = _statuses.Tabs[tp.Text].AllCount;
4876 if (lst.VirtualListSize != count)
4878 lst.VirtualListSize = count;
4885 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4887 this.PurgeListViewItemCache();
4888 _beforeSelectedTab = e.TabPage;
4891 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4895 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4898 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4899 if (!dragEnableRectangle.Contains(e.Location))
4901 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4902 tn = ListTab.SelectedTab.Text;
4905 if (string.IsNullOrEmpty(tn)) return;
4907 foreach (TabPage tb in ListTab.TabPages)
4911 ListTab.DoDragDrop(tb, DragDropEffects.All);
4921 Point cpos = new Point(e.X, e.Y);
4922 for (int i = 0; i < ListTab.TabPages.Count; i++)
4924 Rectangle rect = ListTab.GetTabRect(i);
4925 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4926 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4928 _rclickTabName = ListTab.TabPages[i].Text;
4934 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4936 //_curList.Refresh();
4937 SetMainWindowTitle();
4938 SetStatusLabelUrl();
4939 SetApiStatusLabel();
4940 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4941 TabMenuControl(ListTab.SelectedTab.Text);
4942 this.PushSelectPostChain();
4943 await DispSelectedPost();
4946 private void SetListProperty()
4948 //削除などで見つからない場合は処理せず
4949 if (_curList == null) return;
4950 if (!_isColumnChanged) return;
4952 int[] dispOrder = new int[_curList.Columns.Count];
4953 for (int i = 0; i < _curList.Columns.Count; i++)
4955 for (int j = 0; j < _curList.Columns.Count; j++)
4957 if (_curList.Columns[j].DisplayIndex == i)
4966 foreach (TabPage tb in ListTab.TabPages)
4968 if (!tb.Equals(_curTab))
4970 if (tb.Tag != null && tb.Controls.Count > 0)
4972 DetailsListView lst = (DetailsListView)tb.Tag;
4973 for (int i = 0; i < lst.Columns.Count; i++)
4975 lst.Columns[dispOrder[i]].DisplayIndex = i;
4976 lst.Columns[i].Width = _curList.Columns[i].Width;
4982 _isColumnChanged = false;
4985 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4989 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
4990 || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
4991 || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
4993 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4995 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4997 SetStatusLabelUrl();
5005 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5007 if (e.KeyChar == '@')
5009 if (!this._cfgCommon.UseAtIdSupplement) return;
5011 int cnt = AtIdSupl.ItemCount;
5012 ShowSuplDialog(StatusText, AtIdSupl);
5013 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5016 else if (e.KeyChar == '#')
5018 if (!this._cfgCommon.UseHashSupplement) return;
5019 ShowSuplDialog(StatusText, HashSupl);
5024 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5026 ShowSuplDialog(owner, dialog, 0, "");
5029 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5031 ShowSuplDialog(owner, dialog, offset, "");
5034 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5036 dialog.StartsWith = startswith;
5043 dialog.ShowDialog();
5045 this.TopMost = this._cfgCommon.AlwaysTop;
5046 int selStart = owner.SelectionStart;
5049 if (dialog.DialogResult == DialogResult.OK)
5051 if (!string.IsNullOrEmpty(dialog.inputText))
5055 fHalf = owner.Text.Substring(0, selStart - offset);
5057 if (selStart < owner.Text.Length)
5059 eHalf = owner.Text.Substring(selStart);
5061 owner.Text = fHalf + dialog.inputText + eHalf;
5062 owner.SelectionStart = selStart + dialog.inputText.Length;
5069 fHalf = owner.Text.Substring(0, selStart);
5071 if (selStart < owner.Text.Length)
5073 eHalf = owner.Text.Substring(selStart);
5075 owner.Text = fHalf + eHalf;
5078 owner.SelectionStart = selStart;
5084 private void StatusText_KeyUp(object sender, KeyEventArgs e)
5087 if (!e.Alt && !e.Control && !e.Shift)
5089 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5091 bool isSpace = false;
5092 foreach (char c in StatusText.Text.ToCharArray())
5094 if (c == ' ' || c == ' ')
5107 StatusText.Text = "";
5108 JumpUnreadMenuItem_Click(null, null);
5112 this.StatusText_TextChanged(null, null);
5115 private void StatusText_TextChanged(object sender, EventArgs e)
5118 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5119 lblLen.Text = pLen.ToString();
5122 StatusText.ForeColor = Color.Red;
5126 StatusText.ForeColor = _clInputFont;
5128 if (string.IsNullOrEmpty(StatusText.Text))
5130 this.inReplyTo = null;
5135 /// ツイート投稿前のフッター付与などの前処理を行います
5137 private string FormatStatusText(string statusText)
5139 statusText = statusText.Replace("\r\n", "\n");
5141 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5144 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5147 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5149 // 文中の全角スペースを半角スペース1個にする
5150 statusText = statusText.Replace(" ", " ");
5153 // DM の場合はこれ以降の処理を行わない
5154 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5158 if (this._cfgCommon.PostShiftEnter)
5160 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5164 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5165 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5167 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5170 if (statusText.Contains("RT @"))
5171 disableFooter = true;
5176 var hashtag = this.HashMgr.UseHash;
5177 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5180 header = HashMgr.UseHash + " ";
5182 footer = " " + HashMgr.UseHash;
5187 if (this._cfgLocal.UseRecommendStatus)
5190 footer += this.recommendedStatusFooter;
5192 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5194 // テキストボックスに入力されている文字列を使用する
5195 footer += " " + this._cfgLocal.StatusText.Trim();
5199 statusText = header + statusText + footer;
5201 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5203 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5204 // 参照: https://support.twitter.com/articles/14020
5206 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5207 && !Twitter.DMSendTextRegex.IsMatch(statusText))
5209 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5210 statusText = '\u200b' + statusText;
5218 /// 投稿欄に表示する入力可能な文字数を計算します
5220 private int GetRestStatusCount(string statusText)
5223 var remainCount = this.tw.GetTextLengthRemain(statusText);
5225 if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5227 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5233 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5235 if (sender != this._curList)
5238 var listCache = this._listItemCache;
5239 if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5241 // If the newly requested cache is a subset of the old cache,
5242 // no need to rebuild everything, so do nothing.
5246 // Now we need to rebuild the cache.
5247 this.CreateCache(e.StartIndex, e.EndIndex);
5250 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5252 var listCache = this._listItemCache;
5253 if (listCache != null && listCache.TargetList == sender)
5256 PostClass cacheItemPost;
5257 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5264 // A cache miss, so create a new ListViewItem and pass it back.
5265 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5268 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5272 // 不正な要求に対する間に合わせの応答
5273 string[] sitem = {"", "", "", "", "", "", "", ""};
5274 e.Item = new ImageListViewItem(sitem);
5278 private void CreateCache(int startIndex, int endIndex)
5280 var tabInfo = this._statuses.Tabs[this._curTab.Text];
5282 if (tabInfo.AllCount == 0)
5285 // キャッシュ要求(要求範囲±30を作成)
5286 startIndex = Math.Max(startIndex - 30, 0);
5287 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5289 var cacheLength = endIndex - startIndex + 1;
5291 var posts = tabInfo[startIndex, endIndex]; //配列で取得
5292 var listItems = Enumerable.Range(0, cacheLength)
5293 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5296 var listCache = new ListViewItemCache
5298 TargetList = this._curList,
5299 StartIndex = startIndex,
5300 EndIndex = endIndex,
5302 ListItem = listItems,
5305 Interlocked.Exchange(ref this._listItemCache, listCache);
5309 /// DetailsListView のための ListViewItem のキャッシュを消去する
5311 private void PurgeListViewItemCache()
5313 Interlocked.Exchange(ref this._listItemCache, null);
5316 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5318 StringBuilder mk = new StringBuilder();
5319 //if (Post.IsDeleted) mk.Append("×");
5320 //if (Post.IsMark) mk.Append("♪");
5321 //if (Post.IsProtect) mk.Append("Ю");
5322 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5323 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5324 ImageListViewItem itm;
5325 if (Post.RetweetedId == null)
5327 string[] sitem= {"",
5329 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5330 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5335 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5339 string[] sitem = {"",
5341 Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5342 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5343 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5347 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5349 itm.StateIndex = Post.StateIndex;
5351 bool read = Post.IsRead;
5352 //未読管理していなかったら既読として扱う
5353 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5354 ChangeItemStyleRead(read, itm, Post, null);
5355 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5360 /// 全てのタブの振り分けルールを反映し直します
5362 private void ApplyPostFilters()
5364 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5366 this.PurgeListViewItemCache();
5367 this._curPost = null;
5368 this._curItemIndex = -1;
5369 this._statuses.FilterAll();
5371 foreach (TabPage tabPage in this.ListTab.TabPages)
5373 var tab = this._statuses.Tabs[tabPage.Text];
5375 var listview = (DetailsListView)tabPage.Tag;
5376 using (ControlTransaction.Update(listview))
5378 listview.VirtualListSize = tab.AllCount;
5381 if (this._cfgCommon.TabIconDisp)
5383 if (tab.UnreadCount > 0)
5384 tabPage.ImageIndex = 0;
5386 tabPage.ImageIndex = -1;
5390 if (!this._cfgCommon.TabIconDisp)
5391 this.ListTab.Refresh();
5393 SetMainWindowTitle();
5394 SetStatusLabelUrl();
5398 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5400 e.DrawDefault = true;
5403 private void MyList_HScrolled(object sender, EventArgs e)
5405 DetailsListView listView = (DetailsListView)sender;
5409 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5411 if (e.State == 0) return;
5412 e.DrawDefault = false;
5414 SolidBrush brs2 = null;
5415 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5417 if (e.Item.BackColor == _clSelf)
5418 brs2 = _brsBackColorMine;
5419 else if (e.Item.BackColor == _clAtSelf)
5420 brs2 = _brsBackColorAt;
5421 else if (e.Item.BackColor == _clTarget)
5422 brs2 = _brsBackColorYou;
5423 else if (e.Item.BackColor == _clAtTarget)
5424 brs2 = _brsBackColorAtYou;
5425 else if (e.Item.BackColor == _clAtFromTarget)
5426 brs2 = _brsBackColorAtFromTarget;
5427 else if (e.Item.BackColor == _clAtTo)
5428 brs2 = _brsBackColorAtTo;
5430 brs2 = _brsBackColorNone;
5435 if (((Control)sender).Focused)
5436 brs2 = _brsHighLight;
5438 brs2 = _brsDeactiveSelection;
5440 e.Graphics.FillRectangle(brs2, e.Bounds);
5441 e.DrawFocusRectangle();
5442 this.DrawListViewItemIcon(e);
5445 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5447 if (e.ItemState == 0) return;
5449 if (e.ColumnIndex > 0)
5452 RectangleF rct = e.Bounds;
5453 rct.Width = e.Header.Width;
5454 int fontHeight = e.Item.Font.Height;
5457 rct.Y += fontHeight;
5458 rct.Height -= fontHeight;
5462 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5464 //if (heightDiff > fontHeight * 0.7)
5466 // rct.Height += fontHeight;
5467 // drawLineCount += 1;
5470 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5471 if (!_iconCol && drawLineCount <= 1)
5473 //rct.Inflate(0, heightDiff / -2);
5474 //rct.Height += fontHeight / 2;
5476 else if (heightDiff < fontHeight * 0.7)
5478 //最終行が70%以上欠けていたら、最終行は表示しない
5479 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5480 rct.Height = (fontHeight * drawLineCount) - 1;
5487 //if (!_iconCol && drawLineCount > 1)
5489 // rct.Y += fontHeight * 0.2;
5490 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5495 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5496 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5501 Rectangle rctB = e.Bounds;
5502 rctB.Width = e.Header.Width;
5503 rctB.Height = fontHeight;
5505 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5507 TextRenderer.DrawText(e.Graphics,
5508 e.Item.SubItems[2].Text,
5510 Rectangle.Round(rct),
5512 TextFormatFlags.WordBreak |
5513 TextFormatFlags.EndEllipsis |
5514 TextFormatFlags.GlyphOverhangPadding |
5515 TextFormatFlags.NoPrefix);
5516 TextRenderer.DrawText(e.Graphics,
5517 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 + "]",
5521 TextFormatFlags.SingleLine |
5522 TextFormatFlags.EndEllipsis |
5523 TextFormatFlags.GlyphOverhangPadding |
5524 TextFormatFlags.NoPrefix);
5527 else if (drawLineCount == 1)
5529 TextRenderer.DrawText(e.Graphics,
5532 Rectangle.Round(rct),
5534 TextFormatFlags.SingleLine |
5535 TextFormatFlags.EndEllipsis |
5536 TextFormatFlags.GlyphOverhangPadding |
5537 TextFormatFlags.NoPrefix |
5538 TextFormatFlags.VerticalCenter);
5542 TextRenderer.DrawText(e.Graphics,
5545 Rectangle.Round(rct),
5547 TextFormatFlags.WordBreak |
5548 TextFormatFlags.EndEllipsis |
5549 TextFormatFlags.GlyphOverhangPadding |
5550 TextFormatFlags.NoPrefix);
5552 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5557 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5559 if (_iconSz == 0) return;
5561 ImageListViewItem item = (ImageListViewItem)e.Item;
5563 //e.Bounds.Leftが常に0を指すから自前で計算
5564 Rectangle itemRect = item.Bounds;
5565 var col0 = e.Item.ListView.Columns[0];
5566 itemRect.Width = col0.Width;
5568 if (col0.DisplayIndex > 0)
5570 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5572 if (clm.DisplayIndex < col0.DisplayIndex)
5573 itemRect.X += clm.Width;
5577 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5578 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5579 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5582 var img = item.Image;
5585 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5586 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5588 if (iconRect.Width > 0)
5590 e.Graphics.FillRectangle(Brushes.White, iconRect);
5591 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5594 e.Graphics.DrawImage(img.Image, iconRect);
5596 catch (ArgumentException)
5598 item.RefreshImageAsync();
5604 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5605 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5607 item.GetImageAsync();
5610 if (item.StateIndex > -1)
5612 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5613 if (stateRect.Width > 0)
5615 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5616 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5617 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5622 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5624 base.ScaleControl(factor, specified);
5626 ScaleChildControl(this.TabImage, factor);
5628 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5629 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5631 foreach (var listview in listviews)
5633 ScaleChildControl(listview, factor);
5637 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5639 // ImageListViewItem item = (ImageListViewItem)e.Item;
5640 // if (item.StateImageIndex > -1)
5642 // ////e.Bounds.Leftが常に0を指すから自前で計算
5643 // //Rectangle itemRect = item.Bounds;
5644 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5646 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5648 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5650 // // itemRect.X += clm.Width;
5654 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5655 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5657 // if (rct.Width > 0)
5659 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5660 // //e.Graphics.FillRectangle(Brushes.White, rct);
5661 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5662 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5667 private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5669 var tab = this._statuses.Tabs[this._curTab.Text];
5671 if (tab.AllCount == 0)
5673 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5677 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5682 case SEARCHTYPE.NextSearch: // 次を検索
5683 if (selectedIndex != -1)
5684 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5688 case SEARCHTYPE.PrevSearch: // 前を検索
5689 if (selectedIndex != -1)
5690 startIndex = Math.Max(selectedIndex - 1, 0);
5692 startIndex = tab.AllCount - 1;
5694 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5696 if (selectedIndex != -1)
5697 startIndex = selectedIndex;
5703 Func<string, bool> stringComparer;
5706 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5708 catch (ArgumentException)
5710 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5714 var reverse = searchType == SEARCHTYPE.PrevSearch;
5715 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5716 .DefaultIfEmpty(-1).First();
5718 if (foundIndex == -1)
5720 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5724 this.SelectListItem(this._curList, foundIndex);
5725 this._curList.EnsureVisible(foundIndex);
5728 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5731 this.ShowSearchDialog();
5734 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5736 var previousSearch = this.SearchDialog.ResultOptions;
5737 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5739 this.SearchDialog.Reset();
5740 this.ShowSearchDialog();
5746 previousSearch.Query,
5747 previousSearch.CaseSensitive,
5748 previousSearch.UseRegex,
5749 SEARCHTYPE.NextSearch);
5752 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5754 var previousSearch = this.SearchDialog.ResultOptions;
5755 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5757 this.SearchDialog.Reset();
5758 this.ShowSearchDialog();
5764 previousSearch.Query,
5765 previousSearch.CaseSensitive,
5766 previousSearch.UseRegex,
5767 SEARCHTYPE.PrevSearch);
5771 /// 検索ダイアログを表示し、検索を実行します
5773 private void ShowSearchDialog()
5775 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5777 this.TopMost = this._cfgCommon.AlwaysTop;
5780 this.TopMost = this._cfgCommon.AlwaysTop;
5782 var searchOptions = this.SearchDialog.ResultOptions;
5783 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5785 if (searchOptions.NewTab)
5787 var tabName = Properties.Resources.SearchResults_TabName;
5791 tabName = this._statuses.MakeTabName(tabName);
5793 catch (TabException ex)
5795 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5798 var resultTab = new LocalSearchTabModel(tabName);
5799 this.AddNewTab(resultTab, startup: false);
5800 this._statuses.AddTab(resultTab);
5802 var targetTab = this._statuses.Tabs[this._curTab.Text];
5804 Func<string, bool> stringComparer;
5807 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5809 catch (ArgumentException)
5811 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5815 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5816 if (foundIndices.Length == 0)
5818 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5822 var foundPosts = foundIndices.Select(x => targetTab[x]);
5823 foreach (var post in foundPosts)
5825 resultTab.AddPostQueue(post);
5828 this._statuses.DistributePosts();
5829 this.RefreshTimeline();
5831 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5832 .First(x => x.Text == tabName);
5834 this.ListTab.SelectedTab = tabPage;
5839 searchOptions.Query,
5840 searchOptions.CaseSensitive,
5841 searchOptions.UseRegex,
5842 SEARCHTYPE.DialogSearch);
5845 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5847 this.AddNewTabForSearch(searchOptions.Query);
5851 /// <summary>発言検索に使用するメソッドを生成します</summary>
5852 /// <exception cref="ArgumentException">
5853 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5855 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5859 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5860 var regex = new Regex(query, regexOption);
5862 return x => regex.IsMatch(x);
5866 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5868 return x => x.IndexOf(query, comparisonType) != -1;
5872 private void AboutMenuItem_Click(object sender, EventArgs e)
5874 using (TweenAboutBox about = new TweenAboutBox())
5876 about.ShowDialog(this);
5878 this.TopMost = this._cfgCommon.AlwaysTop;
5881 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5883 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5885 DetailsListView lst = null;
5887 if (ImageSelector.Enabled)
5891 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5894 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5897 ListTab.SelectedIndex = i;
5898 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5899 //_curTab = ListTab.TabPages[i];
5904 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5905 if (idx == -1 && bgnIdx > 0)
5907 for (int i = 0; i < bgnIdx; i++)
5909 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5912 ListTab.SelectedIndex = i;
5913 lst = (DetailsListView)ListTab.TabPages[i].Tag;
5914 //_curTab = ListTab.TabPages[i];
5920 //全部調べたが未読見つからず→先頭タブの最新発言へ
5923 ListTab.SelectedIndex = 0;
5924 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5925 //_curTab = ListTab.TabPages[0];
5926 if (_statuses.SortOrder == SortOrder.Ascending)
5927 idx = lst.VirtualListSize - 1;
5932 if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5934 SelectListItem(lst, idx);
5935 if (_statuses.SortMode == ComparerMode.Id)
5937 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5938 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5944 lst.EnsureVisible(idx);
5949 lst.EnsureVisible(idx);
5955 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5957 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5959 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5960 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5964 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5966 if (_curList.SelectedIndices.Count > 0)
5968 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5969 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5973 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5975 await this.CheckNewVersion(false);
5978 private void RunTweenUp()
5980 ProcessStartInfo pinfo = new ProcessStartInfo();
5981 pinfo.UseShellExecute = true;
5982 pinfo.WorkingDirectory = MyCommon.settingPath;
5983 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5984 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5987 Process.Start(pinfo);
5991 MessageBox.Show("Failed to execute TweenUp3.exe.");
5995 public class VersionInfo
5997 public Version Version { get; set; }
5998 public Uri DownloadUri { get; set; }
5999 public string ReleaseNote { get; set; }
6003 /// OpenTween の最新バージョンの情報を取得します
6005 public async Task<VersionInfo> GetVersionInfoAsync()
6007 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6008 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6010 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6011 .ConfigureAwait(false);
6013 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6014 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6016 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6017 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6019 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6021 return new VersionInfo
6023 Version = Version.Parse(msgHeader[0]),
6024 DownloadUri = new Uri(msgHeader[1]),
6025 ReleaseNote = msgBody,
6029 private async Task CheckNewVersion(bool startup = false)
6031 if (ApplicationSettings.VersionInfoUrl == null)
6032 return; // 更新チェック無効化
6036 var versionInfo = await this.GetVersionInfoAsync();
6038 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6043 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6044 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6045 msgtext = MyCommon.ReplaceAppName(msgtext);
6047 MessageBox.Show(msgtext,
6048 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6049 MessageBoxButtons.OK, MessageBoxIcon.Information);
6054 using (var dialog = new UpdateDialog())
6056 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6057 MyCommon.GetReadableVersion(versionInfo.Version));
6058 dialog.DetailsText = versionInfo.ReleaseNote;
6060 if (dialog.ShowDialog(this) == DialogResult.Yes)
6062 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6068 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6071 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6072 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6073 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6078 private async Task Colorize()
6081 await this.DispSelectedPost();
6082 //件数関連の場合、タイトル即時書き換え
6083 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6084 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6085 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6086 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6088 SetMainWindowTitle();
6090 if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6091 foreach (TabPage tb in ListTab.TabPages)
6093 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6095 if (this._cfgCommon.TabIconDisp)
6097 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6101 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6104 public string createDetailHtml(string orgdata)
6106 if (this._cfgLocal.UseTwemoji)
6107 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6109 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6112 private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6114 if (sender.Equals(displayItem))
6116 this.ClearUserPicture();
6118 var img = displayItem.Image;
6122 img = await img.CloneAsync();
6124 UserPicture.Image = img;
6128 UserPicture.ShowErrorImage();
6133 private Task DispSelectedPost()
6135 return this.DispSelectedPost(false);
6138 private PostClass displayPost = new PostClass();
6141 /// サムネイル表示に使用する CancellationToken の生成元
6143 private CancellationTokenSource thumbnailTokenSource = null;
6145 private async Task DispSelectedPost(bool forceupdate)
6147 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6150 var oldDisplayPost = this.displayPost;
6151 this.displayPost = this._curPost;
6153 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6156 if (displayItem != null)
6158 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6161 displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6162 displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6164 using (ControlTransaction.Update(this.TableLayoutPanel1))
6166 SourceLinkLabel.Text = this._curPost.Source;
6167 SourceLinkLabel.Tag = this._curPost.SourceUri;
6168 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6174 nameText = "DM FROM <- ";
6176 nameText = "DM TO -> ";
6182 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6183 if (_curPost.RetweetedId != null)
6184 nameText += " (RT:" + _curPost.RetweetedBy + ")";
6186 NameLabel.Text = nameText;
6187 NameLabel.Tag = _curPost.ScreenName;
6189 var nameForeColor = SystemColors.ControlText;
6190 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6191 nameForeColor = this._clOWL;
6192 if (_curPost.RetweetedId != null)
6193 nameForeColor = this._clRetweet;
6195 nameForeColor = this._clFav;
6196 NameLabel.ForeColor = nameForeColor;
6198 this.ClearUserPicture();
6200 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6202 var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6205 UserPicture.Image = image?.Clone();
6209 UserPicture.ShowErrorImage();
6213 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6216 if (DumpPostClassToolStripMenuItem.Checked)
6218 StringBuilder sb = new StringBuilder(512);
6220 sb.Append("-----Start PostClass Dump<br>");
6221 sb.AppendFormat("TextFromApi : {0}<br>", _curPost.TextFromApi);
6222 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6223 sb.AppendFormat("StatusId : {0}<br>", _curPost.StatusId.ToString());
6224 //sb.AppendFormat("ImageIndex : {0}<br>", _curPost.ImageIndex.ToString());
6225 sb.AppendFormat("ImageUrl : {0}<br>", _curPost.ImageUrl);
6226 sb.AppendFormat("InReplyToStatusId : {0}<br>", _curPost.InReplyToStatusId.ToString());
6227 sb.AppendFormat("InReplyToUser : {0}<br>", _curPost.InReplyToUser);
6228 sb.AppendFormat("IsDM : {0}<br>", _curPost.IsDm.ToString());
6229 sb.AppendFormat("IsFav : {0}<br>", _curPost.IsFav.ToString());
6230 sb.AppendFormat("IsMark : {0}<br>", _curPost.IsMark.ToString());
6231 sb.AppendFormat("IsMe : {0}<br>", _curPost.IsMe.ToString());
6232 sb.AppendFormat("IsOwl : {0}<br>", _curPost.IsOwl.ToString());
6233 sb.AppendFormat("IsProtect : {0}<br>", _curPost.IsProtect.ToString());
6234 sb.AppendFormat("IsRead : {0}<br>", _curPost.IsRead.ToString());
6235 sb.AppendFormat("IsReply : {0}<br>", _curPost.IsReply.ToString());
6237 foreach (string nm in _curPost.ReplyToList)
6239 sb.AppendFormat("ReplyToList : {0}<br>", nm);
6242 sb.AppendFormat("ScreenName : {0}<br>", _curPost.ScreenName);
6243 sb.AppendFormat("NickName : {0}<br>", _curPost.Nickname);
6244 sb.AppendFormat("Text : {0}<br>", _curPost.Text);
6245 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", _curPost.Text);
6246 sb.AppendFormat("CreatedAt : {0}<br>", _curPost.CreatedAt.ToString());
6247 sb.AppendFormat("Source : {0}<br>", _curPost.Source);
6248 sb.AppendFormat("UserId : {0}<br>", _curPost.UserId);
6249 sb.AppendFormat("FilterHit : {0}<br>", _curPost.FilterHit);
6250 sb.AppendFormat("RetweetedBy : {0}<br>", _curPost.RetweetedBy);
6251 sb.AppendFormat("RetweetedId : {0}<br>", _curPost.RetweetedId);
6253 sb.AppendFormat("Media.Count : {0}<br>", _curPost.Media.Count);
6254 if (_curPost.Media.Count > 0)
6256 for (int i = 0; i < _curPost.Media.Count; i++)
6258 var info = _curPost.Media[i];
6259 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
6260 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
6263 sb.Append("-----End PostClass Dump<br>");
6265 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6269 var loadTasks = new List<Task>();
6271 // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6272 // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6273 if (_curPost.StatusId != oldDisplayPost.StatusId)
6275 using (ControlTransaction.Update(this.PostBrowser))
6277 this.PostBrowser.DocumentText =
6278 this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6280 this.PostBrowser.Document.Window.ScrollTo(0, 0);
6283 this.SplitContainer3.Panel2Collapsed = true;
6285 if (this._cfgCommon.PreviewEnable)
6287 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6288 oldTokenSource?.Cancel();
6290 var token = this.thumbnailTokenSource.Token;
6291 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6294 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6299 await Task.WhenAll(loadTasks);
6301 catch (OperationCanceledException) { }
6305 /// 発言詳細欄のツイートURLを展開する
6307 private async Task AppendQuoteTweetAsync(PostClass post)
6309 var quoteStatusIds = post.QuoteStatusIds;
6310 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6314 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6316 var loadingReplyHtml = string.Empty;
6317 if (post.InReplyToStatusId != null)
6318 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6320 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6322 using (ControlTransaction.Update(this.PostBrowser))
6323 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6326 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6328 if (post.InReplyToStatusId != null)
6329 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6331 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6333 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6334 if (this._curPost != post || this._curPost.IsDeleted)
6337 body = post.Text + string.Concat(quoteHtmls);
6339 using (ControlTransaction.Update(this.PostBrowser))
6340 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6343 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6345 PostClass post = this._statuses[statusId];
6350 post = await this.tw.GetStatusApi(false, statusId)
6351 .ConfigureAwait(false);
6353 catch (WebApiException ex)
6355 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6359 if (!this._statuses.AddQuoteTweet(post))
6360 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6363 return FormatQuoteTweetHtml(post, isReply);
6366 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6368 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6369 " — " + WebUtility.HtmlEncode(post.Nickname) +
6370 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6371 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6373 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6376 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6378 var blockClassName = "quote-tweet";
6381 blockClassName += " reply";
6383 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6384 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6389 /// 指定されたHTMLからリンクを除去します
6391 internal static string StripLinkTagHtml(string html)
6393 // a 要素はネストされていない前提の正規表現パターン
6394 return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6397 private async void MatomeMenuItem_Click(object sender, EventArgs e)
6399 await this.OpenApplicationWebsite();
6402 private async Task OpenApplicationWebsite()
6404 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6407 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6409 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6412 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6414 if (ListTab.SelectedTab != null)
6416 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6418 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6419 if (pnl.Controls["comboSearch"].Focused ||
6420 pnl.Controls["comboLang"].Focused ||
6421 pnl.Controls["buttonSearch"].Focused) return;
6424 if (e.Control || e.Shift || e.Alt)
6425 this._anchorFlag = false;
6428 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6431 e.SuppressKeyPress = true;
6434 if (asyncTask != null)
6439 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6441 private void InitializeShortcuts()
6443 this.shortcutCommands = new[]
6445 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6446 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6447 .FocusedOn(FocusedControl.ListTab)
6448 .Do(() => SendKeys.Send("{DOWN}")),
6450 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6451 .FocusedOn(FocusedControl.ListTab)
6452 .Do(() => SendKeys.Send("{UP}")),
6454 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6455 .FocusedOn(FocusedControl.ListTab)
6456 .Do(() => SendKeys.Send("{PGDN}")),
6458 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6459 .FocusedOn(FocusedControl.ListTab)
6460 .Do(() => SendKeys.Send("{PGUP}")),
6462 ShortcutCommand.Create(Keys.F1)
6463 .Do(() => this.OpenApplicationWebsite()),
6465 ShortcutCommand.Create(Keys.F3)
6466 .Do(() => this.MenuItemSearchNext_Click(null, null)),
6468 ShortcutCommand.Create(Keys.F5)
6469 .Do(() => this.DoRefresh()),
6471 ShortcutCommand.Create(Keys.F6)
6472 .Do(() => this.GetReplyAsync()),
6474 ShortcutCommand.Create(Keys.F7)
6475 .Do(() => this.GetDirectMessagesAsync()),
6477 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6478 .NotFocusedOn(FocusedControl.StatusText)
6479 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6481 ShortcutCommand.Create(Keys.G)
6482 .NotFocusedOn(FocusedControl.StatusText)
6483 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6485 ShortcutCommand.Create(Keys.Right, Keys.N)
6486 .FocusedOn(FocusedControl.ListTab)
6487 .Do(() => this.GoRelPost(forward: true)),
6489 ShortcutCommand.Create(Keys.Left, Keys.P)
6490 .FocusedOn(FocusedControl.ListTab)
6491 .Do(() => this.GoRelPost(forward: false)),
6493 ShortcutCommand.Create(Keys.OemPeriod)
6494 .FocusedOn(FocusedControl.ListTab)
6495 .Do(() => this.GoAnchor()),
6497 ShortcutCommand.Create(Keys.I)
6498 .FocusedOn(FocusedControl.ListTab)
6499 .OnlyWhen(() => this.StatusText.Enabled)
6500 .Do(() => this.StatusText.Focus()),
6502 ShortcutCommand.Create(Keys.Enter)
6503 .FocusedOn(FocusedControl.ListTab)
6504 .Do(() => this.MakeReplyOrDirectStatus()),
6506 ShortcutCommand.Create(Keys.R)
6507 .FocusedOn(FocusedControl.ListTab)
6508 .Do(() => this.DoRefresh()),
6510 ShortcutCommand.Create(Keys.L)
6511 .FocusedOn(FocusedControl.ListTab)
6512 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6514 ShortcutCommand.Create(Keys.H)
6515 .FocusedOn(FocusedControl.ListTab)
6516 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6518 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6519 .FocusedOn(FocusedControl.ListTab)
6520 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6522 ShortcutCommand.Create(Keys.S)
6523 .FocusedOn(FocusedControl.ListTab)
6524 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6526 ShortcutCommand.Create(Keys.A)
6527 .FocusedOn(FocusedControl.ListTab)
6528 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6530 // ] in_reply_to参照元へ戻る
6531 ShortcutCommand.Create(Keys.Oem4)
6532 .FocusedOn(FocusedControl.ListTab)
6533 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6535 // [ in_reply_toへジャンプ
6536 ShortcutCommand.Create(Keys.Oem6)
6537 .FocusedOn(FocusedControl.ListTab)
6538 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6540 ShortcutCommand.Create(Keys.Escape)
6541 .FocusedOn(FocusedControl.ListTab)
6543 this._anchorFlag = false;
6544 if (ListTab.SelectedTab != null)
6546 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6547 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6549 var relTp = ListTab.SelectedTab;
6550 RemoveSpecifiedTab(relTp.Text, false);
6556 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6557 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6558 .FocusedOn(FocusedControl.ListTab)
6559 .Do(() => this._anchorFlag = false, preventDefault: false),
6561 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6562 ShortcutCommand.Create(Keys.Up, Keys.Down)
6563 .FocusedOn(FocusedControl.PostBrowser)
6566 ShortcutCommand.Create(Keys.Control | Keys.R)
6567 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6569 ShortcutCommand.Create(Keys.Control | Keys.D)
6570 .Do(() => this.doStatusDelete()),
6572 ShortcutCommand.Create(Keys.Control | Keys.M)
6573 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6575 ShortcutCommand.Create(Keys.Control | Keys.S)
6576 .Do(() => this.FavoriteChange(FavAdd: true)),
6578 ShortcutCommand.Create(Keys.Control | Keys.I)
6579 .Do(() => this.doRepliedStatusOpen()),
6581 ShortcutCommand.Create(Keys.Control | Keys.Q)
6582 .Do(() => this.doQuoteOfficial()),
6584 ShortcutCommand.Create(Keys.Control | Keys.B)
6585 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6587 ShortcutCommand.Create(Keys.Control | Keys.T)
6588 .Do(() => this.HashManageMenuItem_Click(null, null)),
6590 ShortcutCommand.Create(Keys.Control | Keys.L)
6591 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6593 ShortcutCommand.Create(Keys.Control | Keys.Y)
6594 .NotFocusedOn(FocusedControl.PostBrowser)
6595 .Do(() => this.MultiLineMenuItem_Click(null, null)),
6597 ShortcutCommand.Create(Keys.Control | Keys.F)
6598 .Do(() => this.MenuItemSubSearch_Click(null, null)),
6600 ShortcutCommand.Create(Keys.Control | Keys.U)
6601 .Do(() => this.ShowUserTimeline()),
6603 ShortcutCommand.Create(Keys.Control | Keys.H)
6604 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6606 ShortcutCommand.Create(Keys.Control | Keys.G)
6607 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6609 ShortcutCommand.Create(Keys.Control | Keys.O)
6610 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6612 ShortcutCommand.Create(Keys.Control | Keys.E)
6613 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6615 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6616 .FocusedOn(FocusedControl.ListTab)
6617 .Do(() => this._colorize = true, preventDefault: false),
6619 ShortcutCommand.Create(Keys.Control | Keys.N)
6620 .FocusedOn(FocusedControl.ListTab)
6621 .Do(() => this.GoNextTab(forward: true)),
6623 ShortcutCommand.Create(Keys.Control | Keys.P)
6624 .FocusedOn(FocusedControl.ListTab)
6625 .Do(() => this.GoNextTab(forward: false)),
6627 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6628 .FocusedOn(FocusedControl.ListTab)
6629 .Do(() => this.CopyStot()),
6631 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6632 ShortcutCommand.Create(Keys.Control | Keys.D1)
6633 .FocusedOn(FocusedControl.ListTab)
6634 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6635 .Do(() => this.ListTab.SelectedIndex = 0),
6637 ShortcutCommand.Create(Keys.Control | Keys.D2)
6638 .FocusedOn(FocusedControl.ListTab)
6639 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6640 .Do(() => this.ListTab.SelectedIndex = 1),
6642 ShortcutCommand.Create(Keys.Control | Keys.D3)
6643 .FocusedOn(FocusedControl.ListTab)
6644 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6645 .Do(() => this.ListTab.SelectedIndex = 2),
6647 ShortcutCommand.Create(Keys.Control | Keys.D4)
6648 .FocusedOn(FocusedControl.ListTab)
6649 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6650 .Do(() => this.ListTab.SelectedIndex = 3),
6652 ShortcutCommand.Create(Keys.Control | Keys.D5)
6653 .FocusedOn(FocusedControl.ListTab)
6654 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6655 .Do(() => this.ListTab.SelectedIndex = 4),
6657 ShortcutCommand.Create(Keys.Control | Keys.D6)
6658 .FocusedOn(FocusedControl.ListTab)
6659 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6660 .Do(() => this.ListTab.SelectedIndex = 5),
6662 ShortcutCommand.Create(Keys.Control | Keys.D7)
6663 .FocusedOn(FocusedControl.ListTab)
6664 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6665 .Do(() => this.ListTab.SelectedIndex = 6),
6667 ShortcutCommand.Create(Keys.Control | Keys.D8)
6668 .FocusedOn(FocusedControl.ListTab)
6669 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6670 .Do(() => this.ListTab.SelectedIndex = 7),
6672 ShortcutCommand.Create(Keys.Control | Keys.D9)
6673 .FocusedOn(FocusedControl.ListTab)
6674 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6676 ShortcutCommand.Create(Keys.Control | Keys.A)
6677 .FocusedOn(FocusedControl.StatusText)
6678 .Do(() => this.StatusText.SelectAll()),
6680 ShortcutCommand.Create(Keys.Control | Keys.V)
6681 .FocusedOn(FocusedControl.StatusText)
6682 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6684 ShortcutCommand.Create(Keys.Control | Keys.Up)
6685 .FocusedOn(FocusedControl.StatusText)
6687 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6689 var inReplyToStatusId = this.inReplyTo?.Item1;
6690 var inReplyToScreenName = this.inReplyTo?.Item2;
6691 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6694 if (_hisIdx < 0) _hisIdx = 0;
6696 var historyItem = this._history[this._hisIdx];
6697 StatusText.Text = historyItem.status;
6698 StatusText.SelectionStart = StatusText.Text.Length;
6699 if (historyItem.inReplyToId != null)
6700 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6702 this.inReplyTo = null;
6705 ShortcutCommand.Create(Keys.Control | Keys.Down)
6706 .FocusedOn(FocusedControl.StatusText)
6708 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6710 var inReplyToStatusId = this.inReplyTo?.Item1;
6711 var inReplyToScreenName = this.inReplyTo?.Item2;
6712 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6715 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6717 var historyItem = this._history[this._hisIdx];
6718 StatusText.Text = historyItem.status;
6719 StatusText.SelectionStart = StatusText.Text.Length;
6720 if (historyItem.inReplyToId != null)
6721 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6723 this.inReplyTo = null;
6726 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6727 .FocusedOn(FocusedControl.StatusText)
6729 if (ListTab.SelectedIndex == 0)
6731 ListTab.SelectedIndex = ListTab.TabCount - 1;
6735 ListTab.SelectedIndex -= 1;
6740 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6741 .FocusedOn(FocusedControl.StatusText)
6743 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6745 ListTab.SelectedIndex = 0;
6749 ListTab.SelectedIndex += 1;
6754 ShortcutCommand.Create(Keys.Control | Keys.Y)
6755 .FocusedOn(FocusedControl.PostBrowser)
6757 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6758 MultiLineMenuItem_Click(null, null);
6761 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6762 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6764 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6765 .Do(() => this.DoRefreshMore()),
6767 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6768 .Do(() => this.GetReplyAsync(loadMore: true)),
6770 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6771 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6773 ShortcutCommand.Create(Keys.Shift | Keys.R)
6774 .NotFocusedOn(FocusedControl.StatusText)
6775 .Do(() => this.DoRefreshMore()),
6777 ShortcutCommand.Create(Keys.Shift | Keys.H)
6778 .FocusedOn(FocusedControl.ListTab)
6779 .Do(() => this.GoTopEnd(GoTop: true)),
6781 ShortcutCommand.Create(Keys.Shift | Keys.L)
6782 .FocusedOn(FocusedControl.ListTab)
6783 .Do(() => this.GoTopEnd(GoTop: false)),
6785 ShortcutCommand.Create(Keys.Shift | Keys.M)
6786 .FocusedOn(FocusedControl.ListTab)
6787 .Do(() => this.GoMiddle()),
6789 ShortcutCommand.Create(Keys.Shift | Keys.G)
6790 .FocusedOn(FocusedControl.ListTab)
6791 .Do(() => this.GoLast()),
6793 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6794 .FocusedOn(FocusedControl.ListTab)
6795 .Do(() => this.MoveMiddle()),
6797 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6798 .FocusedOn(FocusedControl.ListTab)
6799 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6801 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6802 .FocusedOn(FocusedControl.ListTab)
6803 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6805 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6806 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6807 .FocusedOn(FocusedControl.ListTab)
6808 .Do(() => this.GoFav(forward: true)),
6810 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6811 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6812 .FocusedOn(FocusedControl.ListTab)
6813 .Do(() => this.GoFav(forward: false)),
6815 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6816 .FocusedOn(FocusedControl.ListTab)
6817 .Do(() => this.GoBackSelectPostChain()),
6819 ShortcutCommand.Create(Keys.Alt | Keys.R)
6820 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6822 ShortcutCommand.Create(Keys.Alt | Keys.P)
6823 .OnlyWhen(() => this._curPost != null)
6824 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6826 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6827 .Do(() => this.ScrollDownPostBrowser(forward: false)),
6829 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6830 .Do(() => this.ScrollDownPostBrowser(forward: true)),
6832 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6833 .Do(() => this.PageDownPostBrowser(forward: false)),
6835 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6836 .Do(() => this.PageDownPostBrowser(forward: true)),
6838 // 別タブの同じ書き込みへ(ALT+←/→)
6839 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6840 .FocusedOn(FocusedControl.ListTab)
6841 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6843 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6844 .FocusedOn(FocusedControl.ListTab)
6845 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6847 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6848 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6850 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6851 .Do(() => this.CopyIdUri()),
6853 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6854 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6855 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6856 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6858 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6859 .Do(() => this.FavoriteChange(FavAdd: false)),
6861 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6862 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6864 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6865 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6867 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6868 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6870 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6871 .Do(() => this.doMoveToRTHome()),
6873 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6874 .Do(() => this.FavorareMenuItem_Click(null, null)),
6876 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6877 .FocusedOn(FocusedControl.StatusText)
6879 if (_curList != null && _curList.VirtualListSize != 0 &&
6880 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6882 var idx = _curList.SelectedIndices[0] - 1;
6883 SelectListItem(_curList, idx);
6884 _curList.EnsureVisible(idx);
6888 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6889 .FocusedOn(FocusedControl.StatusText)
6891 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6892 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6894 var idx = _curList.SelectedIndices[0] + 1;
6895 SelectListItem(_curList, idx);
6896 _curList.EnsureVisible(idx);
6900 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6901 .FocusedOn(FocusedControl.StatusText)
6903 if (StatusText.SelectionStart > 0)
6905 int endidx = StatusText.SelectionStart - 1;
6906 string startstr = "";
6907 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6909 char c = StatusText.Text[i];
6910 if (Char.IsLetterOrDigit(c) || c == '_')
6916 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6917 int cnt = AtIdSupl.ItemCount;
6918 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6919 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6923 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6924 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6934 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6935 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6936 .FocusedOn(FocusedControl.ListTab)
6937 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6939 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6940 .FocusedOn(FocusedControl.ListTab)
6941 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6943 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6944 .FocusedOn(FocusedControl.ListTab)
6945 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6947 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6948 .FocusedOn(FocusedControl.ListTab)
6949 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6951 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6952 .FocusedOn(FocusedControl.ListTab)
6953 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6955 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6956 .FocusedOn(FocusedControl.ListTab)
6957 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6959 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6960 .FocusedOn(FocusedControl.ListTab)
6961 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6963 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6964 .FocusedOn(FocusedControl.ListTab)
6965 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6967 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6968 .FocusedOn(FocusedControl.ListTab)
6969 .Do(() => this.SetSortLastColumn()),
6971 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6972 .Do(() => this.FavoritesRetweetOfficial()),
6974 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6975 .Do(() => this.FavoritesRetweetUnofficial()),
6977 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6978 .Do(() => this.OpenUserAppointUrl()),
6980 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6981 .FocusedOn(FocusedControl.PostBrowser)
6982 .Do(() => this.doReTweetUnofficial()),
6984 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6985 .OnlyWhen(() => this.ExistCurrentPost)
6986 .Do(() => this.doTranslation(_curPost.TextFromApi)),
6988 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6989 .Do(() => this.doReTweetUnofficial()),
6991 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6992 .Do(() => this.CopyUserId()),
6994 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6995 .Do(() => this.tweetThumbnail1.ScrollUp()),
6997 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6998 .Do(() => this.tweetThumbnail1.ScrollDown()),
7000 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7001 .FocusedOn(FocusedControl.ListTab)
7002 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7003 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7007 private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7009 // Task を返す非同期処理があれば asyncTask に代入する
7012 // ShortcutCommand に対応しているコマンドはここで処理される
7013 foreach (var command in this.shortcutCommands)
7015 if (command.IsMatch(keyData, focusedOn))
7017 asyncTask = command.RunCommand();
7018 return command.PreventDefault;
7025 private void ScrollDownPostBrowser(bool forward)
7027 var doc = PostBrowser.Document;
7028 if (doc == null) return;
7030 var tags = doc.GetElementsByTagName("html");
7034 tags[0].ScrollTop += this._fntDetail.Height;
7036 tags[0].ScrollTop -= this._fntDetail.Height;
7040 private void PageDownPostBrowser(bool forward)
7042 var doc = PostBrowser.Document;
7043 if (doc == null) return;
7045 var tags = doc.GetElementsByTagName("html");
7049 tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7051 tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7055 private void GoNextTab(bool forward)
7057 int idx = ListTab.SelectedIndex;
7061 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7066 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7068 ListTab.SelectedIndex = idx;
7071 private void CopyStot()
7074 StringBuilder sb = new StringBuilder();
7075 bool IsProtected = false;
7077 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7078 foreach (int idx in _curList.SelectedIndices)
7080 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7086 if (post.IsDeleted) continue;
7089 if (post.RetweetedId != null)
7090 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7092 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7096 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7101 MessageBox.Show(Properties.Resources.CopyStotText1);
7105 clstr = sb.ToString();
7108 Clipboard.SetDataObject(clstr, false, 5, 100);
7110 catch (Exception ex)
7112 MessageBox.Show(ex.Message);
7117 private void CopyIdUri()
7120 StringBuilder sb = new StringBuilder();
7121 if (this._curTab == null) return;
7122 if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7123 if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7124 foreach (int idx in _curList.SelectedIndices)
7126 var post = _statuses.Tabs[_curTab.Text][idx];
7127 sb.Append(MyCommon.GetStatusUrl(post));
7128 sb.Append(Environment.NewLine);
7132 clstr = sb.ToString();
7135 Clipboard.SetDataObject(clstr, false, 5, 100);
7137 catch (Exception ex)
7139 MessageBox.Show(ex.Message);
7144 private void GoFav(bool forward)
7146 if (_curList.VirtualListSize == 0) return;
7153 if (_curList.SelectedIndices.Count == 0)
7159 fIdx = _curList.SelectedIndices[0] + 1;
7160 if (fIdx > _curList.VirtualListSize - 1) return;
7162 toIdx = _curList.VirtualListSize;
7167 if (_curList.SelectedIndices.Count == 0)
7169 fIdx = _curList.VirtualListSize - 1;
7173 fIdx = _curList.SelectedIndices[0] - 1;
7174 if (fIdx < 0) return;
7180 for (int idx = fIdx; idx != toIdx; idx += stp)
7182 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7184 SelectListItem(_curList, idx);
7185 _curList.EnsureVisible(idx);
7191 private void GoSamePostToAnotherTab(bool left)
7193 if (_curList.VirtualListSize == 0) return;
7199 if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7200 if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7202 targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7207 if (ListTab.SelectedIndex == 0)
7213 fIdx = ListTab.SelectedIndex - 1;
7221 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7227 fIdx = ListTab.SelectedIndex + 1;
7229 toIdx = ListTab.TabCount;
7234 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7236 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7237 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7239 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7241 ListTab.SelectedIndex = tabidx;
7242 SelectListItem(_curList, idx);
7243 _curList.EnsureVisible(idx);
7252 private void GoPost(bool forward)
7254 if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7261 fIdx = _curList.SelectedIndices[0] + 1;
7262 if (fIdx > _curList.VirtualListSize - 1) return;
7263 toIdx = _curList.VirtualListSize;
7268 fIdx = _curList.SelectedIndices[0] - 1;
7269 if (fIdx < 0) return;
7275 if (_curPost.RetweetedId == null)
7277 name = _curPost.ScreenName;
7281 name = _curPost.RetweetedBy;
7283 for (int idx = fIdx; idx != toIdx; idx += stp)
7285 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7287 if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7289 SelectListItem(_curList, idx);
7290 _curList.EnsureVisible(idx);
7296 if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7298 SelectListItem(_curList, idx);
7299 _curList.EnsureVisible(idx);
7306 private void GoRelPost(bool forward)
7308 if (_curList.SelectedIndices.Count == 0) return;
7315 fIdx = _curList.SelectedIndices[0] + 1;
7316 if (fIdx > _curList.VirtualListSize - 1) return;
7317 toIdx = _curList.VirtualListSize;
7322 fIdx = _curList.SelectedIndices[0] - 1;
7323 if (fIdx < 0) return;
7330 if (_curPost == null) return;
7331 _anchorPost = _curPost;
7336 if (_anchorPost == null) return;
7339 for (int idx = fIdx; idx != toIdx; idx += stp)
7341 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7342 if (post.ScreenName == _anchorPost.ScreenName ||
7343 post.RetweetedBy == _anchorPost.ScreenName ||
7344 post.ScreenName == _anchorPost.RetweetedBy ||
7345 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7346 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7347 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7348 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7349 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7351 SelectListItem(_curList, idx);
7352 _curList.EnsureVisible(idx);
7358 private void GoAnchor()
7360 if (_anchorPost == null) return;
7361 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7362 if (idx == -1) return;
7364 SelectListItem(_curList, idx);
7365 _curList.EnsureVisible(idx);
7368 private void GoTopEnd(bool GoTop)
7370 if (_curList.VirtualListSize == 0)
7378 _item = _curList.GetItemAt(0, 25);
7386 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7388 idx = _curList.VirtualListSize - 1;
7392 SelectListItem(_curList, idx);
7395 private void GoMiddle()
7397 if (_curList.VirtualListSize == 0)
7405 _item = _curList.GetItemAt(0, 0);
7415 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7418 idx2 = _curList.VirtualListSize - 1;
7424 idx3 = (idx1 + idx2) / 2;
7426 SelectListItem(_curList, idx3);
7429 private void GoLast()
7431 if (_curList.VirtualListSize == 0) return;
7433 if (_statuses.SortOrder == SortOrder.Ascending)
7435 SelectListItem(_curList, _curList.VirtualListSize - 1);
7436 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7440 SelectListItem(_curList, 0);
7441 _curList.EnsureVisible(0);
7445 private void MoveTop()
7447 if (_curList.SelectedIndices.Count == 0) return;
7448 int idx = _curList.SelectedIndices[0];
7449 if (_statuses.SortOrder == SortOrder.Ascending)
7451 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7455 _curList.EnsureVisible(0);
7457 _curList.EnsureVisible(idx);
7460 private async Task GoInReplyToPostTree()
7462 if (_curPost == null) return;
7464 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7466 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7470 var post = await tw.GetStatusApi(false, _curPost.StatusId);
7472 _curPost.InReplyToStatusId = post.InReplyToStatusId;
7473 _curPost.InReplyToUser = post.InReplyToUser;
7474 _curPost.IsReply = post.IsReply;
7475 this.PurgeListViewItemCache();
7476 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7478 catch (WebApiException ex)
7480 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7484 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7486 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7488 replyChains = new Stack<ReplyChain>();
7490 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7493 string inReplyToTabName;
7494 long inReplyToId = _curPost.InReplyToStatusId.Value;
7495 string inReplyToUser = _curPost.InReplyToUser;
7496 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7498 var inReplyToPosts = from tab in _statuses.Tabs.Values
7499 orderby tab != curTabClass
7500 from post in tab.Posts.Values
7501 where post.StatusId == inReplyToId
7502 let index = tab.IndexOf(post.StatusId)
7504 select new {Tab = tab, Index = index};
7506 var inReplyPost = inReplyToPosts.FirstOrDefault();
7507 if (inReplyPost == null)
7511 await Task.Run(async () =>
7513 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7514 .ConfigureAwait(false);
7517 _statuses.AddPost(post);
7518 _statuses.DistributePosts();
7521 catch (WebApiException ex)
7523 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7524 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7528 this.RefreshTimeline();
7530 inReplyPost = inReplyToPosts.FirstOrDefault();
7531 if (inReplyPost == null)
7533 await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7537 inReplyToTabName = inReplyPost.Tab.TabName;
7538 inReplyToIndex = inReplyPost.Index;
7540 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7541 DetailsListView listView = (DetailsListView)tabPage.Tag;
7543 if (_curTab != tabPage)
7545 this.ListTab.SelectTab(tabPage);
7548 this.SelectListItem(listView, inReplyToIndex);
7549 listView.EnsureVisible(inReplyToIndex);
7552 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7554 if (_curPost == null) return;
7556 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7557 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7561 if (_curPost.InReplyToStatusId != null)
7563 var posts = from t in _statuses.Tabs
7564 from p in t.Value.Posts
7565 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7566 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7568 orderby isForward ? indexOf : indexOf * -1
7569 orderby t.Value != curTabClass
7570 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7573 var postList = posts.ToList();
7574 for (int i = postList.Count - 1; i >= 0; i--)
7577 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7579 postList.RemoveAt(index);
7582 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7583 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7584 if (post == null) post = postList.First();
7585 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7586 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7587 SelectListItem(listView, post.Index);
7588 listView.EnsureVisible(post.Index);
7590 catch (InvalidOperationException)
7598 if (replyChains == null || replyChains.Count < 1)
7600 var posts = from t in _statuses.Tabs
7601 from p in t.Value.Posts
7602 where p.Value.InReplyToStatusId == _curPost.StatusId
7603 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7606 orderby t.Value != curTabClass
7607 select new {Tab = t.Value, Index = indexOf};
7610 var post = posts.First();
7611 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7612 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7613 SelectListItem(listView, post.Index);
7614 listView.EnsureVisible(post.Index);
7616 catch (InvalidOperationException)
7623 ReplyChain chainHead = replyChains.Pop();
7624 if (chainHead.InReplyToId == _curPost.StatusId)
7626 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7635 ListTab.SelectTab(chainHead.OriginalTab);
7641 SelectListItem(_curList, idx);
7642 _curList.EnsureVisible(idx);
7648 this.GoBackInReplyToPostTree(parallel);
7654 private void GoBackSelectPostChain()
7656 if (this.selectPostChains.Count > 1)
7665 this.selectPostChains.Pop();
7666 var tabPostPair = this.selectPostChains.Peek();
7668 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7670 if (tabPostPair.Item2 != null)
7672 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7673 if (idx == -1) continue; //該当ポストが存在しないので無視
7676 tp = tabPostPair.Item1;
7678 this.selectPostChains.Pop();
7680 catch (InvalidOperationException)
7686 while (this.selectPostChains.Count > 1);
7691 //履歴が残り1つであればクリアしておく
7692 if (this.selectPostChains.Count == 1)
7693 this.selectPostChains.Clear();
7697 DetailsListView lst = (DetailsListView)tp.Tag;
7698 this.ListTab.SelectedTab = tp;
7701 SelectListItem(lst, idx);
7702 lst.EnsureVisible(idx);
7708 private void PushSelectPostChain()
7710 int count = this.selectPostChains.Count;
7713 var p = this.selectPostChains.Peek();
7714 if (p.Item1 == this._curTab)
7716 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7717 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7720 if (count >= 2500) TrimPostChain();
7721 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7724 private void TrimPostChain()
7726 if (this.selectPostChains.Count <= 2000) return;
7727 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7728 for (int i = 0; i < 2000; i++)
7730 p.Push(this.selectPostChains.Pop());
7732 this.selectPostChains.Clear();
7733 for (int i = 0; i < 2000; i++)
7735 this.selectPostChains.Push(p.Pop());
7739 private bool GoStatus(long statusId)
7741 if (statusId == 0) return false;
7742 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7744 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7746 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7747 ListTab.SelectedIndex = tabidx;
7748 SelectListItem(_curList, idx);
7749 _curList.EnsureVisible(idx);
7756 private bool GoDirectMessage(long statusId)
7758 if (statusId == 0) return false;
7759 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7761 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7763 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7764 ListTab.SelectedIndex = tabidx;
7765 SelectListItem(_curList, idx);
7766 _curList.EnsureVisible(idx);
7773 private void MyList_MouseClick(object sender, MouseEventArgs e)
7775 _anchorFlag = false;
7778 private void StatusText_Enter(object sender, EventArgs e)
7780 // フォーカスの戻り先を StatusText に設定
7781 this.Tag = StatusText;
7782 StatusText.BackColor = _clInputBackcolor;
7785 public Color InputBackColor
7787 get { return _clInputBackcolor; }
7788 set { _clInputBackcolor = value; }
7791 private void StatusText_Leave(object sender, EventArgs e)
7793 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7794 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7795 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7798 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7801 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7804 e.SuppressKeyPress = true;
7807 this.StatusText_TextChanged(null, null);
7809 if (asyncTask != null)
7813 private void SaveConfigsAll(bool ifModified)
7817 SaveConfigsCommon();
7824 if (ModifySettingCommon) SaveConfigsCommon();
7825 if (ModifySettingLocal) SaveConfigsLocal();
7826 if (ModifySettingAtId) SaveConfigsAtId();
7830 private void SaveConfigsAtId()
7832 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7834 ModifySettingAtId = false;
7835 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7839 private void SaveConfigsCommon()
7841 if (_ignoreConfigSave) return;
7843 ModifySettingCommon = false;
7846 _cfgCommon.UserName = tw.Username;
7847 _cfgCommon.UserId = tw.UserId;
7848 _cfgCommon.Token = tw.AccessToken;
7849 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7851 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7852 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7854 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7857 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7858 switch (_statuses.SortMode)
7860 case ComparerMode.Nickname: //ニックネーム
7861 _cfgCommon.SortColumn = 1;
7863 case ComparerMode.Data: //本文
7864 _cfgCommon.SortColumn = 2;
7866 case ComparerMode.Id: //時刻=発言Id
7867 _cfgCommon.SortColumn = 3;
7869 case ComparerMode.Name: //名前
7870 _cfgCommon.SortColumn = 4;
7872 case ComparerMode.Source: //Source
7873 _cfgCommon.SortColumn = 7;
7877 _cfgCommon.HashTags = HashMgr.HashHistories;
7878 if (HashMgr.IsPermanent)
7880 _cfgCommon.HashSelected = HashMgr.UseHash;
7884 _cfgCommon.HashSelected = "";
7886 _cfgCommon.HashIsHead = HashMgr.IsHead;
7887 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7888 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7889 if (ToolStripFocusLockMenuItem != null &&
7890 ToolStripFocusLockMenuItem.IsDisposed == false)
7892 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7894 _cfgCommon.TrackWord = tw.TrackWord;
7895 _cfgCommon.AllAtReply = tw.AllAtReply;
7896 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7897 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7903 private void SaveConfigsLocal()
7905 if (_ignoreConfigSave) return;
7908 ModifySettingLocal = false;
7909 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7910 _cfgLocal.FormSize = _mySize;
7911 _cfgLocal.FormLocation = _myLoc;
7912 _cfgLocal.SplitterDistance = _mySpDis;
7913 _cfgLocal.PreviewDistance = _mySpDis3;
7914 _cfgLocal.StatusMultiline = StatusText.Multiline;
7915 _cfgLocal.StatusTextHeight = _mySpDis2;
7917 _cfgLocal.FontUnread = _fntUnread;
7918 _cfgLocal.ColorUnread = _clUnread;
7919 _cfgLocal.FontRead = _fntReaded;
7920 _cfgLocal.ColorRead = _clReaded;
7921 _cfgLocal.FontDetail = _fntDetail;
7922 _cfgLocal.ColorDetail = _clDetail;
7923 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7924 _cfgLocal.ColorDetailLink = _clDetailLink;
7925 _cfgLocal.ColorFav = _clFav;
7926 _cfgLocal.ColorOWL = _clOWL;
7927 _cfgLocal.ColorRetweet = _clRetweet;
7928 _cfgLocal.ColorSelf = _clSelf;
7929 _cfgLocal.ColorAtSelf = _clAtSelf;
7930 _cfgLocal.ColorTarget = _clTarget;
7931 _cfgLocal.ColorAtTarget = _clAtTarget;
7932 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7933 _cfgLocal.ColorAtTo = _clAtTo;
7934 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7935 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7936 _cfgLocal.ColorInputFont = _clInputFont;
7937 _cfgLocal.FontInputFont = _fntInputFont;
7939 if (_ignoreConfigSave) return;
7944 private void SaveConfigsTabs()
7946 var tabsSetting = new SettingTabs();
7948 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7949 .Select(x => this._statuses.Tabs[x.Text])
7950 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7952 foreach (var tab in tabs)
7954 if (tab.TabType == MyCommon.TabUsageType.Related || tab.TabType == MyCommon.TabUsageType.SearchResults)
7957 var tabSetting = new SettingTabs.SettingTabItem
7959 TabName = tab.TabName,
7960 TabType = tab.TabType,
7961 UnreadManage = tab.UnreadManage,
7962 Protected = tab.Protected,
7963 Notify = tab.Notify,
7964 SoundFile = tab.SoundFile,
7967 var filterTab = tab as FilterTabModel;
7968 if (filterTab != null)
7969 tabSetting.FilterArray = filterTab.FilterArray;
7971 var userTab = tab as UserTimelineTabModel;
7972 if (userTab != null)
7973 tabSetting.User = userTab.ScreenName;
7975 var searchTab = tab as PublicSearchTabModel;
7976 if (searchTab != null)
7978 tabSetting.SearchWords = searchTab.SearchWords;
7979 tabSetting.SearchLang = searchTab.SearchLang;
7982 var listTab = tab as ListTimelineTabModel;
7983 if (listTab != null)
7984 tabSetting.ListInfo = listTab.ListInfo;
7986 tabsSetting.Tabs.Add(tabSetting);
7992 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7995 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7996 if (ret != DialogResult.OK)
7999 var match = Twitter.StatusUrlRegex.Match(inputText);
8002 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8003 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8009 var statusId = long.Parse(match.Groups["StatusId"].Value);
8010 await this.OpenRelatedTab(statusId);
8012 catch (TabException ex)
8014 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8018 private void SaveLogMenuItem_Click(object sender, EventArgs e)
8020 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8021 Properties.Resources.SaveLogMenuItem_ClickText2,
8022 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8023 if (rslt == DialogResult.Cancel) return;
8025 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8026 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8027 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8028 SaveFileDialog1.FilterIndex = 0;
8029 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8030 SaveFileDialog1.RestoreDirectory = true;
8032 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8034 if (!SaveFileDialog1.ValidateNames) return;
8035 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8037 if (rslt == DialogResult.Yes)
8040 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8042 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8043 string protect = "";
8044 if (post.IsProtect) protect = "Protect";
8045 sw.WriteLine(post.Nickname + "\t" +
8046 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8047 post.CreatedAt.ToString() + "\t" +
8048 post.ScreenName + "\t" +
8049 post.StatusId.ToString() + "\t" +
8050 post.ImageUrl + "\t" +
8051 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8057 foreach (int idx in _curList.SelectedIndices)
8059 PostClass post = _statuses.Tabs[_curTab.Text][idx];
8060 string protect = "";
8061 if (post.IsProtect) protect = "Protect";
8062 sw.WriteLine(post.Nickname + "\t" +
8063 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8064 post.CreatedAt.ToString() + "\t" +
8065 post.ScreenName + "\t" +
8066 post.StatusId.ToString() + "\t" +
8067 post.ImageUrl + "\t" +
8068 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8074 this.TopMost = this._cfgCommon.AlwaysTop;
8077 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8080 bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8083 e.IsInputKey = true;
8087 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8089 var shortcut = (Shortcut)e.KeyData;
8092 case Shortcut.CtrlA:
8093 case Shortcut.CtrlC:
8094 case Shortcut.CtrlIns:
8098 // その他のショートカットキーは無効にする
8099 e.IsInputKey = true;
8105 if (asyncTask != null)
8108 public bool TabRename(ref string tabName)
8111 string newTabText = null;
8112 using (InputTabName inputName = new InputTabName())
8114 inputName.TabName = tabName;
8115 inputName.ShowDialog();
8116 if (inputName.DialogResult == DialogResult.Cancel) return false;
8117 newTabText = inputName.TabName;
8119 this.TopMost = this._cfgCommon.AlwaysTop;
8120 if (!string.IsNullOrEmpty(newTabText))
8123 for (int i = 0; i < ListTab.TabCount; i++)
8125 if (ListTab.TabPages[i].Text == newTabText)
8127 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8128 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8133 for (int i = 0; i < ListTab.TabCount; i++)
8135 if (ListTab.TabPages[i].Text == tabName)
8137 ListTab.TabPages[i].Text = newTabText;
8141 _statuses.RenameTab(tabName, newTabText);
8143 SaveConfigsCommon();
8145 _rclickTabName = newTabText;
8146 tabName = newTabText;
8155 private void ListTab_MouseClick(object sender, MouseEventArgs e)
8157 if (e.Button == MouseButtons.Middle)
8159 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8161 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8163 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8164 this.SaveConfigsTabs();
8171 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8173 string tn = ListTab.SelectedTab.Text;
8177 private void ListTab_MouseDown(object sender, MouseEventArgs e)
8179 if (this._cfgCommon.TabMouseLock) return;
8180 Point cpos = new Point(e.X, e.Y);
8181 if (e.Button == MouseButtons.Left)
8183 for (int i = 0; i < ListTab.TabPages.Count; i++)
8185 if (this.ListTab.GetTabRect(i).Contains(e.Location))
8188 _tabMouseDownPoint = e.Location;
8199 private void ListTab_DragEnter(object sender, DragEventArgs e)
8201 if (e.Data.GetDataPresent(typeof(TabPage)))
8202 e.Effect = DragDropEffects.Move;
8204 e.Effect = DragDropEffects.None;
8207 private void ListTab_DragDrop(object sender, DragEventArgs e)
8209 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8214 Point cpos = new Point(e.X, e.Y);
8215 Point spos = ListTab.PointToClient(cpos);
8217 for (i = 0; i < ListTab.TabPages.Count; i++)
8219 Rectangle rect = ListTab.GetTabRect(i);
8220 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8221 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8223 tn = ListTab.TabPages[i].Text;
8224 if (spos.X <= (rect.Left + rect.Right) / 2)
8233 //タブのないところにドロップ->最後尾へ移動
8234 if (string.IsNullOrEmpty(tn))
8236 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8238 i = ListTab.TabPages.Count - 1;
8241 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8242 if (tp.Text == tn) return;
8244 ReOrderTab(tp.Text, tn, bef);
8247 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8249 var baseIndex = this.GetTabPageIndex(baseTabText);
8250 if (baseIndex == -1)
8253 var targetIndex = this.GetTabPageIndex(targetTabText);
8254 if (targetIndex == -1)
8257 using (ControlTransaction.Layout(this.ListTab))
8259 var mTp = this.ListTab.TabPages[targetIndex];
8260 this.ListTab.TabPages.Remove(mTp);
8262 if (targetIndex < baseIndex)
8265 if (isBeforeBaseTab)
8266 ListTab.TabPages.Insert(baseIndex, mTp);
8268 ListTab.TabPages.Insert(baseIndex + 1, mTp);
8274 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8276 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8277 //isReply:true=@,false=DM
8278 if (!StatusText.Enabled) return;
8279 if (_curList == null) return;
8280 if (_curTab == null) return;
8281 if (!this.ExistCurrentPost) return;
8283 // 複数あてリプライはReplyではなく通常ポスト
8284 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8285 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8286 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8288 if (_curList.SelectedIndices.Count > 0)
8291 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8294 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8297 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8298 StatusText.SelectionStart = StatusText.Text.Length;
8300 this.inReplyTo = null;
8303 if (string.IsNullOrEmpty(StatusText.Text))
8307 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8308 StatusText.Text = "@" + _curPost.ScreenName + " ";
8310 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8311 var inReplyToScreenName = this._curPost.ScreenName;
8312 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8320 //1件選んでEnter or DoubleClick
8321 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8323 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8326 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8327 var inReplyToScreenName = this._curPost.ScreenName;
8328 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8332 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8335 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8338 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8339 this.inReplyTo = null;
8344 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8345 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8346 var inReplyToScreenName = this._curPost.ScreenName;
8347 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8354 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8355 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8356 this.inReplyTo = null;
8361 //1件選んでCtrl-Rの場合(返信先操作せず)
8362 int sidx = StatusText.SelectionStart;
8363 string id = "@" + _curPost.ScreenName + " ";
8366 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8371 StatusText.Text = StatusText.Text.Insert(sidx, id);
8373 //if (StatusText.Text.StartsWith("@"))
8376 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8377 // sidx += 5 + _curPost.ScreenName.Length;
8382 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8383 // sidx += 3 + _curPost.ScreenName.Length;
8385 StatusText.SelectionStart = sidx;
8388 //_reply_to_name = null;
8396 if (!isAuto && !isReply) return;
8398 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8402 //Enter or DoubleClick
8404 string sTxt = StatusText.Text;
8405 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8408 this.inReplyTo = null;
8410 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8412 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8413 if (!sTxt.Contains("@" + post.ScreenName + " "))
8415 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8416 //sTxt = "@" + post.ScreenName + " " + sTxt;
8419 StatusText.Text = sTxt;
8424 if (_curList.SelectedIndices.Count > 1)
8429 int sidx = StatusText.SelectionStart;
8430 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8432 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8433 if (!ids.Contains("@" + post.ScreenName + " ") &&
8434 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8436 ids += "@" + post.ScreenName + " ";
8440 foreach (string nm in post.ReplyToList)
8442 if (!ids.Contains("@" + nm + " ") &&
8443 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8445 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8447 ids += "@" + m.Result("${id}") + " ";
8449 ids += "@" + nm + " ";
8454 if (ids.Length == 0) return;
8455 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8457 StatusText.Text = ". " + StatusText.Text;
8459 this.inReplyTo = null;
8463 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8468 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8470 //if (StatusText.Text.StartsWith("@"))
8472 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8473 // sidx += 2 + ids.Length;
8477 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
8478 // sidx += 1 + ids.Length;
8480 StatusText.SelectionStart = sidx;
8486 //1件のみ選択のC-S-r(返信元付加する可能性あり)
8489 int sidx = StatusText.SelectionStart;
8490 PostClass post = _curPost;
8491 if (!ids.Contains("@" + post.ScreenName + " ") &&
8492 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8494 ids += "@" + post.ScreenName + " ";
8496 foreach (string nm in post.ReplyToList)
8498 if (!ids.Contains("@" + nm + " ") &&
8499 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8501 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8503 ids += "@" + m.Result("${id}") + " ";
8505 ids += "@" + nm + " ";
8508 if (!string.IsNullOrEmpty(post.RetweetedBy))
8510 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8511 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8513 ids += "@" + post.RetweetedBy + " ";
8516 if (ids.Length == 0) return;
8517 if (string.IsNullOrEmpty(StatusText.Text))
8520 StatusText.Text = ids;
8521 StatusText.SelectionStart = ids.Length;
8524 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8525 var inReplyToScreenName = this._curPost.ScreenName;
8526 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8532 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8537 StatusText.Text = StatusText.Text.Insert(sidx, ids);
8539 StatusText.SelectionStart = sidx;
8545 StatusText.SelectionStart = StatusText.Text.Length;
8550 private void ListTab_MouseUp(object sender, MouseEventArgs e)
8555 private static int iconCnt = 0;
8556 private static int blinkCnt = 0;
8557 private static bool blink = false;
8558 private static bool idle = false;
8560 private async Task RefreshTasktrayIcon()
8563 await this.Colorize();
8565 if (!TimerRefreshIcon.Enabled) return;
8566 //Static usCheckCnt As int = 0
8568 //Static iconDlListTopItem As ListViewItem = null
8570 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8571 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8573 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8575 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8581 //if (usCheckCnt > 300) //1min
8584 // if (!this.IsReceivedUserStream)
8586 // TraceOut("ReconnectUserStream");
8587 // tw.ReconnectUserStream();
8591 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8593 if (iconCnt >= this.NIconRefresh.Length)
8601 SaveConfigsAll(true);
8606 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8608 _myStatusError = false;
8612 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8613 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8615 if (blinkCnt > 0) return;
8617 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8619 NotifyIcon1.Icon = ReplyIcon;
8623 NotifyIcon1.Icon = ReplyIconBlink;
8631 //優先度:エラー→オフライン→アイドル
8635 NotifyIcon1.Icon = NIconAtRed;
8638 if (_myStatusOnline)
8640 NotifyIcon1.Icon = NIconAt;
8644 NotifyIcon1.Icon = NIconAtSmoke;
8648 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8651 await this.RefreshTasktrayIcon();
8654 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8656 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8657 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8659 if (ListTab != null && ListTab.SelectedTab != null)
8660 _rclickTabName = ListTab.SelectedTab.Text;
8665 if (_statuses == null) return;
8666 if (_statuses.Tabs == null) return;
8668 TabModel tb = _statuses.Tabs[_rclickTabName];
8669 if (tb == null) return;
8671 NotifyDispMenuItem.Checked = tb.Notify;
8672 this.NotifyTbMenuItem.Checked = tb.Notify;
8674 soundfileListup = true;
8675 SoundFileComboBox.Items.Clear();
8676 this.SoundFileTbComboBox.Items.Clear();
8677 SoundFileComboBox.Items.Add("");
8678 this.SoundFileTbComboBox.Items.Add("");
8679 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8680 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8682 oDir = oDir.GetDirectories("Sounds")[0];
8684 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8686 SoundFileComboBox.Items.Add(oFile.Name);
8687 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8689 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8690 if (idx == -1) idx = 0;
8691 SoundFileComboBox.SelectedIndex = idx;
8692 this.SoundFileTbComboBox.SelectedIndex = idx;
8693 soundfileListup = false;
8694 UreadManageMenuItem.Checked = tb.UnreadManage;
8695 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8697 TabMenuControl(_rclickTabName);
8700 private void TabMenuControl(string tabName)
8702 var tabInfo = _statuses.GetTabByName(tabName);
8704 this.FilterEditMenuItem.Enabled = true;
8705 this.EditRuleTbMenuItem.Enabled = true;
8707 if (tabInfo.IsDefaultTabType)
8709 this.ProtectTabMenuItem.Enabled = false;
8710 this.ProtectTbMenuItem.Enabled = false;
8714 this.ProtectTabMenuItem.Enabled = true;
8715 this.ProtectTbMenuItem.Enabled = true;
8718 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8720 this.ProtectTabMenuItem.Checked = true;
8721 this.ProtectTbMenuItem.Checked = true;
8722 this.DeleteTabMenuItem.Enabled = false;
8723 this.DeleteTbMenuItem.Enabled = false;
8727 this.ProtectTabMenuItem.Checked = false;
8728 this.ProtectTbMenuItem.Checked = false;
8729 this.DeleteTabMenuItem.Enabled = true;
8730 this.DeleteTbMenuItem.Enabled = true;
8734 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8736 var checkState = ((ToolStripMenuItem)sender).Checked;
8739 this.ProtectTbMenuItem.Checked = checkState;
8740 this.ProtectTabMenuItem.Checked = checkState;
8743 this.DeleteTabMenuItem.Enabled = !checkState;
8744 this.DeleteTbMenuItem.Enabled = !checkState;
8746 if (string.IsNullOrEmpty(_rclickTabName)) return;
8747 _statuses.Tabs[_rclickTabName].Protected = checkState;
8752 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8754 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8755 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8757 if (string.IsNullOrEmpty(_rclickTabName)) return;
8758 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8763 public void ChangeTabUnreadManage(string tabName, bool isManage)
8765 var idx = this.GetTabPageIndex(tabName);
8769 _statuses.Tabs[tabName].UnreadManage = isManage;
8770 if (this._cfgCommon.TabIconDisp)
8772 if (_statuses.Tabs[tabName].UnreadCount > 0)
8773 ListTab.TabPages[idx].ImageIndex = 0;
8775 ListTab.TabPages[idx].ImageIndex = -1;
8778 if (_curTab.Text == tabName)
8780 this.PurgeListViewItemCache();
8784 SetMainWindowTitle();
8785 SetStatusLabelUrl();
8786 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8789 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8791 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8792 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8794 if (string.IsNullOrEmpty(_rclickTabName)) return;
8796 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8801 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8803 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8805 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8810 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8812 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8814 RemoveSpecifiedTab(_rclickTabName, true);
8818 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8820 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8822 using (var fltDialog = new FilterDialog())
8824 fltDialog.Owner = this;
8825 fltDialog.SetCurrent(_rclickTabName);
8826 fltDialog.ShowDialog(this);
8828 this.TopMost = this._cfgCommon.AlwaysTop;
8830 this.ApplyPostFilters();
8834 private void AddTabMenuItem_Click(object sender, EventArgs e)
8836 string tabName = null;
8837 MyCommon.TabUsageType tabUsage;
8838 using (InputTabName inputName = new InputTabName())
8840 inputName.TabName = _statuses.MakeTabName("MyTab");
8841 inputName.IsShowUsage = true;
8842 inputName.ShowDialog();
8843 if (inputName.DialogResult == DialogResult.Cancel) return;
8844 tabName = inputName.TabName;
8845 tabUsage = inputName.Usage;
8847 this.TopMost = this._cfgCommon.AlwaysTop;
8848 if (!string.IsNullOrEmpty(tabName))
8851 ListElement list = null;
8852 if (tabUsage == MyCommon.TabUsageType.Lists)
8854 using (ListAvailable listAvail = new ListAvailable())
8856 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8857 if (listAvail.SelectedList == null) return;
8858 list = listAvail.SelectedList;
8865 case MyCommon.TabUsageType.UserDefined:
8866 tab = new FilterTabModel(tabName);
8868 case MyCommon.TabUsageType.PublicSearch:
8869 tab = new PublicSearchTabModel(tabName);
8871 case MyCommon.TabUsageType.Lists:
8872 tab = new ListTimelineTabModel(tabName, list);
8878 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8880 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8881 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8887 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8889 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8890 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8892 if (tabUsage == MyCommon.TabUsageType.Lists)
8894 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8895 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8896 this.GetListTimelineAsync(listTab);
8902 private void TabMenuItem_Click(object sender, EventArgs e)
8904 using (var fltDialog = new FilterDialog())
8906 fltDialog.Owner = this;
8909 foreach (int idx in _curList.SelectedIndices)
8913 if (!SelectTab(out tabName)) return;
8915 fltDialog.SetCurrent(tabName);
8916 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8918 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8922 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8924 fltDialog.ShowDialog(this);
8925 this.TopMost = this._cfgCommon.AlwaysTop;
8929 this.ApplyPostFilters();
8931 if (this.ListTab.SelectedTab != null &&
8932 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8934 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8938 protected override bool ProcessDialogKey(Keys keyData)
8940 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8941 if ((keyData & Keys.KeyCode) == Keys.Enter)
8943 if (StatusText.Focused)
8945 bool _NewLine = false;
8948 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8950 if (StatusText.Multiline)
8952 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8954 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8958 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8962 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8964 if (StatusText.Multiline)
8966 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8968 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8972 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8978 if (StatusText.Multiline)
8980 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8982 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8983 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8987 if (((keyData & Keys.Shift) == Keys.Shift) ||
8988 (((keyData & Keys.Control) != Keys.Control) &&
8989 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8995 int pos1 = StatusText.SelectionStart;
8996 if (StatusText.SelectionLength > 0)
8998 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
9000 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
9001 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
9006 PostButton_Click(null, null);
9010 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9011 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9012 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9014 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9019 return base.ProcessDialogKey(keyData);
9022 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9024 MakeReplyOrDirectStatus(false, true, true);
9027 private void IDRuleMenuItem_Click(object sender, EventArgs e)
9032 if (_curList.SelectedIndices.Count == 0) return;
9035 if (!SelectTab(out tabName)) return;
9037 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
9041 if (tab.TabType != MyCommon.TabUsageType.Mute)
9043 this.MoveOrCopy(out mv, out mk);
9047 // ミュートタブでは常に MoveMatches を true にする
9052 List<string> ids = new List<string>();
9053 foreach (int idx in _curList.SelectedIndices)
9055 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9056 if (!ids.Contains(post.ScreenName))
9058 PostFilterRule fc = new PostFilterRule();
9059 ids.Add(post.ScreenName);
9060 if (post.RetweetedId == null)
9062 fc.FilterName = post.ScreenName;
9066 fc.FilterName = post.RetweetedBy;
9068 fc.UseNameField = true;
9069 fc.MoveMatches = mv;
9070 fc.MarkMatches = mk;
9071 fc.UseRegex = false;
9072 fc.FilterByUrl = false;
9078 List<string> atids = new List<string>();
9079 foreach (string id in ids)
9081 atids.Add("@" + id);
9083 int cnt = AtIdSupl.ItemCount;
9084 AtIdSupl.AddRangeItem(atids.ToArray());
9085 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9088 this.ApplyPostFilters();
9092 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9094 if (this._curList.SelectedIndices.Count == 0)
9097 // タブ選択ダイアログを表示(or追加)
9099 if (!this.SelectTab(out tabName))
9102 var currentTab = this._statuses.Tabs[this._curTab.Text];
9103 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
9107 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9109 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9110 this.MoveOrCopy(out mv, out mk);
9114 // ミュートタブでは常に MoveMatches を true にする
9119 // 振り分けルールに追加するSource
9120 var sources = new HashSet<string>();
9122 foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9124 var post = currentTab[idx];
9125 var filterSource = post.Source;
9127 if (sources.Add(filterSource))
9129 var filter = new PostFilterRule
9131 FilterSource = filterSource,
9135 FilterByUrl = false,
9137 filterTab.AddFilter(filter);
9141 this.ApplyPostFilters();
9142 this.SaveConfigsTabs();
9145 private bool SelectTab(out string tabName)
9152 using (var dialog = new TabsDialog(_statuses))
9154 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9156 var selectedTab = dialog.SelectedTab;
9157 tabName = selectedTab == null ? null : selectedTab.TabName;
9160 ListTab.SelectedTab.Focus();
9162 if (tabName == null)
9164 using (InputTabName inputName = new InputTabName())
9166 inputName.TabName = _statuses.MakeTabName("MyTab");
9167 inputName.ShowDialog();
9168 if (inputName.DialogResult == DialogResult.Cancel) return false;
9169 tabName = inputName.TabName;
9171 this.TopMost = this._cfgCommon.AlwaysTop;
9172 if (!string.IsNullOrEmpty(tabName))
9174 var tab = new FilterTabModel(tabName);
9175 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
9177 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9178 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9196 private void MoveOrCopy(out bool move, out bool mark)
9200 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9201 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9209 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9210 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9220 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9225 private void CopyURLMenuItem_Click(object sender, EventArgs e)
9230 private void SelectAllMenuItem_Click(object sender, EventArgs e)
9232 if (StatusText.Focused)
9235 StatusText.SelectAll();
9239 // ListView上でのCtrl+A
9240 NativeMethods.SelectAllItems(this._curList);
9244 private void MoveMiddle()
9250 if (_curList.SelectedIndices.Count == 0) return;
9252 int idx = _curList.SelectedIndices[0];
9254 _item = _curList.GetItemAt(0, 25);
9260 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9262 idx2 = _curList.VirtualListSize - 1;
9266 idx -= Math.Abs(idx1 - idx2) / 2;
9267 if (idx < 0) idx = 0;
9269 _curList.EnsureVisible(_curList.VirtualListSize - 1);
9270 _curList.EnsureVisible(idx);
9273 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9275 var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9276 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9279 if (linkElements.Length > 0)
9281 UrlDialog.ClearUrl();
9283 string openUrlStr = "";
9285 if (linkElements.Length == 1)
9287 // ツイートに含まれる URL が 1 つのみの場合
9288 // => OpenURL ダイアログを表示せずにリンクを開く
9293 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9295 catch (ArgumentException)
9304 if (string.IsNullOrEmpty(urlStr)) return;
9305 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9307 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9308 await this.OpenUriAsync(new Uri(openUrlStr));
9312 // ツイートに含まれる URL が複数ある場合
9313 // => OpenURL を表示しユーザーが選択したリンクを開く
9315 foreach (var linkElm in linkElements)
9318 string linkText = "";
9322 urlStr = linkElm.GetAttribute("title");
9323 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9324 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9325 linkText = linkElm.InnerText;
9327 catch (ArgumentException)
9336 if (string.IsNullOrEmpty(urlStr)) continue;
9337 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9341 if (UrlDialog.ShowDialog() == DialogResult.OK)
9343 openUrlStr = UrlDialog.SelectedUrl;
9345 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9346 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9353 this.TopMost = this._cfgCommon.AlwaysTop;
9358 private void ClearTabMenuItem_Click(object sender, EventArgs e)
9360 if (string.IsNullOrEmpty(_rclickTabName)) return;
9361 ClearTab(_rclickTabName, true);
9364 private void ClearTab(string tabName, bool showWarning)
9368 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9369 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9375 _statuses.ClearTabIds(tabName);
9376 if (ListTab.SelectedTab.Text == tabName)
9379 _anchorFlag = false;
9380 this.PurgeListViewItemCache();
9384 foreach (TabPage tb in ListTab.TabPages)
9386 if (tb.Text == tabName)
9389 ((DetailsListView)tb.Tag).VirtualListSize = 0;
9393 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9395 SetMainWindowTitle();
9396 SetStatusLabelUrl();
9399 private static long followers = 0;
9401 private void SetMainWindowTitle()
9404 StringBuilder ttl = new StringBuilder(256);
9407 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9408 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9409 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9410 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9412 foreach (var tab in _statuses.Tabs.Values)
9414 ur += tab.UnreadCount;
9419 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9420 ttl.Append(Application.ProductName);
9422 switch (this._cfgCommon.DispLatestPost)
9424 case MyCommon.DispTitleEnum.Ver:
9425 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9427 case MyCommon.DispTitleEnum.Post:
9428 if (_history != null && _history.Count > 1)
9429 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9431 case MyCommon.DispTitleEnum.UnreadRepCount:
9432 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9434 case MyCommon.DispTitleEnum.UnreadAllCount:
9435 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9437 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9438 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9440 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9441 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9443 case MyCommon.DispTitleEnum.OwnStatus:
9444 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9445 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9451 this.Text = ttl.ToString();
9453 catch (AccessViolationException)
9455 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9459 private string GetStatusLabelText()
9462 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9463 if (_statuses == null) return "";
9464 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9465 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9466 if (tbRep == null || tbDm == null) return "";
9467 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9472 StringBuilder slbl = new StringBuilder(256);
9475 foreach (var tab in _statuses.Tabs.Values)
9477 ur += tab.UnreadCount;
9479 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9481 tur = tab.UnreadCount;
9492 UnreadAtCounter = urat;
9494 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9495 if (this._cfgCommon.TimelinePeriod == 0)
9497 slbl.Append(Properties.Resources.SetStatusLabelText2);
9501 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9503 return slbl.ToString();
9506 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9510 if (this.InvokeRequired && !this.IsDisposed)
9512 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
9516 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9517 SetApiStatusLabel(endpointName);
9520 catch (ObjectDisposedException)
9524 catch (InvalidOperationException)
9530 private void SetApiStatusLabel(string endpointName = null)
9532 if (_curTab == null)
9534 this.toolStripApiGauge.ApiEndpoint = null;
9538 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9540 if (endpointName == null)
9545 case MyCommon.TabUsageType.Home:
9546 case MyCommon.TabUsageType.UserDefined:
9547 endpointName = "/statuses/home_timeline";
9550 case MyCommon.TabUsageType.Mentions:
9551 endpointName = "/statuses/mentions_timeline";
9554 case MyCommon.TabUsageType.Favorites:
9555 endpointName = "/favorites/list";
9558 case MyCommon.TabUsageType.DirectMessage:
9559 endpointName = "/direct_messages";
9562 case MyCommon.TabUsageType.UserTimeline:
9563 endpointName = "/statuses/user_timeline";
9566 case MyCommon.TabUsageType.Lists:
9567 endpointName = "/lists/statuses";
9570 case MyCommon.TabUsageType.PublicSearch:
9571 endpointName = "/search/tweets";
9574 case MyCommon.TabUsageType.Related:
9575 endpointName = "/statuses/show/:id";
9582 this.toolStripApiGauge.ApiEndpoint = endpointName;
9586 // 表示中のタブに関連する endpoint であれば更新
9589 switch (endpointName)
9591 case "/statuses/home_timeline":
9592 update = tabType == MyCommon.TabUsageType.Home ||
9593 tabType == MyCommon.TabUsageType.UserDefined;
9596 case "/statuses/mentions_timeline":
9597 update = tabType == MyCommon.TabUsageType.Mentions;
9600 case "/favorites/list":
9601 update = tabType == MyCommon.TabUsageType.Favorites;
9604 case "/direct_messages:":
9605 update = tabType == MyCommon.TabUsageType.DirectMessage;
9608 case "/statuses/user_timeline":
9609 update = tabType == MyCommon.TabUsageType.UserTimeline;
9612 case "/lists/statuses":
9613 update = tabType == MyCommon.TabUsageType.Lists;
9616 case "/search/tweets":
9617 update = tabType == MyCommon.TabUsageType.PublicSearch;
9620 case "/statuses/show/:id":
9621 update = tabType == MyCommon.TabUsageType.Related;
9630 this.toolStripApiGauge.ApiEndpoint = endpointName;
9636 private void SetStatusLabelUrl()
9638 StatusLabelUrl.Text = GetStatusLabelText();
9641 public void SetStatusLabel(string text)
9643 StatusLabel.Text = text;
9646 private static StringBuilder ur = new StringBuilder(64);
9648 private void SetNotifyIconText()
9650 // タスクトレイアイコンのツールチップテキスト書き換え
9652 ur.Remove(0, ur.Length);
9653 if (this._cfgCommon.DispUsername)
9655 ur.Append(tw.Username);
9658 ur.Append(Application.ProductName);
9660 ur.Append("(Debug Build)");
9662 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9665 ur.Append(UnreadCounter);
9667 ur.Append(UnreadAtCounter);
9670 NotifyIcon1.Text = ur.ToString();
9673 internal void CheckReplyTo(string StatusText)
9677 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9679 foreach (Match hm in m)
9681 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9683 hstr += "#" + hm.Result("$3") + " ";
9684 HashSupl.AddItem("#" + hm.Result("$3"));
9687 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9689 hstr += HashMgr.UseHash;
9691 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9693 // 本当にリプライ先指定すべきかどうかの判定
9694 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9696 if (this._cfgCommon.UseAtIdSupplement)
9698 int bCnt = AtIdSupl.ItemCount;
9699 foreach (Match mid in m)
9701 AtIdSupl.AddItem(mid.Result("${id}"));
9703 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9706 // リプライ先ステータスIDの指定がない場合は指定しない
9707 if (this.inReplyTo == null)
9711 // 次の条件を満たす場合に in_reply_to_status_id 指定
9712 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9713 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9714 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9718 var inReplyToScreenName = this.inReplyTo.Item2;
9719 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9721 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9725 foreach (Match mid in m)
9727 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9732 this.inReplyTo = null;
9735 private void TweenMain_Resize(object sender, EventArgs e)
9737 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9739 this.Visible = false;
9741 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9743 // 現在の DPI と設定保存時の DPI との比を取得する
9744 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9746 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9747 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9748 this.DesktopLocation = _cfgLocal.FormLocation;
9749 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9752 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9753 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9754 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9756 this.SplitContainer1.SplitterDistance = splitterDistance;
9760 StatusText.Multiline = _cfgLocal.StatusMultiline;
9761 if (StatusText.Multiline)
9763 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9764 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9765 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9767 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9769 StatusText.Height = statusTextHeight;
9773 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9775 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9779 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9780 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9782 this.SplitContainer3.SplitterDistance = previewDistance;
9785 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9786 this.SplitContainer3.Panel2Collapsed = true;
9788 _initialLayout = false;
9790 if (this.WindowState != FormWindowState.Minimized)
9792 _formWindowState = this.WindowState;
9796 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9798 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9799 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9800 if (PlaySoundMenuItem.Checked)
9802 this._cfgCommon.PlaySound = true;
9806 this._cfgCommon.PlaySound = false;
9808 ModifySettingCommon = true;
9811 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9813 if (this._initialLayout)
9816 int splitterDistance;
9817 switch (this.WindowState)
9819 case FormWindowState.Normal:
9820 splitterDistance = this.SplitContainer1.SplitterDistance;
9822 case FormWindowState.Maximized:
9823 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9824 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9825 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9826 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9832 this._mySpDis = splitterDistance;
9833 this.ModifySettingLocal = true;
9836 private async Task doRepliedStatusOpen()
9838 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9840 if (MyCommon.IsKeyDown(Keys.Shift))
9842 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9845 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9847 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9848 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9852 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9854 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9855 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9856 MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + " (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9859 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9864 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9866 await this.doRepliedStatusOpen();
9870 /// UserPicture.Image に設定されている画像を破棄します。
9872 private void ClearUserPicture()
9874 if (this.UserPicture.Image != null)
9876 var oldImage = this.UserPicture.Image;
9877 this.UserPicture.Image = null;
9882 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9884 //発言詳細のアイコン右クリック時のメニュー制御
9885 if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9887 string name = _curPost.ImageUrl;
9888 if (name != null && name.Length > 0)
9890 int idx = name.LastIndexOf('/');
9893 name = Path.GetFileName(name.Substring(idx));
9894 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9896 name = name.Replace("_normal", "");
9897 this.IconNameToolStripMenuItem.Text = name;
9898 this.IconNameToolStripMenuItem.Enabled = true;
9902 this.IconNameToolStripMenuItem.Enabled = false;
9903 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9908 this.IconNameToolStripMenuItem.Enabled = false;
9909 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9912 this.ReloadIconToolStripMenuItem.Enabled = true;
9914 if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9916 this.SaveIconPictureToolStripMenuItem.Enabled = true;
9920 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9925 this.IconNameToolStripMenuItem.Enabled = false;
9926 this.ReloadIconToolStripMenuItem.Enabled = false;
9927 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9928 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9933 this.IconNameToolStripMenuItem.Enabled = false;
9934 this.ReloadIconToolStripMenuItem.Enabled = false;
9935 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9936 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9938 if (NameLabel.Tag != null)
9940 string id = (string)NameLabel.Tag;
9941 if (id == tw.Username)
9943 FollowToolStripMenuItem.Enabled = false;
9944 UnFollowToolStripMenuItem.Enabled = false;
9945 ShowFriendShipToolStripMenuItem.Enabled = false;
9946 ShowUserStatusToolStripMenuItem.Enabled = true;
9947 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9948 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9949 ListManageUserContextToolStripMenuItem3.Enabled = true;
9953 FollowToolStripMenuItem.Enabled = true;
9954 UnFollowToolStripMenuItem.Enabled = true;
9955 ShowFriendShipToolStripMenuItem.Enabled = true;
9956 ShowUserStatusToolStripMenuItem.Enabled = true;
9957 SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9958 SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9959 ListManageUserContextToolStripMenuItem3.Enabled = true;
9964 FollowToolStripMenuItem.Enabled = false;
9965 UnFollowToolStripMenuItem.Enabled = false;
9966 ShowFriendShipToolStripMenuItem.Enabled = false;
9967 ShowUserStatusToolStripMenuItem.Enabled = false;
9968 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9969 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9970 ListManageUserContextToolStripMenuItem3.Enabled = false;
9974 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9976 if (_curPost == null) return;
9977 string name = _curPost.ImageUrl;
9978 await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9981 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9983 if (this._curPost == null) return;
9985 await this.UserPicture.SetImageFromTask(async () =>
9987 var imageUrl = this._curPost.ImageUrl;
9989 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9990 .ConfigureAwait(false);
9992 return await image.CloneAsync()
9993 .ConfigureAwait(false);
9997 private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9999 if (_curPost == null) return;
10000 string name = _curPost.ImageUrl;
10001 name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10003 this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10005 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10011 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10013 if (_curPost == null) return;
10014 string name = _curPost.ImageUrl;
10016 this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10018 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10022 using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10024 using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10026 using (Graphics g = Graphics.FromImage(bmp2))
10028 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10029 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10031 bmp2.Save(this.SaveFileDialog1.FileName);
10037 //処理中にキャッシュアウトする可能性あり
10042 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10044 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10045 if (multiline != this.StatusText.Multiline)
10047 this.StatusText.Multiline = multiline;
10048 MultiLineMenuItem.Checked = multiline;
10049 ModifySettingLocal = true;
10053 private void StatusText_MultilineChanged(object sender, EventArgs e)
10055 if (this.StatusText.Multiline)
10056 this.StatusText.ScrollBars = ScrollBars.Vertical;
10058 this.StatusText.ScrollBars = ScrollBars.None;
10060 ModifySettingLocal = true;
10063 private void MultiLineMenuItem_Click(object sender, EventArgs e)
10066 StatusText.Multiline = MultiLineMenuItem.Checked;
10067 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10068 if (MultiLineMenuItem.Checked)
10070 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10071 SplitContainer2.SplitterDistance = 0;
10073 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10077 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10079 ModifySettingLocal = true;
10082 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10084 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10085 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10087 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10088 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10089 //Appendix A. Collected ABNF for URI
10090 //http://www.ietf.org/rfc/rfc3986.txt
10092 string result = "";
10094 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10096 if (StatusText.SelectionLength > 0)
10098 string tmp = StatusText.SelectedText;
10099 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10100 if (tmp.StartsWith("http"))
10102 // 文字列が選択されている場合はその文字列について処理
10104 //nico.ms使用、nicovideoにマッチしたら変換
10105 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10107 result = nicoms.Shorten(tmp);
10109 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10111 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10114 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10115 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10116 result = resultUri.AbsoluteUri;
10118 catch (WebApiException e)
10120 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10123 catch (UriFormatException e)
10125 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10134 if (!string.IsNullOrEmpty(result))
10136 urlUndo undotmp = new urlUndo();
10138 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10139 StatusText.SelectedText = result;
10142 undotmp.Before = tmp;
10143 undotmp.After = result;
10145 if (urlUndoBuffer == null)
10147 urlUndoBuffer = new List<urlUndo>();
10148 UrlUndoToolStripMenuItem.Enabled = true;
10151 urlUndoBuffer.Add(undotmp);
10157 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10158 @"(?<url>(?<protocol>https?://)" +
10159 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10160 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10161 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10162 // 正規表現にマッチしたURL文字列をtinyurl化
10163 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10165 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10166 string tmp = mt.Result("${url}");
10167 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10168 urlUndo undotmp = new urlUndo();
10171 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10173 //nico.ms使用、nicovideoにマッチしたら変換
10174 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10176 result = nicoms.Shorten(tmp);
10178 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10180 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10183 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10184 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10185 result = resultUri.AbsoluteUri;
10187 catch (HttpRequestException e)
10189 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10190 // のように長いので「:」が含まれていればそれ以降のみを抽出する
10191 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10193 this.StatusLabel.Text = Converter_Type + ":" + message;
10196 catch (WebApiException e)
10198 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10201 catch (UriFormatException e)
10203 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10212 if (!string.IsNullOrEmpty(result))
10214 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10215 StatusText.SelectedText = result;
10217 undotmp.Before = mt.Result("${url}");
10218 undotmp.After = result;
10220 if (urlUndoBuffer == null)
10222 urlUndoBuffer = new List<urlUndo>();
10223 UrlUndoToolStripMenuItem.Enabled = true;
10226 urlUndoBuffer.Add(undotmp);
10234 private void doUrlUndo()
10236 if (urlUndoBuffer != null)
10238 string tmp = StatusText.Text;
10239 foreach (urlUndo data in urlUndoBuffer)
10241 tmp = tmp.Replace(data.After, data.Before);
10243 StatusText.Text = tmp;
10244 urlUndoBuffer = null;
10245 UrlUndoToolStripMenuItem.Enabled = false;
10246 StatusText.SelectionStart = 0;
10247 StatusText.SelectionLength = 0;
10251 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10253 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10256 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10258 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10261 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10263 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10266 private async void UxnuMenuItem_Click(object sender, EventArgs e)
10268 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10271 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10273 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10275 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10276 Random rnd = new Random();
10277 // 前回使用した短縮URLサービス以外を選択する
10280 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10282 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10283 await UrlConvertAsync(svc);
10287 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10292 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10294 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10295 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10296 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10297 ModifySettingCommon = true;
10300 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10302 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10303 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10304 _cfgCommon.ListLock = ListLockMenuItem.Checked;
10305 ModifySettingCommon = true;
10308 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10310 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10311 MenuStrip1.Tag = new Object();
10312 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10315 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10317 if (this.Tag != null) // 設定された戻り先へ遷移
10319 if (this.Tag == this.ListTab.SelectedTab)
10320 ((Control)this.ListTab.SelectedTab.Tag).Select();
10322 ((Control)this.Tag).Select();
10324 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10326 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10328 this.Tag = ListTab.SelectedTab.Tag;
10329 ((Control)this.Tag).Select();
10332 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10333 MenuStrip1.Tag = null;
10336 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10338 DetailsListView lst = (DetailsListView)sender;
10339 if (_cfgLocal == null) return;
10343 _cfgLocal.Width1 = lst.Columns[0].Width;
10344 _cfgLocal.Width3 = lst.Columns[1].Width;
10348 int[] darr = new int[lst.Columns.Count];
10349 for (int i = 0; i < lst.Columns.Count; i++)
10351 darr[lst.Columns[i].DisplayIndex] = i;
10353 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10355 for (int i = 0; i < lst.Columns.Count; i++)
10360 _cfgLocal.DisplayIndex1 = i;
10363 _cfgLocal.DisplayIndex2 = i;
10366 _cfgLocal.DisplayIndex3 = i;
10369 _cfgLocal.DisplayIndex4 = i;
10372 _cfgLocal.DisplayIndex5 = i;
10375 _cfgLocal.DisplayIndex6 = i;
10378 _cfgLocal.DisplayIndex7 = i;
10381 _cfgLocal.DisplayIndex8 = i;
10385 _cfgLocal.Width1 = lst.Columns[0].Width;
10386 _cfgLocal.Width2 = lst.Columns[1].Width;
10387 _cfgLocal.Width3 = lst.Columns[2].Width;
10388 _cfgLocal.Width4 = lst.Columns[3].Width;
10389 _cfgLocal.Width5 = lst.Columns[4].Width;
10390 _cfgLocal.Width6 = lst.Columns[5].Width;
10391 _cfgLocal.Width7 = lst.Columns[6].Width;
10392 _cfgLocal.Width8 = lst.Columns[7].Width;
10394 ModifySettingLocal = true;
10395 _isColumnChanged = true;
10398 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10400 DetailsListView lst = (DetailsListView)sender;
10401 if (_cfgLocal == null) return;
10404 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10406 _cfgLocal.Width1 = lst.Columns[0].Width;
10407 ModifySettingLocal = true;
10408 _isColumnChanged = true;
10410 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10412 _cfgLocal.Width3 = lst.Columns[1].Width;
10413 ModifySettingLocal = true;
10414 _isColumnChanged = true;
10419 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10421 _cfgLocal.Width1 = lst.Columns[0].Width;
10422 ModifySettingLocal = true;
10423 _isColumnChanged = true;
10425 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10427 _cfgLocal.Width2 = lst.Columns[1].Width;
10428 ModifySettingLocal = true;
10429 _isColumnChanged = true;
10431 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10433 _cfgLocal.Width3 = lst.Columns[2].Width;
10434 ModifySettingLocal = true;
10435 _isColumnChanged = true;
10437 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10439 _cfgLocal.Width4 = lst.Columns[3].Width;
10440 ModifySettingLocal = true;
10441 _isColumnChanged = true;
10443 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10445 _cfgLocal.Width5 = lst.Columns[4].Width;
10446 ModifySettingLocal = true;
10447 _isColumnChanged = true;
10449 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10451 _cfgLocal.Width6 = lst.Columns[5].Width;
10452 ModifySettingLocal = true;
10453 _isColumnChanged = true;
10455 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10457 _cfgLocal.Width7 = lst.Columns[6].Width;
10458 ModifySettingLocal = true;
10459 _isColumnChanged = true;
10461 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10463 _cfgLocal.Width8 = lst.Columns[7].Width;
10464 ModifySettingLocal = true;
10465 _isColumnChanged = true;
10468 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10471 // SaveConfigsLocal();
10475 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10478 string _selText = this.PostBrowser.GetSelectedText();
10481 Clipboard.SetDataObject(_selText, false, 5, 100);
10483 catch (Exception ex)
10485 MessageBox.Show(ex.Message);
10489 private async Task doSearchToolStrip(string url)
10491 //発言詳細で「選択文字列で検索」(選択文字列取得)
10492 string _selText = this.PostBrowser.GetSelectedText();
10494 if (_selText != null)
10496 if (url == Properties.Resources.SearchItem4Url)
10499 AddNewTabForSearch(_selText);
10503 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10504 await this.OpenUriInBrowserAsync(tmp);
10508 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10511 PostBrowser.Document.ExecCommand("SelectAll", false, null);
10514 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10516 await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10519 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10521 await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10524 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10526 await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10529 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10533 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10535 if (link.GetAttribute("href") == this._postBrowserStatusText)
10537 var linkStr = link.GetAttribute("title");
10538 if (string.IsNullOrEmpty(linkStr))
10539 linkStr = link.GetAttribute("href");
10541 Clipboard.SetDataObject(linkStr, false, 5, 100);
10546 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10548 catch (Exception ex)
10550 MessageBox.Show(ex.Message);
10554 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10556 // URLコピーの項目の表示/非表示
10557 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10559 this._postBrowserStatusText = PostBrowser.StatusText;
10560 string name = GetUserId();
10561 UrlCopyContextMenuItem.Enabled = true;
10564 FollowContextMenuItem.Enabled = true;
10565 RemoveContextMenuItem.Enabled = true;
10566 FriendshipContextMenuItem.Enabled = true;
10567 ShowUserStatusContextMenuItem.Enabled = true;
10568 SearchPostsDetailToolStripMenuItem.Enabled = true;
10569 IdFilterAddMenuItem.Enabled = true;
10570 ListManageUserContextToolStripMenuItem.Enabled = true;
10571 SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10575 FollowContextMenuItem.Enabled = false;
10576 RemoveContextMenuItem.Enabled = false;
10577 FriendshipContextMenuItem.Enabled = false;
10578 ShowUserStatusContextMenuItem.Enabled = false;
10579 SearchPostsDetailToolStripMenuItem.Enabled = false;
10580 IdFilterAddMenuItem.Enabled = false;
10581 ListManageUserContextToolStripMenuItem.Enabled = false;
10582 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10585 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10586 UseHashtagMenuItem.Enabled = true;
10588 UseHashtagMenuItem.Enabled = false;
10592 this._postBrowserStatusText = "";
10593 UrlCopyContextMenuItem.Enabled = false;
10594 FollowContextMenuItem.Enabled = false;
10595 RemoveContextMenuItem.Enabled = false;
10596 FriendshipContextMenuItem.Enabled = false;
10597 ShowUserStatusContextMenuItem.Enabled = false;
10598 SearchPostsDetailToolStripMenuItem.Enabled = false;
10599 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10600 UseHashtagMenuItem.Enabled = false;
10601 IdFilterAddMenuItem.Enabled = false;
10602 ListManageUserContextToolStripMenuItem.Enabled = false;
10604 // 文字列選択されていないときは選択文字列関係の項目を非表示に
10605 string _selText = this.PostBrowser.GetSelectedText();
10606 if (_selText == null)
10608 SelectionSearchContextMenuItem.Enabled = false;
10609 SelectionCopyContextMenuItem.Enabled = false;
10610 SelectionTranslationToolStripMenuItem.Enabled = false;
10614 SelectionSearchContextMenuItem.Enabled = true;
10615 SelectionCopyContextMenuItem.Enabled = true;
10616 SelectionTranslationToolStripMenuItem.Enabled = true;
10618 //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10619 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10620 bool fAllFlag = false;
10621 foreach (Match mu in ma)
10623 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10629 this.FriendshipAllMenuItem.Enabled = fAllFlag;
10631 if (_curPost == null)
10632 TranslationToolStripMenuItem.Enabled = false;
10634 TranslationToolStripMenuItem.Enabled = true;
10639 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10641 //発言詳細の選択文字列で現在のタブを検索
10642 string _selText = this.PostBrowser.GetSelectedText();
10644 if (_selText != null)
10646 var searchOptions = new SearchWordDialog.SearchOptions(
10647 SearchWordDialog.SearchType.Timeline,
10650 caseSensitive: false,
10653 this.SearchDialog.ResultOptions = searchOptions;
10656 searchOptions.Query,
10657 searchOptions.CaseSensitive,
10658 searchOptions.UseRegex,
10659 SEARCHTYPE.NextSearch);
10663 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10665 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10666 ModifySettingLocal = true;
10669 private void TweenMain_DragDrop(object sender, DragEventArgs e)
10671 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10673 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10675 SelectMedia_DragDrop(e);
10678 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10680 var url = GetUrlFromDataObject(e.Data);
10683 if (url.Item2 == null)
10684 appendText = url.Item1;
10686 appendText = url.Item2 + " " + url.Item1;
10688 if (this.StatusText.TextLength == 0)
10689 this.StatusText.Text = appendText;
10691 this.StatusText.Text += " " + appendText;
10693 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10695 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10697 this.StatusText.Text += text;
10699 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10701 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10702 if (data != null) StatusText.Text += data;
10707 /// IDataObject から URL とタイトルの対を取得します
10710 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10712 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10713 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10714 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10716 if (data.GetDataPresent("text/x-moz-url"))
10718 // Firefox, Google Chrome で利用可能
10719 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10721 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10723 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10724 if (lines.Length < 2)
10725 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10727 return new Tuple<string, string>(lines[0], lines[1]);
10730 else if (data.GetDataPresent("IESiteModeToUrl"))
10732 // Internet Exproler 用
10733 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10735 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10737 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10738 if (lines.Length < 2)
10739 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10741 return new Tuple<string, string>(lines[0], lines[1]);
10744 else if (data.GetDataPresent("UniformResourceLocatorW"))
10748 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10750 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10751 return new Tuple<string, string>(url, null);
10755 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10758 private void TweenMain_DragEnter(object sender, DragEventArgs e)
10760 if (e.Data.GetDataPresent(DataFormats.FileDrop))
10762 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10764 SelectMedia_DragEnter(e);
10768 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10770 e.Effect = DragDropEffects.Copy;
10773 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10775 e.Effect = DragDropEffects.Copy;
10778 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10780 e.Effect = DragDropEffects.Copy;
10784 e.Effect = DragDropEffects.None;
10787 private void TweenMain_DragOver(object sender, DragEventArgs e)
10791 public bool IsNetworkAvailable()
10794 nw = MyCommon.IsNetworkAvailable();
10795 _myStatusOnline = nw;
10799 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10801 var uriStr = uri.AbsoluteUri;
10803 // OpenTween 内部で使用する URL
10804 if (uri.Authority == "opentween")
10806 await this.OpenInternalUriAsync(uri);
10810 // ハッシュタグを含む Twitter 検索
10811 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10813 // ハッシュタグの場合は、タブで開く
10814 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10815 var pos = unescapedQuery.IndexOf('#');
10816 if (pos == -1) return;
10818 var hash = unescapedQuery.Substring(pos);
10819 this.HashSupl.AddItem(hash);
10820 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10821 this.AddNewTabForSearch(hash);
10826 // フラグが立っている場合は設定と逆の動作をする
10827 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10828 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10830 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10831 if (userUriMatch.Success)
10833 var screenName = userUriMatch.Groups["ScreenName"].Value;
10834 if (this.IsTwitterId(screenName))
10836 this.AddNewTabForUserTimeline(screenName);
10842 // どのパターンにも該当しないURL
10843 await this.OpenUriInBrowserAsync(uriStr);
10847 /// OpenTween 内部の機能を呼び出すための URL を開きます
10849 private async Task OpenInternalUriAsync(Uri uri)
10851 // ツイートを開く (//opentween/status/:status_id)
10852 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10855 var statusId = long.Parse(match.Groups[1].Value);
10856 await this.OpenRelatedTab(statusId);
10861 public Task OpenUriInBrowserAsync(string UriString)
10863 return Task.Run(() =>
10865 string myPath = UriString;
10869 var configBrowserPath = this._cfgLocal.BrowserPath;
10870 if (!string.IsNullOrEmpty(configBrowserPath))
10872 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10874 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10875 string browserPath = configBrowserPath.Substring(1, sep - 1);
10877 if (sep < configBrowserPath.Length - 1)
10879 arg = configBrowserPath.Substring(sep + 1);
10881 myPath = arg + " " + myPath;
10882 System.Diagnostics.Process.Start(browserPath, myPath);
10886 System.Diagnostics.Process.Start(configBrowserPath, myPath);
10891 System.Diagnostics.Process.Start(myPath);
10896 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10901 private void ListTabSelect(TabPage _tab)
10905 this.PurgeListViewItemCache();
10908 _curList = (DetailsListView)_tab.Tag;
10909 if (_curList.SelectedIndices.Count > 0)
10911 _curItemIndex = _curList.SelectedIndices[0];
10912 _curPost = GetCurTabPost(_curItemIndex);
10916 _curItemIndex = -1;
10920 _anchorPost = null;
10921 _anchorFlag = false;
10925 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10929 for (int i = 0; i < _curList.Columns.Count; i++)
10931 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10936 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10938 ListTabSelect(e.TabPage);
10941 private void SelectListItem(DetailsListView LView, int Index)
10944 Rectangle bnd = new Rectangle();
10946 var item = LView.FocusedItem;
10955 LView.SelectedIndices.Clear();
10957 while (LView.SelectedIndices.Count > 0);
10958 item = LView.Items[Index];
10959 item.Selected = true;
10960 item.Focused = true;
10962 if (flg) LView.Invalidate(bnd);
10965 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10968 Rectangle bnd = new Rectangle();
10970 var item = LView.FocusedItem;
10981 LView.SelectedIndices.Clear();
10983 while (LView.SelectedIndices.Count > 0);
10984 LView.SelectItems(Index);
10986 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10988 LView.SelectionMark = selectionMarkIndex;
10990 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10992 LView.Items[focusedIndex].Focused = true;
10994 else if (Index != null && Index.Length != 0)
10996 LView.Items[Index.Last()].Focused = true;
10999 if (flg) LView.Invalidate(bnd);
11002 private void StartUserStream()
11004 tw.NewPostFromStream += tw_NewPostFromStream;
11005 tw.UserStreamStarted += tw_UserStreamStarted;
11006 tw.UserStreamStopped += tw_UserStreamStopped;
11007 tw.PostDeleted += tw_PostDeleted;
11008 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11010 this.RefreshUserStreamsMenu();
11012 if (this._cfgCommon.UserstreamStartup)
11013 tw.StartUserStream();
11016 private async void TweenMain_Shown(object sender, EventArgs e)
11020 using (ControlTransaction.Update(this.PostBrowser))
11022 PostBrowser.Url = new Uri("about:blank");
11023 PostBrowser.DocumentText = ""; //発言詳細部初期化
11030 NotifyIcon1.Visible = true;
11032 if (this.IsNetworkAvailable())
11036 var loadTasks = new List<Task>
11038 this.RefreshMuteUserIdsAsync(),
11039 this.RefreshBlockIdsAsync(),
11040 this.RefreshNoRetweetIdsAsync(),
11041 this.RefreshTwitterConfigurationAsync(),
11042 this.GetHomeTimelineAsync(),
11043 this.GetReplyAsync(),
11044 this.GetDirectMessagesAsync(),
11045 this.GetPublicSearchAllAsync(),
11046 this.GetUserTimelineAllAsync(),
11047 this.GetListTimelineAllAsync(),
11050 if (this._cfgCommon.StartupFollowers)
11051 loadTasks.Add(this.RefreshFollowerIdsAsync());
11053 if (this._cfgCommon.GetFav)
11054 loadTasks.Add(this.GetFavoritesAsync());
11056 var allTasks = Task.WhenAll(loadTasks);
11061 var timeout = Task.Delay(5000);
11062 if (await Task.WhenAny(allTasks, timeout) != timeout)
11066 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11068 if (MyCommon._endingFlag)
11072 if (MyCommon._endingFlag) return;
11074 if (ApplicationSettings.VersionInfoUrl != null)
11076 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11077 if (this._cfgCommon.StartupVersion)
11078 await this.CheckNewVersion(true);
11082 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11083 this.VerUpMenuItem.Enabled = false;
11084 this.VerUpMenuItem.Available = false;
11085 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11088 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11089 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11091 MessageBox.Show(Properties.Resources.ReAuthorizeText);
11092 SettingStripMenuItem_Click(null, null);
11096 var reloadTasks = new List<Task>();
11098 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11099 reloadTasks.Add(this.RefreshFollowerIdsAsync());
11101 if (!tw.GetNoRetweetSuccess)
11102 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11104 if (this.tw.Configuration.PhotoSizeLimit == 0)
11105 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11107 await Task.WhenAll(reloadTasks);
11112 TimerTimeline.Enabled = true;
11115 private async Task doGetFollowersMenu()
11117 await this.RefreshFollowerIdsAsync();
11118 await this.DispSelectedPost(true);
11121 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11123 await this.doGetFollowersMenu();
11126 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11128 doReTweetUnofficial();
11131 private async Task doReTweetOfficial(bool isConfirm)
11134 if (this.ExistCurrentPost)
11136 if (_curPost.IsProtect)
11138 MessageBox.Show("Protected.");
11139 _DoFavRetweetFlags = false;
11142 if (_curList.SelectedIndices.Count > 15)
11144 MessageBox.Show(Properties.Resources.RetweetLimitText);
11145 _DoFavRetweetFlags = false;
11148 else if (_curList.SelectedIndices.Count > 1)
11150 string QuestionText = Properties.Resources.RetweetQuestion2;
11151 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11152 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11154 case DialogResult.Cancel:
11155 case DialogResult.No:
11156 _DoFavRetweetFlags = false;
11162 if (_curPost.IsDm || _curPost.IsMe)
11164 _DoFavRetweetFlags = false;
11167 if (!this._cfgCommon.RetweetNoConfirm)
11169 string Questiontext = Properties.Resources.RetweetQuestion1;
11170 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11171 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11173 _DoFavRetweetFlags = false;
11179 var statusIds = new List<long>();
11180 foreach (int idx in _curList.SelectedIndices)
11182 PostClass post = GetCurTabPost(idx);
11183 if (!post.IsMe && !post.IsProtect && !post.IsDm)
11184 statusIds.Add(post.StatusId);
11187 await this.RetweetAsync(statusIds);
11191 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11193 await this.doReTweetOfficial(true);
11196 private async Task FavoritesRetweetOfficial()
11198 if (!this.ExistCurrentPost) return;
11199 _DoFavRetweetFlags = true;
11200 var retweetTask = this.doReTweetOfficial(true);
11201 if (_DoFavRetweetFlags)
11203 _DoFavRetweetFlags = false;
11204 var favoriteTask = this.FavoriteChange(true, false);
11206 await Task.WhenAll(retweetTask, favoriteTask);
11214 private async Task FavoritesRetweetUnofficial()
11216 if (this.ExistCurrentPost && !_curPost.IsDm)
11218 _DoFavRetweetFlags = true;
11219 var favoriteTask = this.FavoriteChange(true);
11220 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11222 _DoFavRetweetFlags = false;
11223 doReTweetUnofficial();
11226 await favoriteTask;
11231 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11233 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11234 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11235 /// <returns>復元されたツイート本文</returns>
11236 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11238 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11241 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11243 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11245 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11249 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11251 statusHtml = statusHtml.Replace("<br>", " ");
11253 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11254 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
11255 statusHtml = statusHtml.Replace(" ", " ");
11257 return WebUtility.HtmlDecode(statusHtml);
11260 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11262 if (_curPost != null)
11263 await this.DispSelectedPost(true);
11266 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11268 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11269 DebugModeToolStripMenuItem.Visible = true;
11271 DebugModeToolStripMenuItem.Visible = false;
11274 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11276 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11279 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11281 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11284 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11286 if (TraceOutToolStripMenuItem.Checked)
11287 MyCommon.TraceFlag = true;
11289 MyCommon.TraceFlag = false;
11292 private void TweenMain_Deactivate(object sender, EventArgs e)
11294 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11295 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11298 private void TabRenameMenuItem_Click(object sender, EventArgs e)
11300 if (string.IsNullOrEmpty(_rclickTabName)) return;
11301 TabRename(ref _rclickTabName);
11304 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11306 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11309 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11311 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11314 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11316 TwitterApiStatus apiStatus;
11318 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11320 var cancellationToken = dialog.EnableCancellation();
11324 var task = this.tw.GetInfoApi();
11325 apiStatus = await dialog.WaitForAsync(this, task);
11327 catch (WebApiException)
11332 if (cancellationToken.IsCancellationRequested)
11335 if (apiStatus == null)
11337 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11342 using (var apiDlg = new ApiInfoDialog())
11344 apiDlg.ShowDialog(this);
11348 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11350 var id = _curPost?.ScreenName ?? "";
11352 await this.FollowCommand(id);
11355 private async Task FollowCommand(string id)
11357 using (var inputName = new InputTabName())
11359 inputName.FormTitle = "Follow";
11360 inputName.FormDescription = Properties.Resources.FRMessage1;
11361 inputName.TabName = id;
11363 if (inputName.ShowDialog(this) != DialogResult.OK)
11365 if (string.IsNullOrWhiteSpace(inputName.TabName))
11368 id = inputName.TabName.Trim();
11371 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11375 var task = this.twitterApi.FriendshipsCreate(id);
11376 await dialog.WaitForAsync(this, task);
11378 catch (WebApiException ex)
11380 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11385 MessageBox.Show(Properties.Resources.FRMessage3);
11388 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11390 var id = _curPost?.ScreenName ?? "";
11392 await this.RemoveCommand(id, false);
11395 private async Task RemoveCommand(string id, bool skipInput)
11399 using (var inputName = new InputTabName())
11401 inputName.FormTitle = "Unfollow";
11402 inputName.FormDescription = Properties.Resources.FRMessage1;
11403 inputName.TabName = id;
11405 if (inputName.ShowDialog(this) != DialogResult.OK)
11407 if (string.IsNullOrWhiteSpace(inputName.TabName))
11410 id = inputName.TabName.Trim();
11414 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11418 var task = this.twitterApi.FriendshipsDestroy(id);
11419 await dialog.WaitForAsync(this, task);
11421 catch (WebApiException ex)
11423 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11428 MessageBox.Show(Properties.Resources.FRMessage3);
11431 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11433 var id = _curPost?.ScreenName ?? "";
11435 await this.ShowFriendship(id);
11438 private async Task ShowFriendship(string id)
11440 using (var inputName = new InputTabName())
11442 inputName.FormTitle = "Show Friendships";
11443 inputName.FormDescription = Properties.Resources.FRMessage1;
11444 inputName.TabName = id;
11446 if (inputName.ShowDialog(this) != DialogResult.OK)
11448 if (string.IsNullOrWhiteSpace(inputName.TabName))
11451 id = inputName.TabName.Trim();
11454 bool isFollowing, isFollowed;
11456 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11458 var cancellationToken = dialog.EnableCancellation();
11462 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11463 var friendship = await dialog.WaitForAsync(this, task);
11465 isFollowing = friendship.Relationship.Source.Following;
11466 isFollowed = friendship.Relationship.Source.FollowedBy;
11468 catch (WebApiException ex)
11470 if (!cancellationToken.IsCancellationRequested)
11471 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11475 if (cancellationToken.IsCancellationRequested)
11479 string result = "";
11482 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11486 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11490 result += Properties.Resources.GetFriendshipInfo3;
11494 result += Properties.Resources.GetFriendshipInfo4;
11496 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11497 MessageBox.Show(result);
11500 private async Task ShowFriendship(string[] ids)
11502 foreach (string id in ids)
11504 bool isFollowing, isFollowed;
11506 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11508 var cancellationToken = dialog.EnableCancellation();
11512 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11513 var friendship = await dialog.WaitForAsync(this, task);
11515 isFollowing = friendship.Relationship.Source.Following;
11516 isFollowed = friendship.Relationship.Source.FollowedBy;
11518 catch (WebApiException ex)
11520 if (!cancellationToken.IsCancellationRequested)
11521 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11525 if (cancellationToken.IsCancellationRequested)
11529 string result = "";
11535 ff += Properties.Resources.GetFriendshipInfo1;
11539 ff += Properties.Resources.GetFriendshipInfo2;
11542 ff += System.Environment.NewLine + " ";
11545 ff += Properties.Resources.GetFriendshipInfo3;
11549 ff += Properties.Resources.GetFriendshipInfo4;
11551 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11554 if (MessageBox.Show(
11555 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11556 MessageBoxButtons.YesNo,
11557 MessageBoxIcon.Question,
11558 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11560 await this.RemoveCommand(id, true);
11565 MessageBox.Show(result);
11570 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11572 await this.doShowUserStatus(tw.Username, false);
11573 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11575 // doShowUserStatus(tw.Username, false);
11579 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11584 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11585 // URLから切り出した文字列を渡す
11587 public bool IsTwitterId(string name)
11589 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11590 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11592 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11595 private string GetUserId()
11597 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11598 if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11599 return m.Result("${ScreenName}");
11604 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11606 string name = GetUserId();
11608 await this.FollowCommand(name);
11611 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11613 string name = GetUserId();
11615 await this.RemoveCommand(name, false);
11618 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11620 string name = GetUserId();
11622 await this.ShowFriendship(name);
11625 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11627 MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11628 List<string> ids = new List<string>();
11629 foreach (Match mu in ma)
11631 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11633 ids.Add(mu.Result("${ScreenName}"));
11637 await this.ShowFriendship(ids.ToArray());
11640 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11642 string name = GetUserId();
11644 await this.ShowUserStatus(name);
11647 private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11649 string name = GetUserId();
11650 if (name != null) AddNewTabForUserTimeline(name);
11653 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11655 string name = GetUserId();
11656 if (name != null) AddNewTabForSearch("@" + name);
11659 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11661 ModifySettingCommon = true;
11664 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11666 ModifySettingCommon = true;
11669 private void doQuoteOfficial()
11671 if (this.ExistCurrentPost)
11673 if (_curPost.IsDm ||
11674 !StatusText.Enabled) return;
11676 if (_curPost.IsProtect)
11678 MessageBox.Show("Protected.");
11682 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11684 this.inReplyTo = null;
11686 StatusText.SelectionStart = 0;
11687 StatusText.Focus();
11691 private void doReTweetUnofficial()
11694 if (this.ExistCurrentPost)
11696 if (_curPost.IsDm || !StatusText.Enabled)
11699 if (_curPost.IsProtect)
11701 MessageBox.Show("Protected.");
11704 string rtdata = _curPost.Text;
11705 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11707 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11709 // 投稿時に in_reply_to_status_id を付加する
11710 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11711 var inReplyToScreenName = this._curPost.ScreenName;
11712 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11714 StatusText.SelectionStart = 0;
11715 StatusText.Focus();
11719 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11724 private void SearchButton_Click(object sender, EventArgs e)
11727 Control pnl = ((Control)sender).Parent;
11728 if (pnl == null) return;
11729 string tbName = pnl.Parent.Text;
11730 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
11731 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11732 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11733 cmb.Text = cmb.Text.Trim();
11734 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11735 bool Quote = false;
11736 StringBuilder buf = new StringBuilder();
11737 char[] c = cmb.Text.ToCharArray();
11738 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11740 if (cnt > cmb.Text.Length - 4)
11742 buf.Append(cmb.Text.Substring(cnt));
11751 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11753 buf.Append(" OR ");
11758 buf.Append(c[cnt]);
11760 cmb.Text = buf.ToString();
11762 var listView = (DetailsListView)pnl.Parent.Tag;
11764 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
11766 tb.SearchWords = cmb.Text;
11767 tb.SearchLang = cmbLang.Text;
11768 if (string.IsNullOrEmpty(cmb.Text))
11776 int idx = cmb.Items.IndexOf(tb.SearchWords);
11777 if (idx > -1) cmb.Items.RemoveAt(idx);
11778 cmb.Items.Insert(0, tb.SearchWords);
11779 cmb.Text = tb.SearchWords;
11781 this.PurgeListViewItemCache();
11782 listView.VirtualListSize = 0;
11783 _statuses.ClearTabIds(tbName);
11784 SaveConfigsTabs(); //検索条件の保存
11787 this.GetPublicSearchAsync(tb);
11791 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11794 await this.DoRefreshMore();
11798 /// 指定されたタブのListTabにおける位置を返します
11801 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11803 public int GetTabPageIndex(string tabName)
11806 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11808 if (tabPage.Text == tabName)
11817 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11819 if (_statuses.RemovedTab.Count == 0)
11821 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11826 DetailsListView listView = null;
11828 TabModel tb = _statuses.RemovedTab.Pop();
11829 if (tb.TabType == MyCommon.TabUsageType.Related)
11831 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11832 if (relatedTab != null)
11834 // 関連発言なら既存のタブを置き換える
11835 tb.TabName = relatedTab.TabName;
11836 this.ClearTab(tb.TabName, false);
11837 _statuses.Tabs[tb.TabName] = tb;
11839 for (int i = 0; i < ListTab.TabPages.Count; i++)
11841 var tabPage = ListTab.TabPages[i];
11842 if (tb.TabName == tabPage.Text)
11844 listView = (DetailsListView)tabPage.Tag;
11845 ListTab.SelectedIndex = i;
11852 const string TabName = "Related Tweets";
11853 string renamed = TabName;
11854 for (int i = 2; i <= 100; i++)
11856 if (!_statuses.ContainsTab(renamed)) break;
11857 renamed = TabName + i.ToString();
11859 tb.TabName = renamed;
11861 _statuses.AddTab(tb);
11862 AddNewTab(tb, startup: false);
11864 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11865 listView = (DetailsListView)tabPage.Tag;
11866 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11871 string renamed = tb.TabName;
11872 for (int i = 1; i < int.MaxValue; i++)
11874 if (!_statuses.ContainsTab(renamed)) break;
11875 renamed = tb.TabName + "(" + i.ToString() + ")";
11877 tb.TabName = renamed;
11879 _statuses.AddTab(tb);
11880 AddNewTab(tb, startup: false);
11882 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11883 listView = (DetailsListView)tabPage.Tag;
11884 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11888 if (listView != null)
11890 using (ControlTransaction.Update(listView))
11892 listView.VirtualListSize = tb.AllCount;
11898 private async Task doMoveToRTHome()
11900 if (_curList.SelectedIndices.Count > 0)
11902 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11903 if (post.RetweetedId != null)
11905 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11910 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11912 await this.doMoveToRTHome();
11915 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11917 string name = GetUserId();
11923 if (_curList.SelectedIndices.Count == 0) return;
11926 if (!SelectTab(out tabName)) return;
11928 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
11932 if (tab.TabType != MyCommon.TabUsageType.Mute)
11934 this.MoveOrCopy(out mv, out mk);
11938 // ミュートタブでは常に MoveMatches を true にする
11943 PostFilterRule fc = new PostFilterRule();
11944 fc.FilterName = name;
11945 fc.UseNameField = true;
11946 fc.MoveMatches = mv;
11947 fc.MarkMatches = mk;
11948 fc.UseRegex = false;
11949 fc.FilterByUrl = false;
11952 this.ApplyPostFilters();
11957 private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11961 ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11963 if (menuItem.Owner == this.ContextMenuPostBrowser)
11965 user = GetUserId();
11966 if (user == null) return;
11968 else if (this._curPost != null)
11970 user = this._curPost.ScreenName;
11977 if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11981 using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11983 var cancellationToken = dialog.EnableCancellation();
11985 var task = this.tw.GetListsApi();
11986 await dialog.WaitForAsync(this, task);
11988 cancellationToken.ThrowIfCancellationRequested();
11991 catch (OperationCanceledException) { return; }
11992 catch (WebApiException ex)
11994 MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11999 using (MyLists listSelectForm = new MyLists(user, this.tw))
12001 listSelectForm.ShowDialog(this);
12005 private void SearchControls_Enter(object sender, EventArgs e)
12007 Control pnl = (Control)sender;
12008 foreach (Control ctl in pnl.Controls)
12010 ctl.TabStop = true;
12014 private void SearchControls_Leave(object sender, EventArgs e)
12016 Control pnl = (Control)sender;
12017 foreach (Control ctl in pnl.Controls)
12019 ctl.TabStop = false;
12023 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12025 if (ListTab.SelectedTab != null)
12027 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12028 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12032 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12034 Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12037 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12038 HashStripSplitButton.Text = HashMgr.UseHash;
12039 HashToggleMenuItem.Checked = true;
12040 HashToggleToolStripMenuItem.Checked = true;
12042 ModifySettingCommon = true;
12046 private void StatusLabel_DoubleClick(object sender, EventArgs e)
12048 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12051 private void HashManageMenuItem_Click(object sender, EventArgs e)
12053 DialogResult rslt = DialogResult.Cancel;
12056 rslt = HashMgr.ShowDialog();
12062 this.TopMost = this._cfgCommon.AlwaysTop;
12063 if (rslt == DialogResult.Cancel) return;
12064 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12066 HashStripSplitButton.Text = HashMgr.UseHash;
12067 HashToggleMenuItem.Checked = true;
12068 HashToggleToolStripMenuItem.Checked = true;
12072 HashStripSplitButton.Text = "#[-]";
12073 HashToggleMenuItem.Checked = false;
12074 HashToggleToolStripMenuItem.Checked = false;
12076 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12078 // int sidx = StatusText.SelectionStart;
12079 // string hash = HashMgr.UseHash + " ";
12082 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12083 // hash = " " + hash;
12085 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
12086 // sidx += hash.Length;
12087 // StatusText.SelectionStart = sidx;
12088 // StatusText.Focus();
12090 ModifySettingCommon = true;
12091 this.StatusText_TextChanged(null, null);
12094 private void HashToggleMenuItem_Click(object sender, EventArgs e)
12096 HashMgr.ToggleHash();
12097 if (!string.IsNullOrEmpty(HashMgr.UseHash))
12099 HashStripSplitButton.Text = HashMgr.UseHash;
12100 HashToggleMenuItem.Checked = true;
12101 HashToggleToolStripMenuItem.Checked = true;
12105 HashStripSplitButton.Text = "#[-]";
12106 HashToggleMenuItem.Checked = false;
12107 HashToggleToolStripMenuItem.Checked = false;
12109 ModifySettingCommon = true;
12110 this.StatusText_TextChanged(null, null);
12113 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12115 HashToggleMenuItem_Click(null, null);
12118 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12120 if (ListTab.SelectedTab == null) return;
12121 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12122 if (!this.ExistCurrentPost)
12124 this.ReplyOpMenuItem.Enabled = false;
12125 this.ReplyAllOpMenuItem.Enabled = false;
12126 this.DmOpMenuItem.Enabled = false;
12127 this.ShowProfMenuItem.Enabled = false;
12128 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12129 this.ListManageMenuItem.Enabled = false;
12130 this.OpenFavOpMenuItem.Enabled = false;
12131 this.CreateTabRuleOpMenuItem.Enabled = false;
12132 this.CreateIdRuleOpMenuItem.Enabled = false;
12133 this.CreateSourceRuleOpMenuItem.Enabled = false;
12134 this.ReadOpMenuItem.Enabled = false;
12135 this.UnreadOpMenuItem.Enabled = false;
12139 this.ReplyOpMenuItem.Enabled = true;
12140 this.ReplyAllOpMenuItem.Enabled = true;
12141 this.DmOpMenuItem.Enabled = true;
12142 this.ShowProfMenuItem.Enabled = true;
12143 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12144 this.ListManageMenuItem.Enabled = true;
12145 this.OpenFavOpMenuItem.Enabled = true;
12146 this.CreateTabRuleOpMenuItem.Enabled = true;
12147 this.CreateIdRuleOpMenuItem.Enabled = true;
12148 this.CreateSourceRuleOpMenuItem.Enabled = true;
12149 this.ReadOpMenuItem.Enabled = true;
12150 this.UnreadOpMenuItem.Enabled = true;
12153 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12155 this.FavOpMenuItem.Enabled = false;
12156 this.UnFavOpMenuItem.Enabled = false;
12157 this.OpenStatusOpMenuItem.Enabled = false;
12158 this.OpenFavotterOpMenuItem.Enabled = false;
12159 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12160 this.RtOpMenuItem.Enabled = false;
12161 this.RtUnOpMenuItem.Enabled = false;
12162 this.QtOpMenuItem.Enabled = false;
12163 this.FavoriteRetweetMenuItem.Enabled = false;
12164 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12168 this.FavOpMenuItem.Enabled = true;
12169 this.UnFavOpMenuItem.Enabled = true;
12170 this.OpenStatusOpMenuItem.Enabled = true;
12171 this.OpenFavotterOpMenuItem.Enabled = true;
12172 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
12176 this.RtOpMenuItem.Enabled = false; //公式RTは無効に
12177 this.RtUnOpMenuItem.Enabled = true;
12178 this.QtOpMenuItem.Enabled = true;
12179 this.FavoriteRetweetMenuItem.Enabled = false; //公式RTは無効に
12180 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12184 if (_curPost.IsProtect)
12186 this.RtOpMenuItem.Enabled = false;
12187 this.RtUnOpMenuItem.Enabled = false;
12188 this.QtOpMenuItem.Enabled = false;
12189 this.FavoriteRetweetMenuItem.Enabled = false;
12190 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12194 this.RtOpMenuItem.Enabled = true;
12195 this.RtUnOpMenuItem.Enabled = true;
12196 this.QtOpMenuItem.Enabled = true;
12197 this.FavoriteRetweetMenuItem.Enabled = true;
12198 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12203 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12205 this.RefreshPrevOpMenuItem.Enabled = true;
12209 this.RefreshPrevOpMenuItem.Enabled = false;
12211 if (!this.ExistCurrentPost
12212 || _curPost.InReplyToStatusId == null)
12214 OpenRepSourceOpMenuItem.Enabled = false;
12218 OpenRepSourceOpMenuItem.Enabled = true;
12220 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12222 OpenRterHomeMenuItem.Enabled = false;
12226 OpenRterHomeMenuItem.Enabled = true;
12229 if (this.ExistCurrentPost)
12231 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12235 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12237 ContextMenuTabProperty_Opening(sender, null);
12240 public Twitter TwitterInstance
12245 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12247 if (this._initialLayout)
12250 int splitterDistance;
12251 switch (this.WindowState)
12253 case FormWindowState.Normal:
12254 splitterDistance = this.SplitContainer3.SplitterDistance;
12256 case FormWindowState.Maximized:
12257 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12258 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12259 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12260 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12266 this._mySpDis3 = splitterDistance;
12267 this.ModifySettingLocal = true;
12270 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12272 if (_statuses.RemovedTab.Count == 0)
12274 UndoRemoveTabMenuItem.Enabled = false;
12278 UndoRemoveTabMenuItem.Enabled = true;
12280 if (ListTab.SelectedTab != null)
12282 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12283 PublicSearchQueryMenuItem.Enabled = true;
12285 PublicSearchQueryMenuItem.Enabled = false;
12289 PublicSearchQueryMenuItem.Enabled = false;
12291 if (!this.ExistCurrentPost)
12293 this.CopySTOTMenuItem.Enabled = false;
12294 this.CopyURLMenuItem.Enabled = false;
12295 this.CopyUserIdStripMenuItem.Enabled = false;
12299 this.CopySTOTMenuItem.Enabled = true;
12300 this.CopyURLMenuItem.Enabled = true;
12301 this.CopyUserIdStripMenuItem.Enabled = true;
12302 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12303 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12307 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12309 SetNotifyIconText();
12312 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12314 var id = _curPost?.ScreenName ?? "";
12316 await this.ShowUserStatus(id);
12319 private async Task doShowUserStatus(string id, bool ShowInputDialog)
12321 TwitterUser user = null;
12323 if (ShowInputDialog)
12325 using (var inputName = new InputTabName())
12327 inputName.FormTitle = "Show UserStatus";
12328 inputName.FormDescription = Properties.Resources.FRMessage1;
12329 inputName.TabName = id;
12331 if (inputName.ShowDialog(this) != DialogResult.OK)
12333 if (string.IsNullOrWhiteSpace(inputName.TabName))
12336 id = inputName.TabName.Trim();
12340 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12342 var cancellationToken = dialog.EnableCancellation();
12346 var task = this.twitterApi.UsersShow(id);
12347 user = await dialog.WaitForAsync(this, task);
12349 catch (WebApiException ex)
12351 if (!cancellationToken.IsCancellationRequested)
12352 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12356 if (cancellationToken.IsCancellationRequested)
12360 await this.doShowUserStatus(user);
12363 private async Task doShowUserStatus(TwitterUser user)
12365 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12367 var showUserTask = userDialog.ShowUserAsync(user);
12368 userDialog.ShowDialog(this);
12371 this.BringToFront();
12373 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12374 await showUserTask;
12378 private Task ShowUserStatus(string id, bool ShowInputDialog)
12380 return this.doShowUserStatus(id, ShowInputDialog);
12383 private Task ShowUserStatus(string id)
12385 return this.doShowUserStatus(id, true);
12388 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12390 if (NameLabel.Tag != null)
12392 string id = (string)NameLabel.Tag;
12393 if (id != tw.Username)
12395 await this.FollowCommand(id);
12400 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12402 if (NameLabel.Tag != null)
12404 string id = (string)NameLabel.Tag;
12405 if (id != tw.Username)
12407 await this.RemoveCommand(id, false);
12412 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12414 if (NameLabel.Tag != null)
12416 string id = (string)NameLabel.Tag;
12417 if (id != tw.Username)
12419 await this.ShowFriendship(id);
12424 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12426 if (NameLabel.Tag != null)
12428 string id = (string)NameLabel.Tag;
12429 await this.ShowUserStatus(id, false);
12433 private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12435 if (NameLabel.Tag != null)
12437 string id = (string)NameLabel.Tag;
12438 AddNewTabForUserTimeline(id);
12442 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12444 if (NameLabel.Tag != null)
12446 string id = (string)NameLabel.Tag;
12447 AddNewTabForSearch("@" + id);
12451 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12453 if (_curPost != null)
12455 await this.ShowUserStatus(_curPost.ScreenName, false);
12459 private async void RtCountMenuItem_Click(object sender, EventArgs e)
12461 if (!this.ExistCurrentPost)
12464 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12465 TwitterStatus status;
12467 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12469 var cancellationToken = dialog.EnableCancellation();
12473 var task = this.twitterApi.StatusesShow(statusId);
12474 status = await dialog.WaitForAsync(this, task);
12476 catch (WebApiException ex)
12478 if (!cancellationToken.IsCancellationRequested)
12479 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12483 if (cancellationToken.IsCancellationRequested)
12487 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12490 private HookGlobalHotkey _hookGlobalHotkey;
12493 _hookGlobalHotkey = new HookGlobalHotkey(this);
12495 // この呼び出しは、Windows フォーム デザイナで必要です。
12496 InitializeComponent();
12498 // InitializeComponent() 呼び出しの後で初期化を追加します。
12500 if (!this.DesignMode)
12502 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12503 this.StatusText.Dock = DockStyle.Fill;
12506 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12507 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12508 this.gh.NotifyClicked += GrowlHelper_Callback;
12510 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12511 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12513 this.ImageSelector.Visible = false;
12514 this.ImageSelector.Enabled = false;
12515 this.ImageSelector.FilePickDialog = OpenFileDialog1;
12517 this.ReplaceAppName();
12518 this.InitializeShortcuts();
12521 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12523 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12526 this.Visible = false;
12528 else if (Form.ActiveForm == null)
12530 this.Visible = true;
12531 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12533 this.BringToFront();
12534 this.StatusText.Focus();
12538 private void UserPicture_MouseEnter(object sender, EventArgs e)
12540 this.UserPicture.Cursor = Cursors.Hand;
12543 private void UserPicture_MouseLeave(object sender, EventArgs e)
12545 this.UserPicture.Cursor = Cursors.Default;
12548 private async void UserPicture_DoubleClick(object sender, EventArgs e)
12550 if (NameLabel.Tag != null)
12552 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12556 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12558 this.MultiLineMenuItem.PerformClick();
12561 public PostClass CurPost
12563 get { return _curPost; }
12567 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12569 if (ImageSelector.Visible)
12570 ImageSelector.EndSelection();
12572 ImageSelector.BeginSelection();
12575 private void SelectMedia_DragEnter(DragEventArgs e)
12577 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12579 e.Effect = DragDropEffects.Copy;
12582 e.Effect = DragDropEffects.None;
12585 private void SelectMedia_DragDrop(DragEventArgs e)
12588 this.BringToFront();
12589 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12590 StatusText.Focus();
12593 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12595 TimelinePanel.Visible = false;
12596 TimelinePanel.Enabled = false;
12599 private void ImageSelector_EndSelecting(object sender, EventArgs e)
12601 TimelinePanel.Visible = true;
12602 TimelinePanel.Enabled = true;
12603 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12606 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12608 this.AllowDrop = false;
12611 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12613 this.AllowDrop = true;
12616 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12618 if (ImageSelector.Visible)
12620 ModifySettingCommon = true;
12621 SaveConfigsAll(true);
12623 if (ImageSelector.ServiceName.Equals("Twitter"))
12624 this.StatusText_TextChanged(null, null);
12628 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12630 this.StatusText_TextChanged(null, null);
12634 /// StatusTextでCtrl+Vが押下された時の処理
12636 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12638 if (Clipboard.ContainsText())
12640 // clipboardにテキストがある場合は貼り付け処理
12641 this.StatusText.Paste(Clipboard.GetText());
12643 else if (Clipboard.ContainsImage())
12646 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12647 Properties.Resources.PostPictureWarn4,
12648 MessageBoxButtons.OKCancel,
12649 MessageBoxIcon.Question,
12650 MessageBoxDefaultButton.Button2)
12651 == DialogResult.OK)
12653 // clipboardから画像を取得
12654 using (var image = Clipboard.GetImage())
12656 this.ImageSelector.BeginSelection(image);
12663 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12665 using (ListManage form = new ListManage(tw))
12667 form.ShowDialog(this);
12671 public bool ModifySettingCommon { get; set; }
12672 public bool ModifySettingLocal { get; set; }
12673 public bool ModifySettingAtId { get; set; }
12675 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12677 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12678 if (sourceUri != null && e.Button == MouseButtons.Left)
12680 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12684 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12686 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12687 if (sourceUri != null)
12689 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12693 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12695 SetStatusLabelUrl();
12698 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12700 if (this.ExistCurrentPost && !_curPost.IsDm)
12701 RtCountMenuItem.Enabled = true;
12703 RtCountMenuItem.Enabled = false;
12705 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12706 // TinyUrlConvertToolStripMenuItem.Enabled = false;
12708 // TinyUrlConvertToolStripMenuItem.Enabled = true;
12711 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12716 private void CopyUserId()
12718 if (_curPost == null) return;
12719 string clstr = _curPost.ScreenName;
12722 Clipboard.SetDataObject(clstr, false, 5, 100);
12724 catch (Exception ex)
12726 MessageBox.Show(ex.Message);
12730 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12732 if (this.ExistCurrentPost && !_curPost.IsDm)
12736 await this.OpenRelatedTab(this._curPost);
12738 catch (TabException ex)
12740 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12746 /// 指定されたツイートに対する関連発言タブを開きます
12748 /// <param name="statusId">表示するツイートのID</param>
12749 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12750 private async Task OpenRelatedTab(long statusId)
12752 var post = this._statuses[statusId];
12757 post = await this.tw.GetStatusApi(false, statusId);
12759 catch (WebApiException ex)
12761 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12766 await this.OpenRelatedTab(post);
12770 /// 指定されたツイートに対する関連発言タブを開きます
12772 /// <param name="post">表示する対象となるツイート</param>
12773 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12774 private async Task OpenRelatedTab(PostClass post)
12776 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
12777 if (tabRelated != null)
12779 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
12782 var tabName = this._statuses.MakeTabName("Related Tweets");
12784 tabRelated = new RelatedPostsTabModel(tabName, post);
12785 tabRelated.UnreadManage = false;
12786 tabRelated.Notify = false;
12788 this._statuses.AddTab(tabRelated);
12789 this.AddNewTab(tabRelated, startup: false);
12791 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12793 var tabPage = this.ListTab.TabPages[i];
12794 if (tabName == tabPage.Text)
12796 this.ListTab.SelectedIndex = i;
12801 await this.GetRelatedTweetsAsync(tabRelated);
12804 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12806 StringBuilder buf = new StringBuilder();
12807 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12808 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12809 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
12810 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12811 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12814 private void tw_UserIdChanged()
12816 this.ModifySettingCommon = true;
12819 #region "Userstream"
12820 private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12824 if (InvokeRequired && !IsDisposed)
12826 Invoke((Action) (async () =>
12828 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
12829 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12831 this.PurgeListViewItemCache();
12832 ((DetailsListView)_curTab.Tag).Update();
12833 if (_curPost != null && _curPost.StatusId == e.StatusId)
12834 await this.DispSelectedPost(true);
12840 catch (ObjectDisposedException)
12844 catch (InvalidOperationException)
12850 private int userStreamsRefreshing = 0;
12852 private async void tw_NewPostFromStream(object sender, EventArgs e)
12854 if (this._cfgCommon.ReadOldPosts)
12856 _statuses.SetReadHomeTab(); //新着時未読クリア
12859 int rsltAddCount = _statuses.DistributePosts();
12861 this.UpdateTimelineSpeed(rsltAddCount);
12863 if (this._cfgCommon.UserstreamPeriod > 0) return;
12865 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12866 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12870 await this.InvokeAsync(() => this.RefreshTimeline())
12871 .ConfigureAwait(false);
12875 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12880 private void tw_UserStreamStarted(object sender, EventArgs e)
12884 if (InvokeRequired && !IsDisposed)
12886 Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12890 catch (ObjectDisposedException)
12894 catch (InvalidOperationException)
12899 this.RefreshUserStreamsMenu();
12900 this.MenuItemUserStream.Enabled = true;
12902 StatusLabel.Text = "UserStream Started.";
12905 private void tw_UserStreamStopped(object sender, EventArgs e)
12909 if (InvokeRequired && !IsDisposed)
12911 Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12915 catch (ObjectDisposedException)
12919 catch (InvalidOperationException)
12924 this.RefreshUserStreamsMenu();
12925 this.MenuItemUserStream.Enabled = true;
12927 StatusLabel.Text = "UserStream Stopped.";
12930 private void RefreshUserStreamsMenu()
12932 if (this.tw.UserStreamActive)
12934 this.MenuItemUserStream.Text = "&UserStream ▶";
12935 this.StopToolStripMenuItem.Text = "&Stop";
12939 this.MenuItemUserStream.Text = "&UserStream ■";
12940 this.StopToolStripMenuItem.Text = "&Start";
12944 private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12948 if (InvokeRequired && !IsDisposed)
12950 Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12954 catch (ObjectDisposedException)
12958 catch (InvalidOperationException)
12962 var ev = e.EventData;
12963 StatusLabel.Text = "Event: " + ev.Event;
12964 //if (ev.Event == "favorite")
12966 // NotifyFavorite(ev);
12969 if (ev.Event == "favorite" || ev.Event == "unfavorite")
12971 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12973 this.PurgeListViewItemCache();
12974 ((DetailsListView)_curTab.Tag).Update();
12976 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12978 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
12979 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
12984 private void NotifyEvent(Twitter.FormattedEvent ev)
12987 if (BalloonRequired(ev))
12989 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12990 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12991 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12992 StringBuilder title = new StringBuilder();
12993 if (this._cfgCommon.DispUsername)
12995 title.Append(tw.Username);
12996 title.Append(" - ");
13002 title.Append(Application.ProductName);
13003 title.Append(" [");
13004 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13005 title.Append("] by ");
13006 if (!string.IsNullOrEmpty(ev.Username))
13008 title.Append(ev.Username.ToString());
13012 //title.Append("");
13015 if (!string.IsNullOrEmpty(ev.Target))
13017 //NotifyIcon1.BalloonTipText = ev.Target;
13022 //NotifyIcon1.BalloonTipText = " ";
13025 //NotifyIcon1.ShowBalloonTip(500);
13026 if (this._cfgCommon.IsUseNotifyGrowl)
13028 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13029 ev.Id.ToString(), title.ToString(), text);
13033 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13034 NotifyIcon1.BalloonTipTitle = title.ToString();
13035 NotifyIcon1.BalloonTipText = text;
13036 NotifyIcon1.ShowBalloonTip(500);
13041 string snd = this._cfgCommon.EventSoundFile;
13042 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13044 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13048 string dir = Application.StartupPath;
13049 if (Directory.Exists(Path.Combine(dir, "Sounds")))
13051 dir = Path.Combine(dir, "Sounds");
13053 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13065 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13067 MenuItemUserStream.Enabled = false;
13068 if (StopRefreshAllMenuItem.Checked)
13070 StopRefreshAllMenuItem.Checked = false;
13073 if (this.tw.UserStreamActive)
13075 tw.StopUserStream();
13079 tw.StartUserStream();
13083 private static string inputTrack = "";
13085 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13087 if (TrackToolStripMenuItem.Checked)
13089 using (InputTabName inputForm = new InputTabName())
13091 inputForm.TabName = inputTrack;
13092 inputForm.FormTitle = "Input track word";
13093 inputForm.FormDescription = "Track word";
13094 if (inputForm.ShowDialog() != DialogResult.OK)
13096 TrackToolStripMenuItem.Checked = false;
13099 inputTrack = inputForm.TabName.Trim();
13101 if (!inputTrack.Equals(tw.TrackWord))
13103 tw.TrackWord = inputTrack;
13104 this.ModifySettingCommon = true;
13105 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13106 tw.ReconnectUserStream();
13112 tw.ReconnectUserStream();
13114 this.ModifySettingCommon = true;
13117 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13119 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13120 this.ModifySettingCommon = true;
13121 tw.ReconnectUserStream();
13124 private void EventViewerMenuItem_Click(object sender, EventArgs e)
13126 if (evtDialog == null || evtDialog.IsDisposed)
13129 evtDialog = new EventViewerDialog();
13130 evtDialog.Owner = this;
13132 Point pos = evtDialog.Location;
13133 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13134 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13135 evtDialog.Location = pos;
13137 evtDialog.EventSource = tw.StoredEvent;
13138 if (!evtDialog.Visible)
13140 evtDialog.Show(this);
13144 evtDialog.Activate();
13146 this.TopMost = this._cfgCommon.AlwaysTop;
13150 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13152 MyCommon._endingFlag = true;
13156 Application.Restart();
13160 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13164 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13166 if (!string.IsNullOrEmpty(tw.Username))
13167 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13170 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13172 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13175 private async Task doTranslation(string str)
13177 if (string.IsNullOrEmpty(str))
13180 var bing = new Bing();
13183 var translatedText = await bing.TranslateAsync(str,
13185 langTo: this._cfgCommon.TranslateLanguage);
13187 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13189 catch (HttpRequestException e)
13191 this.StatusLabel.Text = "Err:" + e.Message;
13193 catch (OperationCanceledException)
13195 this.StatusLabel.Text = "Err:Timeout";
13199 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13201 if (!this.ExistCurrentPost)
13204 await this.doTranslation(this._curPost.TextFromApi);
13207 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13209 var text = this.PostBrowser.GetSelectedText();
13210 await this.doTranslation(text);
13213 private bool ExistCurrentPost
13217 if (_curPost == null) return false;
13218 if (_curPost.IsDeleted) return false;
13223 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13225 ShowUserTimeline();
13228 private string GetUserIdFromCurPostOrInput(string caption)
13230 var id = _curPost?.ScreenName ?? "";
13232 using (InputTabName inputName = new InputTabName())
13234 inputName.FormTitle = caption;
13235 inputName.FormDescription = Properties.Resources.FRMessage1;
13236 inputName.TabName = id;
13237 if (inputName.ShowDialog() == DialogResult.OK &&
13238 !string.IsNullOrEmpty(inputName.TabName.Trim()))
13240 id = inputName.TabName.Trim();
13250 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13252 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13253 if (!string.IsNullOrEmpty(id))
13255 AddNewTabForUserTimeline(id);
13259 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13261 string id = GetUserIdFromCurPostOrInput("Show Favstar");
13262 if (!string.IsNullOrEmpty(id))
13264 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13268 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13270 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13273 private void TimelineRefreshEnableChange(bool isEnable)
13277 tw.StartUserStream();
13281 tw.StopUserStream();
13283 TimerTimeline.Enabled = isEnable;
13286 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13288 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13291 private async Task OpenUserAppointUrl()
13293 if (this._cfgCommon.UserAppointUrl != null)
13295 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13297 if (_curPost != null)
13299 string xUrl = this._cfgCommon.UserAppointUrl;
13300 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13302 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13303 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13305 await this.OpenUriInBrowserAsync(xUrl);
13310 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13315 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13317 await this.OpenUserAppointUrl();
13320 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13322 string selText = SourceLinkLabel.Text;
13325 Clipboard.SetDataObject(selText, false, 5, 100);
13327 catch (Exception ex)
13329 MessageBox.Show(ex.Message);
13333 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13335 var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13338 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13340 catch (Exception ex)
13342 MessageBox.Show(ex.Message);
13346 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13348 if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13350 SourceCopyMenuItem.Enabled = false;
13351 SourceUrlCopyMenuItem.Enabled = false;
13355 SourceCopyMenuItem.Enabled = true;
13356 SourceUrlCopyMenuItem.Enabled = true;
13360 private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13362 if (Form.ActiveForm == null)
13364 this.BeginInvoke((Action) (() =>
13366 this.Visible = true;
13367 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13369 this.BringToFront();
13370 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13372 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13376 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13382 private void ReplaceAppName()
13384 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13385 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13388 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13390 this.SplitContainer3.Panel2Collapsed = false;
13393 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13395 await this.OpenThumbnailPicture(e.Thumbnail);
13398 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13400 await this.OpenUriInBrowserAsync(e.ImageUrl);
13403 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13405 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13407 await this.OpenUriInBrowserAsync(url);
13410 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13412 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13415 private void PostButton_KeyDown(object sender, KeyEventArgs e)
13417 if (e.KeyCode == Keys.Space)
13419 this.JumpUnreadMenuItem_Click(null, null);
13421 e.SuppressKeyPress = true;
13425 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13427 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13428 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13429 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13430 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13431 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13433 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13436 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13438 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13441 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13443 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13446 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13448 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13451 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13453 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13456 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13458 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13461 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13463 if (this._cfgCommon.IconSize == iconSize) return;
13465 var oldIconCol = _iconCol;
13467 this._cfgCommon.IconSize = iconSize;
13468 ApplyListViewIconSize(iconSize);
13470 if (_iconCol != oldIconCol)
13472 foreach (TabPage tp in ListTab.TabPages)
13474 ResetColumns((DetailsListView)tp.Tag);
13478 _curList?.Refresh();
13480 ModifySettingCommon = true;
13483 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13485 var state = this.LockListSortOrderToolStripMenuItem.Checked;
13486 if (this._cfgCommon.SortOrderLock == state) return;
13488 this._cfgCommon.SortOrderLock = state;
13490 ModifySettingCommon = true;