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;
44 using System.Runtime.InteropServices;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
60 public partial class TweenMain : OTBaseForm
63 private Size _mySize; //画面サイズ
64 private Point _myLoc; //画面位置
65 private int _mySpDis; //区切り位置
66 private int _mySpDis2; //発言欄区切り位置
67 private int _mySpDis3; //プレビュー区切り位置
68 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69 private bool _iconCol; //1列表示の時true(48サイズのとき)
72 private bool _initial; //true:起動時処理中
73 private bool _initialLayout = true;
74 private bool _ignoreConfigSave; //true:起動時処理中
75 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77 private Point _tabMouseDownPoint;
78 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
79 private readonly object _syncObject = new object(); //ロック用
81 private const string detailHtmlFormatHeaderMono =
82 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83 + "<style type=\"text/css\"><!-- "
84 + "body, p, pre {margin: 0;} "
85 + "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%);} "
86 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89 + ".quote-tweet.reply {border-color: #f33;} "
90 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
92 + "</head><body><pre>";
93 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94 private const string detailHtmlFormatHeaderColor =
95 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96 + "<style type=\"text/css\"><!-- "
97 + "body, p, pre {margin: 0;} "
98 + "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%);} "
99 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
105 + "</head><body><p>";
106 private const string detailHtmlFormatFooterColor = "</p></body></html>";
107 private string detailHtmlFormatHeader;
108 private string detailHtmlFormatFooter;
110 private bool _myStatusError = false;
111 private bool _myStatusOnline = false;
112 private bool soundfileListup = false;
113 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
116 private TwitterApi twitterApi = new TwitterApi();
120 private GrowlHelper gh = new GrowlHelper(ApplicationSettings.ApplicationName);
123 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
124 private OpenURL UrlDialog = new OpenURL();
125 public AtIdSupplement AtIdSupl; //@id補助
126 public AtIdSupplement HashSupl; //Hashtag補助
127 public HashtagManage HashMgr;
128 private EventViewerDialog evtDialog;
131 private Font _fntUnread; //未読用フォント
132 private Color _clUnread; //未読用文字色
133 private Font _fntReaded; //既読用フォント
134 private Color _clReaded; //既読用文字色
135 private Color _clFav; //Fav用文字色
136 private Color _clOWL; //片思い用文字色
137 private Color _clRetweet; //Retweet用文字色
138 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
139 private Font _fntDetail; //発言詳細部用フォント
140 private Color _clDetail; //発言詳細部用色
141 private Color _clDetailLink; //発言詳細部用リンク文字色
142 private Color _clDetailBackcolor; //発言詳細部用背景色
143 private Color _clSelf; //自分の発言用背景色
144 private Color _clAtSelf; //自分宛返信用背景色
145 private Color _clTarget; //選択発言者の他の発言用背景色
146 private Color _clAtTarget; //選択発言中の返信先用背景色
147 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
148 private Color _clAtTo; //選択発言の唯一@先
149 private Color _clListBackcolor; //リスト部通常発言背景色
150 private Color _clInputBackcolor; //入力欄背景色
151 private Color _clInputFont; //入力欄文字色
152 private Font _fntInputFont; //入力欄フォント
153 private ImageCache IconCache; //アイコン画像リスト
154 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
155 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
156 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
157 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
158 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
159 private Icon MainIcon; //Main.ico 画面左上のアイコン
160 private Icon ReplyIcon; //5g
161 private Icon ReplyIconBlink; //6g
163 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
165 private PostClass _anchorPost;
166 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
168 private List<StatusTextHistory> _history = new List<StatusTextHistory>(); //発言履歴
169 private int _hisIdx; //発言履歴カレントインデックス
171 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
172 private (long StatusId, string ScreenName)? inReplyTo = null; // リプライ先のステータスID・スクリーン名
175 private List<DateTimeUtc> _postTimestamps = new List<DateTimeUtc>();
176 private List<DateTimeUtc> _favTimestamps = new List<DateTimeUtc>();
179 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
180 private SolidBrush _brsBackColorMine;
181 private SolidBrush _brsBackColorAt;
182 private SolidBrush _brsBackColorYou;
183 private SolidBrush _brsBackColorAtYou;
184 private SolidBrush _brsBackColorAtFromTarget;
185 private SolidBrush _brsBackColorAtTo;
186 private SolidBrush _brsBackColorNone;
187 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
188 private StringFormat sfTab = new StringFormat();
190 //////////////////////////////////////////////////////////////////////////////////////////////////////////
191 private TabInformations _statuses;
194 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
197 /// キャッシュクリアのために null が代入されることがあるため、
198 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
199 /// 一旦ローカル変数に代入してから参照すること。
201 private ListViewItemCache _listItemCache = null;
203 internal class ListViewItemCache
205 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
206 public ListView TargetList { get; set; }
208 /// <summary>キャッシュする範囲の開始インデックス</summary>
209 public int StartIndex { get; set; }
211 /// <summary>キャッシュする範囲の終了インデックス</summary>
212 public int EndIndex { get; set; }
214 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
215 public ListViewItem[] ListItem { get; set; }
217 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
218 public PostClass[] Post { get; set; }
220 /// <summary>キャッシュされたアイテムの件数</summary>
222 => this.EndIndex - this.StartIndex + 1;
224 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
225 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
226 public bool Contains(int index)
227 => index >= this.StartIndex && index <= this.EndIndex;
229 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool IsSupersetOf(int rangeStart, int rangeEnd)
232 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
234 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
235 /// <returns>取得に成功すれば true、それ以外は false</returns>
236 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
238 if (this.Contains(index))
240 item = this.ListItem[index - this.StartIndex];
241 post = this.Post[index - this.StartIndex];
253 private bool _isColumnChanged = false;
255 private const int MAX_WORKER_THREADS = 20;
256 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
257 private CancellationTokenSource workerCts = new CancellationTokenSource();
258 private IProgress<string> workerProgress;
260 private int UnreadCounter = -1;
261 private int UnreadAtCounter = -1;
263 private string[] ColumnOrgText = new string[9];
264 private string[] ColumnText = new string[9];
266 private bool _DoFavRetweetFlags = false;
267 private bool osResumed = false;
269 //////////////////////////////////////////////////////////////////////////////////////////////////////////
270 private bool _colorize = false;
272 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
273 private ThrottlingTimer RefreshThrottlingTimer;
275 private string recommendedStatusFooter;
276 private bool urlMultibyteSplit = false;
277 private bool preventSmsCommand = true;
280 private struct urlUndo
282 public string Before;
286 private List<urlUndo> urlUndoBuffer = null;
288 private struct ReplyChain
290 public long OriginalId;
291 public long InReplyToId;
292 public TabModel OriginalTab;
294 public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
296 this.OriginalId = originalId;
297 this.InReplyToId = inReplyToId;
298 this.OriginalTab = originalTab;
302 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
303 private Stack<(TabModel, PostClass)> selectPostChains = new Stack<(TabModel, PostClass)>(); //ポスト選択履歴
305 public TabModel CurrentTab
306 => this._statuses.SelectedTab;
308 public string CurrentTabName
309 => this._statuses.SelectedTabName;
311 public TabPage CurrentTabPage
312 => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
314 public DetailsListView CurrentListView
315 => (DetailsListView)this.CurrentTabPage.Tag;
317 public PostClass CurrentPost
318 => this.CurrentTab.SelectedPost;
321 internal enum SEARCHTYPE
328 private class StatusTextHistory
330 public string status = "";
331 public (long StatusId, string ScreenName)? inReplyTo = null;
332 public string imageService = ""; //画像投稿サービス名
333 public IMediaItem[] mediaItems = null;
334 public StatusTextHistory()
337 public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
339 this.status = status;
340 this.inReplyTo = inReplyTo;
344 private void TweenMain_Activated(object sender, EventArgs e)
346 //画面がアクティブになったら、発言欄の背景色戻す
347 if (StatusText.Focused)
349 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
353 private bool disposed = false;
356 /// 使用中のリソースをすべてクリーンアップします。
358 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
359 protected override void Dispose(bool disposing)
361 base.Dispose(disposing);
368 this.components?.Dispose();
371 SearchDialog.Dispose();
374 NIconAtRed?.Dispose();
375 NIconAtSmoke?.Dispose();
376 foreach (var iconRefresh in this.NIconRefresh)
378 iconRefresh?.Dispose();
382 ReplyIcon?.Dispose();
383 ReplyIconBlink?.Dispose();
384 _listViewImageList.Dispose();
385 _brsHighLight.Dispose();
386 _brsBackColorMine?.Dispose();
387 _brsBackColorAt?.Dispose();
388 _brsBackColorYou?.Dispose();
389 _brsBackColorAtYou?.Dispose();
390 _brsBackColorAtFromTarget?.Dispose();
391 _brsBackColorAtTo?.Dispose();
392 _brsBackColorNone?.Dispose();
393 _brsDeactiveSelection?.Dispose();
397 this.workerCts.Cancel();
399 if (IconCache != null)
401 this.IconCache.CancelAsync();
402 this.IconCache.Dispose();
405 this.thumbnailTokenSource?.Dispose();
408 this.twitterApi.Dispose();
409 this._hookGlobalHotkey.Dispose();
412 // 終了時にRemoveHandlerしておかないとメモリリークする
413 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
414 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
415 Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
417 this.disposed = true;
420 private void LoadIcons()
422 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
423 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
426 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
429 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
432 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
435 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
437 // タスクトレイ: オフライン時アイコン
438 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
440 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
441 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
442 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
444 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
445 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
446 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
447 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
448 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
450 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
452 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
453 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
454 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
455 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
456 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
458 if (iconReply != null && iconReplyBlink != null)
460 this.ReplyIcon = iconReply;
461 this.ReplyIconBlink = iconReplyBlink;
465 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
466 this.ReplyIconBlink = this.NIconAt;
469 if (iconRefresh1 == null)
471 this.NIconRefresh = new[] {
472 Properties.Resources.Refresh, Properties.Resources.Refresh2,
473 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
476 else if (iconRefresh2 == null)
478 this.NIconRefresh = new[] { iconRefresh1 };
480 else if (iconRefresh3 == null)
482 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
484 else if (iconRefresh4 == null)
486 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
488 else // iconRefresh1 から iconRefresh4 まで全て揃っている
490 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
494 private Icon LoadIcon(string filePath)
496 if (!File.Exists(filePath))
501 return new Icon(filePath);
509 private void InitColumns(ListView list, bool startup)
511 this.InitColumnText();
513 ColumnHeader[] columns = null;
520 new ColumnHeader(), // アイコン
521 new ColumnHeader(), // 本文
524 columns[0].Text = this.ColumnText[0];
525 columns[1].Text = this.ColumnText[2];
529 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
531 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
532 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
533 columns[0].DisplayIndex = 0;
534 columns[1].DisplayIndex = 1;
539 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
541 columns[idx].Width = curListColumn.Width;
542 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
551 new ColumnHeader(), // アイコン
552 new ColumnHeader(), // ニックネーム
553 new ColumnHeader(), // 本文
554 new ColumnHeader(), // 日付
555 new ColumnHeader(), // ユーザID
556 new ColumnHeader(), // 未読
557 new ColumnHeader(), // マーク&プロテクト
558 new ColumnHeader(), // ソース
561 foreach (var i in Enumerable.Range(0, columns.Length))
562 columns[i].Text = this.ColumnText[i];
566 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
568 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
569 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
570 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
571 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
572 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
573 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
574 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
575 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
577 var displayIndex = new[] {
578 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
579 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
580 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
581 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
584 foreach (var i in Enumerable.Range(0, displayIndex.Length))
586 columns[i].DisplayIndex = displayIndex[i];
592 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
594 columns[idx].Width = curListColumn.Width;
595 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
601 list.Columns.AddRange(columns);
609 foreach (var column in columns)
615 private void InitColumnText()
618 ColumnText[1] = Properties.Resources.AddNewTabText2;
619 ColumnText[2] = Properties.Resources.AddNewTabText3;
620 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
621 ColumnText[4] = Properties.Resources.AddNewTabText5;
624 ColumnText[7] = "Source";
626 ColumnOrgText[0] = "";
627 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
628 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
629 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
630 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
631 ColumnOrgText[5] = "";
632 ColumnOrgText[6] = "";
633 ColumnOrgText[7] = "Source";
636 switch (_statuses.SortMode)
638 case ComparerMode.Nickname: //ニックネーム
641 case ComparerMode.Data: //本文
644 case ComparerMode.Id: //時刻=発言Id
647 case ComparerMode.Name: //名前
650 case ComparerMode.Source: //Source
657 if (_statuses.SortOrder == SortOrder.Descending)
659 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
660 ColumnText[2] = ColumnOrgText[2] + "▾";
664 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
665 ColumnText[2] = ColumnOrgText[2] + "▴";
670 if (_statuses.SortOrder == SortOrder.Descending)
672 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
673 ColumnText[c] = ColumnOrgText[c] + "▾";
677 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
678 ColumnText[c] = ColumnOrgText[c] + "▴";
683 private void InitializeTraceFrag()
686 TraceOutToolStripMenuItem.Checked = true;
687 MyCommon.TraceFlag = true;
689 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
691 TraceOutToolStripMenuItem.Checked = true;
692 MyCommon.TraceFlag = true;
696 private void TweenMain_Load(object sender, EventArgs e)
698 _ignoreConfigSave = true;
699 this.Visible = false;
701 if (MyApplication.StartupOptions.ContainsKey("d"))
702 MyCommon.TraceFlag = true;
704 InitializeTraceFrag();
706 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
708 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
710 Regex.CacheSize = 100;
713 _statuses = TabInformations.GetInstance();
717 this.Icon = MainIcon; //メインフォーム(TweenMain)
718 NotifyIcon1.Icon = NIconAt; //タスクトレイ
719 TabImage.Images.Add(TabIcon); //タブ見出し
721 //<<<<<<<<<設定関連>>>>>>>>>
725 // 現在の DPI と設定保存時の DPI との比を取得する
726 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
729 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
730 if (fontUIGlobal != null)
732 OTBaseForm.GlobalFont = fontUIGlobal;
733 this.Font = fontUIGlobal;
737 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
739 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
740 SettingManager.Common.TimelinePeriod = 15;
742 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
743 SettingManager.Common.ReplyPeriod = 15;
745 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
746 SettingManager.Common.DMPeriod = 15;
748 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
749 SettingManager.Common.PubSearchPeriod = 30;
751 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
752 SettingManager.Common.UserTimelinePeriod = 15;
754 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
755 SettingManager.Common.ListsPeriod = 15;
758 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
759 SettingManager.Common.CountApi = 60;
760 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
761 SettingManager.Common.CountApiReply = 40;
763 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
764 SettingManager.Common.MoreCountApi = 200;
765 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
766 SettingManager.Common.FirstCountApi = 100;
768 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
769 SettingManager.Common.FavoritesCountApi = 40;
770 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
771 SettingManager.Common.ListCountApi = 100;
772 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
773 SettingManager.Common.SearchCountApi = 100;
774 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
775 SettingManager.Common.UserTimelineCountApi = 20;
777 //廃止サービスが選択されていた場合ux.nuへ読み替え
778 if (SettingManager.Common.AutoShortUrlFirst < 0)
779 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
781 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
782 this.tw = new Twitter(this.twitterApi);
785 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
786 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
790 Networking.Initialize();
792 bool saveRequired = false;
793 bool firstRun = false;
795 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
796 if (string.IsNullOrEmpty(tw.Username))
801 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
802 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
803 string.IsNullOrEmpty(tw.Username))
805 Application.Exit(); //強制終了
811 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
812 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
813 Networking.SetWebProxy(SettingManager.Local.ProxyType,
814 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
815 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
816 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
818 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
819 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
820 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
821 tw.TrackWord = SettingManager.Common.TrackWord;
822 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
823 tw.AllAtReply = SettingManager.Common.AllAtReply;
824 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
825 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
826 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
827 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
828 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
830 // アクセストークンが有効であるか確認する
831 // ここが Twitter API への最初のアクセスになるようにすること
834 this.tw.VerifyCredentials();
836 catch (WebApiException ex)
838 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
839 ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
843 //プロキシ設定等の通信まわりの初期化が済んでから処理する
844 ThumbnailGenerator.InitializeGenerator();
846 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
847 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
848 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
850 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
853 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
856 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
857 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
858 HashMgr = new HashtagManage(HashSupl,
859 SettingManager.Common.HashTags.ToArray(),
860 SettingManager.Common.HashSelected,
861 SettingManager.Common.HashIsPermanent,
862 SettingManager.Common.HashIsHead,
863 SettingManager.Common.HashIsNotAddToAtReply);
864 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
867 this.IconCache = new ImageCache();
868 this.tweetDetailsView.IconCache = this.IconCache;
871 _fntUnread = SettingManager.Local.FontUnread;
872 _clUnread = SettingManager.Local.ColorUnread;
873 _fntReaded = SettingManager.Local.FontRead;
874 _clReaded = SettingManager.Local.ColorRead;
875 _clFav = SettingManager.Local.ColorFav;
876 _clOWL = SettingManager.Local.ColorOWL;
877 _clRetweet = SettingManager.Local.ColorRetweet;
878 _fntDetail = SettingManager.Local.FontDetail;
879 _clDetail = SettingManager.Local.ColorDetail;
880 _clDetailLink = SettingManager.Local.ColorDetailLink;
881 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
882 _clSelf = SettingManager.Local.ColorSelf;
883 _clAtSelf = SettingManager.Local.ColorAtSelf;
884 _clTarget = SettingManager.Local.ColorTarget;
885 _clAtTarget = SettingManager.Local.ColorAtTarget;
886 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
887 _clAtTo = SettingManager.Local.ColorAtTo;
888 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
889 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
890 _clInputFont = SettingManager.Local.ColorInputFont;
891 _fntInputFont = SettingManager.Local.FontInputFont;
893 _brsBackColorMine = new SolidBrush(_clSelf);
894 _brsBackColorAt = new SolidBrush(_clAtSelf);
895 _brsBackColorYou = new SolidBrush(_clTarget);
896 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
897 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
898 _brsBackColorAtTo = new SolidBrush(_clAtTo);
899 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
900 _brsBackColorNone = new SolidBrush(_clListBackcolor);
902 // StringFormatオブジェクトへの事前設定
903 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
904 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
905 //sf.FormatFlags = StringFormatFlags.LineLimit; //
906 sfTab.Alignment = StringAlignment.Center;
907 sfTab.LineAlignment = StringAlignment.Center;
909 InitDetailHtmlFormat();
911 //Regex statregex = new Regex("^0*");
912 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
914 _history.Add(new StatusTextHistory());
916 this.inReplyTo = null;
919 SearchDialog.Owner = this;
920 UrlDialog.Owner = this;
923 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
924 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
926 //新着取得時のリストスクロールをするか。trueならスクロールしない
927 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
928 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
930 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
931 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
934 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
935 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
936 _myLoc = SettingManager.Local.FormLocation;
938 if (this.WindowState != FormWindowState.Minimized)
940 Rectangle tbarRect = new Rectangle(this._myLoc, 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._myLoc = new Point(0, 0);
956 this.DesktopLocation = this._myLoc;
958 this.TopMost = SettingManager.Common.AlwaysTop;
959 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
960 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
961 if (SettingManager.Local.PreviewDistance == -1)
963 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965 SettingManager.Local.PreviewDistance = _mySpDis3;
969 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
971 //this.Tween_ClientSizeChanged(this, null);
972 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
973 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
975 StatusText.Font = _fntInputFont;
976 StatusText.ForeColor = _clInputFont;
978 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
979 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
980 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
982 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
983 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
985 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
986 if (SettingManager.Common.UnreadManage == false)
988 ReadedStripMenuItem.Enabled = false;
989 UnreadStripMenuItem.Enabled = false;
992 //リンク先URL表示部の初期化(画面左下)
993 StatusLabelUrl.Text = "";
995 StatusLabel.Text = "";
996 StatusLabel.AutoToolTip = false;
997 StatusLabel.ToolTipText = "";
999 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1001 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1002 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1003 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1004 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1006 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1007 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1008 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1009 this.SplitContainer2.Panel2.AccessibleName = "";
1011 ////////////////////////////////////////////////////////////////////////////////
1012 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1013 var mode = ComparerMode.Id;
1014 switch (SettingManager.Common.SortColumn)
1016 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1020 mode = ComparerMode.Id; //Idソートに読み替え
1023 mode = ComparerMode.Nickname;
1026 mode = ComparerMode.Data;
1029 mode = ComparerMode.Id;
1032 mode = ComparerMode.Name;
1035 mode = ComparerMode.Source;
1038 _statuses.SetSortMode(mode, sortOrder);
1039 ////////////////////////////////////////////////////////////////////////////////
1041 ApplyListViewIconSize(SettingManager.Common.IconSize);
1043 //<<<<<<<<タブ関連>>>>>>>
1047 //デフォルトタブの存在チェック、ない場合には追加
1048 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1049 this._statuses.AddTab(new HomeTabModel());
1051 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1052 this._statuses.AddTab(new MentionsTabModel());
1054 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1055 this._statuses.AddTab(new DirectMessagesTabModel());
1057 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1058 this._statuses.AddTab(new FavoritesTabModel());
1060 if (this._statuses.MuteTab == null)
1061 this._statuses.AddTab(new MuteTabModel());
1063 foreach (var tab in _statuses.Tabs)
1065 if (!AddNewTab(tab, startup: true))
1066 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1069 this._statuses.SelectTab(this.ListTab.SelectedTab.Text);
1071 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
1072 Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
1074 if (SettingManager.Common.TabIconDisp)
1076 ListTab.DrawMode = TabDrawMode.Normal;
1080 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1081 ListTab.DrawItem += ListTab_DrawItem;
1082 ListTab.ImageList = null;
1085 if (SettingManager.Common.HotkeyEnabled)
1088 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1089 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1090 modKey |= HookGlobalHotkey.ModKeys.Alt;
1091 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1092 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1093 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1094 modKey |= HookGlobalHotkey.ModKeys.Shift;
1095 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1096 modKey |= HookGlobalHotkey.ModKeys.Win;
1098 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1101 if (SettingManager.Common.IsUseNotifyGrowl)
1104 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1106 SetMainWindowTitle();
1107 SetNotifyIconText();
1109 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1111 this.Visible = true;
1116 var streamingRefreshInterval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1117 this.RefreshThrottlingTimer = new ThrottlingTimer(streamingRefreshInterval,
1118 () => this.InvokeAsync(() => this.RefreshTimeline()));
1120 TimerTimeline.AutoReset = true;
1121 TimerTimeline.SynchronizingObject = this;
1123 TimerTimeline.Interval = 1000;
1124 TimerTimeline.Enabled = true;
1126 TimerRefreshIcon.Interval = 200;
1127 TimerRefreshIcon.Enabled = true;
1129 _ignoreConfigSave = false;
1130 this.TweenMain_Resize(null, null);
1131 if (saveRequired) SaveConfigsAll(false);
1133 foreach (var ua in SettingManager.Common.UserAccounts)
1135 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1137 ua.UserId = tw.UserId;
1144 // 初回起動時だけ右下のメニューを目立たせる
1145 HashStripSplitButton.ShowDropDown();
1149 private void InitDetailHtmlFormat()
1151 if (SettingManager.Common.IsMonospace)
1153 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1154 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1158 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1159 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1162 detailHtmlFormatHeader = detailHtmlFormatHeader
1163 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1164 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1165 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1166 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1167 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1168 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1171 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1176 txt = this._statuses.Tabs[e.Index].TabName;
1183 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1184 if (e.State == DrawItemState.Selected)
1186 e.DrawFocusRectangle();
1191 if (_statuses.Tabs[txt].UnreadCount > 0)
1194 fore = System.Drawing.SystemBrushes.ControlText;
1198 fore = System.Drawing.SystemBrushes.ControlText;
1200 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1203 private void LoadConfig()
1205 SettingManager.Local = SettingManager.Local;
1207 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1208 if (SettingManager.Local.ScaleDimension.IsEmpty)
1209 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1211 var tabSettings = SettingManager.Tabs;
1212 foreach (var tabSetting in tabSettings.Tabs)
1215 switch (tabSetting.TabType)
1217 case MyCommon.TabUsageType.Home:
1218 tab = new HomeTabModel(tabSetting.TabName);
1220 case MyCommon.TabUsageType.Mentions:
1221 tab = new MentionsTabModel(tabSetting.TabName);
1223 case MyCommon.TabUsageType.DirectMessage:
1224 tab = new DirectMessagesTabModel(tabSetting.TabName);
1226 case MyCommon.TabUsageType.Favorites:
1227 tab = new FavoritesTabModel(tabSetting.TabName);
1229 case MyCommon.TabUsageType.UserDefined:
1230 tab = new FilterTabModel(tabSetting.TabName);
1232 case MyCommon.TabUsageType.UserTimeline:
1233 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1235 case MyCommon.TabUsageType.PublicSearch:
1236 tab = new PublicSearchTabModel(tabSetting.TabName)
1238 SearchWords = tabSetting.SearchWords,
1239 SearchLang = tabSetting.SearchLang,
1242 case MyCommon.TabUsageType.Lists:
1243 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1245 case MyCommon.TabUsageType.Mute:
1246 tab = new MuteTabModel(tabSetting.TabName);
1252 tab.UnreadManage = tabSetting.UnreadManage;
1253 tab.Protected = tabSetting.Protected;
1254 tab.Notify = tabSetting.Notify;
1255 tab.SoundFile = tabSetting.SoundFile;
1257 if (tab.IsDistributableTabType)
1259 var filterTab = (FilterTabModel)tab;
1260 filterTab.FilterArray = tabSetting.FilterArray;
1261 filterTab.FilterModified = false;
1264 if (this._statuses.ContainsTab(tab.TabName))
1265 tab.TabName = this._statuses.MakeTabName("MyTab");
1267 this._statuses.AddTab(tab);
1269 if (_statuses.Tabs.Count == 0)
1271 _statuses.AddTab(new HomeTabModel());
1272 _statuses.AddTab(new MentionsTabModel());
1273 _statuses.AddTab(new DirectMessagesTabModel());
1274 _statuses.AddTab(new FavoritesTabModel());
1278 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1280 if (!TimerTimeline.Enabled) return;
1284 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1285 var newTimer = new ThrottlingTimer(interval, () => this.InvokeAsync(() => this.RefreshTimeline()));
1286 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1293 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1295 private static int homeCounter = 0;
1296 private static int mentionCounter = 0;
1297 private static int dmCounter = 0;
1298 private static int pubSearchCounter = 0;
1299 private static int userTimelineCounter = 0;
1300 private static int listsCounter = 0;
1301 private static int ResumeWait = 0;
1302 private static int refreshFollowers = 0;
1304 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1306 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1307 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1308 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1309 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1310 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1311 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1312 Interlocked.Increment(ref refreshFollowers);
1314 var refreshTasks = new List<Task>();
1317 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1319 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1320 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1321 refreshTasks.Add(this.RefreshTabAsync<HomeTabModel>());
1322 ResetTimers.Timeline = false;
1324 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1326 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1327 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1328 refreshTasks.Add(this.RefreshTabAsync<MentionsTabModel>());
1329 ResetTimers.Reply = false;
1331 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1333 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1334 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1335 refreshTasks.Add(this.RefreshTabAsync<DirectMessagesTabModel>());
1336 ResetTimers.DirectMessage = false;
1338 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1340 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1341 if (!ResetTimers.PublicSearch)
1342 refreshTasks.Add(this.RefreshTabAsync<PublicSearchTabModel>());
1343 ResetTimers.PublicSearch = false;
1345 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1347 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1348 if (!ResetTimers.UserTimeline)
1349 refreshTasks.Add(this.RefreshTabAsync<UserTimelineTabModel>());
1350 ResetTimers.UserTimeline = false;
1352 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1354 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1355 if (!ResetTimers.Lists)
1356 refreshTasks.Add(this.RefreshTabAsync<ListTimelineTabModel>());
1357 ResetTimers.Lists = false;
1359 if (refreshFollowers > 6 * 3600)
1361 Interlocked.Exchange(ref refreshFollowers, 0);
1362 refreshTasks.AddRange(new[]
1364 this.doGetFollowersMenu(),
1365 this.RefreshNoRetweetIdsAsync(),
1366 this.RefreshTwitterConfigurationAsync(),
1371 Interlocked.Increment(ref ResumeWait);
1372 if (ResumeWait > 30)
1375 Interlocked.Exchange(ref ResumeWait, 0);
1376 refreshTasks.AddRange(new[]
1378 this.RefreshTabAsync<HomeTabModel>(),
1379 this.RefreshTabAsync<MentionsTabModel>(),
1380 this.RefreshTabAsync<DirectMessagesTabModel>(),
1381 this.RefreshTabAsync<PublicSearchTabModel>(),
1382 this.RefreshTabAsync<UserTimelineTabModel>(),
1383 this.RefreshTabAsync<ListTimelineTabModel>(),
1384 this.doGetFollowersMenu(),
1385 this.RefreshTwitterConfigurationAsync(),
1390 await Task.WhenAll(refreshTasks);
1393 private void RefreshTimeline()
1395 var curTabModel = this.CurrentTab;
1396 var curListView = this.CurrentListView;
1398 // 現在表示中のタブのスクロール位置を退避
1399 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1401 // 各タブのリスト上の選択位置などを退避
1402 var listSelections = this.SaveListViewSelection();
1406 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1407 out var newMentionOrDm, out var isDelete);
1409 if (MyCommon._endingFlag) return;
1412 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1414 var tabPage = this.ListTab.TabPages[index];
1415 var listView = (DetailsListView)tabPage.Tag;
1417 if (listView.VirtualListSize != tab.AllCount || isDelete)
1419 using (ControlTransaction.Update(listView))
1421 if (listView == curListView)
1422 this.PurgeListViewItemCache();
1427 listView.VirtualListSize = tab.AllCount;
1429 catch (NullReferenceException ex)
1431 // WinForms 内部で ListView.set_TopItem が発生させている例外
1432 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1433 MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1437 this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1444 if (SettingManager.Common.TabIconDisp)
1446 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1448 var tabPage = this.ListTab.TabPages[index];
1449 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1450 tabPage.ImageIndex = 0; // 未読アイコン
1455 this.ListTab.Refresh();
1460 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1463 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1465 SetMainWindowTitle();
1466 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1468 HashSupl.AddRangeItem(tw.GetHashList());
1472 internal struct ListViewScroll
1474 public ScrollLockMode ScrollLockMode { get; set; }
1475 public long? TopItemStatusId { get; set; }
1478 internal enum ScrollLockMode
1480 /// <summary>固定しない</summary>
1483 /// <summary>最上部に固定する</summary>
1486 /// <summary>最下部に固定する</summary>
1489 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1494 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1496 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1498 var listScroll = new ListViewScroll
1500 ScrollLockMode = this.GetScrollLockMode(listView),
1503 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1505 var topItemIndex = listView.TopItem?.Index ?? -1;
1506 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1507 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1513 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1515 if (this._statuses.SortMode == ComparerMode.Id)
1517 if (this._statuses.SortOrder == SortOrder.Ascending)
1520 if (this.ListLockMenuItem.Checked)
1521 return ScrollLockMode.None;
1523 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1526 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1527 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1528 return ScrollLockMode.FixedToBottom;
1530 return ScrollLockMode.None;
1535 if (this.ListLockMenuItem.Checked)
1536 return ScrollLockMode.FixedToItem;
1538 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1539 var topItem = listView.TopItem;
1540 if (topItem == null || topItem.Index == 0)
1541 return ScrollLockMode.FixedToTop;
1543 return ScrollLockMode.FixedToItem;
1548 return ScrollLockMode.FixedToItem;
1552 internal struct ListViewSelection
1554 public long[] SelectedStatusIds { get; set; }
1555 public long? SelectionMarkStatusId { get; set; }
1556 public long? FocusedStatusId { get; set; }
1560 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1562 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1564 var listsDict = new Dictionary<string, ListViewSelection>();
1566 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1568 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1569 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1576 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1578 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1580 if (listView.VirtualListSize == 0)
1582 return new ListViewSelection
1584 SelectedStatusIds = Array.Empty<long>(),
1585 SelectionMarkStatusId = null,
1586 FocusedStatusId = null,
1590 return new ListViewSelection
1592 SelectedStatusIds = tab.SelectedStatusIds,
1593 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1594 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1598 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1600 var index = listView.FocusedItem?.Index ?? -1;
1602 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1605 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1607 var index = listView.SelectionMark;
1609 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1613 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1615 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1617 if (listView.VirtualListSize == 0)
1620 switch (listScroll.ScrollLockMode)
1622 case ScrollLockMode.FixedToTop:
1623 listView.EnsureVisible(0);
1625 case ScrollLockMode.FixedToBottom:
1626 listView.EnsureVisible(listView.VirtualListSize - 1);
1628 case ScrollLockMode.FixedToItem:
1629 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1632 var topItem = listView.Items[topIndex];
1635 listView.TopItem = topItem;
1637 catch (NullReferenceException)
1639 listView.EnsureVisible(listView.VirtualListSize - 1);
1640 listView.EnsureVisible(topIndex);
1644 case ScrollLockMode.None:
1651 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1653 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1655 // status_id から ListView 上のインデックスに変換
1656 int[] selectedIndices = null;
1657 if (listSelection.SelectedStatusIds != null)
1658 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1660 var focusedIndex = -1;
1661 if (listSelection.FocusedStatusId != null)
1662 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1664 var selectionMarkIndex = -1;
1665 if (listSelection.SelectionMarkStatusId != null)
1666 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1668 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1671 private bool BalloonRequired()
1673 var ev = new Twitter.FormattedEvent
1675 Eventtype = MyCommon.EVENTTYPE.None,
1678 return BalloonRequired(ev);
1681 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1683 if (type == MyCommon.EVENTTYPE.None)
1686 if (!SettingManager.Common.EventNotifyEnabled)
1689 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1692 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1697 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1700 private bool BalloonRequired(Twitter.FormattedEvent ev)
1705 if (NativeMethods.IsScreenSaverRunning())
1709 if (!this.NewPostPopMenuItem.Checked)
1711 // 「新着通知が無効でもイベントを通知する」にも該当しない
1712 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1716 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1717 if (SettingManager.Common.LimitBalloon)
1719 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1723 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1726 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1728 if (SettingManager.Common.ReadOwnPost)
1730 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1735 if (BalloonRequired())
1737 if (notifyPosts != null && notifyPosts.Length > 0)
1739 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1740 if (SettingManager.Common.IsUseNotifyGrowl)
1742 StringBuilder sb = new StringBuilder();
1746 foreach (PostClass post in notifyPosts)
1748 if (!(notifyPosts.Length > 3))
1754 if (post.IsReply && !post.IsExcludeReply) reply = true;
1755 if (post.IsDm) dm = true;
1756 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1757 switch (SettingManager.Common.NameBalloon)
1759 case MyCommon.NameBalloonEnum.UserID:
1760 sb.Append(post.ScreenName).Append(" : ");
1762 case MyCommon.NameBalloonEnum.NickName:
1763 sb.Append(post.Nickname).Append(" : ");
1766 sb.Append(post.TextFromApi);
1767 if (notifyPosts.Length > 3)
1769 if (notifyPosts.Last() != post) continue;
1772 StringBuilder title = new StringBuilder();
1773 GrowlHelper.NotifyType nt;
1774 if (SettingManager.Common.DispUsername)
1776 title.Append(tw.Username);
1777 title.Append(" - ");
1785 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1786 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1787 title.Append(ApplicationSettings.ApplicationName);
1788 title.Append(" [DM] ");
1789 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1790 nt = GrowlHelper.NotifyType.DirectMessage;
1794 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1795 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1796 title.Append(ApplicationSettings.ApplicationName);
1797 title.Append(" [Reply!] ");
1798 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1799 nt = GrowlHelper.NotifyType.Reply;
1803 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1804 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1805 title.Append(ApplicationSettings.ApplicationName);
1807 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1808 nt = GrowlHelper.NotifyType.Notify;
1810 string bText = sb.ToString();
1811 if (string.IsNullOrEmpty(bText)) return;
1813 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1814 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1819 StringBuilder sb = new StringBuilder();
1822 foreach (PostClass post in notifyPosts)
1824 if (post.IsReply && !post.IsExcludeReply) reply = true;
1825 if (post.IsDm) dm = true;
1826 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1827 switch (SettingManager.Common.NameBalloon)
1829 case MyCommon.NameBalloonEnum.UserID:
1830 sb.Append(post.ScreenName).Append(" : ");
1832 case MyCommon.NameBalloonEnum.NickName:
1833 sb.Append(post.Nickname).Append(" : ");
1836 sb.Append(post.TextFromApi);
1839 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1840 StringBuilder title = new StringBuilder();
1842 if (SettingManager.Common.DispUsername)
1844 title.Append(tw.Username);
1845 title.Append(" - ");
1853 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1854 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1855 ntIcon = ToolTipIcon.Warning;
1856 title.Append(ApplicationSettings.ApplicationName);
1857 title.Append(" [DM] ");
1858 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1862 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1863 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1864 ntIcon = ToolTipIcon.Warning;
1865 title.Append(ApplicationSettings.ApplicationName);
1866 title.Append(" [Reply!] ");
1867 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1871 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1872 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1873 ntIcon = ToolTipIcon.Info;
1874 title.Append(ApplicationSettings.ApplicationName);
1876 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1878 string bText = sb.ToString();
1879 if (string.IsNullOrEmpty(bText)) return;
1880 //NotifyIcon1.BalloonTipText = sb.ToString();
1881 //NotifyIcon1.ShowBalloonTip(500);
1882 NotifyIcon1.BalloonTipTitle = title.ToString();
1883 NotifyIcon1.BalloonTipText = bText;
1884 NotifyIcon1.BalloonTipIcon = ntIcon;
1885 NotifyIcon1.ShowBalloonTip(500);
1891 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1895 string dir = Application.StartupPath;
1896 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1898 dir = Path.Combine(dir, "Sounds");
1900 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1910 //mentions新着時に画面ブリンク
1911 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1913 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1917 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1919 var listView = this.CurrentListView;
1920 if (listView != sender)
1923 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1924 this.CurrentTab.SelectPosts(indices);
1926 if (listView.SelectedIndices.Count != 1)
1929 var index = listView.SelectedIndices[0];
1930 if (index > listView.VirtualListSize - 1) return;
1932 this.PushSelectPostChain();
1934 var post = this.CurrentPost;
1935 this._statuses.SetReadAllTab(post.StatusId, read: true);
1937 ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1943 private void ChangeCacheStyleRead(bool Read, int Index)
1945 var tabInfo = this.CurrentTab;
1946 //Read:true=既読 false=未読
1947 //未読管理していなかったら既読として扱う
1948 if (!tabInfo.UnreadManage ||
1949 !SettingManager.Common.UnreadManage) Read = true;
1951 var listCache = this._listItemCache;
1952 if (listCache == null)
1955 // キャッシュに含まれていないアイテムは対象外
1956 if (!listCache.TryGetValue(Index, out var itm, out var post))
1959 ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
1962 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1969 Item.SubItems[5].Text = "";
1974 Item.SubItems[5].Text = "★";
1980 else if (Post.RetweetedId != null)
1982 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1984 else if (Read || !SettingManager.Common.UseUnreadStyle)
1989 if (DList == null || Item.Index == -1)
1991 Item.ForeColor = cl;
1992 if (SettingManager.Common.UseUnreadStyle)
1998 if (SettingManager.Common.UseUnreadStyle)
1999 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2001 DList.ChangeItemForeColor(Item.Index, cl);
2002 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2006 private void ColorizeList()
2008 //Index:更新対象のListviewItem.Index。Colorを返す。
2009 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2012 _post = _anchorPost;
2014 _post = this.CurrentPost;
2016 if (_post == null) return;
2018 var listCache = this._listItemCache;
2019 if (listCache == null)
2022 var index = listCache.StartIndex;
2023 var listView = (DetailsListView)listCache.TargetList;
2024 foreach (var cachedPost in listCache.Post)
2026 var backColor = this.JudgeColor(_post, cachedPost);
2027 listView.ChangeItemBackColor(index++, backColor);
2031 private void ColorizeList(ListViewItem Item, int Index)
2033 //Index:更新対象のListviewItem.Index。Colorを返す。
2034 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2037 _post = _anchorPost;
2039 _post = this.CurrentPost;
2041 PostClass tPost = GetCurTabPost(Index);
2043 if (_post == null) return;
2045 if (Item.Index == -1)
2046 Item.BackColor = JudgeColor(_post, tPost);
2048 this.CurrentListView.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2051 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2054 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2057 else if (TargetPost.IsMe)
2060 else if (TargetPost.IsReply)
2063 else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2065 cl = _clAtFromTarget;
2066 else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2069 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2074 cl = _clListBackcolor;
2079 private void StatusTextHistoryBack()
2081 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2082 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2085 if (this._hisIdx < 0)
2088 var historyItem = this._history[this._hisIdx];
2089 this.inReplyTo = historyItem.inReplyTo;
2090 this.StatusText.Text = historyItem.status;
2091 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2094 private void StatusTextHistoryForward()
2096 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2097 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2100 if (this._hisIdx > this._history.Count - 1)
2101 this._hisIdx = this._history.Count - 1;
2103 var historyItem = this._history[this._hisIdx];
2104 this.inReplyTo = historyItem.inReplyTo;
2105 this.StatusText.Text = historyItem.status;
2106 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2109 private async void PostButton_Click(object sender, EventArgs e)
2111 if (StatusText.Text.Trim().Length == 0)
2113 if (!ImageSelector.Enabled)
2115 await this.DoRefresh();
2120 var currentPost = this.CurrentPost;
2121 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2123 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2125 MessageBoxButtons.YesNoCancel,
2126 MessageBoxIcon.Question);
2129 case DialogResult.Yes:
2130 StatusText.Text = "";
2131 await this.doReTweetOfficial(false);
2133 case DialogResult.Cancel:
2138 if (TextContainsOnlyMentions(this.StatusText.Text))
2140 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2141 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2143 if (ret != DialogResult.OK)
2147 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2149 if (SettingManager.Common.Nicoms)
2151 StatusText.SelectionStart = StatusText.Text.Length;
2152 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2154 //if (SettingDialog.UrlConvertAuto)
2156 // StatusText.SelectionStart = StatusText.Text.Length;
2157 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2159 //else if (SettingDialog.Nicoms)
2161 // StatusText.SelectionStart = StatusText.Text.Length;
2162 // UrlConvert(UrlConverter.Nicoms);
2164 StatusText.SelectionStart = StatusText.Text.Length;
2165 CheckReplyTo(StatusText.Text);
2167 var status = new PostStatusParams();
2169 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2170 if (this.GetRestStatusCount(statusTextCompat) >= 0)
2172 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2173 // 収まる場合はこれらのオプションを使用せずに投稿する
2174 status.Text = statusTextCompat;
2175 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2179 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2180 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2182 status.AttachmentUrl = attachmentUrl;
2184 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2186 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2187 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2189 status.AutoPopulateReplyMetadata = true;
2191 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2192 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2197 if (this.GetRestStatusCount(status.Text) < 0)
2199 // 文字数制限を超えているが強制的に投稿するか
2200 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2201 if (ret != DialogResult.OK)
2205 IMediaUploadService uploadService = null;
2206 IMediaItem[] uploadItems = null;
2207 if (ImageSelector.Visible)
2210 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2213 uploadService = this.ImageSelector.GetService(serviceName);
2216 this.inReplyTo = null;
2217 StatusText.Text = "";
2218 _history.Add(new StatusTextHistory());
2219 _hisIdx = _history.Count - 1;
2220 if (!SettingManager.Common.FocusLockToStatusText)
2221 this.CurrentListView.Focus();
2222 urlUndoBuffer = null;
2223 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2226 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2228 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2229 await this.OpenUriInBrowserAsync(tmp);
2232 await this.PostMessageAsync(status, uploadService, uploadItems);
2235 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2237 MyCommon._endingFlag = true;
2241 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2243 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2245 //_endingFlag=false:フォームの×ボタン
2247 this.Visible = false;
2251 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2252 _ignoreConfigSave = true;
2253 MyCommon._endingFlag = true;
2254 TimerTimeline.Enabled = false;
2255 TimerRefreshIcon.Enabled = false;
2259 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2261 this.Visible = true;
2262 if (this.WindowState == FormWindowState.Minimized)
2264 this.WindowState = FormWindowState.Normal;
2267 this.BringToFront();
2270 private static int errorCount = 0;
2272 private static bool CheckAccountValid()
2274 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2280 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2289 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2290 private Task RefreshTabAsync<T>() where T : TabModel
2291 => this.RefreshTabAsync<T>(backward: false);
2293 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2294 private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2297 from tab in this._statuses.GetTabsByType<T>()
2298 select this.RefreshTabAsync(tab, backward);
2300 return Task.WhenAll(loadTasks);
2303 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2304 private Task RefreshTabAsync(TabModel tab)
2305 => this.RefreshTabAsync(tab, backward: false);
2307 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2308 private async Task RefreshTabAsync(TabModel tab, bool backward)
2310 await this.workerSemaphore.WaitAsync();
2314 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2315 this.RefreshTimeline();
2317 catch (WebApiException ex)
2319 this._myStatusError = true;
2324 case HomeTabModel _:
2325 tabType = "GetTimeline";
2327 case MentionsTabModel _:
2328 tabType = "GetTimeline";
2330 case DirectMessagesTabModel _:
2331 tabType = "GetDirectMessage";
2333 case FavoritesTabModel _:
2334 tabType = "GetFavorites";
2336 case PublicSearchTabModel _:
2337 tabType = "GetSearch";
2339 case UserTimelineTabModel _:
2340 tabType = "GetUserTimeline";
2342 case ListTimelineTabModel _:
2343 tabType = "GetListStatus";
2345 case RelatedPostsTabModel _:
2346 tabType = "GetRelatedTweets";
2349 tabType = tab.GetType().Name.Replace("Model", "");
2353 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2357 this.workerSemaphore.Release();
2361 private async Task FavAddAsync(long statusId, TabModel tab)
2363 await this.workerSemaphore.WaitAsync();
2367 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2369 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2371 catch (WebApiException ex)
2373 this._myStatusError = true;
2374 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2378 this.workerSemaphore.Release();
2382 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2384 if (ct.IsCancellationRequested)
2387 if (!CheckAccountValid())
2388 throw new WebApiException("Auth error. Check your account");
2390 if (!tab.Posts.TryGetValue(statusId, out var post))
2396 await Task.Run(async () =>
2398 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2404 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2406 .ConfigureAwait(false);
2408 catch (TwitterApiException ex)
2409 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2411 // エラーコード 139 のみの場合は成功と見なす
2414 if (SettingManager.Common.RestrictFavCheck)
2416 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2417 .ConfigureAwait(false);
2419 if (status.Favorited != true)
2420 throw new WebApiException("NG(Restricted?)");
2423 this._favTimestamps.Add(DateTimeUtc.Now);
2426 if (this._statuses.ContainsKey(statusId))
2428 var postTl = this._statuses[statusId];
2429 postTl.IsFav = true;
2431 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2432 favTab.AddPostQueue(postTl);
2435 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2436 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2438 if (tb.Contains(statusId))
2439 tb.Posts[statusId].IsFav = true;
2442 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2444 catch (WebApiException)
2446 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2451 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2452 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2454 if (this._favTimestamps[i] < oneHour)
2455 this._favTimestamps.RemoveAt(i);
2458 this._statuses.DistributePosts();
2461 if (ct.IsCancellationRequested)
2464 this.RefreshTimeline();
2466 if (this.CurrentTabName == tab.TabName)
2468 using (ControlTransaction.Update(this.CurrentListView))
2470 var idx = tab.IndexOf(statusId);
2472 this.ChangeCacheStyleRead(post.IsRead, idx);
2475 var currentPost = this.CurrentPost;
2476 if (currentPost != null && statusId == currentPost.StatusId)
2477 await this.DispSelectedPost(true); // 選択アイテム再表示
2481 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2483 await this.workerSemaphore.WaitAsync();
2487 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2489 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2491 catch (WebApiException ex)
2493 this._myStatusError = true;
2494 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2498 this.workerSemaphore.Release();
2502 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2504 if (ct.IsCancellationRequested)
2507 if (!CheckAccountValid())
2508 throw new WebApiException("Auth error. Check your account");
2510 var successIds = new List<long>();
2512 await Task.Run(async () =>
2516 var failedCount = 0;
2517 foreach (var statusId in statusIds)
2521 var post = tab.Posts[statusId];
2523 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2530 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2532 .ConfigureAwait(false);
2534 catch (WebApiException)
2540 successIds.Add(statusId);
2541 post.IsFav = false; // リスト再描画必要
2543 if (this._statuses.ContainsKey(statusId))
2545 this._statuses[statusId].IsFav = false;
2548 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2549 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2551 if (tb.Contains(statusId))
2552 tb.Posts[statusId].IsFav = false;
2557 if (ct.IsCancellationRequested)
2560 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2561 foreach (var statusId in successIds)
2563 // ツイートが削除された訳ではないので IsDeleted はセットしない
2564 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2567 this.RefreshTimeline();
2569 if (this.CurrentTabName == tab.TabName)
2571 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2577 using (ControlTransaction.Update(this.CurrentListView))
2579 foreach (var statusId in successIds)
2581 var idx = tab.IndexOf(statusId);
2585 var post = tab.Posts[statusId];
2586 this.ChangeCacheStyleRead(post.IsRead, idx);
2590 var currentPost = this.CurrentPost;
2591 if (currentPost != null && successIds.Contains(currentPost.StatusId))
2592 await this.DispSelectedPost(true); // 選択アイテム再表示
2597 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService uploadService, IMediaItem[] uploadItems)
2599 await this.workerSemaphore.WaitAsync();
2603 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2605 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2607 catch (WebApiException ex)
2609 this._myStatusError = true;
2610 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2614 this.workerSemaphore.Release();
2618 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2619 IMediaUploadService uploadService, IMediaItem[] uploadItems)
2621 if (ct.IsCancellationRequested)
2624 if (!CheckAccountValid())
2625 throw new WebApiException("Auth error. Check your account");
2627 p.Report("Posting...");
2629 PostClass post = null;
2634 await Task.Run(async () =>
2636 var postParamsWithMedia = postParams;
2638 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2640 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2641 .ConfigureAwait(false);
2644 post = await this.tw.PostStatus(postParamsWithMedia)
2645 .ConfigureAwait(false);
2648 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2650 catch (WebApiException ex)
2652 // 処理は中断せずエラーの表示のみ行う
2653 errMsg = $"Err:{ex.Message}(PostMessage)";
2655 this._myStatusError = true;
2657 catch (UnauthorizedAccessException ex)
2659 // アップロード対象のファイルが開けなかった場合など
2660 errMsg = $"Err:{ex.Message}(PostMessage)";
2662 this._myStatusError = true;
2666 // 使い終わった MediaItem は破棄する
2667 if (uploadItems != null)
2669 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2671 disposableItem.Dispose();
2676 if (ct.IsCancellationRequested)
2679 if (!string.IsNullOrEmpty(errMsg) &&
2680 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2681 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2683 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2685 var ret = MessageBox.Show(
2687 "Failed to update status",
2688 MessageBoxButtons.RetryCancel,
2689 MessageBoxIcon.Question);
2691 if (ret == DialogResult.Retry)
2693 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2697 this.StatusTextHistoryBack();
2698 this.StatusText.Focus();
2700 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2701 if (SettingManager.Common.FocusLockToStatusText)
2702 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2707 this._postTimestamps.Add(DateTimeUtc.Now);
2709 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2710 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2712 if (this._postTimestamps[i] < oneHour)
2713 this._postTimestamps.RemoveAt(i);
2716 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2718 this.HashMgr.ClearHashtag();
2719 this.HashStripSplitButton.Text = "#[-]";
2720 this.HashTogglePullDownMenuItem.Checked = false;
2721 this.HashToggleMenuItem.Checked = false;
2724 this.SetMainWindowTitle();
2727 if (!this.tw.UserStreamActive)
2729 if (SettingManager.Common.PostAndGet)
2730 await this.RefreshTabAsync<HomeTabModel>();
2735 this._statuses.AddPost(post);
2736 this._statuses.DistributePosts();
2737 this.RefreshTimeline();
2743 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2745 await this.workerSemaphore.WaitAsync();
2749 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2751 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2753 catch (WebApiException ex)
2755 this._myStatusError = true;
2756 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2760 this.workerSemaphore.Release();
2764 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2766 if (ct.IsCancellationRequested)
2769 if (!CheckAccountValid())
2770 throw new WebApiException("Auth error. Check your account");
2773 if (!SettingManager.Common.UnreadManage)
2776 read = this._initial && SettingManager.Common.Read;
2778 p.Report("Posting...");
2780 var posts = new List<PostClass>();
2782 await Task.Run(async () =>
2784 foreach (var statusId in statusIds)
2786 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2787 if (post != null) posts.Add(post);
2791 if (ct.IsCancellationRequested)
2794 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2796 this._postTimestamps.Add(DateTimeUtc.Now);
2798 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2799 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2801 if (this._postTimestamps[i] < oneHour)
2802 this._postTimestamps.RemoveAt(i);
2806 if (!this.tw.UserStreamActive)
2808 // 自分のRTはTLの更新では取得できない場合があるので、
2809 // 投稿時取得の有無に関わらず追加しておく
2810 posts.ForEach(post => this._statuses.AddPost(post));
2812 if (SettingManager.Common.PostAndGet)
2813 await this.RefreshTabAsync<HomeTabModel>();
2816 this._statuses.DistributePosts();
2817 this.RefreshTimeline();
2822 private async Task RefreshFollowerIdsAsync()
2824 await this.workerSemaphore.WaitAsync();
2827 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2829 await this.tw.RefreshFollowerIds();
2831 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2833 this.RefreshTimeline();
2834 this.PurgeListViewItemCache();
2835 this.CurrentListView.Refresh();
2837 catch (WebApiException ex)
2839 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2843 this.workerSemaphore.Release();
2847 private async Task RefreshNoRetweetIdsAsync()
2849 await this.workerSemaphore.WaitAsync();
2852 await this.tw.RefreshNoRetweetIds();
2854 this.StatusLabel.Text = "NoRetweetIds refreshed";
2856 catch (WebApiException ex)
2858 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2862 this.workerSemaphore.Release();
2866 private async Task RefreshBlockIdsAsync()
2868 await this.workerSemaphore.WaitAsync();
2871 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2873 await this.tw.RefreshBlockIds();
2875 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2877 catch (WebApiException ex)
2879 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2883 this.workerSemaphore.Release();
2887 private async Task RefreshTwitterConfigurationAsync()
2889 await this.workerSemaphore.WaitAsync();
2892 await this.tw.RefreshConfiguration();
2894 if (this.tw.Configuration.PhotoSizeLimit != 0)
2896 foreach (var service in this.ImageSelector.GetServices())
2898 service.UpdateTwitterConfiguration(this.tw.Configuration);
2902 this.PurgeListViewItemCache();
2903 this.CurrentListView.Refresh();
2905 catch (WebApiException ex)
2907 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2911 this.workerSemaphore.Release();
2915 private async Task RefreshMuteUserIdsAsync()
2917 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2921 await tw.RefreshMuteUserIdsAsync();
2923 catch (WebApiException ex)
2925 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2929 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
2932 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2934 if (e.Button == MouseButtons.Left)
2936 this.Visible = true;
2937 if (this.WindowState == FormWindowState.Minimized)
2939 this.WindowState = _formWindowState;
2942 this.BringToFront();
2946 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2948 switch (SettingManager.Common.ListDoubleClickAction)
2951 MakeReplyOrDirectStatus();
2954 await this.FavoriteChange(true);
2957 var post = this.CurrentPost;
2959 await this.ShowUserStatus(post.ScreenName, false);
2962 await ShowUserTimeline();
2965 ShowRelatedStatusesMenuItem_Click(null, null);
2968 MoveToHomeToolStripMenuItem_Click(null, null);
2971 StatusOpenMenuItem_Click(null, null);
2979 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2980 => await this.FavoriteChange(true);
2982 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2983 => await this.FavoriteChange(false);
2986 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2987 => await this.FavoritesRetweetOfficial();
2989 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2990 => await this.FavoritesRetweetUnofficial();
2992 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
2994 var tab = this.CurrentTab;
2995 var posts = tab.SelectedPosts;
2997 //trueでFavAdd,falseでFavRemove
2998 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2999 || !this.ExistCurrentPost) return;
3001 if (posts.Length > 1)
3006 // https://support.twitter.com/articles/76915#favoriting
3007 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3008 _DoFavRetweetFlags = false;
3013 if (multiFavoriteChangeDialogEnable)
3015 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3016 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3017 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3019 if (confirm == DialogResult.Cancel)
3027 var selectedPost = posts.Single();
3028 if (selectedPost.IsFav)
3030 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3034 await this.FavAddAsync(selectedPost.StatusId, tab);
3038 var selectedPosts = posts.Where(x => x.IsFav);
3039 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3040 if (statusIds.Length == 0)
3042 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3046 await this.FavRemoveAsync(statusIds, tab);
3050 private PostClass GetCurTabPost(int Index)
3052 var listCache = this._listItemCache;
3053 if (listCache != null)
3055 if (listCache.TryGetValue(Index, out var item, out var post))
3059 return this.CurrentTab[Index];
3062 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3064 var post = this.CurrentPost;
3066 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3068 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3071 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3073 var post = this.CurrentPost;
3075 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3078 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3080 if ((!_initialLayout) && this.Visible)
3082 if (this.WindowState == FormWindowState.Normal)
3084 _mySize = this.ClientSize;
3085 _mySpDis = this.SplitContainer1.SplitterDistance;
3086 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3087 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3088 ModifySettingLocal = true;
3093 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3095 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3096 if (comparerMode == null)
3099 this.SetSortColumn(comparerMode.Value);
3103 /// 列インデックスからソートを行う ComparerMode を求める
3105 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3106 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3107 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3110 return ComparerMode.Id;
3112 switch (columnIndex)
3115 return ComparerMode.Nickname;
3117 return ComparerMode.Data;
3119 return ComparerMode.Id;
3121 return ComparerMode.Name;
3123 return ComparerMode.Source;
3125 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3131 /// 発言一覧の指定した位置の列でソートする
3133 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3134 private void SetSortColumnByDisplayIndex(int columnIndex)
3136 // 表示上の列の位置から ColumnHeader を求める
3137 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3138 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3143 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3144 if (comparerMode == null)
3147 this.SetSortColumn(comparerMode.Value);
3151 /// 発言一覧の最後列の項目でソートする
3153 private void SetSortLastColumn()
3155 // 表示上の最後列にある ColumnHeader を求める
3156 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3157 .OrderByDescending(x => x.DisplayIndex)
3160 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3161 if (comparerMode == null)
3164 this.SetSortColumn(comparerMode.Value);
3168 /// 発言一覧を指定された ComparerMode に基づいてソートする
3170 private void SetSortColumn(ComparerMode sortColumn)
3172 if (SettingManager.Common.SortOrderLock)
3175 this._statuses.ToggleSortOrder(sortColumn);
3176 this.InitColumnText();
3178 var list = this.CurrentListView;
3181 list.Columns[0].Text = this.ColumnText[0];
3182 list.Columns[1].Text = this.ColumnText[2];
3186 for (var i = 0; i <= 7; i++)
3188 list.Columns[i].Text = this.ColumnText[i];
3192 this.PurgeListViewItemCache();
3194 var tab = this.CurrentTab;
3195 var post = this.CurrentPost;
3196 if (tab.AllCount > 0 && post != null)
3198 var idx = tab.IndexOf(post.StatusId);
3201 this.SelectListItem(list, idx);
3202 list.EnsureVisible(idx);
3207 this.ModifySettingCommon = true;
3210 private void TweenMain_LocationChanged(object sender, EventArgs e)
3212 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3214 _myLoc = this.DesktopLocation;
3215 ModifySettingLocal = true;
3219 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3221 if (!this.ExistCurrentPost)
3223 ReplyStripMenuItem.Enabled = false;
3224 ReplyAllStripMenuItem.Enabled = false;
3225 DMStripMenuItem.Enabled = false;
3226 ShowProfileMenuItem.Enabled = false;
3227 ShowUserTimelineContextMenuItem.Enabled = false;
3228 ListManageUserContextToolStripMenuItem2.Enabled = false;
3229 MoveToFavToolStripMenuItem.Enabled = false;
3230 TabMenuItem.Enabled = false;
3231 IDRuleMenuItem.Enabled = false;
3232 SourceRuleMenuItem.Enabled = false;
3233 ReadedStripMenuItem.Enabled = false;
3234 UnreadStripMenuItem.Enabled = false;
3238 ShowProfileMenuItem.Enabled = true;
3239 ListManageUserContextToolStripMenuItem2.Enabled = true;
3240 ReplyStripMenuItem.Enabled = true;
3241 ReplyAllStripMenuItem.Enabled = true;
3242 DMStripMenuItem.Enabled = true;
3243 ShowUserTimelineContextMenuItem.Enabled = true;
3244 MoveToFavToolStripMenuItem.Enabled = true;
3245 TabMenuItem.Enabled = true;
3246 IDRuleMenuItem.Enabled = true;
3247 SourceRuleMenuItem.Enabled = true;
3248 ReadedStripMenuItem.Enabled = true;
3249 UnreadStripMenuItem.Enabled = true;
3251 var tab = this.CurrentTab;
3252 var post = this.CurrentPost;
3253 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
3255 FavAddToolStripMenuItem.Enabled = false;
3256 FavRemoveToolStripMenuItem.Enabled = false;
3257 StatusOpenMenuItem.Enabled = false;
3258 ShowRelatedStatusesMenuItem.Enabled = false;
3260 ReTweetStripMenuItem.Enabled = false;
3261 ReTweetUnofficialStripMenuItem.Enabled = false;
3262 QuoteStripMenuItem.Enabled = false;
3263 FavoriteRetweetContextMenu.Enabled = false;
3264 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3268 FavAddToolStripMenuItem.Enabled = true;
3269 FavRemoveToolStripMenuItem.Enabled = true;
3270 StatusOpenMenuItem.Enabled = true;
3271 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3273 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3275 ReTweetStripMenuItem.Enabled = false;
3276 ReTweetUnofficialStripMenuItem.Enabled = false;
3277 QuoteStripMenuItem.Enabled = false;
3278 FavoriteRetweetContextMenu.Enabled = false;
3279 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3283 ReTweetStripMenuItem.Enabled = true;
3284 ReTweetUnofficialStripMenuItem.Enabled = true;
3285 QuoteStripMenuItem.Enabled = true;
3286 FavoriteRetweetContextMenu.Enabled = true;
3287 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3290 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3292 // RefreshMoreStripMenuItem.Enabled = true;
3296 // RefreshMoreStripMenuItem.Enabled = false;
3298 if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
3300 RepliedStatusOpenMenuItem.Enabled = false;
3304 RepliedStatusOpenMenuItem.Enabled = true;
3306 if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
3308 MoveToRTHomeMenuItem.Enabled = false;
3312 MoveToRTHomeMenuItem.Enabled = true;
3315 if (this.ExistCurrentPost)
3317 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3318 if (post.RetweetedByUserId == this.tw.UserId)
3319 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3321 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3325 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3326 => this.MakeReplyOrDirectStatus(false, true);
3328 private void DMStripMenuItem_Click(object sender, EventArgs e)
3329 => this.MakeReplyOrDirectStatus(false, false);
3331 private async Task doStatusDelete()
3333 var posts = this.CurrentTab.SelectedPosts;
3334 if (posts.Length == 0)
3337 // 選択されたツイートの中に削除可能なものが一つでもあるか
3338 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3341 var ret = MessageBox.Show(this,
3342 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3343 Properties.Resources.DeleteStripMenuItem_ClickText2,
3344 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3346 if (ret != DialogResult.OK)
3349 var currentListView = this.CurrentListView;
3350 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3352 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3354 Exception lastException = null;
3355 foreach (var post in posts)
3357 if (!post.CanDeleteBy(this.tw.UserId))
3364 await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3368 if (post.RetweetedByUserId == this.tw.UserId)
3370 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3372 await this.twitterApi.StatusesDestroy(post.StatusId)
3377 if (post.UserId == this.tw.UserId)
3379 if (post.RetweetedId != null)
3380 // 他人に RT された自分のツイート
3381 // => RT 元の自分のツイートを削除
3382 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3387 await this.twitterApi.StatusesDestroy(post.StatusId)
3393 catch (WebApiException ex)
3399 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3402 if (lastException == null)
3403 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3405 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3407 this.PurgeListViewItemCache();
3409 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3411 var tabPage = this.ListTab.TabPages[index];
3412 var listView = (DetailsListView)tabPage.Tag;
3414 using (ControlTransaction.Update(listView))
3416 listView.VirtualListSize = tab.AllCount;
3418 if (tab.TabName == this.CurrentTabName)
3420 listView.SelectedIndices.Clear();
3422 if (tab.AllCount != 0)
3425 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3426 selectedIndex = focusedIndex;
3428 selectedIndex = tab.AllCount - 1;
3430 listView.SelectedIndices.Add(selectedIndex);
3431 listView.EnsureVisible(selectedIndex);
3432 listView.FocusedItem = listView.Items[selectedIndex];
3437 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3439 if (tabPage.ImageIndex == 0)
3440 tabPage.ImageIndex = -1; // タブアイコン
3444 if (!SettingManager.Common.TabIconDisp)
3445 this.ListTab.Refresh();
3449 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3450 => await this.doStatusDelete();
3452 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3454 using (ControlTransaction.Update(this.CurrentListView))
3456 var tab = this.CurrentTab;
3457 foreach (var statusId in tab.SelectedStatusIds)
3459 this._statuses.SetReadAllTab(statusId, read: true);
3460 var idx = tab.IndexOf(statusId);
3461 ChangeCacheStyleRead(true, idx);
3465 if (SettingManager.Common.TabIconDisp)
3467 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3469 if (tab.UnreadCount == 0)
3471 var tabPage = this.ListTab.TabPages[index];
3472 if (tabPage.ImageIndex == 0)
3473 tabPage.ImageIndex = -1; // タブアイコン
3477 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3480 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3482 using (ControlTransaction.Update(this.CurrentListView))
3484 var tab = this.CurrentTab;
3485 foreach (var statusId in tab.SelectedStatusIds)
3487 this._statuses.SetReadAllTab(statusId, read: false);
3488 var idx = tab.IndexOf(statusId);
3489 ChangeCacheStyleRead(false, idx);
3493 if (SettingManager.Common.TabIconDisp)
3495 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3497 if (tab.UnreadCount > 0)
3499 var tabPage = this.ListTab.TabPages[index];
3500 if (tabPage.ImageIndex == -1)
3501 tabPage.ImageIndex = 0; // タブアイコン
3505 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3508 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3509 => await this.DoRefresh();
3511 private async Task DoRefresh()
3512 => await this.RefreshTabAsync(this.CurrentTab);
3514 private async Task DoRefreshMore()
3515 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3517 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3519 DialogResult result = DialogResult.Abort;
3521 using (var settingDialog = new AppendSettingDialog())
3523 settingDialog.Icon = this.MainIcon;
3524 settingDialog.Owner = this;
3525 settingDialog.ShowInTaskbar = showTaskbarIcon;
3526 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3528 settingDialog.tw = this.tw;
3529 settingDialog.twitterApi = this.twitterApi;
3531 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3535 result = settingDialog.ShowDialog(this);
3539 return DialogResult.Abort;
3542 if (result == DialogResult.OK)
3546 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3554 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3557 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3559 var oldIconSz = SettingManager.Common.IconSize;
3561 if (ShowSettingDialog() == DialogResult.OK)
3565 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3566 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3567 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3568 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3569 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3570 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3571 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3573 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3574 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3575 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3576 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3577 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3578 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3580 ImageSelector.Reset(tw, this.tw.Configuration);
3584 if (SettingManager.Common.TabIconDisp)
3586 ListTab.DrawItem -= ListTab_DrawItem;
3587 ListTab.DrawMode = TabDrawMode.Normal;
3588 ListTab.ImageList = this.TabImage;
3592 ListTab.DrawItem -= ListTab_DrawItem;
3593 ListTab.DrawItem += ListTab_DrawItem;
3594 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3595 ListTab.ImageList = null;
3598 catch (Exception ex)
3600 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3601 ex.Data["IsTerminatePermission"] = false;
3607 if (!SettingManager.Common.UnreadManage)
3609 ReadedStripMenuItem.Enabled = false;
3610 UnreadStripMenuItem.Enabled = false;
3611 if (SettingManager.Common.TabIconDisp)
3613 foreach (TabPage myTab in ListTab.TabPages)
3615 myTab.ImageIndex = -1;
3621 ReadedStripMenuItem.Enabled = true;
3622 UnreadStripMenuItem.Enabled = true;
3625 catch (Exception ex)
3627 ex.Data["Instance"] = "ListTab(UnreadManage)";
3628 ex.Data["IsTerminatePermission"] = false;
3635 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3637 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3638 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3639 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3641 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3642 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3643 _fntUnread = SettingManager.Local.FontUnread;
3644 _clUnread = SettingManager.Local.ColorUnread;
3645 _fntReaded = SettingManager.Local.FontRead;
3646 _clReaded = SettingManager.Local.ColorRead;
3647 _clFav = SettingManager.Local.ColorFav;
3648 _clOWL = SettingManager.Local.ColorOWL;
3649 _clRetweet = SettingManager.Local.ColorRetweet;
3650 _fntDetail = SettingManager.Local.FontDetail;
3651 _clDetail = SettingManager.Local.ColorDetail;
3652 _clDetailLink = SettingManager.Local.ColorDetailLink;
3653 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3654 _clSelf = SettingManager.Local.ColorSelf;
3655 _clAtSelf = SettingManager.Local.ColorAtSelf;
3656 _clTarget = SettingManager.Local.ColorTarget;
3657 _clAtTarget = SettingManager.Local.ColorAtTarget;
3658 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3659 _clAtTo = SettingManager.Local.ColorAtTo;
3660 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3661 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3662 _clInputFont = SettingManager.Local.ColorInputFont;
3663 _fntInputFont = SettingManager.Local.FontInputFont;
3664 _brsBackColorMine.Dispose();
3665 _brsBackColorAt.Dispose();
3666 _brsBackColorYou.Dispose();
3667 _brsBackColorAtYou.Dispose();
3668 _brsBackColorAtFromTarget.Dispose();
3669 _brsBackColorAtTo.Dispose();
3670 _brsBackColorNone.Dispose();
3671 _brsBackColorMine = new SolidBrush(_clSelf);
3672 _brsBackColorAt = new SolidBrush(_clAtSelf);
3673 _brsBackColorYou = new SolidBrush(_clTarget);
3674 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3675 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3676 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3677 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3681 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3682 StatusText.Font = _fntInputFont;
3683 StatusText.ForeColor = _clInputFont;
3685 catch (Exception ex)
3687 MessageBox.Show(ex.Message);
3692 InitDetailHtmlFormat();
3694 catch (Exception ex)
3696 ex.Data["Instance"] = "Font";
3697 ex.Data["IsTerminatePermission"] = false;
3703 if (SettingManager.Common.TabIconDisp)
3705 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3707 var tabPage = this.ListTab.TabPages[index];
3708 if (tab.UnreadCount == 0)
3709 tabPage.ImageIndex = -1;
3711 tabPage.ImageIndex = 0;
3715 catch (Exception ex)
3717 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3718 ex.Data["IsTerminatePermission"] = false;
3724 var oldIconCol = _iconCol;
3726 if (SettingManager.Common.IconSize != oldIconSz)
3727 ApplyListViewIconSize(SettingManager.Common.IconSize);
3729 foreach (TabPage tp in ListTab.TabPages)
3731 DetailsListView lst = (DetailsListView)tp.Tag;
3733 using (ControlTransaction.Update(lst))
3735 lst.GridLines = SettingManager.Common.ShowGrid;
3736 lst.Font = _fntReaded;
3737 lst.BackColor = _clListBackcolor;
3739 if (_iconCol != oldIconCol)
3744 catch (Exception ex)
3746 ex.Data["Instance"] = "ListView(IconSize)";
3747 ex.Data["IsTerminatePermission"] = false;
3751 SetMainWindowTitle();
3752 SetNotifyIconText();
3754 this.PurgeListViewItemCache();
3755 this.CurrentListView.Refresh();
3758 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3759 if (SettingManager.Common.HotkeyEnabled)
3761 ///グローバルホットキーの登録。設定で変更可能にするかも
3762 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3763 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3764 modKey |= HookGlobalHotkey.ModKeys.Alt;
3765 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3766 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3767 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3768 modKey |= HookGlobalHotkey.ModKeys.Shift;
3769 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3770 modKey |= HookGlobalHotkey.ModKeys.Win;
3772 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3775 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3778 StatusText_TextChanged(null, null);
3787 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3788 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3791 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3793 this.TopMost = SettingManager.Common.AlwaysTop;
3794 SaveConfigsAll(false);
3796 if (tw.UserId != oldUser.UserId)
3797 await this.doGetFollowersMenu();
3803 private void SetTabAlignment()
3805 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3806 if (ListTab.Alignment == newAlignment) return;
3808 // 各タブのリスト上の選択位置などを退避
3809 var listSelections = this.SaveListViewSelection();
3811 ListTab.Alignment = newAlignment;
3813 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3815 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3816 using (ControlTransaction.Update(lst))
3819 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3824 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3830 case MyCommon.IconSizes.IconNone:
3833 case MyCommon.IconSizes.Icon16:
3836 case MyCommon.IconSizes.Icon24:
3839 case MyCommon.IconSizes.Icon48:
3842 case MyCommon.IconSizes.Icon48_2:
3850 // ディスプレイの DPI 設定を考慮したサイズを設定する
3851 _listViewImageList.ImageSize = new Size(
3853 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3857 _listViewImageList.ImageSize = new Size(1, 1);
3861 private void ResetColumns(DetailsListView list)
3863 using (ControlTransaction.Update(list))
3864 using (ControlTransaction.Layout(list, false))
3867 list.ColumnClick -= MyList_ColumnClick;
3868 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3869 list.ColumnReordered -= MyList_ColumnReordered;
3870 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3872 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3873 list.Columns.Clear();
3874 cols.ForEach(col => col.Dispose());
3877 InitColumns(list, true);
3879 list.ColumnClick += MyList_ColumnClick;
3880 list.DrawColumnHeader += MyList_DrawColumnHeader;
3881 list.ColumnReordered += MyList_ColumnReordered;
3882 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3886 public void AddNewTabForSearch(string searchWord)
3888 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3889 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3891 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
3893 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3894 this.ListTab.SelectedIndex = tabIndex;
3899 string tabName = searchWord;
3900 for (int i = 0; i <= 100; i++)
3902 if (_statuses.ContainsTab(tabName))
3908 var tab = new PublicSearchTabModel(tabName);
3909 _statuses.AddTab(tab);
3910 AddNewTab(tab, startup: false);
3912 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3914 var tabPage = this.CurrentTabPage;
3915 ComboBox cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3916 cmb.Items.Add(searchWord);
3917 cmb.Text = searchWord;
3920 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
3923 private async Task ShowUserTimeline()
3925 if (!this.ExistCurrentPost) return;
3926 await this.AddNewTabForUserTimeline(this.CurrentPost.ScreenName);
3929 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3931 if (e.KeyCode == Keys.Escape)
3933 RemoveSpecifiedTab(this.CurrentTabName, false);
3935 e.SuppressKeyPress = true;
3939 public async Task AddNewTabForUserTimeline(string user)
3941 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3942 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
3944 if (tb.ScreenName == user)
3946 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3947 this.ListTab.SelectedIndex = tabIndex;
3952 string tabName = "user:" + user;
3953 while (_statuses.ContainsTab(tabName))
3958 var tab = new UserTimelineTabModel(tabName, user);
3959 this._statuses.AddTab(tab);
3960 this.AddNewTab(tab, startup: false);
3962 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3965 await this.RefreshTabAsync(tab);
3968 public bool AddNewTab(TabModel tab, bool startup)
3971 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
3975 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
3977 var _tabPage = new TabPage();
3978 var _listCustom = new DetailsListView();
3980 int cnt = this._statuses.Tabs.Count;
3982 ///ToDo:Create and set controls follow tabtypes
3984 using (ControlTransaction.Update(_listCustom))
3985 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3986 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3987 using (ControlTransaction.Layout(this.SplitContainer1, false))
3988 using (ControlTransaction.Layout(this.ListTab, false))
3989 using (ControlTransaction.Layout(this))
3990 using (ControlTransaction.Layout(_tabPage, false))
3992 _tabPage.Controls.Add(_listCustom);
3995 var userTab = tab as UserTimelineTabModel;
3996 var listTab = tab as ListTimelineTabModel;
3997 var searchTab = tab as PublicSearchTabModel;
3999 if (userTab != null || listTab != null)
4001 var label = new Label
4003 Dock = DockStyle.Top,
4008 if (listTab != null)
4010 label.Text = listTab.ListInfo.ToString();
4012 else if (userTab != null)
4014 label.Text = userTab.ScreenName + "'s Timeline";
4016 label.TextAlign = ContentAlignment.MiddleLeft;
4017 using (ComboBox tmpComboBox = new ComboBox())
4019 label.Height = tmpComboBox.Height;
4021 _tabPage.Controls.Add(label);
4024 else if (searchTab != null)
4026 var pnl = new Panel();
4028 var lbl = new Label();
4029 var cmb = new ComboBox();
4030 var btn = new Button();
4031 var cmbLang = new ComboBox();
4033 using (ControlTransaction.Layout(pnl, false))
4035 pnl.Controls.Add(cmb);
4036 pnl.Controls.Add(cmbLang);
4037 pnl.Controls.Add(btn);
4038 pnl.Controls.Add(lbl);
4039 pnl.Name = "panelSearch";
4041 pnl.Dock = DockStyle.Top;
4042 pnl.Height = cmb.Height;
4043 pnl.Enter += SearchControls_Enter;
4044 pnl.Leave += SearchControls_Leave;
4047 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4048 cmb.Dock = DockStyle.Fill;
4049 cmb.Name = "comboSearch";
4050 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4051 cmb.ImeMode = ImeMode.NoControl;
4052 cmb.TabStop = false;
4054 cmb.AutoCompleteMode = AutoCompleteMode.None;
4055 cmb.KeyDown += SearchComboBox_KeyDown;
4058 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4059 cmbLang.Dock = DockStyle.Right;
4061 cmbLang.Name = "comboLang";
4062 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4063 cmbLang.TabStop = false;
4064 cmbLang.TabIndex = 2;
4065 cmbLang.Items.Add("");
4066 cmbLang.Items.Add("ja");
4067 cmbLang.Items.Add("en");
4068 cmbLang.Items.Add("ar");
4069 cmbLang.Items.Add("da");
4070 cmbLang.Items.Add("nl");
4071 cmbLang.Items.Add("fa");
4072 cmbLang.Items.Add("fi");
4073 cmbLang.Items.Add("fr");
4074 cmbLang.Items.Add("de");
4075 cmbLang.Items.Add("hu");
4076 cmbLang.Items.Add("is");
4077 cmbLang.Items.Add("it");
4078 cmbLang.Items.Add("no");
4079 cmbLang.Items.Add("pl");
4080 cmbLang.Items.Add("pt");
4081 cmbLang.Items.Add("ru");
4082 cmbLang.Items.Add("es");
4083 cmbLang.Items.Add("sv");
4084 cmbLang.Items.Add("th");
4086 lbl.Text = "Search(C-S-f)";
4087 lbl.Name = "label1";
4088 lbl.Dock = DockStyle.Left;
4090 lbl.Height = cmb.Height;
4091 lbl.TextAlign = ContentAlignment.MiddleLeft;
4094 btn.Text = "Search";
4095 btn.Name = "buttonSearch";
4096 btn.UseVisualStyleBackColor = true;
4097 btn.Dock = DockStyle.Right;
4098 btn.TabStop = false;
4100 btn.Click += SearchButton_Click;
4102 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4104 cmb.Items.Add(searchTab.SearchWords);
4105 cmb.Text = searchTab.SearchWords;
4108 cmbLang.Text = searchTab.SearchLang;
4110 _tabPage.Controls.Add(pnl);
4114 _tabPage.Tag = _listCustom;
4115 this.ListTab.Controls.Add(_tabPage);
4117 _tabPage.Location = new Point(4, 4);
4118 _tabPage.Name = "CTab" + cnt;
4119 _tabPage.Size = new Size(380, 260);
4120 _tabPage.TabIndex = 2 + cnt;
4121 _tabPage.Text = tab.TabName;
4122 _tabPage.UseVisualStyleBackColor = true;
4123 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4125 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4126 _listCustom.TabIndex = 1;
4127 _listCustom.AllowColumnReorder = true;
4128 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4129 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4130 _listCustom.Dock = DockStyle.Fill;
4131 _listCustom.FullRowSelect = true;
4132 _listCustom.HideSelection = false;
4133 _listCustom.Location = new Point(0, 0);
4134 _listCustom.Margin = new Padding(0);
4135 _listCustom.Name = "CList" + Environment.TickCount;
4136 _listCustom.ShowItemToolTips = true;
4137 _listCustom.Size = new Size(380, 260);
4138 _listCustom.UseCompatibleStateImageBehavior = false;
4139 _listCustom.View = View.Details;
4140 _listCustom.OwnerDraw = true;
4141 _listCustom.VirtualMode = true;
4142 _listCustom.Font = _fntReaded;
4143 _listCustom.BackColor = _clListBackcolor;
4145 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4146 _listCustom.AllowDrop = true;
4148 _listCustom.SmallImageList = _listViewImageList;
4150 InitColumns(_listCustom, startup);
4152 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4153 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4154 _listCustom.ColumnClick += MyList_ColumnClick;
4155 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4156 _listCustom.DragDrop += TweenMain_DragDrop;
4157 _listCustom.DragEnter += TweenMain_DragEnter;
4158 _listCustom.DragOver += TweenMain_DragOver;
4159 _listCustom.DrawItem += MyList_DrawItem;
4160 _listCustom.MouseClick += MyList_MouseClick;
4161 _listCustom.ColumnReordered += MyList_ColumnReordered;
4162 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4163 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4164 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4165 _listCustom.DrawSubItem += MyList_DrawSubItem;
4166 _listCustom.HScrolled += MyList_HScrolled;
4172 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4174 var tabInfo = _statuses.GetTabByName(TabName);
4175 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4179 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4180 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4181 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4187 var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4191 var _tabPage = this.ListTab.TabPages[tabIndex];
4193 SetListProperty(); //他のタブに列幅等を反映
4196 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4197 _tabPage.Tag = null;
4199 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4200 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4201 using (ControlTransaction.Layout(this.SplitContainer1, false))
4202 using (ControlTransaction.Layout(this.ListTab, false))
4203 using (ControlTransaction.Layout(this))
4204 using (ControlTransaction.Layout(_tabPage, false))
4206 if (this.CurrentTabName == TabName)
4208 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4209 this._beforeSelectedTab = null;
4211 this.ListTab.Controls.Remove(_tabPage);
4214 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4216 using (Control label = _tabPage.Controls["labelUser"])
4218 _tabPage.Controls.Remove(label);
4221 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4223 using (Control pnl = _tabPage.Controls["panelSearch"])
4225 pnl.Enter -= SearchControls_Enter;
4226 pnl.Leave -= SearchControls_Leave;
4227 _tabPage.Controls.Remove(pnl);
4229 foreach (Control ctrl in pnl.Controls)
4231 if (ctrl.Name == "buttonSearch")
4233 ctrl.Click -= SearchButton_Click;
4235 else if (ctrl.Name == "comboSearch")
4237 ctrl.KeyDown -= SearchComboBox_KeyDown;
4239 pnl.Controls.Remove(ctrl);
4245 _tabPage.Controls.Remove(_listCustom);
4247 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4248 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4249 _listCustom.ColumnClick -= MyList_ColumnClick;
4250 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4251 _listCustom.DragDrop -= TweenMain_DragDrop;
4252 _listCustom.DragEnter -= TweenMain_DragEnter;
4253 _listCustom.DragOver -= TweenMain_DragOver;
4254 _listCustom.DrawItem -= MyList_DrawItem;
4255 _listCustom.MouseClick -= MyList_MouseClick;
4256 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4257 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4258 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4259 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4260 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4261 _listCustom.HScrolled -= MyList_HScrolled;
4263 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4264 _listCustom.Columns.Clear();
4265 cols.ForEach(col => col.Dispose());
4268 _listCustom.ContextMenuStrip = null;
4269 _listCustom.ColumnHeaderContextMenuStrip = null;
4270 _listCustom.Font = null;
4272 _listCustom.SmallImageList = null;
4273 _listCustom.ListViewItemSorter = null;
4276 this.PurgeListViewItemCache();
4280 _listCustom.Dispose();
4281 _statuses.RemoveTab(TabName);
4283 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4285 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4286 lst.VirtualListSize = tab.AllCount;
4292 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4294 this.PurgeListViewItemCache();
4295 _beforeSelectedTab = e.TabPage;
4298 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4302 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4305 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4306 if (!dragEnableRectangle.Contains(e.Location))
4308 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4309 tn = this.CurrentTabName;
4312 if (string.IsNullOrEmpty(tn)) return;
4314 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4317 var tabPage = this.ListTab.TabPages[tabIndex];
4318 ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4326 Point cpos = new Point(e.X, e.Y);
4327 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4329 var rect = ListTab.GetTabRect(index);
4330 if (rect.Contains(cpos))
4332 _rclickTabName = tab.TabName;
4338 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4340 //_curList.Refresh();
4341 SetMainWindowTitle();
4342 SetStatusLabelUrl();
4343 SetApiStatusLabel();
4344 if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4345 this.Tag = ListTab.Tag;
4346 TabMenuControl(this.CurrentTabName);
4347 this.PushSelectPostChain();
4348 await DispSelectedPost();
4351 private void SetListProperty()
4353 if (!_isColumnChanged) return;
4355 var currentListView = this.CurrentListView;
4357 int[] dispOrder = new int[currentListView.Columns.Count];
4358 for (int i = 0; i < currentListView.Columns.Count; i++)
4360 for (int j = 0; j < currentListView.Columns.Count; j++)
4362 if (currentListView.Columns[j].DisplayIndex == i)
4371 foreach (TabPage tb in ListTab.TabPages)
4373 if (tb.Text == this.CurrentTabName)
4376 if (tb.Tag != null && tb.Controls.Count > 0)
4378 DetailsListView lst = (DetailsListView)tb.Tag;
4379 for (int i = 0; i < lst.Columns.Count; i++)
4381 lst.Columns[dispOrder[i]].DisplayIndex = i;
4382 lst.Columns[i].Width = currentListView.Columns[i].Width;
4387 _isColumnChanged = false;
4390 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4392 if (e.KeyChar == '@')
4394 if (!SettingManager.Common.UseAtIdSupplement) return;
4396 int cnt = AtIdSupl.ItemCount;
4397 ShowSuplDialog(StatusText, AtIdSupl);
4398 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4401 else if (e.KeyChar == '#')
4403 if (!SettingManager.Common.UseHashSupplement) return;
4404 ShowSuplDialog(StatusText, HashSupl);
4409 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4410 => this.ShowSuplDialog(owner, dialog, 0, "");
4412 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4413 => this.ShowSuplDialog(owner, dialog, offset, "");
4415 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4417 dialog.StartsWith = startswith;
4424 dialog.ShowDialog();
4426 this.TopMost = SettingManager.Common.AlwaysTop;
4427 int selStart = owner.SelectionStart;
4430 if (dialog.DialogResult == DialogResult.OK)
4432 if (!string.IsNullOrEmpty(dialog.inputText))
4436 fHalf = owner.Text.Substring(0, selStart - offset);
4438 if (selStart < owner.Text.Length)
4440 eHalf = owner.Text.Substring(selStart);
4442 owner.Text = fHalf + dialog.inputText + eHalf;
4443 owner.SelectionStart = selStart + dialog.inputText.Length;
4450 fHalf = owner.Text.Substring(0, selStart);
4452 if (selStart < owner.Text.Length)
4454 eHalf = owner.Text.Substring(selStart);
4456 owner.Text = fHalf + eHalf;
4459 owner.SelectionStart = selStart;
4465 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4468 if (!e.Alt && !e.Control && !e.Shift)
4470 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4472 bool isSpace = false;
4473 foreach (char c in StatusText.Text)
4475 if (c == ' ' || c == ' ')
4488 StatusText.Text = "";
4489 JumpUnreadMenuItem_Click(null, null);
4493 this.StatusText_TextChanged(null, null);
4496 private void StatusText_TextChanged(object sender, EventArgs e)
4499 int pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4500 lblLen.Text = pLen.ToString();
4503 StatusText.ForeColor = Color.Red;
4507 StatusText.ForeColor = _clInputFont;
4510 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4512 if (string.IsNullOrEmpty(StatusText.Text))
4514 this.inReplyTo = null;
4519 /// メンション以外の文字列が含まれていないテキストであるか判定します
4521 internal static bool TextContainsOnlyMentions(string text)
4523 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4526 foreach (var mention in mentions)
4528 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4530 if (!string.IsNullOrWhiteSpace(textPart))
4533 startIndex = mention.Indices[1];
4536 var textPartLast = text.Substring(startIndex);
4538 if (!string.IsNullOrWhiteSpace(textPartLast))
4545 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4547 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4549 List<long> _autoPopulatedUserIds = new List<long>();
4551 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4552 if (replyToPost != null)
4554 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4556 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4557 _autoPopulatedUserIds.Add(replyToPost.UserId);
4559 foreach (var (userId, screenName) in replyToPost.ReplyToList)
4561 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4563 statusText = statusText.Substring(screenName.Length + 2);
4564 _autoPopulatedUserIds.Add(userId);
4570 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4576 /// attachment_url に指定可能な URL が含まれていれば除去
4578 private string RemoveAttachmentUrl(string statusText, out string attachmentUrl)
4580 attachmentUrl = null;
4582 // attachment_url は media_id と同時に使用できない
4583 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4586 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4590 attachmentUrl = match.Value;
4593 statusText = statusText.Substring(0, match.Index);
4595 // テキストと URL の間にスペースが含まれていれば除去
4596 return statusText.TrimEnd(' ');
4599 private string FormatStatusTextExtended(string statusText)
4600 => this.FormatStatusTextExtended(statusText, out var autoPopulatedUserIds, out var attachmentUrl);
4603 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4605 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string attachmentUrl)
4607 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4609 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4611 return this.FormatStatusText(statusText);
4615 /// ツイート投稿前のフッター付与などの前処理を行います
4617 private string FormatStatusText(string statusText)
4619 statusText = statusText.Replace("\r\n", "\n");
4621 if (this.urlMultibyteSplit)
4624 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4627 if (SettingManager.Common.WideSpaceConvert)
4629 // 文中の全角スペースを半角スペース1個にする
4630 statusText = statusText.Replace(" ", " ");
4633 // DM の場合はこれ以降の処理を行わない
4634 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4638 if (SettingManager.Common.PostShiftEnter)
4640 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4644 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4645 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4647 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4650 if (statusText.Contains("RT @"))
4651 disableFooter = true;
4653 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4654 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4656 var mentionSelf = $"@{this.tw.Username} ";
4657 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4659 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4660 statusText = statusText.Substring(mentionSelf.Length);
4667 var hashtag = this.HashMgr.UseHash;
4668 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4671 header = HashMgr.UseHash + " ";
4673 footer = " " + HashMgr.UseHash;
4678 if (SettingManager.Local.UseRecommendStatus)
4681 footer += this.recommendedStatusFooter;
4683 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4685 // テキストボックスに入力されている文字列を使用する
4686 footer += " " + SettingManager.Local.StatusText.Trim();
4690 statusText = header + statusText + footer;
4692 if (this.preventSmsCommand)
4694 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4695 // 参照: https://support.twitter.com/articles/14020
4697 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4698 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4700 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4701 statusText = '\u200b' + statusText;
4709 /// 投稿欄に表示する入力可能な文字数を計算します
4711 private int GetRestStatusCount(string statusText)
4713 var remainCount = this.tw.GetTextLengthRemain(statusText);
4715 var uploadService = this.GetSelectedImageService();
4716 if (uploadService != null)
4718 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4719 remainCount -= uploadService.GetReservedTextLength(1);
4725 private IMediaUploadService GetSelectedImageService()
4726 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4728 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4730 if (sender != this.CurrentListView)
4733 var listCache = this._listItemCache;
4734 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4736 // If the newly requested cache is a subset of the old cache,
4737 // no need to rebuild everything, so do nothing.
4741 // Now we need to rebuild the cache.
4742 this.CreateCache(e.StartIndex, e.EndIndex);
4745 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4747 var listCache = this._listItemCache;
4748 if (listCache?.TargetList == sender)
4750 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4757 // A cache miss, so create a new ListViewItem and pass it back.
4758 var tabPage = (TabPage)((DetailsListView)sender).Parent;
4759 var tab = this._statuses.Tabs[tabPage.Text];
4762 e.Item = this.CreateItem(tab, tab[e.ItemIndex], e.ItemIndex);
4766 // 不正な要求に対する間に合わせの応答
4767 string[] sitem = {"", "", "", "", "", "", "", ""};
4768 e.Item = new ImageListViewItem(sitem);
4772 private void CreateCache(int startIndex, int endIndex)
4774 var tabInfo = this.CurrentTab;
4776 if (tabInfo.AllCount == 0)
4779 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4780 int FilterRange(int index)
4781 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4783 // キャッシュ要求(要求範囲±30を作成)
4784 startIndex = FilterRange(startIndex - 30);
4785 endIndex = FilterRange(endIndex + 30);
4787 var cacheLength = endIndex - startIndex + 1;
4789 var tab = this.CurrentTab;
4790 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4791 var listItems = Enumerable.Range(0, cacheLength)
4792 .Select(x => this.CreateItem(tab, posts[x], startIndex + x))
4795 var listCache = new ListViewItemCache
4797 TargetList = this.CurrentListView,
4798 StartIndex = startIndex,
4799 EndIndex = endIndex,
4801 ListItem = listItems,
4804 Interlocked.Exchange(ref this._listItemCache, listCache);
4808 /// DetailsListView のための ListViewItem のキャッシュを消去する
4810 private void PurgeListViewItemCache()
4811 => Interlocked.Exchange(ref this._listItemCache, null);
4813 private ListViewItem CreateItem(TabModel tab, PostClass Post, int Index)
4815 StringBuilder mk = new StringBuilder();
4816 //if (Post.IsDeleted) mk.Append("×");
4817 //if (Post.IsMark) mk.Append("♪");
4818 //if (Post.IsProtect) mk.Append("Ю");
4819 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4820 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4821 ImageListViewItem itm;
4822 if (Post.RetweetedId == null)
4824 string[] sitem= {"",
4826 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4827 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4832 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4836 string[] sitem = {"",
4838 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4839 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4840 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4844 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4846 itm.StateIndex = Post.StateIndex;
4849 bool read = Post.IsRead;
4850 // 未読管理していなかったら既読として扱う
4851 if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4854 ChangeItemStyleRead(read, itm, Post, null);
4856 if (tab.TabName == this.CurrentTabName)
4857 this.ColorizeList(itm, Index);
4863 /// 全てのタブの振り分けルールを反映し直します
4865 private void ApplyPostFilters()
4867 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4869 this.PurgeListViewItemCache();
4870 this._statuses.FilterAll();
4872 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4874 var tabPage = this.ListTab.TabPages[index];
4875 var listview = (DetailsListView)tabPage.Tag;
4876 using (ControlTransaction.Update(listview))
4878 listview.VirtualListSize = tab.AllCount;
4881 if (SettingManager.Common.TabIconDisp)
4883 if (tab.UnreadCount > 0)
4884 tabPage.ImageIndex = 0;
4886 tabPage.ImageIndex = -1;
4890 if (!SettingManager.Common.TabIconDisp)
4891 this.ListTab.Refresh();
4893 SetMainWindowTitle();
4894 SetStatusLabelUrl();
4898 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4899 => e.DrawDefault = true;
4901 private void MyList_HScrolled(object sender, EventArgs e)
4902 => ((DetailsListView)sender).Refresh();
4904 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4906 if (e.State == 0) return;
4907 e.DrawDefault = false;
4909 SolidBrush brs2 = null;
4910 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4912 if (e.Item.BackColor == _clSelf)
4913 brs2 = _brsBackColorMine;
4914 else if (e.Item.BackColor == _clAtSelf)
4915 brs2 = _brsBackColorAt;
4916 else if (e.Item.BackColor == _clTarget)
4917 brs2 = _brsBackColorYou;
4918 else if (e.Item.BackColor == _clAtTarget)
4919 brs2 = _brsBackColorAtYou;
4920 else if (e.Item.BackColor == _clAtFromTarget)
4921 brs2 = _brsBackColorAtFromTarget;
4922 else if (e.Item.BackColor == _clAtTo)
4923 brs2 = _brsBackColorAtTo;
4925 brs2 = _brsBackColorNone;
4930 if (((Control)sender).Focused)
4931 brs2 = _brsHighLight;
4933 brs2 = _brsDeactiveSelection;
4935 e.Graphics.FillRectangle(brs2, e.Bounds);
4936 e.DrawFocusRectangle();
4937 this.DrawListViewItemIcon(e);
4940 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
4942 if (e.ItemState == 0) return;
4944 if (e.ColumnIndex > 0)
4947 var post = (PostClass)e.Item.Tag;
4949 RectangleF rct = e.Bounds;
4950 rct.Width = e.Header.Width;
4951 int fontHeight = e.Item.Font.Height;
4954 rct.Y += fontHeight;
4955 rct.Height -= fontHeight;
4958 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
4960 //if (heightDiff > fontHeight * 0.7)
4962 // rct.Height += fontHeight;
4963 // drawLineCount += 1;
4966 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
4967 if (!_iconCol && drawLineCount <= 1)
4969 //rct.Inflate(0, heightDiff / -2);
4970 //rct.Height += fontHeight / 2;
4972 else if (heightDiff < fontHeight * 0.7)
4974 //最終行が70%以上欠けていたら、最終行は表示しない
4975 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
4976 rct.Height = (fontHeight * drawLineCount) - 1;
4983 //if (!_iconCol && drawLineCount > 1)
4985 // rct.Y += fontHeight * 0.2;
4986 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
4991 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
4992 (((Control)sender).Focused) ? _clHighLight : //選択中の行
4997 Rectangle rctB = e.Bounds;
4998 rctB.Width = e.Header.Width;
4999 rctB.Height = fontHeight;
5001 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5003 TextRenderer.DrawText(e.Graphics,
5004 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5006 Rectangle.Round(rct),
5008 TextFormatFlags.WordBreak |
5009 TextFormatFlags.EndEllipsis |
5010 TextFormatFlags.GlyphOverhangPadding |
5011 TextFormatFlags.NoPrefix);
5012 TextRenderer.DrawText(e.Graphics,
5013 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 + "]",
5017 TextFormatFlags.SingleLine |
5018 TextFormatFlags.EndEllipsis |
5019 TextFormatFlags.GlyphOverhangPadding |
5020 TextFormatFlags.NoPrefix);
5026 if (e.ColumnIndex != 2)
5027 text = e.SubItem.Text;
5029 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5031 if (drawLineCount == 1)
5033 TextRenderer.DrawText(e.Graphics,
5036 Rectangle.Round(rct),
5038 TextFormatFlags.SingleLine |
5039 TextFormatFlags.EndEllipsis |
5040 TextFormatFlags.GlyphOverhangPadding |
5041 TextFormatFlags.NoPrefix |
5042 TextFormatFlags.VerticalCenter);
5046 TextRenderer.DrawText(e.Graphics,
5049 Rectangle.Round(rct),
5051 TextFormatFlags.WordBreak |
5052 TextFormatFlags.EndEllipsis |
5053 TextFormatFlags.GlyphOverhangPadding |
5054 TextFormatFlags.NoPrefix);
5057 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5062 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5064 if (_iconSz == 0) return;
5066 ImageListViewItem item = (ImageListViewItem)e.Item;
5068 //e.Bounds.Leftが常に0を指すから自前で計算
5069 Rectangle itemRect = item.Bounds;
5070 var col0 = e.Item.ListView.Columns[0];
5071 itemRect.Width = col0.Width;
5073 if (col0.DisplayIndex > 0)
5075 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5077 if (clm.DisplayIndex < col0.DisplayIndex)
5078 itemRect.X += clm.Width;
5082 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5083 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5084 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5087 var img = item.Image;
5090 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5091 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5093 if (iconRect.Width > 0)
5095 e.Graphics.FillRectangle(Brushes.White, iconRect);
5096 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5099 e.Graphics.DrawImage(img.Image, iconRect);
5101 catch (ArgumentException)
5103 item.RefreshImageAsync();
5109 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5110 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5112 item.GetImageAsync();
5115 if (item.StateIndex > -1)
5117 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5118 if (stateRect.Width > 0)
5120 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5121 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5122 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5127 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5129 base.ScaleControl(factor, specified);
5131 ScaleChildControl(this.TabImage, factor);
5133 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5134 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5136 foreach (var listview in listviews)
5138 ScaleChildControl(listview, factor);
5142 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5144 // ImageListViewItem item = (ImageListViewItem)e.Item;
5145 // if (item.StateImageIndex > -1)
5147 // ////e.Bounds.Leftが常に0を指すから自前で計算
5148 // //Rectangle itemRect = item.Bounds;
5149 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5151 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5153 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5155 // // itemRect.X += clm.Width;
5159 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5160 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5162 // if (rct.Width > 0)
5164 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5165 // //e.Graphics.FillRectangle(Brushes.White, rct);
5166 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5167 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5172 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5174 var tab = this.CurrentTab;
5176 if (tab.AllCount == 0)
5178 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5182 var selectedIndex = tab.SelectedIndex;
5187 case SEARCHTYPE.NextSearch: // 次を検索
5188 if (selectedIndex != -1)
5189 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5193 case SEARCHTYPE.PrevSearch: // 前を検索
5194 if (selectedIndex != -1)
5195 startIndex = Math.Max(selectedIndex - 1, 0);
5197 startIndex = tab.AllCount - 1;
5199 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5201 if (selectedIndex != -1)
5202 startIndex = selectedIndex;
5208 Func<string, bool> stringComparer;
5211 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5213 catch (ArgumentException)
5215 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5219 var reverse = searchType == SEARCHTYPE.PrevSearch;
5220 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5221 .DefaultIfEmpty(-1).First();
5223 if (foundIndex == -1)
5225 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5229 var listView = this.CurrentListView;
5230 this.SelectListItem(listView, foundIndex);
5231 listView.EnsureVisible(foundIndex);
5234 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5235 => this.ShowSearchDialog(); // 検索メニュー
5237 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5239 var previousSearch = this.SearchDialog.ResultOptions;
5240 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5242 this.SearchDialog.Reset();
5243 this.ShowSearchDialog();
5249 previousSearch.Query,
5250 previousSearch.CaseSensitive,
5251 previousSearch.UseRegex,
5252 SEARCHTYPE.NextSearch);
5255 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5257 var previousSearch = this.SearchDialog.ResultOptions;
5258 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5260 this.SearchDialog.Reset();
5261 this.ShowSearchDialog();
5267 previousSearch.Query,
5268 previousSearch.CaseSensitive,
5269 previousSearch.UseRegex,
5270 SEARCHTYPE.PrevSearch);
5274 /// 検索ダイアログを表示し、検索を実行します
5276 private void ShowSearchDialog()
5278 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5280 this.TopMost = SettingManager.Common.AlwaysTop;
5283 this.TopMost = SettingManager.Common.AlwaysTop;
5285 var searchOptions = this.SearchDialog.ResultOptions;
5286 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5288 if (searchOptions.NewTab)
5290 var tabName = Properties.Resources.SearchResults_TabName;
5294 tabName = this._statuses.MakeTabName(tabName);
5296 catch (TabException ex)
5298 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5301 var resultTab = new LocalSearchTabModel(tabName);
5302 this.AddNewTab(resultTab, startup: false);
5303 this._statuses.AddTab(resultTab);
5305 var targetTab = this.CurrentTab;
5307 Func<string, bool> stringComparer;
5310 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5312 catch (ArgumentException)
5314 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5318 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5319 if (foundIndices.Length == 0)
5321 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5325 var foundPosts = foundIndices.Select(x => targetTab[x]);
5326 foreach (var post in foundPosts)
5328 resultTab.AddPostQueue(post);
5331 this._statuses.DistributePosts();
5332 this.RefreshTimeline();
5334 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5335 this.ListTab.SelectedIndex = tabIndex;
5340 searchOptions.Query,
5341 searchOptions.CaseSensitive,
5342 searchOptions.UseRegex,
5343 SEARCHTYPE.DialogSearch);
5346 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5348 this.AddNewTabForSearch(searchOptions.Query);
5352 /// <summary>発言検索に使用するメソッドを生成します</summary>
5353 /// <exception cref="ArgumentException">
5354 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5356 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5360 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5361 var regex = new Regex(query, regexOption);
5363 return x => regex.IsMatch(x);
5367 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5369 return x => x.IndexOf(query, comparisonType) != -1;
5373 private void AboutMenuItem_Click(object sender, EventArgs e)
5375 using (TweenAboutBox about = new TweenAboutBox())
5377 about.ShowDialog(this);
5379 this.TopMost = SettingManager.Common.AlwaysTop;
5382 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5384 var bgnIdx = this._statuses.SelectedTabIndex;
5386 if (ImageSelector.Enabled)
5389 TabModel foundTab = null;
5392 DetailsListView lst = null;
5395 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5397 var unreadIndex = tab.NextUnreadIndex;
5398 if (unreadIndex != -1)
5400 ListTab.SelectedIndex = index;
5402 foundIndex = unreadIndex;
5403 lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5408 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5409 if (foundTab == null && bgnIdx > 0)
5411 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5413 var unreadIndex = tab.NextUnreadIndex;
5414 if (unreadIndex != -1)
5416 ListTab.SelectedIndex = index;
5418 foundIndex = unreadIndex;
5419 lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5425 if (foundTab == null)
5427 //全部調べたが未読見つからず→先頭タブの最新発言へ
5428 ListTab.SelectedIndex = 0;
5429 var tabPage = this.ListTab.TabPages[0];
5430 var tab = this._statuses.Tabs[0];
5432 if (tab.AllCount == 0)
5435 if (_statuses.SortOrder == SortOrder.Ascending)
5436 foundIndex = tab.AllCount - 1;
5440 lst = (DetailsListView)tabPage.Tag;
5443 SelectListItem(lst, foundIndex);
5445 if (_statuses.SortMode == ComparerMode.Id)
5447 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5448 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5454 lst.EnsureVisible(foundIndex);
5459 lst.EnsureVisible(foundIndex);
5465 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5467 var tab = this.CurrentTab;
5468 var post = this.CurrentPost;
5469 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5470 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5473 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5474 => await this.CheckNewVersion(false);
5476 private void RunTweenUp()
5478 var pinfo = new ProcessStartInfo
5480 UseShellExecute = true,
5481 WorkingDirectory = MyCommon.settingPath,
5482 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5483 Arguments = "\"" + Application.StartupPath + "\"",
5488 Process.Start(pinfo);
5492 MessageBox.Show("Failed to execute TweenUp3.exe.");
5496 public class VersionInfo
5498 public Version Version { get; set; }
5499 public Uri DownloadUri { get; set; }
5500 public string ReleaseNote { get; set; }
5504 /// OpenTween の最新バージョンの情報を取得します
5506 public async Task<VersionInfo> GetVersionInfoAsync()
5508 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5509 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5511 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5512 .ConfigureAwait(false);
5514 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5515 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5517 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5518 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5520 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5522 return new VersionInfo
5524 Version = Version.Parse(msgHeader[0]),
5525 DownloadUri = new Uri(msgHeader[1]),
5526 ReleaseNote = msgBody,
5530 private async Task CheckNewVersion(bool startup = false)
5532 if (ApplicationSettings.VersionInfoUrl == null)
5533 return; // 更新チェック無効化
5537 var versionInfo = await this.GetVersionInfoAsync();
5539 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5544 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5545 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5546 msgtext = MyCommon.ReplaceAppName(msgtext);
5548 MessageBox.Show(msgtext,
5549 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5550 MessageBoxButtons.OK, MessageBoxIcon.Information);
5555 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5558 using (var dialog = new UpdateDialog())
5560 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5561 MyCommon.GetReadableVersion(versionInfo.Version));
5562 dialog.DetailsText = versionInfo.ReleaseNote;
5564 if (dialog.ShowDialog(this) == DialogResult.Yes)
5566 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5568 else if (dialog.SkipButtonPressed)
5570 SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5571 this.ModifySettingCommon = true;
5577 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5580 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5581 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5582 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5587 private async Task Colorize()
5590 await this.DispSelectedPost();
5591 //件数関連の場合、タイトル即時書き換え
5592 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5593 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5594 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5595 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5597 SetMainWindowTitle();
5599 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5600 SetStatusLabelUrl();
5602 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5604 if (tab.UnreadCount == 0)
5606 if (SettingManager.Common.TabIconDisp)
5608 var tabPage = this.ListTab.TabPages[index];
5609 if (tabPage.ImageIndex == 0)
5610 tabPage.ImageIndex = -1;
5614 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5617 public string createDetailHtml(string orgdata)
5618 => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5620 private Task DispSelectedPost()
5621 => this.DispSelectedPost(false);
5623 private PostClass displayPost = new PostClass();
5626 /// サムネイル表示に使用する CancellationToken の生成元
5628 private CancellationTokenSource thumbnailTokenSource = null;
5630 private async Task DispSelectedPost(bool forceupdate)
5632 var currentPost = this.CurrentPost;
5633 if (currentPost == null)
5636 var oldDisplayPost = this.displayPost;
5637 this.displayPost = currentPost;
5639 if (!forceupdate && currentPost.Equals(oldDisplayPost))
5642 var loadTasks = new List<Task>
5644 this.tweetDetailsView.ShowPostDetails(currentPost),
5647 this.SplitContainer3.Panel2Collapsed = true;
5649 if (SettingManager.Common.PreviewEnable)
5651 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5652 oldTokenSource?.Cancel();
5654 var token = this.thumbnailTokenSource.Token;
5655 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5660 await Task.WhenAll(loadTasks);
5662 catch (OperationCanceledException) { }
5665 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5666 => await this.OpenApplicationWebsite();
5668 private async Task OpenApplicationWebsite()
5669 => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5671 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5672 => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5674 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5676 var tab = this.CurrentTab;
5677 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5679 Control pnl = this.CurrentTabPage.Controls["panelSearch"];
5680 if (pnl.Controls["comboSearch"].Focused ||
5681 pnl.Controls["comboLang"].Focused ||
5682 pnl.Controls["buttonSearch"].Focused) return;
5685 if (e.Control || e.Shift || e.Alt)
5686 this._anchorFlag = false;
5688 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5691 e.SuppressKeyPress = true;
5694 if (asyncTask != null)
5698 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5700 private void InitializeShortcuts()
5702 this.shortcutCommands = new[]
5704 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5705 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5706 .FocusedOn(FocusedControl.ListTab)
5707 .Do(() => SendKeys.Send("{DOWN}")),
5709 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5710 .FocusedOn(FocusedControl.ListTab)
5711 .Do(() => SendKeys.Send("{UP}")),
5713 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5714 .FocusedOn(FocusedControl.ListTab)
5715 .Do(() => SendKeys.Send("{PGDN}")),
5717 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5718 .FocusedOn(FocusedControl.ListTab)
5719 .Do(() => SendKeys.Send("{PGUP}")),
5721 ShortcutCommand.Create(Keys.F1)
5722 .Do(() => this.OpenApplicationWebsite()),
5724 ShortcutCommand.Create(Keys.F3)
5725 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5727 ShortcutCommand.Create(Keys.F5)
5728 .Do(() => this.DoRefresh()),
5730 ShortcutCommand.Create(Keys.F6)
5731 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5733 ShortcutCommand.Create(Keys.F7)
5734 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5736 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5737 .NotFocusedOn(FocusedControl.StatusText)
5738 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5740 ShortcutCommand.Create(Keys.G)
5741 .NotFocusedOn(FocusedControl.StatusText)
5742 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5744 ShortcutCommand.Create(Keys.Right, Keys.N)
5745 .FocusedOn(FocusedControl.ListTab)
5746 .Do(() => this.GoRelPost(forward: true)),
5748 ShortcutCommand.Create(Keys.Left, Keys.P)
5749 .FocusedOn(FocusedControl.ListTab)
5750 .Do(() => this.GoRelPost(forward: false)),
5752 ShortcutCommand.Create(Keys.OemPeriod)
5753 .FocusedOn(FocusedControl.ListTab)
5754 .Do(() => this.GoAnchor()),
5756 ShortcutCommand.Create(Keys.I)
5757 .FocusedOn(FocusedControl.ListTab)
5758 .OnlyWhen(() => this.StatusText.Enabled)
5759 .Do(() => this.StatusText.Focus()),
5761 ShortcutCommand.Create(Keys.Enter)
5762 .FocusedOn(FocusedControl.ListTab)
5763 .Do(() => this.MakeReplyOrDirectStatus()),
5765 ShortcutCommand.Create(Keys.R)
5766 .FocusedOn(FocusedControl.ListTab)
5767 .Do(() => this.DoRefresh()),
5769 ShortcutCommand.Create(Keys.L)
5770 .FocusedOn(FocusedControl.ListTab)
5771 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5773 ShortcutCommand.Create(Keys.H)
5774 .FocusedOn(FocusedControl.ListTab)
5775 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5777 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5778 .FocusedOn(FocusedControl.ListTab)
5779 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5781 ShortcutCommand.Create(Keys.S)
5782 .FocusedOn(FocusedControl.ListTab)
5783 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5785 ShortcutCommand.Create(Keys.A)
5786 .FocusedOn(FocusedControl.ListTab)
5787 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5789 // ] in_reply_to参照元へ戻る
5790 ShortcutCommand.Create(Keys.Oem4)
5791 .FocusedOn(FocusedControl.ListTab)
5792 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5794 // [ in_reply_toへジャンプ
5795 ShortcutCommand.Create(Keys.Oem6)
5796 .FocusedOn(FocusedControl.ListTab)
5797 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5799 ShortcutCommand.Create(Keys.Escape)
5800 .FocusedOn(FocusedControl.ListTab)
5802 this._anchorFlag = false;
5803 var tab = this.CurrentTab;
5804 var tabtype = tab.TabType;
5805 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5807 RemoveSpecifiedTab(tab.TabName, false);
5812 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5813 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5814 .FocusedOn(FocusedControl.ListTab)
5815 .Do(() => this._anchorFlag = false, preventDefault: false),
5817 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5818 ShortcutCommand.Create(Keys.Up, Keys.Down)
5819 .FocusedOn(FocusedControl.PostBrowser)
5822 ShortcutCommand.Create(Keys.Control | Keys.R)
5823 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5825 ShortcutCommand.Create(Keys.Control | Keys.D)
5826 .Do(() => this.doStatusDelete()),
5828 ShortcutCommand.Create(Keys.Control | Keys.M)
5829 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5831 ShortcutCommand.Create(Keys.Control | Keys.S)
5832 .Do(() => this.FavoriteChange(FavAdd: true)),
5834 ShortcutCommand.Create(Keys.Control | Keys.I)
5835 .Do(() => this.doRepliedStatusOpen()),
5837 ShortcutCommand.Create(Keys.Control | Keys.Q)
5838 .Do(() => this.doQuoteOfficial()),
5840 ShortcutCommand.Create(Keys.Control | Keys.B)
5841 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5843 ShortcutCommand.Create(Keys.Control | Keys.T)
5844 .Do(() => this.HashManageMenuItem_Click(null, null)),
5846 ShortcutCommand.Create(Keys.Control | Keys.L)
5847 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5849 ShortcutCommand.Create(Keys.Control | Keys.Y)
5850 .NotFocusedOn(FocusedControl.PostBrowser)
5851 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5853 ShortcutCommand.Create(Keys.Control | Keys.F)
5854 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5856 ShortcutCommand.Create(Keys.Control | Keys.U)
5857 .Do(() => this.ShowUserTimeline()),
5859 ShortcutCommand.Create(Keys.Control | Keys.H)
5860 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5862 ShortcutCommand.Create(Keys.Control | Keys.G)
5863 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5865 ShortcutCommand.Create(Keys.Control | Keys.O)
5866 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5868 ShortcutCommand.Create(Keys.Control | Keys.E)
5869 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5871 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5872 .FocusedOn(FocusedControl.ListTab)
5873 .Do(() => this._colorize = true, preventDefault: false),
5875 ShortcutCommand.Create(Keys.Control | Keys.N)
5876 .FocusedOn(FocusedControl.ListTab)
5877 .Do(() => this.GoNextTab(forward: true)),
5879 ShortcutCommand.Create(Keys.Control | Keys.P)
5880 .FocusedOn(FocusedControl.ListTab)
5881 .Do(() => this.GoNextTab(forward: false)),
5883 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5884 .FocusedOn(FocusedControl.ListTab)
5885 .Do(() => this.CopyStot()),
5887 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5888 ShortcutCommand.Create(Keys.Control | Keys.D1)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5891 .Do(() => this.ListTab.SelectedIndex = 0),
5893 ShortcutCommand.Create(Keys.Control | Keys.D2)
5894 .FocusedOn(FocusedControl.ListTab)
5895 .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5896 .Do(() => this.ListTab.SelectedIndex = 1),
5898 ShortcutCommand.Create(Keys.Control | Keys.D3)
5899 .FocusedOn(FocusedControl.ListTab)
5900 .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5901 .Do(() => this.ListTab.SelectedIndex = 2),
5903 ShortcutCommand.Create(Keys.Control | Keys.D4)
5904 .FocusedOn(FocusedControl.ListTab)
5905 .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5906 .Do(() => this.ListTab.SelectedIndex = 3),
5908 ShortcutCommand.Create(Keys.Control | Keys.D5)
5909 .FocusedOn(FocusedControl.ListTab)
5910 .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5911 .Do(() => this.ListTab.SelectedIndex = 4),
5913 ShortcutCommand.Create(Keys.Control | Keys.D6)
5914 .FocusedOn(FocusedControl.ListTab)
5915 .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5916 .Do(() => this.ListTab.SelectedIndex = 5),
5918 ShortcutCommand.Create(Keys.Control | Keys.D7)
5919 .FocusedOn(FocusedControl.ListTab)
5920 .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
5921 .Do(() => this.ListTab.SelectedIndex = 6),
5923 ShortcutCommand.Create(Keys.Control | Keys.D8)
5924 .FocusedOn(FocusedControl.ListTab)
5925 .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
5926 .Do(() => this.ListTab.SelectedIndex = 7),
5928 ShortcutCommand.Create(Keys.Control | Keys.D9)
5929 .FocusedOn(FocusedControl.ListTab)
5930 .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
5932 ShortcutCommand.Create(Keys.Control | Keys.A)
5933 .FocusedOn(FocusedControl.StatusText)
5934 .Do(() => this.StatusText.SelectAll()),
5936 ShortcutCommand.Create(Keys.Control | Keys.V)
5937 .FocusedOn(FocusedControl.StatusText)
5938 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
5940 ShortcutCommand.Create(Keys.Control | Keys.Up)
5941 .FocusedOn(FocusedControl.StatusText)
5942 .Do(() => this.StatusTextHistoryBack()),
5944 ShortcutCommand.Create(Keys.Control | Keys.Down)
5945 .FocusedOn(FocusedControl.StatusText)
5946 .Do(() => this.StatusTextHistoryForward()),
5948 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
5949 .FocusedOn(FocusedControl.StatusText)
5951 if (ListTab.SelectedIndex == 0)
5953 ListTab.SelectedIndex = ListTab.TabCount - 1;
5957 ListTab.SelectedIndex -= 1;
5962 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
5963 .FocusedOn(FocusedControl.StatusText)
5965 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
5967 ListTab.SelectedIndex = 0;
5971 ListTab.SelectedIndex += 1;
5976 ShortcutCommand.Create(Keys.Control | Keys.Y)
5977 .FocusedOn(FocusedControl.PostBrowser)
5979 var multiline = !SettingManager.Local.StatusMultiline;
5980 SettingManager.Local.StatusMultiline = multiline;
5981 MultiLineMenuItem.Checked = multiline;
5982 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
5985 ShortcutCommand.Create(Keys.Shift | Keys.F3)
5986 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
5988 ShortcutCommand.Create(Keys.Shift | Keys.F5)
5989 .Do(() => this.DoRefreshMore()),
5991 ShortcutCommand.Create(Keys.Shift | Keys.F6)
5992 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
5994 ShortcutCommand.Create(Keys.Shift | Keys.F7)
5995 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
5997 ShortcutCommand.Create(Keys.Shift | Keys.R)
5998 .NotFocusedOn(FocusedControl.StatusText)
5999 .Do(() => this.DoRefreshMore()),
6001 ShortcutCommand.Create(Keys.Shift | Keys.H)
6002 .FocusedOn(FocusedControl.ListTab)
6003 .Do(() => this.GoTopEnd(GoTop: true)),
6005 ShortcutCommand.Create(Keys.Shift | Keys.L)
6006 .FocusedOn(FocusedControl.ListTab)
6007 .Do(() => this.GoTopEnd(GoTop: false)),
6009 ShortcutCommand.Create(Keys.Shift | Keys.M)
6010 .FocusedOn(FocusedControl.ListTab)
6011 .Do(() => this.GoMiddle()),
6013 ShortcutCommand.Create(Keys.Shift | Keys.G)
6014 .FocusedOn(FocusedControl.ListTab)
6015 .Do(() => this.GoLast()),
6017 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6018 .FocusedOn(FocusedControl.ListTab)
6019 .Do(() => this.MoveMiddle()),
6021 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6022 .FocusedOn(FocusedControl.ListTab)
6023 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6025 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6026 .FocusedOn(FocusedControl.ListTab)
6027 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6029 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6030 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6031 .FocusedOn(FocusedControl.ListTab)
6032 .Do(() => this.GoFav(forward: true)),
6034 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6035 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6036 .FocusedOn(FocusedControl.ListTab)
6037 .Do(() => this.GoFav(forward: false)),
6039 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6040 .FocusedOn(FocusedControl.ListTab)
6041 .Do(() => this.GoBackSelectPostChain()),
6043 ShortcutCommand.Create(Keys.Alt | Keys.R)
6044 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6046 ShortcutCommand.Create(Keys.Alt | Keys.P)
6047 .OnlyWhen(() => this.CurrentPost != null)
6048 .Do(() => this.doShowUserStatus(this.CurrentPost.ScreenName, ShowInputDialog: false)),
6050 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6051 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6053 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6054 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6056 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6057 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6059 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6060 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6062 // 別タブの同じ書き込みへ(ALT+←/→)
6063 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6064 .FocusedOn(FocusedControl.ListTab)
6065 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6067 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6068 .FocusedOn(FocusedControl.ListTab)
6069 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6071 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6072 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6074 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6075 .Do(() => this.CopyIdUri()),
6077 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6078 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6079 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6081 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6082 .Do(() => this.FavoriteChange(FavAdd: false)),
6084 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6085 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6087 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6088 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6090 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6091 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6093 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6094 .Do(() => this.doMoveToRTHome()),
6096 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6097 .FocusedOn(FocusedControl.StatusText)
6099 var tab = this.CurrentTab;
6100 var selectedIndex = tab.SelectedIndex;
6101 if (selectedIndex != -1 && selectedIndex > 0)
6103 var listView = this.CurrentListView;
6104 var idx = selectedIndex - 1;
6105 SelectListItem(listView, idx);
6106 listView.EnsureVisible(idx);
6110 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6111 .FocusedOn(FocusedControl.StatusText)
6113 var tab = this.CurrentTab;
6114 var selectedIndex = tab.SelectedIndex;
6115 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6117 var listView = this.CurrentListView;
6118 var idx = selectedIndex + 1;
6119 SelectListItem(listView, idx);
6120 listView.EnsureVisible(idx);
6124 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6125 .FocusedOn(FocusedControl.StatusText)
6127 if (StatusText.SelectionStart > 0)
6129 int endidx = StatusText.SelectionStart - 1;
6130 string startstr = "";
6131 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6133 char c = StatusText.Text[i];
6134 if (Char.IsLetterOrDigit(c) || c == '_')
6140 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6141 int cnt = AtIdSupl.ItemCount;
6142 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6143 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6147 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6148 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6158 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6159 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6160 .FocusedOn(FocusedControl.ListTab)
6161 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6163 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6164 .FocusedOn(FocusedControl.ListTab)
6165 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6167 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6168 .FocusedOn(FocusedControl.ListTab)
6169 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6171 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6172 .FocusedOn(FocusedControl.ListTab)
6173 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6175 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6176 .FocusedOn(FocusedControl.ListTab)
6177 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6179 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6180 .FocusedOn(FocusedControl.ListTab)
6181 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6183 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6184 .FocusedOn(FocusedControl.ListTab)
6185 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6187 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6188 .FocusedOn(FocusedControl.ListTab)
6189 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6191 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6192 .FocusedOn(FocusedControl.ListTab)
6193 .Do(() => this.SetSortLastColumn()),
6195 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6196 .FocusedOn(FocusedControl.ListTab)
6197 .Do(() => this.FavoritesRetweetOfficial()),
6199 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6200 .FocusedOn(FocusedControl.ListTab)
6201 .Do(() => this.FavoritesRetweetUnofficial()),
6203 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6204 .FocusedOn(FocusedControl.ListTab)
6205 .Do(() => this.OpenUserAppointUrl()),
6207 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6208 .FocusedOn(FocusedControl.PostBrowser)
6209 .Do(() => this.doReTweetUnofficial()),
6211 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6212 .OnlyWhen(() => this.ExistCurrentPost)
6213 .Do(() => this.tweetDetailsView.DoTranslation()),
6215 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6216 .Do(() => this.doReTweetUnofficial()),
6218 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6219 .Do(() => this.CopyUserId()),
6221 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6222 .Do(() => this.tweetThumbnail1.ScrollUp()),
6224 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6225 .Do(() => this.tweetThumbnail1.ScrollDown()),
6227 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6228 .FocusedOn(FocusedControl.ListTab)
6229 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6230 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6234 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6236 // Task を返す非同期処理があれば asyncTask に代入する
6239 // ShortcutCommand に対応しているコマンドはここで処理される
6240 foreach (var command in this.shortcutCommands)
6242 if (command.IsMatch(keyData, focusedOn))
6244 asyncTask = command.RunCommand();
6245 return command.PreventDefault;
6252 private void GoNextTab(bool forward)
6254 int idx = this._statuses.SelectedTabIndex;
6255 var tabCount = this._statuses.Tabs.Count;
6259 if (idx > tabCount - 1) idx = 0;
6264 if (idx < 0) idx = tabCount - 1;
6266 ListTab.SelectedIndex = idx;
6269 private void CopyStot()
6272 StringBuilder sb = new StringBuilder();
6273 var tab = this.CurrentTab;
6274 bool IsProtected = false;
6275 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6276 foreach (var post in tab.SelectedPosts)
6278 if (post.IsDeleted) continue;
6281 if (post.RetweetedId != null)
6282 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6284 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6288 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6293 MessageBox.Show(Properties.Resources.CopyStotText1);
6297 clstr = sb.ToString();
6300 Clipboard.SetDataObject(clstr, false, 5, 100);
6302 catch (Exception ex)
6304 MessageBox.Show(ex.Message);
6309 private void CopyIdUri()
6311 var tab = this.CurrentTab;
6312 if (tab == null || tab is DirectMessagesTabModel)
6315 var copyUrls = new List<string>();
6316 foreach (var post in tab.SelectedPosts)
6317 copyUrls.Add(MyCommon.GetStatusUrl(post));
6319 if (copyUrls.Count == 0)
6324 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6326 catch (ExternalException ex)
6328 MessageBox.Show(ex.Message);
6332 private void GoFav(bool forward)
6334 var tab = this.CurrentTab;
6335 if (tab.AllCount == 0)
6338 var selectedIndex = tab.SelectedIndex;
6346 if (selectedIndex == -1)
6352 fIdx = selectedIndex + 1;
6353 if (fIdx > tab.AllCount - 1) return;
6355 toIdx = tab.AllCount;
6360 if (selectedIndex == -1)
6362 fIdx = tab.AllCount - 1;
6366 fIdx = selectedIndex - 1;
6367 if (fIdx < 0) return;
6373 for (int idx = fIdx; idx != toIdx; idx += stp)
6377 var listView = this.CurrentListView;
6378 SelectListItem(listView, idx);
6379 listView.EnsureVisible(idx);
6385 private void GoSamePostToAnotherTab(bool left)
6387 var tab = this.CurrentTab;
6389 // Directタブは対象外(見つかるはずがない)
6390 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6393 var selectedStatusId = tab.SelectedStatusId;
6394 if (selectedStatusId == -1)
6397 int fIdx, toIdx, stp;
6402 if (ListTab.SelectedIndex == 0)
6408 fIdx = ListTab.SelectedIndex - 1;
6416 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6422 fIdx = ListTab.SelectedIndex + 1;
6424 toIdx = ListTab.TabCount;
6428 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6430 var targetTab = this._statuses.Tabs[tabidx];
6433 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6436 var foundIndex = targetTab.IndexOf(selectedStatusId);
6437 if (foundIndex != -1)
6439 ListTab.SelectedIndex = tabidx;
6440 var listView = this.CurrentListView;
6441 SelectListItem(listView, foundIndex);
6442 listView.EnsureVisible(foundIndex);
6448 private void GoPost(bool forward)
6450 var tab = this.CurrentTab;
6451 var currentPost = this.CurrentPost;
6453 if (currentPost == null)
6456 var selectedIndex = tab.SelectedIndex;
6458 int fIdx, toIdx, stp;
6462 fIdx = selectedIndex + 1;
6463 if (fIdx > tab.AllCount - 1) return;
6464 toIdx = tab.AllCount;
6469 fIdx = selectedIndex - 1;
6470 if (fIdx < 0) return;
6476 if (currentPost.RetweetedId == null)
6478 name = currentPost.ScreenName;
6482 name = currentPost.RetweetedBy;
6484 for (int idx = fIdx; idx != toIdx; idx += stp)
6486 var post = tab[idx];
6487 if (post.RetweetedId == null)
6489 if (post.ScreenName == name)
6491 var listView = this.CurrentListView;
6492 SelectListItem(listView, idx);
6493 listView.EnsureVisible(idx);
6499 if (post.RetweetedBy == name)
6501 var listView = this.CurrentListView;
6502 SelectListItem(listView, idx);
6503 listView.EnsureVisible(idx);
6510 private void GoRelPost(bool forward)
6512 var tab = this.CurrentTab;
6513 var selectedIndex = tab.SelectedIndex;
6515 if (selectedIndex == -1)
6518 int fIdx, toIdx, stp;
6522 fIdx = selectedIndex + 1;
6523 if (fIdx > tab.AllCount - 1) return;
6524 toIdx = tab.AllCount;
6529 fIdx = selectedIndex - 1;
6530 if (fIdx < 0) return;
6537 var currentPost = this.CurrentPost;
6538 if (currentPost == null) return;
6539 _anchorPost = currentPost;
6544 if (_anchorPost == null) return;
6547 for (int idx = fIdx; idx != toIdx; idx += stp)
6549 var post = tab[idx];
6550 if (post.ScreenName == _anchorPost.ScreenName ||
6551 post.RetweetedBy == _anchorPost.ScreenName ||
6552 post.ScreenName == _anchorPost.RetweetedBy ||
6553 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6554 _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6555 _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6556 post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6557 post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6559 var listView = this.CurrentListView;
6560 SelectListItem(listView, idx);
6561 listView.EnsureVisible(idx);
6567 private void GoAnchor()
6569 if (_anchorPost == null) return;
6570 int idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6571 if (idx == -1) return;
6573 var listView = this.CurrentListView;
6574 SelectListItem(listView, idx);
6575 listView.EnsureVisible(idx);
6578 private void GoTopEnd(bool GoTop)
6580 var listView = this.CurrentListView;
6581 if (listView.VirtualListSize == 0)
6589 _item = listView.GetItemAt(0, 25);
6597 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6599 idx = listView.VirtualListSize - 1;
6603 SelectListItem(listView, idx);
6606 private void GoMiddle()
6608 var listView = this.CurrentListView;
6609 if (listView.VirtualListSize == 0)
6617 _item = listView.GetItemAt(0, 0);
6627 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6630 idx2 = listView.VirtualListSize - 1;
6636 idx3 = (idx1 + idx2) / 2;
6638 SelectListItem(listView, idx3);
6641 private void GoLast()
6643 var listView = this.CurrentListView;
6644 if (listView.VirtualListSize == 0) return;
6646 if (_statuses.SortOrder == SortOrder.Ascending)
6648 SelectListItem(listView, listView.VirtualListSize - 1);
6649 listView.EnsureVisible(listView.VirtualListSize - 1);
6653 SelectListItem(listView, 0);
6654 listView.EnsureVisible(0);
6658 private void MoveTop()
6660 var listView = this.CurrentListView;
6661 if (listView.SelectedIndices.Count == 0) return;
6662 int idx = listView.SelectedIndices[0];
6663 if (_statuses.SortOrder == SortOrder.Ascending)
6665 listView.EnsureVisible(listView.VirtualListSize - 1);
6669 listView.EnsureVisible(0);
6671 listView.EnsureVisible(idx);
6674 private async Task GoInReplyToPostTree()
6676 var curTabClass = this.CurrentTab;
6677 var currentPost = this.CurrentPost;
6679 if (currentPost == null)
6682 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6686 var post = await tw.GetStatusApi(false, currentPost.StatusId);
6688 currentPost.InReplyToStatusId = post.InReplyToStatusId;
6689 currentPost.InReplyToUser = post.InReplyToUser;
6690 currentPost.IsReply = post.IsReply;
6691 this.PurgeListViewItemCache();
6693 var index = curTabClass.SelectedIndex;
6694 this.CurrentListView.RedrawItems(index, index, false);
6696 catch (WebApiException ex)
6698 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6702 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6704 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6706 replyChains = new Stack<ReplyChain>();
6708 replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6711 string inReplyToTabName;
6712 var inReplyToId = currentPost.InReplyToStatusId.Value;
6713 var inReplyToUser = currentPost.InReplyToUser;
6715 var inReplyToPosts = from tab in _statuses.Tabs
6716 orderby tab != curTabClass
6717 from post in tab.Posts.Values
6718 where post.StatusId == inReplyToId
6719 let index = tab.IndexOf(post.StatusId)
6721 select new {Tab = tab, Index = index};
6723 var inReplyPost = inReplyToPosts.FirstOrDefault();
6724 if (inReplyPost == null)
6728 await Task.Run(async () =>
6730 var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6731 .ConfigureAwait(false);
6734 _statuses.AddPost(post);
6735 _statuses.DistributePosts();
6738 catch (WebApiException ex)
6740 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6741 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6745 this.RefreshTimeline();
6747 inReplyPost = inReplyToPosts.FirstOrDefault();
6748 if (inReplyPost == null)
6750 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6754 inReplyToTabName = inReplyPost.Tab.TabName;
6755 inReplyToIndex = inReplyPost.Index;
6757 var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6758 var tabPage = this.ListTab.TabPages[tabIndex];
6759 DetailsListView listView = (DetailsListView)tabPage.Tag;
6761 if (this.CurrentTabName != inReplyToTabName)
6763 this.ListTab.SelectedIndex = tabIndex;
6766 this.SelectListItem(listView, inReplyToIndex);
6767 listView.EnsureVisible(inReplyToIndex);
6770 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6772 var curTabClass = this.CurrentTab;
6773 var currentPost = this.CurrentPost;
6775 if (currentPost == null)
6780 if (currentPost.InReplyToStatusId != null)
6782 var posts = from t in _statuses.Tabs
6784 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6785 let indexOf = t.IndexOf(p.Value.StatusId)
6787 orderby isForward ? indexOf : indexOf * -1
6788 orderby t != curTabClass
6789 select new {Tab = t, Post = p.Value, Index = indexOf};
6792 var postList = posts.ToList();
6793 for (int i = postList.Count - 1; i >= 0; i--)
6796 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6798 postList.RemoveAt(index);
6801 var currentIndex = this.CurrentTab.SelectedIndex;
6802 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex; });
6803 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6804 if (post == null) post = postList.First();
6805 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6806 this.ListTab.SelectedIndex = tabIndex;
6807 var listView = this.CurrentListView;
6808 SelectListItem(listView, post.Index);
6809 listView.EnsureVisible(post.Index);
6811 catch (InvalidOperationException)
6819 if (replyChains == null || replyChains.Count < 1)
6821 var posts = from t in _statuses.Tabs
6823 where p.Value.InReplyToStatusId == currentPost.StatusId
6824 let indexOf = t.IndexOf(p.Value.StatusId)
6827 orderby t != curTabClass
6828 select new {Tab = t, Index = indexOf};
6831 var post = posts.First();
6832 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6833 this.ListTab.SelectedIndex = tabIndex;
6834 var listView = this.CurrentListView;
6835 SelectListItem(listView, post.Index);
6836 listView.EnsureVisible(post.Index);
6838 catch (InvalidOperationException)
6845 ReplyChain chainHead = replyChains.Pop();
6846 if (chainHead.InReplyToId == currentPost.StatusId)
6848 var tab = chainHead.OriginalTab;
6849 if (!this._statuses.Tabs.Contains(tab))
6855 var idx = tab.IndexOf(chainHead.OriginalId);
6862 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6865 this.ListTab.SelectedIndex = tabIndex;
6871 var listView = this.CurrentListView;
6872 SelectListItem(listView, idx);
6873 listView.EnsureVisible(idx);
6880 this.GoBackInReplyToPostTree(parallel);
6886 private void GoBackSelectPostChain()
6888 if (this.selectPostChains.Count > 1)
6891 TabModel foundTab = null;
6897 this.selectPostChains.Pop();
6898 var (tab, post) = this.selectPostChains.Peek();
6900 if (!this._statuses.Tabs.Contains(tab))
6901 continue; // 該当タブが存在しないので無視
6905 idx = tab.IndexOf(post.StatusId);
6906 if (idx == -1) continue; //該当ポストが存在しないので無視
6911 this.selectPostChains.Pop();
6913 catch (InvalidOperationException)
6919 while (this.selectPostChains.Count > 1);
6921 if (foundTab == null)
6924 //履歴が残り1つであればクリアしておく
6925 if (this.selectPostChains.Count == 1)
6926 this.selectPostChains.Clear();
6930 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
6931 var tabPage = this.ListTab.TabPages[tabIndex];
6932 var lst = (DetailsListView)tabPage.Tag;
6933 this.ListTab.SelectedIndex = tabIndex;
6937 SelectListItem(lst, idx);
6938 lst.EnsureVisible(idx);
6944 private void PushSelectPostChain()
6946 var currentTab = this.CurrentTab;
6947 var currentPost = this.CurrentPost;
6949 int count = this.selectPostChains.Count;
6952 var (tab, post) = this.selectPostChains.Peek();
6953 if (tab == currentTab)
6955 if (post == currentPost) return; //最新の履歴と同一
6956 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
6959 if (count >= 2500) TrimPostChain();
6960 this.selectPostChains.Push((currentTab, currentPost));
6963 private void TrimPostChain()
6965 if (this.selectPostChains.Count <= 2000) return;
6966 var p = new Stack<(TabModel, PostClass)>(2000);
6967 for (int i = 0; i < 2000; i++)
6969 p.Push(this.selectPostChains.Pop());
6971 this.selectPostChains.Clear();
6972 for (int i = 0; i < 2000; i++)
6974 this.selectPostChains.Push(p.Pop());
6978 private bool GoStatus(long statusId)
6980 if (statusId == 0) return false;
6982 var tab = this._statuses.Tabs
6983 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
6984 .Where(x => x.Contains(statusId))
6990 var index = tab.IndexOf(statusId);
6992 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6993 this.ListTab.SelectedIndex = tabIndex;
6995 var listView = this.CurrentListView;
6996 this.SelectListItem(listView, index);
6997 listView.EnsureVisible(index);
7002 private bool GoDirectMessage(long statusId)
7004 if (statusId == 0) return false;
7006 var tab = this._statuses.GetTabByType<DirectMessagesTabModel>();
7007 var index = tab.IndexOf(statusId);
7012 var tabIndex = this._statuses.Tabs.IndexOf(tab);
7013 this.ListTab.SelectedIndex = tabIndex;
7015 var listView = this.CurrentListView;
7016 this.SelectListItem(listView, index);
7017 listView.EnsureVisible(index);
7022 private void MyList_MouseClick(object sender, MouseEventArgs e)
7023 => this._anchorFlag = false;
7025 private void StatusText_Enter(object sender, EventArgs e)
7027 // フォーカスの戻り先を StatusText に設定
7028 this.Tag = StatusText;
7029 StatusText.BackColor = _clInputBackcolor;
7032 public Color InputBackColor
7034 get => _clInputBackcolor;
7035 set => _clInputBackcolor = value;
7038 private void StatusText_Leave(object sender, EventArgs e)
7040 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7041 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7042 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7045 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7047 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7050 e.SuppressKeyPress = true;
7053 this.StatusText_TextChanged(null, null);
7055 if (asyncTask != null)
7059 private void SaveConfigsAll(bool ifModified)
7063 SaveConfigsCommon();
7070 if (ModifySettingCommon) SaveConfigsCommon();
7071 if (ModifySettingLocal) SaveConfigsLocal();
7072 if (ModifySettingAtId) SaveConfigsAtId();
7076 private void SaveConfigsAtId()
7078 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7080 ModifySettingAtId = false;
7081 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7082 SettingManager.SaveAtIdList();
7085 private void SaveConfigsCommon()
7087 if (_ignoreConfigSave) return;
7089 ModifySettingCommon = false;
7092 SettingManager.Common.UserName = tw.Username;
7093 SettingManager.Common.UserId = tw.UserId;
7094 SettingManager.Common.Token = tw.AccessToken;
7095 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7096 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7097 switch (_statuses.SortMode)
7099 case ComparerMode.Nickname: //ニックネーム
7100 SettingManager.Common.SortColumn = 1;
7102 case ComparerMode.Data: //本文
7103 SettingManager.Common.SortColumn = 2;
7105 case ComparerMode.Id: //時刻=発言Id
7106 SettingManager.Common.SortColumn = 3;
7108 case ComparerMode.Name: //名前
7109 SettingManager.Common.SortColumn = 4;
7111 case ComparerMode.Source: //Source
7112 SettingManager.Common.SortColumn = 7;
7116 SettingManager.Common.HashTags = HashMgr.HashHistories;
7117 if (HashMgr.IsPermanent)
7119 SettingManager.Common.HashSelected = HashMgr.UseHash;
7123 SettingManager.Common.HashSelected = "";
7125 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7126 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7127 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7128 SettingManager.Common.TrackWord = tw.TrackWord;
7129 SettingManager.Common.AllAtReply = tw.AllAtReply;
7130 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7131 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7133 SettingManager.SaveCommon();
7137 private void SaveConfigsLocal()
7139 if (_ignoreConfigSave) return;
7142 ModifySettingLocal = false;
7143 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7144 SettingManager.Local.FormSize = _mySize;
7145 SettingManager.Local.FormLocation = _myLoc;
7146 SettingManager.Local.SplitterDistance = _mySpDis;
7147 SettingManager.Local.PreviewDistance = _mySpDis3;
7148 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7149 SettingManager.Local.StatusTextHeight = _mySpDis2;
7151 SettingManager.Local.FontUnread = _fntUnread;
7152 SettingManager.Local.ColorUnread = _clUnread;
7153 SettingManager.Local.FontRead = _fntReaded;
7154 SettingManager.Local.ColorRead = _clReaded;
7155 SettingManager.Local.FontDetail = _fntDetail;
7156 SettingManager.Local.ColorDetail = _clDetail;
7157 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7158 SettingManager.Local.ColorDetailLink = _clDetailLink;
7159 SettingManager.Local.ColorFav = _clFav;
7160 SettingManager.Local.ColorOWL = _clOWL;
7161 SettingManager.Local.ColorRetweet = _clRetweet;
7162 SettingManager.Local.ColorSelf = _clSelf;
7163 SettingManager.Local.ColorAtSelf = _clAtSelf;
7164 SettingManager.Local.ColorTarget = _clTarget;
7165 SettingManager.Local.ColorAtTarget = _clAtTarget;
7166 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7167 SettingManager.Local.ColorAtTo = _clAtTo;
7168 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7169 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7170 SettingManager.Local.ColorInputFont = _clInputFont;
7171 SettingManager.Local.FontInputFont = _fntInputFont;
7173 if (_ignoreConfigSave) return;
7174 SettingManager.SaveLocal();
7178 private void SaveConfigsTabs()
7180 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7182 var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7184 foreach (var tab in tabs)
7186 if (!tab.IsPermanentTabType)
7189 var tabSetting = new SettingTabs.SettingTabItem
7191 TabName = tab.TabName,
7192 TabType = tab.TabType,
7193 UnreadManage = tab.UnreadManage,
7194 Protected = tab.Protected,
7195 Notify = tab.Notify,
7196 SoundFile = tab.SoundFile,
7201 case FilterTabModel filterTab:
7202 tabSetting.FilterArray = filterTab.FilterArray;
7204 case UserTimelineTabModel userTab:
7205 tabSetting.User = userTab.ScreenName;
7207 case PublicSearchTabModel searchTab:
7208 tabSetting.SearchWords = searchTab.SearchWords;
7209 tabSetting.SearchLang = searchTab.SearchLang;
7211 case ListTimelineTabModel listTab:
7212 tabSetting.ListInfo = listTab.ListInfo;
7216 tabSettingList.Add(tabSetting);
7219 SettingManager.Tabs.Tabs = tabSettingList;
7220 SettingManager.SaveTabs();
7223 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7225 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7226 if (ret != DialogResult.OK)
7229 var match = Twitter.StatusUrlRegex.Match(inputText);
7232 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7233 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7239 var statusId = long.Parse(match.Groups["StatusId"].Value);
7240 await this.OpenRelatedTab(statusId);
7242 catch (TabException ex)
7244 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7248 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7250 var tab = this.CurrentTab;
7252 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7253 Properties.Resources.SaveLogMenuItem_ClickText2,
7254 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7255 if (rslt == DialogResult.Cancel) return;
7257 SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7258 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7259 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7260 SaveFileDialog1.FilterIndex = 0;
7261 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7262 SaveFileDialog1.RestoreDirectory = true;
7264 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7266 if (!SaveFileDialog1.ValidateNames) return;
7267 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7269 if (rslt == DialogResult.Yes)
7272 for (int idx = 0; idx < tab.AllCount; idx++)
7274 var post = tab[idx];
7275 string protect = "";
7276 if (post.IsProtect) protect = "Protect";
7277 sw.WriteLine(post.Nickname + "\t" +
7278 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7279 post.CreatedAt.ToLocalTimeString() + "\t" +
7280 post.ScreenName + "\t" +
7281 post.StatusId + "\t" +
7282 post.ImageUrl + "\t" +
7283 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7289 foreach (var post in this.CurrentTab.SelectedPosts)
7291 string protect = "";
7292 if (post.IsProtect) protect = "Protect";
7293 sw.WriteLine(post.Nickname + "\t" +
7294 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7295 post.CreatedAt.ToLocalTimeString() + "\t" +
7296 post.ScreenName + "\t" +
7297 post.StatusId + "\t" +
7298 post.ImageUrl + "\t" +
7299 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7305 this.TopMost = SettingManager.Common.AlwaysTop;
7308 public bool TabRename(string origTabName, out string newTabName)
7312 using (InputTabName inputName = new InputTabName())
7314 inputName.TabName = origTabName;
7315 inputName.ShowDialog();
7316 if (inputName.DialogResult == DialogResult.Cancel) return false;
7317 newTabName = inputName.TabName;
7319 this.TopMost = SettingManager.Common.AlwaysTop;
7320 if (!string.IsNullOrEmpty(newTabName))
7323 if (this._statuses.ContainsTab(newTabName))
7325 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7326 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7330 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7331 var tabPage = this.ListTab.TabPages[tabIndex];
7334 if (tabPage != null)
7335 tabPage.Text = newTabName;
7337 _statuses.RenameTab(origTabName, newTabName);
7339 SaveConfigsCommon();
7341 _rclickTabName = newTabName;
7350 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7352 if (e.Button == MouseButtons.Middle)
7354 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7356 if (this.ListTab.GetTabRect(index).Contains(e.Location))
7358 this.RemoveSpecifiedTab(tab.TabName, true);
7359 this.SaveConfigsTabs();
7366 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7367 => this.TabRename(this.CurrentTabName, out var _);
7369 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7371 if (SettingManager.Common.TabMouseLock) return;
7372 if (e.Button == MouseButtons.Left)
7374 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7376 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7379 _tabMouseDownPoint = e.Location;
7390 private void ListTab_DragEnter(object sender, DragEventArgs e)
7392 if (e.Data.GetDataPresent(typeof(TabPage)))
7393 e.Effect = DragDropEffects.Move;
7395 e.Effect = DragDropEffects.None;
7398 private void ListTab_DragDrop(object sender, DragEventArgs e)
7400 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7405 Point cpos = new Point(e.X, e.Y);
7406 Point spos = ListTab.PointToClient(cpos);
7407 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7409 Rectangle rect = ListTab.GetTabRect(index);
7410 if (rect.Contains(spos))
7413 if (spos.X <= (rect.Left + rect.Right) / 2)
7422 //タブのないところにドロップ->最後尾へ移動
7423 if (string.IsNullOrEmpty(tn))
7425 var lastTab = this._statuses.Tabs.Last();
7426 tn = lastTab.TabName;
7430 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7431 if (tp.Text == tn) return;
7433 ReOrderTab(tp.Text, tn, bef);
7436 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7438 var baseIndex = this.GetTabPageIndex(baseTabText);
7439 if (baseIndex == -1)
7442 var targetIndex = this.GetTabPageIndex(targetTabText);
7443 if (targetIndex == -1)
7446 using (ControlTransaction.Layout(this.ListTab))
7448 var tab = this._statuses.Tabs[targetIndex];
7449 var tabPage = this.ListTab.TabPages[targetIndex];
7451 this.ListTab.TabPages.Remove(tabPage);
7453 if (targetIndex < baseIndex)
7456 if (!isBeforeBaseTab)
7459 this._statuses.MoveTab(baseIndex, tab);
7461 ListTab.TabPages.Insert(baseIndex, tabPage);
7467 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7469 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7470 //isReply:true=@,false=DM
7471 if (!StatusText.Enabled) return;
7472 if (!this.ExistCurrentPost) return;
7474 var tab = this.CurrentTab;
7475 var selectedPosts = tab.SelectedPosts;
7477 // 複数あてリプライはReplyではなく通常ポスト
7478 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7479 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7480 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7482 if (selectedPosts.Length > 0)
7485 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7487 var post = selectedPosts.Single();
7490 if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7493 this.inReplyTo = null;
7494 StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7495 StatusText.SelectionStart = StatusText.Text.Length;
7499 if (string.IsNullOrEmpty(StatusText.Text))
7502 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7503 var inReplyToScreenName = post.ScreenName;
7504 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7506 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7507 StatusText.Text = "@" + post.ScreenName + " ";
7515 //1件選んでEnter or DoubleClick
7516 if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7518 if (this.inReplyTo?.ScreenName == post.ScreenName)
7521 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7522 var inReplyToScreenName = post.ScreenName;
7523 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7527 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7530 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7533 this.inReplyTo = null;
7534 StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7539 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7540 var inReplyToScreenName = post.ScreenName;
7541 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7542 StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7549 this.inReplyTo = null;
7550 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7555 //1件選んでCtrl-Rの場合(返信先操作せず)
7556 int sidx = StatusText.SelectionStart;
7557 string id = "@" + post.ScreenName + " ";
7560 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7565 StatusText.Text = StatusText.Text.Insert(sidx, id);
7567 //if (StatusText.Text.StartsWith("@"))
7570 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7571 // sidx += 5 + _curPost.ScreenName.Length;
7576 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7577 // sidx += 3 + _curPost.ScreenName.Length;
7579 StatusText.SelectionStart = sidx;
7582 //_reply_to_name = null;
7590 if (!isAuto && !isReply) return;
7592 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7596 //Enter or DoubleClick
7598 string sTxt = StatusText.Text;
7599 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7602 this.inReplyTo = null;
7604 foreach (var post in selectedPosts)
7606 if (!sTxt.Contains("@" + post.ScreenName + " "))
7608 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7609 //sTxt = "@" + post.ScreenName + " " + sTxt;
7612 StatusText.Text = sTxt;
7618 if (selectedPosts.Length > 1)
7623 int sidx = StatusText.SelectionStart;
7624 foreach (var post in selectedPosts)
7626 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7628 ids += "@" + post.ScreenName + " ";
7632 foreach (var (_, screenName) in post.ReplyToList)
7634 if (!ids.Contains("@" + screenName + " ") &&
7635 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7637 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7639 ids += "@" + m.Result("${id}") + " ";
7641 ids += "@" + screenName + " ";
7646 if (ids.Length == 0) return;
7647 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7649 this.inReplyTo = null;
7650 StatusText.Text = ". " + StatusText.Text;
7655 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7660 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7662 //if (StatusText.Text.StartsWith("@"))
7664 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7665 // sidx += 2 + ids.Length;
7669 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7670 // sidx += 1 + ids.Length;
7672 StatusText.SelectionStart = sidx;
7678 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7681 int sidx = StatusText.SelectionStart;
7682 var post = selectedPosts.Single();
7683 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7685 ids += "@" + post.ScreenName + " ";
7687 foreach (var (_, screenName) in post.ReplyToList)
7689 if (!ids.Contains("@" + screenName + " ") &&
7690 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7692 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7694 ids += "@" + m.Result("${id}") + " ";
7696 ids += "@" + screenName + " ";
7699 if (!string.IsNullOrEmpty(post.RetweetedBy))
7701 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7703 ids += "@" + post.RetweetedBy + " ";
7706 if (ids.Length == 0) return;
7707 if (string.IsNullOrEmpty(StatusText.Text))
7710 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7711 var inReplyToScreenName = post.ScreenName;
7712 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7714 StatusText.Text = ids;
7715 StatusText.SelectionStart = ids.Length;
7722 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7727 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7729 StatusText.SelectionStart = sidx;
7735 StatusText.SelectionStart = StatusText.Text.Length;
7740 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7741 => this._tabDrag = false;
7743 private static int iconCnt = 0;
7744 private static int blinkCnt = 0;
7745 private static bool blink = false;
7746 private static bool idle = false;
7748 private async Task RefreshTasktrayIcon()
7751 await this.Colorize();
7753 if (!TimerRefreshIcon.Enabled) return;
7754 //Static usCheckCnt As int = 0
7756 //Static iconDlListTopItem As ListViewItem = null
7758 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7759 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7761 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7763 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7769 //if (usCheckCnt > 300) //1min
7772 // if (!this.IsReceivedUserStream)
7774 // TraceOut("ReconnectUserStream");
7775 // tw.ReconnectUserStream();
7779 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7781 if (iconCnt >= this.NIconRefresh.Length)
7789 SaveConfigsAll(true);
7794 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7796 _myStatusError = false;
7800 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7801 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7803 if (blinkCnt > 0) return;
7805 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7807 NotifyIcon1.Icon = ReplyIcon;
7811 NotifyIcon1.Icon = ReplyIconBlink;
7819 //優先度:エラー→オフライン→アイドル
7823 NotifyIcon1.Icon = NIconAtRed;
7826 if (_myStatusOnline)
7828 NotifyIcon1.Icon = NIconAt;
7832 NotifyIcon1.Icon = NIconAtSmoke;
7836 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7837 => await this.RefreshTasktrayIcon(); // 200ms
7839 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7841 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7842 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7843 _rclickTabName = this.CurrentTabName;
7845 if (_statuses == null) return;
7846 if (_statuses.Tabs == null) return;
7848 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7851 NotifyDispMenuItem.Checked = tb.Notify;
7852 this.NotifyTbMenuItem.Checked = tb.Notify;
7854 soundfileListup = true;
7855 SoundFileComboBox.Items.Clear();
7856 this.SoundFileTbComboBox.Items.Clear();
7857 SoundFileComboBox.Items.Add("");
7858 this.SoundFileTbComboBox.Items.Add("");
7859 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7860 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7862 oDir = oDir.GetDirectories("Sounds")[0];
7864 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
7866 SoundFileComboBox.Items.Add(oFile.Name);
7867 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7869 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7870 if (idx == -1) idx = 0;
7871 SoundFileComboBox.SelectedIndex = idx;
7872 this.SoundFileTbComboBox.SelectedIndex = idx;
7873 soundfileListup = false;
7874 UreadManageMenuItem.Checked = tb.UnreadManage;
7875 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7877 TabMenuControl(_rclickTabName);
7880 private void TabMenuControl(string tabName)
7882 var tabInfo = _statuses.GetTabByName(tabName);
7884 this.FilterEditMenuItem.Enabled = true;
7885 this.EditRuleTbMenuItem.Enabled = true;
7887 if (tabInfo.IsDefaultTabType)
7889 this.ProtectTabMenuItem.Enabled = false;
7890 this.ProtectTbMenuItem.Enabled = false;
7894 this.ProtectTabMenuItem.Enabled = true;
7895 this.ProtectTbMenuItem.Enabled = true;
7898 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7900 this.ProtectTabMenuItem.Checked = true;
7901 this.ProtectTbMenuItem.Checked = true;
7902 this.DeleteTabMenuItem.Enabled = false;
7903 this.DeleteTbMenuItem.Enabled = false;
7907 this.ProtectTabMenuItem.Checked = false;
7908 this.ProtectTbMenuItem.Checked = false;
7909 this.DeleteTabMenuItem.Enabled = true;
7910 this.DeleteTbMenuItem.Enabled = true;
7914 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7916 var checkState = ((ToolStripMenuItem)sender).Checked;
7919 this.ProtectTbMenuItem.Checked = checkState;
7920 this.ProtectTabMenuItem.Checked = checkState;
7923 this.DeleteTabMenuItem.Enabled = !checkState;
7924 this.DeleteTbMenuItem.Enabled = !checkState;
7926 if (string.IsNullOrEmpty(_rclickTabName)) return;
7927 _statuses.Tabs[_rclickTabName].Protected = checkState;
7932 private void UreadManageMenuItem_Click(object sender, EventArgs e)
7934 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7935 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7937 if (string.IsNullOrEmpty(_rclickTabName)) return;
7938 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7943 public void ChangeTabUnreadManage(string tabName, bool isManage)
7945 var idx = this.GetTabPageIndex(tabName);
7949 var tab = this._statuses.Tabs[tabName];
7950 tab.UnreadManage = isManage;
7952 if (SettingManager.Common.TabIconDisp)
7954 var tabPage = this.ListTab.TabPages[idx];
7955 if (tab.UnreadCount > 0)
7956 tabPage.ImageIndex = 0;
7958 tabPage.ImageIndex = -1;
7961 if (this.CurrentTabName == tabName)
7963 this.PurgeListViewItemCache();
7964 this.CurrentListView.Refresh();
7967 SetMainWindowTitle();
7968 SetStatusLabelUrl();
7969 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
7972 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
7974 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7975 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
7977 if (string.IsNullOrEmpty(_rclickTabName)) return;
7979 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
7984 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
7986 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
7988 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
7993 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
7995 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
7996 _rclickTabName = this.CurrentTabName;
7998 RemoveSpecifiedTab(_rclickTabName, true);
8002 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8004 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8006 using (var fltDialog = new FilterDialog())
8008 fltDialog.Owner = this;
8009 fltDialog.SetCurrent(_rclickTabName);
8010 fltDialog.ShowDialog(this);
8012 this.TopMost = SettingManager.Common.AlwaysTop;
8014 this.ApplyPostFilters();
8018 private async void AddTabMenuItem_Click(object sender, EventArgs e)
8020 string tabName = null;
8021 MyCommon.TabUsageType tabUsage;
8022 using (InputTabName inputName = new InputTabName())
8024 inputName.TabName = _statuses.MakeTabName("MyTab");
8025 inputName.IsShowUsage = true;
8026 inputName.ShowDialog();
8027 if (inputName.DialogResult == DialogResult.Cancel) return;
8028 tabName = inputName.TabName;
8029 tabUsage = inputName.Usage;
8031 this.TopMost = SettingManager.Common.AlwaysTop;
8032 if (!string.IsNullOrEmpty(tabName))
8035 ListElement list = null;
8036 if (tabUsage == MyCommon.TabUsageType.Lists)
8038 using (ListAvailable listAvail = new ListAvailable())
8040 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8041 if (listAvail.SelectedList == null) return;
8042 list = listAvail.SelectedList;
8049 case MyCommon.TabUsageType.UserDefined:
8050 tab = new FilterTabModel(tabName);
8052 case MyCommon.TabUsageType.PublicSearch:
8053 tab = new PublicSearchTabModel(tabName);
8055 case MyCommon.TabUsageType.Lists:
8056 tab = new ListTimelineTabModel(tabName, list);
8062 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8064 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8065 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8072 var tabIndex = this._statuses.Tabs.Count - 1;
8074 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8076 ListTab.SelectedIndex = tabIndex;
8077 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8079 if (tabUsage == MyCommon.TabUsageType.Lists)
8081 ListTab.SelectedIndex = tabIndex;
8082 await this.RefreshTabAsync(this.CurrentTab);
8088 private void TabMenuItem_Click(object sender, EventArgs e)
8090 using (var fltDialog = new FilterDialog())
8092 fltDialog.Owner = this;
8095 foreach (var post in this.CurrentTab.SelectedPosts)
8098 if (!SelectTab(out var tabName)) return;
8100 fltDialog.SetCurrent(tabName);
8102 if (post.RetweetedId == null)
8104 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
8108 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
8110 fltDialog.ShowDialog(this);
8111 this.TopMost = SettingManager.Common.AlwaysTop;
8115 this.ApplyPostFilters();
8119 protected override bool ProcessDialogKey(Keys keyData)
8121 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8122 if ((keyData & Keys.KeyCode) == Keys.Enter)
8124 if (StatusText.Focused)
8126 bool _NewLine = false;
8129 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8131 if (StatusText.Multiline)
8133 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8135 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8139 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8143 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8145 if (StatusText.Multiline)
8147 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8149 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8153 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8159 if (StatusText.Multiline)
8161 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8163 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8164 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8168 if (((keyData & Keys.Shift) == Keys.Shift) ||
8169 (((keyData & Keys.Control) != Keys.Control) &&
8170 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8176 int pos1 = StatusText.SelectionStart;
8177 if (StatusText.SelectionLength > 0)
8179 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8181 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8182 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8187 PostButton_Click(null, null);
8193 var tab = this.CurrentTab;
8194 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8196 var tabPage = this.CurrentTabPage;
8197 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8198 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8200 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
8207 return base.ProcessDialogKey(keyData);
8210 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8211 => this.MakeReplyOrDirectStatus(false, true, true);
8213 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8215 var tab = this.CurrentTab;
8216 var selectedPosts = tab.SelectedPosts;
8219 if (selectedPosts.Length == 0)
8222 var screenNameArray = selectedPosts
8223 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8226 this.AddFilterRuleByScreenName(screenNameArray);
8228 if (screenNameArray.Length != 0)
8230 List<string> atids = new List<string>();
8231 foreach (var screenName in screenNameArray)
8233 atids.Add("@" + screenName);
8235 int cnt = AtIdSupl.ItemCount;
8236 AtIdSupl.AddRangeItem(atids.ToArray());
8237 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8241 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8243 var tab = this.CurrentTab;
8244 var selectedPosts = tab.SelectedPosts;
8246 if (selectedPosts.Length == 0)
8249 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8251 this.AddFilterRuleBySource(sourceArray);
8254 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8257 if (!SelectTab(out var tabName)) return;
8259 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8263 if (tab.TabType != MyCommon.TabUsageType.Mute)
8265 this.MoveOrCopy(out mv, out mk);
8269 // ミュートタブでは常に MoveMatches を true にする
8274 foreach (var screenName in screenNameArray)
8276 tab.AddFilter(new PostFilterRule
8278 FilterName = screenName,
8279 UseNameField = true,
8283 FilterByUrl = false,
8287 this.ApplyPostFilters();
8291 public void AddFilterRuleBySource(params string[] sourceArray)
8293 // タブ選択ダイアログを表示(or追加)
8294 if (!this.SelectTab(out var tabName))
8297 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8301 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8303 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8304 this.MoveOrCopy(out mv, out mk);
8308 // ミュートタブでは常に MoveMatches を true にする
8313 // 振り分けルールに追加するSource
8314 foreach (var source in sourceArray)
8316 filterTab.AddFilter(new PostFilterRule
8318 FilterSource = source,
8322 FilterByUrl = false,
8326 this.ApplyPostFilters();
8327 this.SaveConfigsTabs();
8330 private bool SelectTab(out string tabName)
8337 using (var dialog = new TabsDialog(_statuses))
8339 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8341 tabName = dialog.SelectedTab?.TabName;
8344 this.CurrentTabPage.Focus();
8346 if (tabName == null)
8348 using (InputTabName inputName = new InputTabName())
8350 inputName.TabName = _statuses.MakeTabName("MyTab");
8351 inputName.ShowDialog();
8352 if (inputName.DialogResult == DialogResult.Cancel) return false;
8353 tabName = inputName.TabName;
8355 this.TopMost = SettingManager.Common.AlwaysTop;
8356 if (!string.IsNullOrEmpty(tabName))
8358 var tab = new FilterTabModel(tabName);
8359 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8361 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8362 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8380 private void MoveOrCopy(out bool move, out bool mark)
8384 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8385 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8393 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8394 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8405 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8408 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8409 => this.CopyIdUri();
8411 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8413 if (StatusText.Focused)
8416 StatusText.SelectAll();
8420 // ListView上でのCtrl+A
8421 NativeMethods.SelectAllItems(this.CurrentListView);
8425 private void MoveMiddle()
8431 var listView = this.CurrentListView;
8432 if (listView.SelectedIndices.Count == 0) return;
8434 int idx = listView.SelectedIndices[0];
8436 _item = listView.GetItemAt(0, 25);
8442 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8444 idx2 = listView.VirtualListSize - 1;
8448 idx -= Math.Abs(idx1 - idx2) / 2;
8449 if (idx < 0) idx = 0;
8451 listView.EnsureVisible(listView.VirtualListSize - 1);
8452 listView.EnsureVisible(idx);
8455 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8457 var linkElements = this.tweetDetailsView.GetLinkElements();
8459 if (linkElements.Length > 0)
8461 UrlDialog.ClearUrl();
8463 string openUrlStr = "";
8465 if (linkElements.Length == 1)
8467 // ツイートに含まれる URL が 1 つのみの場合
8468 // => OpenURL ダイアログを表示せずにリンクを開く
8473 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8475 catch (ArgumentException)
8484 if (string.IsNullOrEmpty(urlStr)) return;
8485 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8487 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8488 await this.OpenUriAsync(new Uri(openUrlStr));
8492 // ツイートに含まれる URL が複数ある場合
8493 // => OpenURL を表示しユーザーが選択したリンクを開く
8495 foreach (var linkElm in linkElements)
8498 string linkText = "";
8502 urlStr = linkElm.GetAttribute("title");
8503 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8504 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8505 linkText = linkElm.InnerText;
8507 catch (ArgumentException)
8516 if (string.IsNullOrEmpty(urlStr)) continue;
8517 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8521 if (UrlDialog.ShowDialog() == DialogResult.OK)
8523 openUrlStr = UrlDialog.SelectedUrl;
8525 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8526 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8533 this.TopMost = SettingManager.Common.AlwaysTop;
8538 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8540 if (string.IsNullOrEmpty(_rclickTabName)) return;
8541 ClearTab(_rclickTabName, true);
8544 private void ClearTab(string tabName, bool showWarning)
8548 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8549 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8555 _statuses.ClearTabIds(tabName);
8556 if (this.CurrentTabName == tabName)
8559 _anchorFlag = false;
8560 this.PurgeListViewItemCache();
8563 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8564 var tabPage = this.ListTab.TabPages[tabIndex];
8565 tabPage.ImageIndex = -1;
8567 var listView = (DetailsListView)tabPage.Tag;
8568 listView.VirtualListSize = 0;
8570 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8572 SetMainWindowTitle();
8573 SetStatusLabelUrl();
8576 private static long followers = 0;
8578 private void SetMainWindowTitle()
8581 StringBuilder ttl = new StringBuilder(256);
8584 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8585 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8586 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8587 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8589 foreach (var tab in _statuses.Tabs)
8591 ur += tab.UnreadCount;
8596 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8597 ttl.Append(ApplicationSettings.ApplicationName);
8599 switch (SettingManager.Common.DispLatestPost)
8601 case MyCommon.DispTitleEnum.Ver:
8602 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8604 case MyCommon.DispTitleEnum.Post:
8605 if (_history != null && _history.Count > 1)
8606 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8608 case MyCommon.DispTitleEnum.UnreadRepCount:
8609 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8611 case MyCommon.DispTitleEnum.UnreadAllCount:
8612 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8614 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8615 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8617 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8618 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8620 case MyCommon.DispTitleEnum.OwnStatus:
8621 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8622 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8628 this.Text = ttl.ToString();
8630 catch (AccessViolationException)
8632 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8636 private string GetStatusLabelText()
8639 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8640 if (_statuses == null) return "";
8641 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8642 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8643 if (tbRep == null || tbDm == null) return "";
8644 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8649 StringBuilder slbl = new StringBuilder(256);
8652 foreach (var tab in _statuses.Tabs)
8654 ur += tab.UnreadCount;
8656 if (tab.TabName == this.CurrentTabName)
8658 tur = tab.UnreadCount;
8669 UnreadAtCounter = urat;
8671 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8673 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8674 if (SettingManager.Common.TimelinePeriod == 0)
8676 slbl.Append(Properties.Resources.SetStatusLabelText2);
8680 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8682 return slbl.ToString();
8685 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8689 if (this.InvokeRequired && !this.IsDisposed)
8691 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8695 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8696 SetApiStatusLabel(endpointName);
8699 catch (ObjectDisposedException)
8703 catch (InvalidOperationException)
8709 private void SetApiStatusLabel(string endpointName = null)
8711 var tabType = this.CurrentTab.TabType;
8713 if (endpointName == null)
8718 case MyCommon.TabUsageType.Home:
8719 case MyCommon.TabUsageType.UserDefined:
8720 endpointName = "/statuses/home_timeline";
8723 case MyCommon.TabUsageType.Mentions:
8724 endpointName = "/statuses/mentions_timeline";
8727 case MyCommon.TabUsageType.Favorites:
8728 endpointName = "/favorites/list";
8731 case MyCommon.TabUsageType.DirectMessage:
8732 endpointName = "/direct_messages/events/list";
8735 case MyCommon.TabUsageType.UserTimeline:
8736 endpointName = "/statuses/user_timeline";
8739 case MyCommon.TabUsageType.Lists:
8740 endpointName = "/lists/statuses";
8743 case MyCommon.TabUsageType.PublicSearch:
8744 endpointName = "/search/tweets";
8747 case MyCommon.TabUsageType.Related:
8748 endpointName = "/statuses/show/:id";
8755 this.toolStripApiGauge.ApiEndpoint = endpointName;
8759 // 表示中のタブに関連する endpoint であれば更新
8762 switch (endpointName)
8764 case "/statuses/home_timeline":
8765 update = tabType == MyCommon.TabUsageType.Home ||
8766 tabType == MyCommon.TabUsageType.UserDefined;
8769 case "/statuses/mentions_timeline":
8770 update = tabType == MyCommon.TabUsageType.Mentions;
8773 case "/favorites/list":
8774 update = tabType == MyCommon.TabUsageType.Favorites;
8777 case "/direct_messages/events/list":
8778 update = tabType == MyCommon.TabUsageType.DirectMessage;
8781 case "/statuses/user_timeline":
8782 update = tabType == MyCommon.TabUsageType.UserTimeline;
8785 case "/lists/statuses":
8786 update = tabType == MyCommon.TabUsageType.Lists;
8789 case "/search/tweets":
8790 update = tabType == MyCommon.TabUsageType.PublicSearch;
8793 case "/statuses/show/:id":
8794 update = tabType == MyCommon.TabUsageType.Related;
8803 this.toolStripApiGauge.ApiEndpoint = endpointName;
8808 private void SetStatusLabelUrl()
8809 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8811 public void SetStatusLabel(string text)
8812 => this.StatusLabel.Text = text;
8814 private void SetNotifyIconText()
8816 var ur = new StringBuilder(64);
8818 // タスクトレイアイコンのツールチップテキスト書き換え
8820 ur.Remove(0, ur.Length);
8821 if (SettingManager.Common.DispUsername)
8823 ur.Append(tw.Username);
8826 ur.Append(ApplicationSettings.ApplicationName);
8828 ur.Append("(Debug Build)");
8830 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8833 ur.Append(UnreadCounter);
8835 ur.Append(UnreadAtCounter);
8838 NotifyIcon1.Text = ur.ToString();
8841 internal void CheckReplyTo(string StatusText)
8845 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8847 foreach (Match hm in m)
8849 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8851 hstr += "#" + hm.Result("$3") + " ";
8852 HashSupl.AddItem("#" + hm.Result("$3"));
8855 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8857 hstr += HashMgr.UseHash;
8859 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8861 // 本当にリプライ先指定すべきかどうかの判定
8862 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8864 if (SettingManager.Common.UseAtIdSupplement)
8866 int bCnt = AtIdSupl.ItemCount;
8867 foreach (Match mid in m)
8869 AtIdSupl.AddItem(mid.Result("${id}"));
8871 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
8874 // リプライ先ステータスIDの指定がない場合は指定しない
8875 if (this.inReplyTo == null)
8879 // 次の条件を満たす場合に in_reply_to_status_id 指定
8880 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8881 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8882 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8886 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8887 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8889 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8893 foreach (Match mid in m)
8895 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8900 this.inReplyTo = null;
8903 private void TweenMain_Resize(object sender, EventArgs e)
8905 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8907 this.Visible = false;
8909 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8911 // 現在の DPI と設定保存時の DPI との比を取得する
8912 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8914 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8917 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8918 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8919 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8921 this.SplitContainer1.SplitterDistance = splitterDistance;
8925 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8926 if (StatusText.Multiline)
8928 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8929 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8930 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8932 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8934 StatusText.Height = statusTextHeight;
8938 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8940 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8944 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8945 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8947 this.SplitContainer3.SplitterDistance = previewDistance;
8950 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8951 this.SplitContainer3.Panel2Collapsed = true;
8953 _initialLayout = false;
8955 if (this.WindowState != FormWindowState.Minimized)
8957 _formWindowState = this.WindowState;
8961 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8963 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8964 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8965 if (PlaySoundMenuItem.Checked)
8967 SettingManager.Common.PlaySound = true;
8971 SettingManager.Common.PlaySound = false;
8973 ModifySettingCommon = true;
8976 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
8978 if (this._initialLayout)
8981 int splitterDistance;
8982 switch (this.WindowState)
8984 case FormWindowState.Normal:
8985 splitterDistance = this.SplitContainer1.SplitterDistance;
8987 case FormWindowState.Maximized:
8988 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8989 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
8990 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
8991 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
8997 this._mySpDis = splitterDistance;
8998 this.ModifySettingLocal = true;
9001 private async Task doRepliedStatusOpen()
9003 var currentPost = this.CurrentPost;
9004 if (this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
9006 if (MyCommon.IsKeyDown(Keys.Shift))
9008 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9011 if (_statuses.ContainsKey(currentPost.InReplyToStatusId.Value))
9013 PostClass repPost = _statuses[currentPost.InReplyToStatusId.Value];
9014 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9018 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9020 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
9021 PostClass repPost = _statuses[currentPost.InReplyToStatusId.Value];
9022 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9025 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9030 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9031 => await this.doRepliedStatusOpen();
9033 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9035 if (this._initialLayout)
9036 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9038 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9039 if (multiline != this.StatusText.Multiline)
9041 this.StatusText.Multiline = multiline;
9042 SettingManager.Local.StatusMultiline = multiline;
9043 ModifySettingLocal = true;
9047 private void StatusText_MultilineChanged(object sender, EventArgs e)
9049 if (this.StatusText.Multiline)
9050 this.StatusText.ScrollBars = ScrollBars.Vertical;
9052 this.StatusText.ScrollBars = ScrollBars.None;
9054 ModifySettingLocal = true;
9057 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9060 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9061 StatusText.Multiline = menuItemChecked;
9062 SettingManager.Local.StatusMultiline = menuItemChecked;
9063 if (menuItemChecked)
9065 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9066 SplitContainer2.SplitterDistance = 0;
9068 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9072 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9074 ModifySettingLocal = true;
9077 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9079 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9081 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9082 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9083 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9085 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9090 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9091 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9093 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9094 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9095 //Appendix A. Collected ABNF for URI
9096 //http://www.ietf.org/rfc/rfc3986.txt
9100 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9102 if (StatusText.SelectionLength > 0)
9104 string tmp = StatusText.SelectedText;
9105 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9106 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9108 // 文字列が選択されている場合はその文字列について処理
9110 //nico.ms使用、nicovideoにマッチしたら変換
9111 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9113 result = nicoms.Shorten(tmp);
9115 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9117 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9120 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9121 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9122 result = resultUri.AbsoluteUri;
9124 catch (WebApiException e)
9126 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9129 catch (UriFormatException e)
9131 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9140 if (!string.IsNullOrEmpty(result))
9142 urlUndo undotmp = new urlUndo();
9144 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9145 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9146 if (origUrlIndex == -1)
9149 StatusText.Select(origUrlIndex, tmp.Length);
9150 StatusText.SelectedText = result;
9153 undotmp.Before = tmp;
9154 undotmp.After = result;
9156 if (urlUndoBuffer == null)
9158 urlUndoBuffer = new List<urlUndo>();
9159 UrlUndoToolStripMenuItem.Enabled = true;
9162 urlUndoBuffer.Add(undotmp);
9168 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9169 @"(?<url>(?<protocol>https?://)" +
9170 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9171 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9172 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9173 // 正規表現にマッチしたURL文字列をtinyurl化
9174 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9176 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9177 string tmp = mt.Result("${url}");
9178 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9179 urlUndo undotmp = new urlUndo();
9182 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9184 //nico.ms使用、nicovideoにマッチしたら変換
9185 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9187 result = nicoms.Shorten(tmp);
9189 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9191 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9194 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9195 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9196 result = resultUri.AbsoluteUri;
9198 catch (HttpRequestException e)
9200 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9201 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9202 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9204 this.StatusLabel.Text = Converter_Type + ":" + message;
9207 catch (WebApiException e)
9209 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9212 catch (UriFormatException e)
9214 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9223 if (!string.IsNullOrEmpty(result))
9225 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9226 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9227 if (origUrlIndex == -1)
9230 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9231 StatusText.SelectedText = result;
9233 undotmp.Before = mt.Result("${url}");
9234 undotmp.After = result;
9236 if (urlUndoBuffer == null)
9238 urlUndoBuffer = new List<urlUndo>();
9239 UrlUndoToolStripMenuItem.Enabled = true;
9242 urlUndoBuffer.Add(undotmp);
9250 private void doUrlUndo()
9252 if (urlUndoBuffer != null)
9254 string tmp = StatusText.Text;
9255 foreach (urlUndo data in urlUndoBuffer)
9257 tmp = tmp.Replace(data.After, data.Before);
9259 StatusText.Text = tmp;
9260 urlUndoBuffer = null;
9261 UrlUndoToolStripMenuItem.Enabled = false;
9262 StatusText.SelectionStart = 0;
9263 StatusText.SelectionLength = 0;
9267 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9268 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9270 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9271 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9273 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9274 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9276 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9278 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9280 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9281 Random rnd = new Random();
9282 // 前回使用した短縮URLサービス以外を選択する
9285 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9287 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9288 await UrlConvertAsync(svc);
9292 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9293 => this.doUrlUndo();
9295 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9297 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9298 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9299 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9300 ModifySettingCommon = true;
9303 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9305 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9306 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9307 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9308 ModifySettingCommon = true;
9311 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9313 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9314 MenuStrip1.Tag = new Object();
9315 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9318 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9320 var currentTabPage = this.CurrentTabPage;
9321 if (this.Tag != null) // 設定された戻り先へ遷移
9323 if (this.Tag == currentTabPage)
9324 ((Control)currentTabPage.Tag).Select();
9326 ((Control)this.Tag).Select();
9328 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9330 this.Tag = currentTabPage.Tag;
9331 ((Control)this.Tag).Select();
9333 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9334 MenuStrip1.Tag = null;
9337 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9339 DetailsListView lst = (DetailsListView)sender;
9340 if (SettingManager.Local == null) return;
9344 SettingManager.Local.Width1 = lst.Columns[0].Width;
9345 SettingManager.Local.Width3 = lst.Columns[1].Width;
9349 int[] darr = new int[lst.Columns.Count];
9350 for (int i = 0; i < lst.Columns.Count; i++)
9352 darr[lst.Columns[i].DisplayIndex] = i;
9354 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9356 for (int i = 0; i < lst.Columns.Count; i++)
9361 SettingManager.Local.DisplayIndex1 = i;
9364 SettingManager.Local.DisplayIndex2 = i;
9367 SettingManager.Local.DisplayIndex3 = i;
9370 SettingManager.Local.DisplayIndex4 = i;
9373 SettingManager.Local.DisplayIndex5 = i;
9376 SettingManager.Local.DisplayIndex6 = i;
9379 SettingManager.Local.DisplayIndex7 = i;
9382 SettingManager.Local.DisplayIndex8 = i;
9386 SettingManager.Local.Width1 = lst.Columns[0].Width;
9387 SettingManager.Local.Width2 = lst.Columns[1].Width;
9388 SettingManager.Local.Width3 = lst.Columns[2].Width;
9389 SettingManager.Local.Width4 = lst.Columns[3].Width;
9390 SettingManager.Local.Width5 = lst.Columns[4].Width;
9391 SettingManager.Local.Width6 = lst.Columns[5].Width;
9392 SettingManager.Local.Width7 = lst.Columns[6].Width;
9393 SettingManager.Local.Width8 = lst.Columns[7].Width;
9395 ModifySettingLocal = true;
9396 _isColumnChanged = true;
9399 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9401 DetailsListView lst = (DetailsListView)sender;
9402 if (SettingManager.Local == null) return;
9405 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9407 SettingManager.Local.Width1 = lst.Columns[0].Width;
9408 ModifySettingLocal = true;
9409 _isColumnChanged = true;
9411 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9413 SettingManager.Local.Width3 = lst.Columns[1].Width;
9414 ModifySettingLocal = true;
9415 _isColumnChanged = true;
9420 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9422 SettingManager.Local.Width1 = lst.Columns[0].Width;
9423 ModifySettingLocal = true;
9424 _isColumnChanged = true;
9426 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9428 SettingManager.Local.Width2 = lst.Columns[1].Width;
9429 ModifySettingLocal = true;
9430 _isColumnChanged = true;
9432 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9434 SettingManager.Local.Width3 = lst.Columns[2].Width;
9435 ModifySettingLocal = true;
9436 _isColumnChanged = true;
9438 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9440 SettingManager.Local.Width4 = lst.Columns[3].Width;
9441 ModifySettingLocal = true;
9442 _isColumnChanged = true;
9444 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9446 SettingManager.Local.Width5 = lst.Columns[4].Width;
9447 ModifySettingLocal = true;
9448 _isColumnChanged = true;
9450 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9452 SettingManager.Local.Width6 = lst.Columns[5].Width;
9453 ModifySettingLocal = true;
9454 _isColumnChanged = true;
9456 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9458 SettingManager.Local.Width7 = lst.Columns[6].Width;
9459 ModifySettingLocal = true;
9460 _isColumnChanged = true;
9462 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9464 SettingManager.Local.Width8 = lst.Columns[7].Width;
9465 ModifySettingLocal = true;
9466 _isColumnChanged = true;
9469 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9472 // SaveConfigsLocal();
9476 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9478 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9479 ModifySettingLocal = true;
9482 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9484 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9486 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9488 SelectMedia_DragDrop(e);
9491 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9493 var (url, title) = GetUrlFromDataObject(e.Data);
9499 appendText = title + " " + url;
9501 if (this.StatusText.TextLength == 0)
9502 this.StatusText.Text = appendText;
9504 this.StatusText.Text += " " + appendText;
9506 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9508 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9510 this.StatusText.Text += text;
9512 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9514 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9515 if (data != null) StatusText.Text += data;
9520 /// IDataObject から URL とタイトルの対を取得します
9523 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9525 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9526 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9527 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9529 if (data.GetDataPresent("text/x-moz-url"))
9531 // Firefox, Google Chrome で利用可能
9532 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9534 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9536 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9537 if (lines.Length < 2)
9538 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9540 return (lines[0], lines[1]);
9543 else if (data.GetDataPresent("IESiteModeToUrl"))
9545 // Internet Exproler 用
9546 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9548 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9550 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9551 if (lines.Length < 2)
9552 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9554 return (lines[0], lines[1]);
9557 else if (data.GetDataPresent("UniformResourceLocatorW"))
9561 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9563 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9568 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9571 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9573 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9575 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9577 SelectMedia_DragEnter(e);
9581 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9583 e.Effect = DragDropEffects.Copy;
9586 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9588 e.Effect = DragDropEffects.Copy;
9591 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9593 e.Effect = DragDropEffects.Copy;
9597 e.Effect = DragDropEffects.None;
9600 private void TweenMain_DragOver(object sender, DragEventArgs e)
9604 public bool IsNetworkAvailable()
9607 nw = MyCommon.IsNetworkAvailable();
9608 _myStatusOnline = nw;
9612 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9614 var uriStr = uri.AbsoluteUri;
9616 // OpenTween 内部で使用する URL
9617 if (uri.Authority == "opentween")
9619 await this.OpenInternalUriAsync(uri);
9623 // ハッシュタグを含む Twitter 検索
9624 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9627 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9628 var pos = unescapedQuery.IndexOf('#');
9629 if (pos == -1) return;
9631 var hash = unescapedQuery.Substring(pos);
9632 this.HashSupl.AddItem(hash);
9633 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9634 this.AddNewTabForSearch(hash);
9639 // フラグが立っている場合は設定と逆の動作をする
9640 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9641 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9643 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9644 if (userUriMatch.Success)
9646 var screenName = userUriMatch.Groups["ScreenName"].Value;
9647 if (this.IsTwitterId(screenName))
9649 await this.AddNewTabForUserTimeline(screenName);
9656 await this.OpenUriInBrowserAsync(uriStr);
9660 /// OpenTween 内部の機能を呼び出すための URL を開きます
9662 private async Task OpenInternalUriAsync(Uri uri)
9664 // ツイートを開く (//opentween/status/:status_id)
9665 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9668 var statusId = long.Parse(match.Groups[1].Value);
9669 await this.OpenRelatedTab(statusId);
9674 public Task OpenUriInBrowserAsync(string UriString)
9676 return Task.Run(() =>
9678 string myPath = UriString;
9682 var configBrowserPath = SettingManager.Local.BrowserPath;
9683 if (!string.IsNullOrEmpty(configBrowserPath))
9685 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9687 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9688 string browserPath = configBrowserPath.Substring(1, sep - 1);
9690 if (sep < configBrowserPath.Length - 1)
9692 arg = configBrowserPath.Substring(sep + 1);
9694 myPath = arg + " " + myPath;
9695 System.Diagnostics.Process.Start(browserPath, myPath);
9699 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9704 System.Diagnostics.Process.Start(myPath);
9709 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9714 private void ListTabSelect(TabPage _tab)
9718 this.PurgeListViewItemCache();
9720 this._statuses.SelectTab(_tab.Text);
9722 var listView = this.CurrentListView;
9725 _anchorFlag = false;
9729 listView.Columns[1].Text = ColumnText[2];
9733 for (int i = 0; i < listView.Columns.Count; i++)
9735 listView.Columns[i].Text = ColumnText[i];
9740 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9741 => this.ListTabSelect(e.TabPage);
9743 private void SelectListItem(DetailsListView LView, int Index)
9746 Rectangle bnd = new Rectangle();
9748 var item = LView.FocusedItem;
9757 LView.SelectedIndices.Clear();
9759 while (LView.SelectedIndices.Count > 0);
9760 item = LView.Items[Index];
9761 item.Selected = true;
9762 item.Focused = true;
9764 if (flg) LView.Invalidate(bnd);
9767 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9770 Rectangle bnd = new Rectangle();
9772 var item = LView.FocusedItem;
9783 LView.SelectedIndices.Clear();
9785 while (LView.SelectedIndices.Count > 0);
9786 LView.SelectItems(Index);
9788 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9790 LView.SelectionMark = selectionMarkIndex;
9792 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9794 LView.Items[focusedIndex].Focused = true;
9796 else if (Index != null && Index.Length != 0)
9798 LView.Items[Index.Last()].Focused = true;
9801 if (flg) LView.Invalidate(bnd);
9804 private void StartUserStream()
9806 tw.NewPostFromStream += tw_NewPostFromStream;
9807 tw.UserStreamStarted += tw_UserStreamStarted;
9808 tw.UserStreamStopped += tw_UserStreamStopped;
9809 tw.PostDeleted += tw_PostDeleted;
9810 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9812 this.RefreshUserStreamsMenu();
9814 if (SettingManager.Common.UserstreamStartup)
9815 tw.StartUserStream();
9818 private async void TweenMain_Shown(object sender, EventArgs e)
9820 NotifyIcon1.Visible = true;
9822 if (this.IsNetworkAvailable())
9826 var loadTasks = new List<Task>
9828 this.RefreshMuteUserIdsAsync(),
9829 this.RefreshBlockIdsAsync(),
9830 this.RefreshNoRetweetIdsAsync(),
9831 this.RefreshTwitterConfigurationAsync(),
9832 this.RefreshTabAsync<HomeTabModel>(),
9833 this.RefreshTabAsync<MentionsTabModel>(),
9834 this.RefreshTabAsync<DirectMessagesTabModel>(),
9835 this.RefreshTabAsync<PublicSearchTabModel>(),
9836 this.RefreshTabAsync<UserTimelineTabModel>(),
9837 this.RefreshTabAsync<ListTimelineTabModel>(),
9840 if (SettingManager.Common.StartupFollowers)
9841 loadTasks.Add(this.RefreshFollowerIdsAsync());
9843 if (SettingManager.Common.GetFav)
9844 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9846 var allTasks = Task.WhenAll(loadTasks);
9851 var timeout = Task.Delay(5000);
9852 if (await Task.WhenAny(allTasks, timeout) != timeout)
9856 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9858 if (MyCommon._endingFlag)
9862 if (MyCommon._endingFlag) return;
9864 if (ApplicationSettings.VersionInfoUrl != null)
9866 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9867 if (SettingManager.Common.StartupVersion)
9868 await this.CheckNewVersion(true);
9872 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9873 this.VerUpMenuItem.Enabled = false;
9874 this.VerUpMenuItem.Available = false;
9875 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9878 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9879 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9881 MessageBox.Show(Properties.Resources.ReAuthorizeText);
9882 SettingStripMenuItem_Click(null, null);
9886 var reloadTasks = new List<Task>();
9888 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9889 reloadTasks.Add(this.RefreshFollowerIdsAsync());
9891 if (!tw.GetNoRetweetSuccess)
9892 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9894 if (this.tw.Configuration.PhotoSizeLimit == 0)
9895 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9897 await Task.WhenAll(reloadTasks);
9902 TimerTimeline.Enabled = true;
9905 private async Task doGetFollowersMenu()
9907 await this.RefreshFollowerIdsAsync();
9908 await this.DispSelectedPost(true);
9911 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9912 => await this.doGetFollowersMenu();
9914 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9915 => this.doReTweetUnofficial();
9917 private async Task doReTweetOfficial(bool isConfirm)
9920 if (this.ExistCurrentPost)
9922 var selectedPosts = this.CurrentTab.SelectedPosts;
9924 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9926 if (selectedPosts.Any(x => x.IsProtect))
9927 MessageBox.Show("Protected.");
9929 _DoFavRetweetFlags = false;
9933 if (selectedPosts.Length > 15)
9935 MessageBox.Show(Properties.Resources.RetweetLimitText);
9936 _DoFavRetweetFlags = false;
9939 else if (selectedPosts.Length > 1)
9941 string QuestionText = Properties.Resources.RetweetQuestion2;
9942 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9943 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9945 case DialogResult.Cancel:
9946 case DialogResult.No:
9947 _DoFavRetweetFlags = false;
9953 if (!SettingManager.Common.RetweetNoConfirm)
9955 string Questiontext = Properties.Resources.RetweetQuestion1;
9956 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9957 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9959 _DoFavRetweetFlags = false;
9965 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9967 await this.RetweetAsync(statusIds);
9971 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9972 => await this.doReTweetOfficial(true);
9974 private async Task FavoritesRetweetOfficial()
9976 if (!this.ExistCurrentPost) return;
9977 _DoFavRetweetFlags = true;
9978 var retweetTask = this.doReTweetOfficial(true);
9979 if (_DoFavRetweetFlags)
9981 _DoFavRetweetFlags = false;
9982 var favoriteTask = this.FavoriteChange(true, false);
9984 await Task.WhenAll(retweetTask, favoriteTask);
9992 private async Task FavoritesRetweetUnofficial()
9994 var post = this.CurrentPost;
9995 if (this.ExistCurrentPost && !post.IsDm)
9997 _DoFavRetweetFlags = true;
9998 var favoriteTask = this.FavoriteChange(true);
9999 if (!post.IsProtect && _DoFavRetweetFlags)
10001 _DoFavRetweetFlags = false;
10002 doReTweetUnofficial();
10005 await favoriteTask;
10010 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10012 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10013 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10014 /// <returns>復元されたツイート本文</returns>
10015 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10017 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10020 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10022 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10024 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10026 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
10030 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10032 statusHtml = statusHtml.Replace("<br>", " ");
10034 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10035 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10036 statusHtml = statusHtml.Replace(" ", " ");
10038 return WebUtility.HtmlDecode(statusHtml);
10041 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10043 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10045 if (this.CurrentPost != null)
10046 await this.DispSelectedPost(true);
10049 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10051 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10052 DebugModeToolStripMenuItem.Visible = true;
10054 DebugModeToolStripMenuItem.Visible = false;
10057 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10058 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10060 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10061 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10063 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10064 => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10066 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10068 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10069 ModifySettingCommon = true;
10072 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10074 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10075 ModifySettingCommon = true;
10078 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10080 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10081 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10082 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10083 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10084 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10085 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10088 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10090 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10091 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10092 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10093 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10094 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10095 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10098 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10100 if (TraceOutToolStripMenuItem.Checked)
10101 MyCommon.TraceFlag = true;
10103 MyCommon.TraceFlag = false;
10106 private void TweenMain_Deactivate(object sender, EventArgs e)
10107 => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10109 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10111 if (string.IsNullOrEmpty(_rclickTabName)) return;
10113 TabRename(_rclickTabName, out var _);
10116 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10117 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10119 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10120 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10122 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10124 TwitterApiStatus apiStatus;
10126 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10128 var cancellationToken = dialog.EnableCancellation();
10132 var task = this.tw.GetInfoApi();
10133 apiStatus = await dialog.WaitForAsync(this, task);
10135 catch (WebApiException)
10140 if (cancellationToken.IsCancellationRequested)
10143 if (apiStatus == null)
10145 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10150 using (var apiDlg = new ApiInfoDialog())
10152 apiDlg.ShowDialog(this);
10156 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10158 var id = this.CurrentPost?.ScreenName ?? "";
10160 await this.FollowCommand(id);
10163 internal async Task FollowCommand(string id)
10165 using (var inputName = new InputTabName())
10167 inputName.FormTitle = "Follow";
10168 inputName.FormDescription = Properties.Resources.FRMessage1;
10169 inputName.TabName = id;
10171 if (inputName.ShowDialog(this) != DialogResult.OK)
10173 if (string.IsNullOrWhiteSpace(inputName.TabName))
10176 id = inputName.TabName.Trim();
10179 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10183 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10184 await dialog.WaitForAsync(this, task);
10186 catch (WebApiException ex)
10188 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10193 MessageBox.Show(Properties.Resources.FRMessage3);
10196 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10198 var id = this.CurrentPost?.ScreenName ?? "";
10200 await this.RemoveCommand(id, false);
10203 internal async Task RemoveCommand(string id, bool skipInput)
10207 using (var inputName = new InputTabName())
10209 inputName.FormTitle = "Unfollow";
10210 inputName.FormDescription = Properties.Resources.FRMessage1;
10211 inputName.TabName = id;
10213 if (inputName.ShowDialog(this) != DialogResult.OK)
10215 if (string.IsNullOrWhiteSpace(inputName.TabName))
10218 id = inputName.TabName.Trim();
10222 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10226 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10227 await dialog.WaitForAsync(this, task);
10229 catch (WebApiException ex)
10231 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10236 MessageBox.Show(Properties.Resources.FRMessage3);
10239 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10241 var id = this.CurrentPost?.ScreenName ?? "";
10243 await this.ShowFriendship(id);
10246 internal async Task ShowFriendship(string id)
10248 using (var inputName = new InputTabName())
10250 inputName.FormTitle = "Show Friendships";
10251 inputName.FormDescription = Properties.Resources.FRMessage1;
10252 inputName.TabName = id;
10254 if (inputName.ShowDialog(this) != DialogResult.OK)
10256 if (string.IsNullOrWhiteSpace(inputName.TabName))
10259 id = inputName.TabName.Trim();
10262 bool isFollowing, isFollowed;
10264 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10266 var cancellationToken = dialog.EnableCancellation();
10270 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10271 var friendship = await dialog.WaitForAsync(this, task);
10273 isFollowing = friendship.Relationship.Source.Following;
10274 isFollowed = friendship.Relationship.Source.FollowedBy;
10276 catch (WebApiException ex)
10278 if (!cancellationToken.IsCancellationRequested)
10279 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10283 if (cancellationToken.IsCancellationRequested)
10287 string result = "";
10290 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10294 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10298 result += Properties.Resources.GetFriendshipInfo3;
10302 result += Properties.Resources.GetFriendshipInfo4;
10304 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10305 MessageBox.Show(result);
10308 internal async Task ShowFriendship(string[] ids)
10310 foreach (string id in ids)
10312 bool isFollowing, isFollowed;
10314 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10316 var cancellationToken = dialog.EnableCancellation();
10320 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10321 var friendship = await dialog.WaitForAsync(this, task);
10323 isFollowing = friendship.Relationship.Source.Following;
10324 isFollowed = friendship.Relationship.Source.FollowedBy;
10326 catch (WebApiException ex)
10328 if (!cancellationToken.IsCancellationRequested)
10329 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10333 if (cancellationToken.IsCancellationRequested)
10337 string result = "";
10343 ff += Properties.Resources.GetFriendshipInfo1;
10347 ff += Properties.Resources.GetFriendshipInfo2;
10350 ff += System.Environment.NewLine + " ";
10353 ff += Properties.Resources.GetFriendshipInfo3;
10357 ff += Properties.Resources.GetFriendshipInfo4;
10359 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10362 if (MessageBox.Show(
10363 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10364 MessageBoxButtons.YesNo,
10365 MessageBoxIcon.Question,
10366 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10368 await this.RemoveCommand(id, true);
10373 MessageBox.Show(result);
10378 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10379 => await this.doShowUserStatus(tw.Username, false);
10381 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10382 // URLから切り出した文字列を渡す
10384 public bool IsTwitterId(string name)
10386 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10387 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10389 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10392 private void doQuoteOfficial()
10394 if (this.ExistCurrentPost)
10396 var post = this.CurrentPost;
10397 if (post.IsDm || !StatusText.Enabled)
10400 if (post.IsProtect)
10402 MessageBox.Show("Protected.");
10406 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10408 this.inReplyTo = null;
10410 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10412 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10413 StatusText.Focus();
10417 private void doReTweetUnofficial()
10420 if (this.ExistCurrentPost)
10422 var post = this.CurrentPost;
10423 if (post.IsDm || !StatusText.Enabled)
10426 if (post.IsProtect)
10428 MessageBox.Show("Protected.");
10431 string rtdata = post.Text;
10432 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10434 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10436 // 投稿時に in_reply_to_status_id を付加する
10437 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10438 var inReplyToScreenName = post.ScreenName;
10439 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10441 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10443 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10444 StatusText.Focus();
10448 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10449 => this.doQuoteOfficial();
10451 private async void SearchButton_Click(object sender, EventArgs e)
10454 Control pnl = ((Control)sender).Parent;
10455 if (pnl == null) return;
10456 string tbName = pnl.Parent.Text;
10457 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10458 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10459 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10460 cmb.Text = cmb.Text.Trim();
10461 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10462 bool Quote = false;
10463 StringBuilder buf = new StringBuilder();
10464 char[] c = cmb.Text.ToCharArray();
10465 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10467 if (cnt > cmb.Text.Length - 4)
10469 buf.Append(cmb.Text.Substring(cnt));
10478 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10480 buf.Append(" OR ");
10485 buf.Append(c[cnt]);
10487 cmb.Text = buf.ToString();
10489 var listView = (DetailsListView)pnl.Parent.Tag;
10491 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10493 tb.SearchWords = cmb.Text;
10494 tb.SearchLang = cmbLang.Text;
10495 if (string.IsNullOrEmpty(cmb.Text))
10503 int idx = cmb.Items.IndexOf(tb.SearchWords);
10504 if (idx > -1) cmb.Items.RemoveAt(idx);
10505 cmb.Items.Insert(0, tb.SearchWords);
10506 cmb.Text = tb.SearchWords;
10508 this.PurgeListViewItemCache();
10509 listView.VirtualListSize = 0;
10510 _statuses.ClearTabIds(tbName);
10511 SaveConfigsTabs(); //検索条件の保存
10515 await this.RefreshTabAsync(tb);
10518 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10519 => await this.DoRefreshMore(); // もっと前を取得
10522 /// 指定されたタブのListTabにおける位置を返します
10525 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10527 public int GetTabPageIndex(string tabName)
10528 => this._statuses.Tabs.IndexOf(tabName);
10530 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10532 if (_statuses.RemovedTab.Count == 0)
10534 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10539 DetailsListView listView = null;
10541 TabModel tb = _statuses.RemovedTab.Pop();
10542 if (tb.TabType == MyCommon.TabUsageType.Related)
10544 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10545 if (relatedTab != null)
10547 // 関連発言なら既存のタブを置き換える
10548 tb.TabName = relatedTab.TabName;
10549 this.ClearTab(tb.TabName, false);
10551 this._statuses.ReplaceTab(tb);
10553 var tabIndex = this._statuses.Tabs.IndexOf(tb);
10554 var tabPage = this.ListTab.TabPages[tabIndex];
10555 listView = (DetailsListView)tabPage.Tag;
10556 this.ListTab.SelectedIndex = tabIndex;
10560 const string TabName = "Related Tweets";
10561 string renamed = TabName;
10562 for (int i = 2; i <= 100; i++)
10564 if (!_statuses.ContainsTab(renamed)) break;
10565 renamed = TabName + i;
10567 tb.TabName = renamed;
10569 _statuses.AddTab(tb);
10570 AddNewTab(tb, startup: false);
10572 var tabIndex = this._statuses.Tabs.Count - 1;
10573 var tabPage = this.ListTab.TabPages[tabIndex];
10575 listView = (DetailsListView)tabPage.Tag;
10576 this.ListTab.SelectedIndex = tabIndex;
10581 string renamed = tb.TabName;
10582 for (int i = 1; i < int.MaxValue; i++)
10584 if (!_statuses.ContainsTab(renamed)) break;
10585 renamed = tb.TabName + "(" + i + ")";
10587 tb.TabName = renamed;
10589 _statuses.AddTab(tb);
10590 AddNewTab(tb, startup: false);
10592 var tabIndex = this._statuses.Tabs.Count - 1;
10593 var tabPage = this.ListTab.TabPages[tabIndex];
10595 listView = (DetailsListView)tabPage.Tag;
10596 this.ListTab.SelectedIndex = tabIndex;
10600 if (listView != null)
10602 using (ControlTransaction.Update(listView))
10604 listView.VirtualListSize = tb.AllCount;
10610 private async Task doMoveToRTHome()
10612 var post = this.CurrentPost;
10613 if (post != null && post.RetweetedId != null)
10614 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10617 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10618 => await this.doMoveToRTHome();
10620 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10622 var screenName = this.CurrentPost?.ScreenName;
10623 if (screenName != null)
10624 this.ListManageUserContext(screenName);
10627 public void ListManageUserContext(string screenName)
10629 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10631 listSelectForm.ShowDialog(this);
10635 private void SearchControls_Enter(object sender, EventArgs e)
10637 Control pnl = (Control)sender;
10638 foreach (Control ctl in pnl.Controls)
10640 ctl.TabStop = true;
10644 private void SearchControls_Leave(object sender, EventArgs e)
10646 Control pnl = (Control)sender;
10647 foreach (Control ctl in pnl.Controls)
10649 ctl.TabStop = false;
10653 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10655 var tab = this.CurrentTab;
10656 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10657 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10660 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10661 => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10663 private void HashManageMenuItem_Click(object sender, EventArgs e)
10665 DialogResult rslt = DialogResult.Cancel;
10668 rslt = HashMgr.ShowDialog();
10674 this.TopMost = SettingManager.Common.AlwaysTop;
10675 if (rslt == DialogResult.Cancel) return;
10676 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10678 HashStripSplitButton.Text = HashMgr.UseHash;
10679 HashTogglePullDownMenuItem.Checked = true;
10680 HashToggleMenuItem.Checked = true;
10684 HashStripSplitButton.Text = "#[-]";
10685 HashTogglePullDownMenuItem.Checked = false;
10686 HashToggleMenuItem.Checked = false;
10688 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10690 // int sidx = StatusText.SelectionStart;
10691 // string hash = HashMgr.UseHash + " ";
10694 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10695 // hash = " " + hash;
10697 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10698 // sidx += hash.Length;
10699 // StatusText.SelectionStart = sidx;
10700 // StatusText.Focus();
10702 ModifySettingCommon = true;
10703 this.StatusText_TextChanged(null, null);
10706 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10708 HashMgr.ToggleHash();
10709 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10711 HashStripSplitButton.Text = HashMgr.UseHash;
10712 HashToggleMenuItem.Checked = true;
10713 HashTogglePullDownMenuItem.Checked = true;
10717 HashStripSplitButton.Text = "#[-]";
10718 HashToggleMenuItem.Checked = false;
10719 HashTogglePullDownMenuItem.Checked = false;
10721 ModifySettingCommon = true;
10722 this.StatusText_TextChanged(null, null);
10725 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10726 => this.HashToggleMenuItem_Click(null, null);
10728 public void SetPermanentHashtag(string hashtag)
10730 HashMgr.SetPermanentHash("#" + hashtag);
10731 HashStripSplitButton.Text = HashMgr.UseHash;
10732 HashTogglePullDownMenuItem.Checked = true;
10733 HashToggleMenuItem.Checked = true;
10735 ModifySettingCommon = true;
10738 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10740 if (!this.ExistCurrentPost)
10742 this.ReplyOpMenuItem.Enabled = false;
10743 this.ReplyAllOpMenuItem.Enabled = false;
10744 this.DmOpMenuItem.Enabled = false;
10745 this.ShowProfMenuItem.Enabled = false;
10746 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10747 this.ListManageMenuItem.Enabled = false;
10748 this.OpenFavOpMenuItem.Enabled = false;
10749 this.CreateTabRuleOpMenuItem.Enabled = false;
10750 this.CreateIdRuleOpMenuItem.Enabled = false;
10751 this.CreateSourceRuleOpMenuItem.Enabled = false;
10752 this.ReadOpMenuItem.Enabled = false;
10753 this.UnreadOpMenuItem.Enabled = false;
10757 this.ReplyOpMenuItem.Enabled = true;
10758 this.ReplyAllOpMenuItem.Enabled = true;
10759 this.DmOpMenuItem.Enabled = true;
10760 this.ShowProfMenuItem.Enabled = true;
10761 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10762 this.ListManageMenuItem.Enabled = true;
10763 this.OpenFavOpMenuItem.Enabled = true;
10764 this.CreateTabRuleOpMenuItem.Enabled = true;
10765 this.CreateIdRuleOpMenuItem.Enabled = true;
10766 this.CreateSourceRuleOpMenuItem.Enabled = true;
10767 this.ReadOpMenuItem.Enabled = true;
10768 this.UnreadOpMenuItem.Enabled = true;
10771 var tab = this.CurrentTab;
10772 var post = this.CurrentPost;
10773 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
10775 this.FavOpMenuItem.Enabled = false;
10776 this.UnFavOpMenuItem.Enabled = false;
10777 this.OpenStatusOpMenuItem.Enabled = false;
10778 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10779 this.RtOpMenuItem.Enabled = false;
10780 this.RtUnOpMenuItem.Enabled = false;
10781 this.QtOpMenuItem.Enabled = false;
10782 this.FavoriteRetweetMenuItem.Enabled = false;
10783 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10787 this.FavOpMenuItem.Enabled = true;
10788 this.UnFavOpMenuItem.Enabled = true;
10789 this.OpenStatusOpMenuItem.Enabled = true;
10790 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10792 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10794 this.RtOpMenuItem.Enabled = false;
10795 this.RtUnOpMenuItem.Enabled = false;
10796 this.QtOpMenuItem.Enabled = false;
10797 this.FavoriteRetweetMenuItem.Enabled = false;
10798 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10802 this.RtOpMenuItem.Enabled = true;
10803 this.RtUnOpMenuItem.Enabled = true;
10804 this.QtOpMenuItem.Enabled = true;
10805 this.FavoriteRetweetMenuItem.Enabled = true;
10806 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10810 if (tab.TabType != MyCommon.TabUsageType.Favorites)
10812 this.RefreshPrevOpMenuItem.Enabled = true;
10816 this.RefreshPrevOpMenuItem.Enabled = false;
10818 if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
10820 OpenRepSourceOpMenuItem.Enabled = false;
10824 OpenRepSourceOpMenuItem.Enabled = true;
10826 if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
10828 OpenRterHomeMenuItem.Enabled = false;
10832 OpenRterHomeMenuItem.Enabled = true;
10835 if (this.ExistCurrentPost)
10837 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10841 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10842 => this.ContextMenuTabProperty_Opening(sender, null);
10844 public Twitter TwitterInstance
10847 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10849 if (this._initialLayout)
10852 int splitterDistance;
10853 switch (this.WindowState)
10855 case FormWindowState.Normal:
10856 splitterDistance = this.SplitContainer3.SplitterDistance;
10858 case FormWindowState.Maximized:
10859 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10860 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10861 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10862 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10868 this._mySpDis3 = splitterDistance;
10869 this.ModifySettingLocal = true;
10872 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10874 if (_statuses.RemovedTab.Count == 0)
10876 UndoRemoveTabMenuItem.Enabled = false;
10880 UndoRemoveTabMenuItem.Enabled = true;
10883 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10884 PublicSearchQueryMenuItem.Enabled = true;
10886 PublicSearchQueryMenuItem.Enabled = false;
10888 if (!this.ExistCurrentPost)
10890 this.CopySTOTMenuItem.Enabled = false;
10891 this.CopyURLMenuItem.Enabled = false;
10892 this.CopyUserIdStripMenuItem.Enabled = false;
10896 this.CopySTOTMenuItem.Enabled = true;
10897 this.CopyURLMenuItem.Enabled = true;
10898 this.CopyUserIdStripMenuItem.Enabled = true;
10900 var post = this.CurrentPost;
10901 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10902 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10906 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10907 => this.SetNotifyIconText();
10909 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10910 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10912 private async Task doShowUserStatus(string id, bool ShowInputDialog)
10914 TwitterUser user = null;
10916 if (ShowInputDialog)
10918 using (var inputName = new InputTabName())
10920 inputName.FormTitle = "Show UserStatus";
10921 inputName.FormDescription = Properties.Resources.FRMessage1;
10922 inputName.TabName = id;
10924 if (inputName.ShowDialog(this) != DialogResult.OK)
10926 if (string.IsNullOrWhiteSpace(inputName.TabName))
10929 id = inputName.TabName.Trim();
10933 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10935 var cancellationToken = dialog.EnableCancellation();
10939 var task = this.twitterApi.UsersShow(id);
10940 user = await dialog.WaitForAsync(this, task);
10942 catch (WebApiException ex)
10944 if (!cancellationToken.IsCancellationRequested)
10945 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10949 if (cancellationToken.IsCancellationRequested)
10953 await this.doShowUserStatus(user);
10956 private async Task doShowUserStatus(TwitterUser user)
10958 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
10960 var showUserTask = userDialog.ShowUserAsync(user);
10961 userDialog.ShowDialog(this);
10964 this.BringToFront();
10966 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10967 await showUserTask;
10971 internal Task ShowUserStatus(string id, bool ShowInputDialog)
10972 => this.doShowUserStatus(id, ShowInputDialog);
10974 internal Task ShowUserStatus(string id)
10975 => this.doShowUserStatus(id, true);
10977 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10979 var post = this.CurrentPost;
10982 await this.ShowUserStatus(post.ScreenName, false);
10986 private async void RtCountMenuItem_Click(object sender, EventArgs e)
10988 if (!this.ExistCurrentPost)
10991 var post = this.CurrentPost;
10992 var statusId = post.RetweetedId ?? post.StatusId;
10993 TwitterStatus status;
10995 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
10997 var cancellationToken = dialog.EnableCancellation();
11001 var task = this.twitterApi.StatusesShow(statusId);
11002 status = await dialog.WaitForAsync(this, task);
11004 catch (WebApiException ex)
11006 if (!cancellationToken.IsCancellationRequested)
11007 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11011 if (cancellationToken.IsCancellationRequested)
11015 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11018 private HookGlobalHotkey _hookGlobalHotkey;
11021 _hookGlobalHotkey = new HookGlobalHotkey(this);
11023 // この呼び出しは、Windows フォーム デザイナで必要です。
11024 InitializeComponent();
11026 // InitializeComponent() 呼び出しの後で初期化を追加します。
11028 if (!this.DesignMode)
11030 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11031 this.StatusText.Dock = DockStyle.Fill;
11034 this.tweetDetailsView.Owner = this;
11036 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11037 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11038 this.gh.NotifyClicked += GrowlHelper_Callback;
11040 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11041 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11043 this.ImageSelector.Visible = false;
11044 this.ImageSelector.Enabled = false;
11045 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11047 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11049 this.ReplaceAppName();
11050 this.InitializeShortcuts();
11053 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11055 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11058 this.Visible = false;
11060 else if (Form.ActiveForm == null)
11062 this.Visible = true;
11063 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11065 this.BringToFront();
11066 this.StatusText.Focus();
11070 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11071 => this.MultiLinePullDownMenuItem.PerformClick();
11074 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11076 if (ImageSelector.Visible)
11077 ImageSelector.EndSelection();
11079 ImageSelector.BeginSelection();
11082 private void SelectMedia_DragEnter(DragEventArgs e)
11084 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11086 e.Effect = DragDropEffects.Copy;
11089 e.Effect = DragDropEffects.None;
11092 private void SelectMedia_DragDrop(DragEventArgs e)
11095 this.BringToFront();
11096 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11097 StatusText.Focus();
11100 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11102 TimelinePanel.Visible = false;
11103 TimelinePanel.Enabled = false;
11106 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11108 TimelinePanel.Visible = true;
11109 TimelinePanel.Enabled = true;
11110 this.CurrentListView.Focus();
11113 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11114 => this.AllowDrop = false;
11116 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11117 => this.AllowDrop = true;
11119 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11121 if (ImageSelector.Visible)
11123 ModifySettingCommon = true;
11124 SaveConfigsAll(true);
11126 this.StatusText_TextChanged(null, null);
11130 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11131 => this.StatusText_TextChanged(null, null);
11134 /// StatusTextでCtrl+Vが押下された時の処理
11136 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11140 if (Clipboard.ContainsText())
11142 // clipboardにテキストがある場合は貼り付け処理
11143 this.StatusText.Paste(Clipboard.GetText());
11145 else if (Clipboard.ContainsImage())
11148 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11149 Properties.Resources.PostPictureWarn4,
11150 MessageBoxButtons.OKCancel,
11151 MessageBoxIcon.Question,
11152 MessageBoxDefaultButton.Button2)
11153 == DialogResult.OK)
11155 // clipboardから画像を取得
11156 using (var image = Clipboard.GetImage())
11158 this.ImageSelector.BeginSelection(image);
11163 catch (ExternalException ex)
11165 MessageBox.Show(ex.Message);
11170 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11172 using (ListManage form = new ListManage(tw))
11174 form.ShowDialog(this);
11178 public bool ModifySettingCommon { get; set; }
11179 public bool ModifySettingLocal { get; set; }
11180 public bool ModifySettingAtId { get; set; }
11182 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11184 var post = this.CurrentPost;
11185 if (this.ExistCurrentPost && !post.IsDm)
11186 RtCountMenuItem.Enabled = true;
11188 RtCountMenuItem.Enabled = false;
11190 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11191 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11193 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11196 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11197 => this.CopyUserId();
11199 private void CopyUserId()
11201 var post = this.CurrentPost;
11202 if (post == null) return;
11203 var clstr = post.ScreenName;
11206 Clipboard.SetDataObject(clstr, false, 5, 100);
11208 catch (Exception ex)
11210 MessageBox.Show(ex.Message);
11214 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11216 var post = this.CurrentPost;
11217 if (this.ExistCurrentPost && !post.IsDm)
11221 await this.OpenRelatedTab(post);
11223 catch (TabException ex)
11225 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11231 /// 指定されたツイートに対する関連発言タブを開きます
11233 /// <param name="statusId">表示するツイートのID</param>
11234 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11235 public async Task OpenRelatedTab(long statusId)
11237 var post = this._statuses[statusId];
11242 post = await this.tw.GetStatusApi(false, statusId);
11244 catch (WebApiException ex)
11246 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11251 await this.OpenRelatedTab(post);
11255 /// 指定されたツイートに対する関連発言タブを開きます
11257 /// <param name="post">表示する対象となるツイート</param>
11258 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11259 private async Task OpenRelatedTab(PostClass post)
11261 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11262 if (tabRelated != null)
11264 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11267 var tabName = this._statuses.MakeTabName("Related Tweets");
11269 tabRelated = new RelatedPostsTabModel(tabName, post)
11271 UnreadManage = false,
11275 this._statuses.AddTab(tabRelated);
11276 this.AddNewTab(tabRelated, startup: false);
11278 this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11280 await this.RefreshTabAsync(tabRelated);
11282 var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11284 if (tabIndex != -1)
11286 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11288 var tabPage = this.ListTab.TabPages[tabIndex];
11289 var listView = (DetailsListView)tabPage.Tag;
11290 var targetPost = tabRelated.TargetPost;
11291 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11293 if (index != -1 && index < listView.Items.Count)
11295 listView.SelectedIndices.Add(index);
11296 listView.Items[index].Focused = true;
11301 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11303 StringBuilder buf = new StringBuilder();
11304 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11305 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11306 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11307 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11308 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11311 private void tw_UserIdChanged()
11312 => this.ModifySettingCommon = true;
11314 #region "Userstream"
11315 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11319 if (InvokeRequired && !IsDisposed)
11321 await this.InvokeAsync(async () =>
11323 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11324 if (this.CurrentTab.Contains(e.StatusId))
11326 this.PurgeListViewItemCache();
11327 this.CurrentListView.Update();
11328 var post = this.CurrentPost;
11329 if (post != null && post.StatusId == e.StatusId)
11330 await this.DispSelectedPost(true);
11336 catch (ObjectDisposedException)
11340 catch (InvalidOperationException)
11346 private void tw_NewPostFromStream(object sender, EventArgs e)
11348 if (SettingManager.Common.ReadOldPosts)
11350 _statuses.SetReadHomeTab(); //新着時未読クリア
11353 this._statuses.DistributePosts();
11355 this.RefreshThrottlingTimer.Invoke();
11358 private async void tw_UserStreamStarted(object sender, EventArgs e)
11362 if (InvokeRequired && !IsDisposed)
11364 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11368 catch (ObjectDisposedException)
11372 catch (InvalidOperationException)
11377 this.RefreshUserStreamsMenu();
11378 this.MenuItemUserStream.Enabled = true;
11380 StatusLabel.Text = "UserStream Started.";
11383 private async void tw_UserStreamStopped(object sender, EventArgs e)
11387 if (InvokeRequired && !IsDisposed)
11389 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11393 catch (ObjectDisposedException)
11397 catch (InvalidOperationException)
11402 this.RefreshUserStreamsMenu();
11403 this.MenuItemUserStream.Enabled = true;
11405 StatusLabel.Text = "UserStream Stopped.";
11408 private void RefreshUserStreamsMenu()
11410 if (this.tw.UserStreamActive)
11412 this.MenuItemUserStream.Text = "&UserStream ▶";
11413 this.StopToolStripMenuItem.Text = "&Stop";
11417 this.MenuItemUserStream.Text = "&UserStream ■";
11418 this.StopToolStripMenuItem.Text = "&Start";
11422 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11426 if (InvokeRequired && !IsDisposed)
11428 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11432 catch (ObjectDisposedException)
11436 catch (InvalidOperationException)
11440 var ev = e.EventData;
11441 StatusLabel.Text = "Event: " + ev.Event;
11442 //if (ev.Event == "favorite")
11444 // NotifyFavorite(ev);
11447 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11449 if (this.CurrentTab.Contains(ev.Id))
11451 this.PurgeListViewItemCache();
11452 this.CurrentListView.Update();
11454 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11456 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11457 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11462 private void NotifyEvent(Twitter.FormattedEvent ev)
11465 if (BalloonRequired(ev))
11467 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11468 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11469 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11470 StringBuilder title = new StringBuilder();
11471 if (SettingManager.Common.DispUsername)
11473 title.Append(tw.Username);
11474 title.Append(" - ");
11480 title.Append(ApplicationSettings.ApplicationName);
11481 title.Append(" [");
11482 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11483 title.Append("] by ");
11484 if (!string.IsNullOrEmpty(ev.Username))
11486 title.Append(ev.Username);
11490 //title.Append("");
11493 if (!string.IsNullOrEmpty(ev.Target))
11495 //NotifyIcon1.BalloonTipText = ev.Target;
11500 //NotifyIcon1.BalloonTipText = " ";
11503 //NotifyIcon1.ShowBalloonTip(500);
11504 if (SettingManager.Common.IsUseNotifyGrowl)
11506 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11507 ev.Id.ToString(), title.ToString(), text);
11511 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11512 NotifyIcon1.BalloonTipTitle = title.ToString();
11513 NotifyIcon1.BalloonTipText = text;
11514 NotifyIcon1.ShowBalloonTip(500);
11519 string snd = SettingManager.Common.EventSoundFile;
11520 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11522 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11526 string dir = Application.StartupPath;
11527 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11529 dir = Path.Combine(dir, "Sounds");
11531 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11543 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11545 MenuItemUserStream.Enabled = false;
11546 if (StopRefreshAllMenuItem.Checked)
11548 StopRefreshAllMenuItem.Checked = false;
11551 if (this.tw.UserStreamActive)
11553 tw.StopUserStream();
11557 tw.StartUserStream();
11561 private static string inputTrack = "";
11563 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11565 if (TrackToolStripMenuItem.Checked)
11567 using (InputTabName inputForm = new InputTabName())
11569 inputForm.TabName = inputTrack;
11570 inputForm.FormTitle = "Input track word";
11571 inputForm.FormDescription = "Track word";
11572 if (inputForm.ShowDialog() != DialogResult.OK)
11574 TrackToolStripMenuItem.Checked = false;
11577 inputTrack = inputForm.TabName.Trim();
11579 if (!inputTrack.Equals(tw.TrackWord))
11581 tw.TrackWord = inputTrack;
11582 this.ModifySettingCommon = true;
11583 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11584 tw.ReconnectUserStream();
11590 tw.ReconnectUserStream();
11592 this.ModifySettingCommon = true;
11595 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11597 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11598 this.ModifySettingCommon = true;
11599 tw.ReconnectUserStream();
11602 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11604 if (evtDialog == null || evtDialog.IsDisposed)
11606 this.evtDialog = new EventViewerDialog
11612 this.evtDialog.Location = new Point
11614 X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11615 Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11618 evtDialog.EventSource = tw.StoredEvent;
11619 if (!evtDialog.Visible)
11621 evtDialog.Show(this);
11625 evtDialog.Activate();
11627 this.TopMost = SettingManager.Common.AlwaysTop;
11631 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11633 MyCommon._endingFlag = true;
11637 Application.Restart();
11641 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11645 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11646 => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11648 private bool ExistCurrentPost
11652 var post = this.CurrentPost;
11653 return post != null && !post.IsDeleted;
11657 private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11658 => await this.ShowUserTimeline();
11660 private string GetUserIdFromCurPostOrInput(string caption)
11662 var id = this.CurrentPost?.ScreenName ?? "";
11664 using (InputTabName inputName = new InputTabName())
11666 inputName.FormTitle = caption;
11667 inputName.FormDescription = Properties.Resources.FRMessage1;
11668 inputName.TabName = id;
11669 if (inputName.ShowDialog() == DialogResult.OK &&
11670 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11672 id = inputName.TabName.Trim();
11682 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11684 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11685 if (!string.IsNullOrEmpty(id))
11687 await this.AddNewTabForUserTimeline(id);
11691 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11693 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11696 private async void SystemEvents_TimeChanged(object sender, EventArgs e)
11698 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11700 TimeZoneInfo.ClearCachedData();
11702 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11704 if (curTimeOffset != prevTimeOffset)
11707 this.PurgeListViewItemCache();
11708 this.CurrentListView.Refresh();
11710 await this.DispSelectedPost(forceupdate: true);
11714 private void TimelineRefreshEnableChange(bool isEnable)
11718 tw.StartUserStream();
11722 tw.StopUserStream();
11724 TimerTimeline.Enabled = isEnable;
11727 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11728 => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11730 private async Task OpenUserAppointUrl()
11732 if (SettingManager.Common.UserAppointUrl != null)
11734 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11736 var post = this.CurrentPost;
11739 string xUrl = SettingManager.Common.UserAppointUrl;
11740 xUrl = xUrl.Replace("{ID}", post.ScreenName);
11742 var statusId = post.RetweetedId ?? post.StatusId;
11743 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11745 await this.OpenUriInBrowserAsync(xUrl);
11750 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11755 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11756 => await this.OpenUserAppointUrl();
11758 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11760 if (Form.ActiveForm == null)
11762 await this.InvokeAsync(() =>
11764 this.Visible = true;
11765 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11767 this.BringToFront();
11768 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11770 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11774 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11780 private void ReplaceAppName()
11782 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11783 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11786 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11787 => this.SplitContainer3.Panel2Collapsed = false;
11789 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11790 => await this.OpenThumbnailPicture(e.Thumbnail);
11792 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11793 => await this.OpenUriInBrowserAsync(e.ImageUrl);
11795 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11797 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11799 await this.OpenUriInBrowserAsync(url);
11802 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11803 => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11805 private void PostButton_KeyDown(object sender, KeyEventArgs e)
11807 if (e.KeyCode == Keys.Space)
11809 this.JumpUnreadMenuItem_Click(null, null);
11811 e.SuppressKeyPress = true;
11815 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11817 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11818 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11819 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11820 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11821 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11823 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11826 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11827 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11829 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11830 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11832 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11833 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11835 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11836 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11838 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11839 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11841 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11843 if (SettingManager.Common.IconSize == iconSize) return;
11845 var oldIconCol = _iconCol;
11847 SettingManager.Common.IconSize = iconSize;
11848 ApplyListViewIconSize(iconSize);
11850 if (_iconCol != oldIconCol)
11852 foreach (TabPage tp in ListTab.TabPages)
11854 ResetColumns((DetailsListView)tp.Tag);
11858 this.CurrentListView.Refresh();
11860 ModifySettingCommon = true;
11863 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11865 var state = this.LockListSortOrderToolStripMenuItem.Checked;
11866 if (SettingManager.Common.SortOrderLock == state) return;
11868 SettingManager.Common.SortOrderLock = state;
11870 ModifySettingCommon = true;
11873 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11875 if (!string.IsNullOrEmpty(e.StatusText))
11877 this.StatusLabelUrl.Text = e.StatusText;
11881 this.SetStatusLabelUrl();