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.
30 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Connection;
56 using OpenTween.Models;
57 using OpenTween.OpenTweenCustomControl;
58 using OpenTween.Setting;
59 using OpenTween.Thumbnail;
63 public partial class TweenMain : OTBaseForm
67 /// <summary>画面サイズ</summary>
70 /// <summary>画面位置</summary>
73 /// <summary>区切り位置</summary>
76 /// <summary>発言欄区切り位置</summary>
77 private int _mySpDis2;
79 /// <summary>プレビュー区切り位置</summary>
80 private int _mySpDis3;
82 /// <summary>アイコンサイズ</summary>
84 /// 現在は16、24、48の3種類。将来直接数字指定可能とする
85 /// 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様
89 private bool _iconCol; // 1列表示の時true(48サイズのとき)
92 private bool _initial; // true:起動時処理中
93 private bool _initialLayout = true;
94 private bool _ignoreConfigSave; // true:起動時処理中
96 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
97 private bool _tabDrag;
99 private TabPage? _beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
100 private Point _tabMouseDownPoint;
102 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
103 private string? _rclickTabName;
105 private readonly object _syncObject = new object(); // ロック用
107 private const string detailHtmlFormatHeaderMono =
108 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
109 + "<style type=\"text/css\"><!-- "
110 + "body, p, pre {margin: 0;} "
111 + "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%);} "
112 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
113 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
114 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
115 + ".quote-tweet.reply {border-color: #f33;} "
116 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
118 + "</head><body><pre>";
119 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
120 private const string detailHtmlFormatHeaderColor =
121 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
122 + "<style type=\"text/css\"><!-- "
123 + "body, p, pre {margin: 0;} "
124 + "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%);} "
125 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
126 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
127 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
128 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
129 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
131 + "</head><body><p>";
132 private const string detailHtmlFormatFooterColor = "</p></body></html>";
133 private string detailHtmlFormatHeader = null!;
134 private string detailHtmlFormatFooter = null!;
136 private bool _myStatusError = false;
137 private bool _myStatusOnline = false;
138 private bool soundfileListup = false;
139 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
142 private readonly TwitterApi twitterApi = new TwitterApi();
143 private Twitter tw = null!;
146 private readonly GrowlHelper gh = new GrowlHelper(ApplicationSettings.ApplicationName);
150 /// <summary>検索画面インスタンス</summary>
151 internal SearchWordDialog SearchDialog = new SearchWordDialog();
153 private readonly OpenURL UrlDialog = new OpenURL();
155 /// <summary>@id補助</summary>
156 public AtIdSupplement AtIdSupl = null!;
158 /// <summary>Hashtag補助</summary>
159 public AtIdSupplement HashSupl = null!;
161 public HashtagManage HashMgr = null!;
162 private EventViewerDialog evtDialog = null!;
166 /// <summary>未読用フォント</summary>
167 private Font _fntUnread = null!;
169 /// <summary>未読用文字色</summary>
170 private Color _clUnread;
172 /// <summary>既読用フォント</summary>
173 private Font _fntReaded = null!;
175 /// <summary>既読用文字色</summary>
176 private Color _clReaded;
178 /// <summary>Fav用文字色</summary>
179 private Color _clFav;
181 /// <summary>片思い用文字色</summary>
182 private Color _clOWL;
184 /// <summary>Retweet用文字色</summary>
185 private Color _clRetweet;
187 /// <summary>選択中の行用文字色</summary>
188 private readonly Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);
190 /// <summary>発言詳細部用フォント</summary>
191 private Font _fntDetail = null!;
193 /// <summary>発言詳細部用色</summary>
194 private Color _clDetail;
196 /// <summary>発言詳細部用リンク文字色</summary>
197 private Color _clDetailLink;
199 /// <summary>発言詳細部用背景色</summary>
200 private Color _clDetailBackcolor;
202 /// <summary>自分の発言用背景色</summary>
203 private Color _clSelf;
205 /// <summary>自分宛返信用背景色</summary>
206 private Color _clAtSelf;
208 /// <summary>選択発言者の他の発言用背景色</summary>
209 private Color _clTarget;
211 /// <summary>選択発言中の返信先用背景色</summary>
212 private Color _clAtTarget;
214 /// <summary>選択発言者への返信発言用背景色</summary>
215 private Color _clAtFromTarget;
217 /// <summary>選択発言の唯一@先</summary>
218 private Color _clAtTo;
220 /// <summary>リスト部通常発言背景色</summary>
221 private Color _clListBackcolor;
223 /// <summary>入力欄背景色</summary>
224 private Color _clInputBackcolor;
226 /// <summary>入力欄文字色</summary>
227 private Color _clInputFont;
229 /// <summary>入力欄フォント</summary>
230 private Font _fntInputFont = null!;
232 /// <summary>アイコン画像リスト</summary>
233 private ImageCache IconCache = null!;
235 /// <summary>タスクトレイアイコン:通常時 (At.ico)</summary>
236 private Icon NIconAt = null!;
238 /// <summary>タスクトレイアイコン:通信エラー時 (AtRed.ico)</summary>
239 private Icon NIconAtRed = null!;
241 /// <summary>タスクトレイアイコン:オフライン時 (AtSmoke.ico)</summary>
242 private Icon NIconAtSmoke = null!;
244 /// <summary>タスクトレイアイコン:更新中 (Refresh.ico)</summary>
245 private Icon[] NIconRefresh = new Icon[4];
247 /// <summary>未読のあるタブ用アイコン (Tab.ico)</summary>
248 private Icon TabIcon = null!;
250 /// <summary>画面左上のアイコン (Main.ico)</summary>
251 private Icon MainIcon = null!;
253 private Icon ReplyIcon = null!;
254 private Icon ReplyIconBlink = null!;
256 private readonly ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
258 private PostClass? _anchorPost;
259 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
261 /// <summary>発言履歴</summary>
262 private readonly List<StatusTextHistory> _history = new List<StatusTextHistory>();
264 /// <summary>発言履歴カレントインデックス</summary>
267 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
269 /// <summary>リプライ先のステータスID・スクリーン名</summary>
270 private (long StatusId, string ScreenName)? inReplyTo = null;
273 private readonly List<DateTimeUtc> _postTimestamps = new List<DateTimeUtc>();
274 private readonly List<DateTimeUtc> _favTimestamps = new List<DateTimeUtc>();
277 private readonly SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
278 private SolidBrush _brsBackColorMine = null!;
279 private SolidBrush _brsBackColorAt = null!;
280 private SolidBrush _brsBackColorYou = null!;
281 private SolidBrush _brsBackColorAtYou = null!;
282 private SolidBrush _brsBackColorAtFromTarget = null!;
283 private SolidBrush _brsBackColorAtTo = null!;
284 private SolidBrush _brsBackColorNone = null!;
286 /// <summary>Listにフォーカスないときの選択行の背景色</summary>
287 private readonly SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace));
289 private readonly StringFormat sfTab = new StringFormat();
291 //////////////////////////////////////////////////////////////////////////////////////////////////////////
292 private TabInformations _statuses = null!;
295 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
298 /// キャッシュクリアのために null が代入されることがあるため、
299 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
300 /// 一旦ローカル変数に代入してから参照すること。
302 private ListViewItemCache? _listItemCache = null;
304 internal class ListViewItemCache
306 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
307 public ListView TargetList { get; set; } = null!;
309 /// <summary>キャッシュする範囲の開始インデックス</summary>
310 public int StartIndex { get; set; }
312 /// <summary>キャッシュする範囲の終了インデックス</summary>
313 public int EndIndex { get; set; }
315 /// <summary>キャッシュされた範囲に対応する <see cref="ListViewItem"/> と <see cref="PostClass"/> の組</summary>
316 public (ListViewItem, PostClass)[] Cache { get; set; } = null!;
318 /// <summary>キャッシュされたアイテムの件数</summary>
320 => this.EndIndex - this.StartIndex + 1;
322 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
323 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
324 public bool Contains(int index)
325 => index >= this.StartIndex && index <= this.EndIndex;
327 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
328 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
329 public bool IsSupersetOf(int rangeStart, int rangeEnd)
330 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
332 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
333 /// <returns>取得に成功すれば true、それ以外は false</returns>
334 public bool TryGetValue(int index, [NotNullWhen(true)] out ListViewItem? item, [NotNullWhen(true)] out PostClass? post)
336 if (this.Contains(index))
338 (item, post) = this.Cache[index - this.StartIndex];
350 private bool _isColumnChanged = false;
352 private const int MAX_WORKER_THREADS = 20;
353 private readonly SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
354 private readonly CancellationTokenSource workerCts = new CancellationTokenSource();
355 private readonly IProgress<string> workerProgress = null!;
357 private int UnreadCounter = -1;
358 private int UnreadAtCounter = -1;
360 private readonly string[] ColumnOrgText = new string[9];
361 private readonly string[] ColumnText = new string[9];
363 private bool _DoFavRetweetFlags = false;
365 //////////////////////////////////////////////////////////////////////////////////////////////////////////
367 private readonly TimelineScheduler timelineScheduler = new TimelineScheduler();
368 private ThrottlingTimer RefreshThrottlingTimer = null!;
369 private ThrottlingTimer colorizeDebouncer = null!;
370 private ThrottlingTimer selectionDebouncer = null!;
371 private ThrottlingTimer saveConfigDebouncer = null!;
373 private string recommendedStatusFooter = null!;
374 private bool urlMultibyteSplit = false;
375 private bool preventSmsCommand = true;
378 private struct urlUndo
380 public string Before;
384 private List<urlUndo>? urlUndoBuffer = null;
386 private readonly struct ReplyChain
388 public readonly long OriginalId;
389 public readonly long InReplyToId;
390 public readonly TabModel OriginalTab;
392 public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
394 this.OriginalId = originalId;
395 this.InReplyToId = inReplyToId;
396 this.OriginalTab = originalTab;
400 /// <summary>[, ]でのリプライ移動の履歴</summary>
401 private Stack<ReplyChain>? replyChains;
403 /// <summary>ポスト選択履歴</summary>
404 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new Stack<(TabModel, PostClass?)>();
406 public TabModel CurrentTab
407 => this._statuses.SelectedTab;
409 public string CurrentTabName
410 => this._statuses.SelectedTabName;
412 public TabPage CurrentTabPage
413 => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
415 public DetailsListView CurrentListView
416 => (DetailsListView)this.CurrentTabPage.Tag;
418 public PostClass? CurrentPost
419 => this.CurrentTab.SelectedPost;
421 /// <summary>検索処理タイプ</summary>
422 internal enum SEARCHTYPE
429 private class StatusTextHistory
431 public string status = "";
432 public (long StatusId, string ScreenName)? inReplyTo = null;
434 /// <summary>画像投稿サービス名</summary>
435 public string imageService = "";
437 public IMediaItem[]? mediaItems = null;
438 public StatusTextHistory()
441 public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
443 this.status = status;
444 this.inReplyTo = inReplyTo;
448 private void TweenMain_Activated(object sender, EventArgs e)
450 //画面がアクティブになったら、発言欄の背景色戻す
451 if (StatusText.Focused)
453 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
457 private bool disposed = false;
460 /// 使用中のリソースをすべてクリーンアップします。
462 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
463 protected override void Dispose(bool disposing)
465 base.Dispose(disposing);
472 this.components?.Dispose();
475 SearchDialog.Dispose();
478 NIconAtRed?.Dispose();
479 NIconAtSmoke?.Dispose();
480 foreach (var iconRefresh in this.NIconRefresh)
482 iconRefresh?.Dispose();
486 ReplyIcon?.Dispose();
487 ReplyIconBlink?.Dispose();
488 _listViewImageList.Dispose();
489 _brsHighLight.Dispose();
490 _brsBackColorMine?.Dispose();
491 _brsBackColorAt?.Dispose();
492 _brsBackColorYou?.Dispose();
493 _brsBackColorAtYou?.Dispose();
494 _brsBackColorAtFromTarget?.Dispose();
495 _brsBackColorAtTo?.Dispose();
496 _brsBackColorNone?.Dispose();
497 _brsDeactiveSelection?.Dispose();
501 this.workerCts.Cancel();
503 if (IconCache != null)
505 this.IconCache.CancelAsync();
506 this.IconCache.Dispose();
509 this.thumbnailTokenSource?.Dispose();
512 this.twitterApi.Dispose();
513 this._hookGlobalHotkey.Dispose();
516 // 終了時にRemoveHandlerしておかないとメモリリークする
517 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
518 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
519 Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
521 this.disposed = true;
524 private void LoadIcons()
526 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
527 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
530 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
533 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
536 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
539 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
541 // タスクトレイ: オフライン時アイコン
542 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
544 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
545 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
546 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
548 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
549 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
550 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
551 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
552 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
554 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
556 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
557 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
558 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
559 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
560 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
562 if (iconReply != null && iconReplyBlink != null)
564 this.ReplyIcon = iconReply;
565 this.ReplyIconBlink = iconReplyBlink;
569 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
570 this.ReplyIconBlink = this.NIconAt;
573 if (iconRefresh1 == null)
575 this.NIconRefresh = new[] {
576 Properties.Resources.Refresh, Properties.Resources.Refresh2,
577 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
580 else if (iconRefresh2 == null)
582 this.NIconRefresh = new[] { iconRefresh1 };
584 else if (iconRefresh3 == null)
586 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
588 else if (iconRefresh4 == null)
590 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
592 else // iconRefresh1 から iconRefresh4 まで全て揃っている
594 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
598 private Icon? LoadIcon(string filePath)
600 if (!File.Exists(filePath))
605 return new Icon(filePath);
613 private void InitColumns(ListView list, bool startup)
615 this.InitColumnText();
617 ColumnHeader[]? columns = null;
624 new ColumnHeader(), // アイコン
625 new ColumnHeader(), // 本文
628 columns[0].Text = this.ColumnText[0];
629 columns[1].Text = this.ColumnText[2];
633 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
635 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
636 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
637 columns[0].DisplayIndex = 0;
638 columns[1].DisplayIndex = 1;
643 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
645 columns[idx].Width = curListColumn.Width;
646 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
655 new ColumnHeader(), // アイコン
656 new ColumnHeader(), // ニックネーム
657 new ColumnHeader(), // 本文
658 new ColumnHeader(), // 日付
659 new ColumnHeader(), // ユーザID
660 new ColumnHeader(), // 未読
661 new ColumnHeader(), // マーク&プロテクト
662 new ColumnHeader(), // ソース
665 foreach (var i in Enumerable.Range(0, columns.Length))
666 columns[i].Text = this.ColumnText[i];
670 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
672 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
673 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
674 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
675 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
676 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
677 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
678 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
679 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
681 var displayIndex = new[] {
682 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
683 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
684 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
685 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
688 foreach (var i in Enumerable.Range(0, displayIndex.Length))
690 columns[i].DisplayIndex = displayIndex[i];
696 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
698 columns[idx].Width = curListColumn.Width;
699 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
705 list.Columns.AddRange(columns);
713 foreach (var column in columns)
719 private void InitColumnText()
722 ColumnText[1] = Properties.Resources.AddNewTabText2;
723 ColumnText[2] = Properties.Resources.AddNewTabText3;
724 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
725 ColumnText[4] = Properties.Resources.AddNewTabText5;
728 ColumnText[7] = "Source";
730 ColumnOrgText[0] = "";
731 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
732 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
733 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
734 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
735 ColumnOrgText[5] = "";
736 ColumnOrgText[6] = "";
737 ColumnOrgText[7] = "Source";
740 switch (_statuses.SortMode)
742 case ComparerMode.Nickname: //ニックネーム
745 case ComparerMode.Data: //本文
748 case ComparerMode.Id: //時刻=発言Id
751 case ComparerMode.Name: //名前
754 case ComparerMode.Source: //Source
761 if (_statuses.SortOrder == SortOrder.Descending)
763 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
764 ColumnText[2] = ColumnOrgText[2] + "▾";
768 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
769 ColumnText[2] = ColumnOrgText[2] + "▴";
774 if (_statuses.SortOrder == SortOrder.Descending)
776 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
777 ColumnText[c] = ColumnOrgText[c] + "▾";
781 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
782 ColumnText[c] = ColumnOrgText[c] + "▴";
787 private void InitializeTraceFrag()
790 TraceOutToolStripMenuItem.Checked = true;
791 MyCommon.TraceFlag = true;
793 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
795 TraceOutToolStripMenuItem.Checked = true;
796 MyCommon.TraceFlag = true;
800 private void TweenMain_Load(object sender, EventArgs e)
802 _ignoreConfigSave = true;
803 this.Visible = false;
805 if (MyApplication.StartupOptions.ContainsKey("d"))
806 MyCommon.TraceFlag = true;
808 InitializeTraceFrag();
810 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
812 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
814 Regex.CacheSize = 100;
817 _statuses = TabInformations.GetInstance();
821 this.Icon = MainIcon; //メインフォーム(TweenMain)
822 NotifyIcon1.Icon = NIconAt; //タスクトレイ
823 TabImage.Images.Add(TabIcon); //タブ見出し
825 //<<<<<<<<<設定関連>>>>>>>>>
829 // 現在の DPI と設定保存時の DPI との比を取得する
830 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
833 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
834 if (fontUIGlobal != null)
836 OTBaseForm.GlobalFont = fontUIGlobal;
837 this.Font = fontUIGlobal;
841 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
843 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
844 SettingManager.Common.TimelinePeriod = 15;
846 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
847 SettingManager.Common.ReplyPeriod = 15;
849 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
850 SettingManager.Common.DMPeriod = 15;
852 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
853 SettingManager.Common.PubSearchPeriod = 30;
855 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
856 SettingManager.Common.UserTimelinePeriod = 15;
858 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
859 SettingManager.Common.ListsPeriod = 15;
862 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
863 SettingManager.Common.CountApi = 60;
864 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
865 SettingManager.Common.CountApiReply = 40;
867 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
868 SettingManager.Common.MoreCountApi = 200;
869 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
870 SettingManager.Common.FirstCountApi = 100;
872 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
873 SettingManager.Common.FavoritesCountApi = 40;
874 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
875 SettingManager.Common.ListCountApi = 100;
876 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
877 SettingManager.Common.SearchCountApi = 100;
878 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
879 SettingManager.Common.UserTimelineCountApi = 20;
881 //廃止サービスが選択されていた場合ux.nuへ読み替え
882 if (SettingManager.Common.AutoShortUrlFirst < 0)
883 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
885 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
886 this.tw = new Twitter(this.twitterApi);
889 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
890 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
894 Networking.Initialize();
896 var saveRequired = false;
897 var firstRun = false;
899 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
900 if (string.IsNullOrEmpty(tw.Username))
905 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
906 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
907 string.IsNullOrEmpty(tw.Username))
909 Application.Exit(); //強制終了
915 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
916 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
917 Networking.SetWebProxy(SettingManager.Local.ProxyType,
918 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
919 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
920 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
922 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
923 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
924 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
925 tw.TrackWord = SettingManager.Common.TrackWord;
926 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(tw.TrackWord);
927 tw.AllAtReply = SettingManager.Common.AllAtReply;
928 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
929 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
930 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
931 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
932 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
934 // アクセストークンが有効であるか確認する
935 // ここが Twitter API への最初のアクセスになるようにすること
938 this.tw.VerifyCredentials();
940 catch (WebApiException ex)
942 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
943 ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
947 //プロキシ設定等の通信まわりの初期化が済んでから処理する
948 ThumbnailGenerator.InitializeGenerator();
950 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
951 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
952 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
954 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
957 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
960 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
961 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
962 HashMgr = new HashtagManage(HashSupl,
963 SettingManager.Common.HashTags.ToArray(),
964 SettingManager.Common.HashSelected,
965 SettingManager.Common.HashIsPermanent,
966 SettingManager.Common.HashIsHead,
967 SettingManager.Common.HashIsNotAddToAtReply);
968 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
971 this.IconCache = new ImageCache();
972 this.tweetDetailsView.IconCache = this.IconCache;
975 _fntUnread = SettingManager.Local.FontUnread;
976 _clUnread = SettingManager.Local.ColorUnread;
977 _fntReaded = SettingManager.Local.FontRead;
978 _clReaded = SettingManager.Local.ColorRead;
979 _clFav = SettingManager.Local.ColorFav;
980 _clOWL = SettingManager.Local.ColorOWL;
981 _clRetweet = SettingManager.Local.ColorRetweet;
982 _fntDetail = SettingManager.Local.FontDetail;
983 _clDetail = SettingManager.Local.ColorDetail;
984 _clDetailLink = SettingManager.Local.ColorDetailLink;
985 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
986 _clSelf = SettingManager.Local.ColorSelf;
987 _clAtSelf = SettingManager.Local.ColorAtSelf;
988 _clTarget = SettingManager.Local.ColorTarget;
989 _clAtTarget = SettingManager.Local.ColorAtTarget;
990 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
991 _clAtTo = SettingManager.Local.ColorAtTo;
992 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
993 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
994 _clInputFont = SettingManager.Local.ColorInputFont;
995 _fntInputFont = SettingManager.Local.FontInputFont;
997 _brsBackColorMine = new SolidBrush(_clSelf);
998 _brsBackColorAt = new SolidBrush(_clAtSelf);
999 _brsBackColorYou = new SolidBrush(_clTarget);
1000 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
1001 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
1002 _brsBackColorAtTo = new SolidBrush(_clAtTo);
1003 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
1004 _brsBackColorNone = new SolidBrush(_clListBackcolor);
1006 // StringFormatオブジェクトへの事前設定
1007 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
1008 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
1009 //sf.FormatFlags = StringFormatFlags.LineLimit; //
1010 sfTab.Alignment = StringAlignment.Center;
1011 sfTab.LineAlignment = StringAlignment.Center;
1013 InitDetailHtmlFormat();
1015 //Regex statregex = new Regex("^0*");
1016 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
1018 _history.Add(new StatusTextHistory());
1020 this.inReplyTo = null;
1023 SearchDialog.Owner = this;
1024 UrlDialog.Owner = this;
1027 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
1028 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
1030 //新着取得時のリストスクロールをするか。trueならスクロールしない
1031 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
1032 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
1034 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1035 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1038 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
1039 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1040 _myLoc = SettingManager.Local.FormLocation;
1042 if (this.WindowState != FormWindowState.Minimized)
1044 var tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1045 var outOfScreen = true;
1046 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1048 foreach (var scr in Screen.AllScreens)
1050 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1052 outOfScreen = false;
1058 this._myLoc = new Point(0, 0);
1060 this.DesktopLocation = this._myLoc;
1062 this.TopMost = SettingManager.Common.AlwaysTop;
1063 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
1064 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
1065 if (SettingManager.Local.PreviewDistance == -1)
1067 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
1068 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
1069 SettingManager.Local.PreviewDistance = _mySpDis3;
1073 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
1075 //this.Tween_ClientSizeChanged(this, null);
1076 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1077 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1079 StatusText.Font = _fntInputFont;
1080 StatusText.ForeColor = _clInputFont;
1082 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
1083 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
1084 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
1086 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1087 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
1089 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1090 if (SettingManager.Common.UnreadManage == false)
1092 ReadedStripMenuItem.Enabled = false;
1093 UnreadStripMenuItem.Enabled = false;
1096 //リンク先URL表示部の初期化(画面左下)
1097 StatusLabelUrl.Text = "";
1099 StatusLabel.Text = "";
1100 StatusLabel.AutoToolTip = false;
1101 StatusLabel.ToolTipText = "";
1103 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1105 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1106 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1107 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1108 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1110 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1111 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1112 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1113 this.SplitContainer2.Panel2.AccessibleName = "";
1115 ////////////////////////////////////////////////////////////////////////////////
1116 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1117 var mode = ComparerMode.Id;
1118 switch (SettingManager.Common.SortColumn)
1120 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1124 mode = ComparerMode.Id; //Idソートに読み替え
1127 mode = ComparerMode.Nickname;
1130 mode = ComparerMode.Data;
1133 mode = ComparerMode.Id;
1136 mode = ComparerMode.Name;
1139 mode = ComparerMode.Source;
1142 _statuses.SetSortMode(mode, sortOrder);
1143 ////////////////////////////////////////////////////////////////////////////////
1145 ApplyListViewIconSize(SettingManager.Common.IconSize);
1147 //<<<<<<<<タブ関連>>>>>>>
1151 //デフォルトタブの存在チェック、ない場合には追加
1152 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1153 this._statuses.AddTab(new HomeTabModel());
1155 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1156 this._statuses.AddTab(new MentionsTabModel());
1158 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1159 this._statuses.AddTab(new DirectMessagesTabModel());
1161 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1162 this._statuses.AddTab(new FavoritesTabModel());
1164 if (this._statuses.MuteTab == null)
1165 this._statuses.AddTab(new MuteTabModel());
1167 foreach (var tab in _statuses.Tabs)
1169 if (!AddNewTab(tab, startup: true))
1170 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1173 this._statuses.SelectTab(this.ListTab.SelectedTab.Text);
1175 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
1176 Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
1178 if (SettingManager.Common.TabIconDisp)
1180 ListTab.DrawMode = TabDrawMode.Normal;
1184 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1185 ListTab.DrawItem += ListTab_DrawItem;
1186 ListTab.ImageList = null;
1189 if (SettingManager.Common.HotkeyEnabled)
1192 var modKey = HookGlobalHotkey.ModKeys.None;
1193 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1194 modKey |= HookGlobalHotkey.ModKeys.Alt;
1195 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1196 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1197 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1198 modKey |= HookGlobalHotkey.ModKeys.Shift;
1199 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1200 modKey |= HookGlobalHotkey.ModKeys.Win;
1202 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1205 if (SettingManager.Common.IsUseNotifyGrowl)
1208 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1210 SetMainWindowTitle();
1211 SetNotifyIconText();
1213 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1215 this.Visible = true;
1220 this.timelineScheduler.UpdateHome = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
1221 this.timelineScheduler.UpdateMention = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
1222 this.timelineScheduler.UpdateDm = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
1223 this.timelineScheduler.UpdatePublicSearch = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
1224 this.timelineScheduler.UpdateUser = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
1225 this.timelineScheduler.UpdateList = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
1226 this.timelineScheduler.UpdateConfig = () => this.InvokeAsync(() => Task.WhenAll(new[]
1228 this.doGetFollowersMenu(),
1229 this.RefreshBlockIdsAsync(),
1230 this.RefreshMuteUserIdsAsync(),
1231 this.RefreshNoRetweetIdsAsync(),
1232 this.RefreshTwitterConfigurationAsync(),
1234 this.RefreshTimelineScheduler();
1236 var streamingRefreshInterval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1237 this.RefreshThrottlingTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), streamingRefreshInterval);
1238 this.colorizeDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.ColorizeList()), TimeSpan.FromMilliseconds(100), leading: true);
1239 this.selectionDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
1240 this.saveConfigDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
1243 TimerRefreshIcon.Interval = 200;
1244 TimerRefreshIcon.Enabled = false;
1246 _ignoreConfigSave = false;
1247 this.TweenMain_Resize(this, EventArgs.Empty);
1248 if (saveRequired) SaveConfigsAll(false);
1250 foreach (var ua in SettingManager.Common.UserAccounts)
1252 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1254 ua.UserId = tw.UserId;
1261 // 初回起動時だけ右下のメニューを目立たせる
1262 HashStripSplitButton.ShowDropDown();
1266 private void InitDetailHtmlFormat()
1268 if (SettingManager.Common.IsMonospace)
1270 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1271 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1275 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1276 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1279 detailHtmlFormatHeader = detailHtmlFormatHeader
1280 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1281 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1282 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1283 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1284 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1285 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1288 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1293 txt = this._statuses.Tabs[e.Index].TabName;
1300 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1301 if (e.State == DrawItemState.Selected)
1303 e.DrawFocusRectangle();
1308 if (_statuses.Tabs[txt].UnreadCount > 0)
1311 fore = System.Drawing.SystemBrushes.ControlText;
1315 fore = System.Drawing.SystemBrushes.ControlText;
1317 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1320 private void LoadConfig()
1322 SettingManager.Local = SettingManager.Local;
1324 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1325 if (SettingManager.Local.ScaleDimension.IsEmpty)
1326 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1328 var tabSettings = SettingManager.Tabs;
1329 foreach (var tabSetting in tabSettings.Tabs)
1332 switch (tabSetting.TabType)
1334 case MyCommon.TabUsageType.Home:
1335 tab = new HomeTabModel(tabSetting.TabName);
1337 case MyCommon.TabUsageType.Mentions:
1338 tab = new MentionsTabModel(tabSetting.TabName);
1340 case MyCommon.TabUsageType.DirectMessage:
1341 tab = new DirectMessagesTabModel(tabSetting.TabName);
1343 case MyCommon.TabUsageType.Favorites:
1344 tab = new FavoritesTabModel(tabSetting.TabName);
1346 case MyCommon.TabUsageType.UserDefined:
1347 tab = new FilterTabModel(tabSetting.TabName);
1349 case MyCommon.TabUsageType.UserTimeline:
1350 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User!);
1352 case MyCommon.TabUsageType.PublicSearch:
1353 tab = new PublicSearchTabModel(tabSetting.TabName)
1355 SearchWords = tabSetting.SearchWords,
1356 SearchLang = tabSetting.SearchLang,
1359 case MyCommon.TabUsageType.Lists:
1360 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo!);
1362 case MyCommon.TabUsageType.Mute:
1363 tab = new MuteTabModel(tabSetting.TabName);
1369 tab.UnreadManage = tabSetting.UnreadManage;
1370 tab.Protected = tabSetting.Protected;
1371 tab.Notify = tabSetting.Notify;
1372 tab.SoundFile = tabSetting.SoundFile;
1374 if (tab.IsDistributableTabType)
1376 var filterTab = (FilterTabModel)tab;
1377 filterTab.FilterArray = tabSetting.FilterArray;
1378 filterTab.FilterModified = false;
1381 if (this._statuses.ContainsTab(tab.TabName))
1382 tab.TabName = this._statuses.MakeTabName("MyTab");
1384 this._statuses.AddTab(tab);
1386 if (_statuses.Tabs.Count == 0)
1388 _statuses.AddTab(new HomeTabModel());
1389 _statuses.AddTab(new MentionsTabModel());
1390 _statuses.AddTab(new DirectMessagesTabModel());
1391 _statuses.AddTab(new FavoritesTabModel());
1395 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1399 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1400 var newTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), interval);
1401 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1405 this.RefreshTimelineScheduler();
1408 private void RefreshTimelineScheduler()
1410 this.timelineScheduler.UpdateIntervalHome = TimeSpan.FromSeconds(SettingManager.Common.TimelinePeriod);
1411 this.timelineScheduler.UpdateIntervalMention = TimeSpan.FromSeconds(SettingManager.Common.ReplyPeriod);
1412 this.timelineScheduler.UpdateIntervalDm = TimeSpan.FromSeconds(SettingManager.Common.DMPeriod);
1413 this.timelineScheduler.UpdateIntervalPublicSearch = TimeSpan.FromSeconds(SettingManager.Common.PubSearchPeriod);
1414 this.timelineScheduler.UpdateIntervalUser = TimeSpan.FromSeconds(SettingManager.Common.UserTimelinePeriod);
1415 this.timelineScheduler.UpdateIntervalList = TimeSpan.FromSeconds(SettingManager.Common.ListsPeriod);
1416 this.timelineScheduler.UpdateIntervalConfig = TimeSpan.FromHours(6);
1417 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
1419 this.timelineScheduler.RefreshSchedule();
1422 private void MarkSettingCommonModified()
1424 if (this.saveConfigDebouncer == null)
1427 this.ModifySettingCommon = true;
1428 this.saveConfigDebouncer.Call();
1431 private void MarkSettingLocalModified()
1433 if (this.saveConfigDebouncer == null)
1436 this.ModifySettingLocal = true;
1437 this.saveConfigDebouncer.Call();
1440 internal void MarkSettingAtIdModified()
1442 if (this.saveConfigDebouncer == null)
1445 this.ModifySettingAtId = true;
1446 this.saveConfigDebouncer.Call();
1449 private void RefreshTimeline()
1451 var curTabModel = this.CurrentTab;
1452 var curListView = this.CurrentListView;
1454 // 現在表示中のタブのスクロール位置を退避
1455 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1457 // 各タブのリスト上の選択位置などを退避
1458 var listSelections = this.SaveListViewSelection();
1462 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1463 out var newMentionOrDm, out var isDelete);
1465 if (MyCommon._endingFlag) return;
1468 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1470 var tabPage = this.ListTab.TabPages[index];
1471 var listView = (DetailsListView)tabPage.Tag;
1473 if (listView.VirtualListSize != tab.AllCount || isDelete)
1475 using (ControlTransaction.Update(listView))
1477 if (listView == curListView)
1478 this.PurgeListViewItemCache();
1483 listView.VirtualListSize = tab.AllCount;
1485 catch (NullReferenceException ex)
1487 // WinForms 内部で ListView.set_TopItem が発生させている例外
1488 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1489 MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1493 this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1500 if (SettingManager.Common.TabIconDisp)
1502 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1504 var tabPage = this.ListTab.TabPages[index];
1505 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1506 tabPage.ImageIndex = 0; // 未読アイコン
1511 this.ListTab.Refresh();
1516 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1519 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1521 SetMainWindowTitle();
1522 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1524 HashSupl.AddRangeItem(tw.GetHashList());
1528 internal struct ListViewScroll
1530 public ScrollLockMode ScrollLockMode { get; set; }
1531 public long? TopItemStatusId { get; set; }
1534 internal enum ScrollLockMode
1536 /// <summary>固定しない</summary>
1539 /// <summary>最上部に固定する</summary>
1542 /// <summary>最下部に固定する</summary>
1545 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1550 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1552 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1554 var listScroll = new ListViewScroll
1556 ScrollLockMode = this.GetScrollLockMode(listView),
1559 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1561 var topItemIndex = listView.TopItem?.Index ?? -1;
1562 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1563 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1569 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1571 if (this._statuses.SortMode == ComparerMode.Id)
1573 if (this._statuses.SortOrder == SortOrder.Ascending)
1576 if (this.ListLockMenuItem.Checked)
1577 return ScrollLockMode.None;
1579 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1582 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1583 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1584 return ScrollLockMode.FixedToBottom;
1586 return ScrollLockMode.None;
1591 if (this.ListLockMenuItem.Checked)
1592 return ScrollLockMode.FixedToItem;
1594 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1595 var topItem = listView.TopItem;
1596 if (topItem == null || topItem.Index == 0)
1597 return ScrollLockMode.FixedToTop;
1599 return ScrollLockMode.FixedToItem;
1604 return ScrollLockMode.FixedToItem;
1608 internal struct ListViewSelection
1610 public long[]? SelectedStatusIds { get; set; }
1611 public long? SelectionMarkStatusId { get; set; }
1612 public long? FocusedStatusId { get; set; }
1616 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1618 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1620 var listsDict = new Dictionary<string, ListViewSelection>();
1622 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1624 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1625 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1632 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1634 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1636 if (listView.VirtualListSize == 0)
1638 return new ListViewSelection
1640 SelectedStatusIds = Array.Empty<long>(),
1641 SelectionMarkStatusId = null,
1642 FocusedStatusId = null,
1646 return new ListViewSelection
1648 SelectedStatusIds = tab.SelectedStatusIds,
1649 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1650 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1654 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1656 var index = listView.FocusedItem?.Index ?? -1;
1658 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1661 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1663 var index = listView.SelectionMark;
1665 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1669 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1671 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1673 if (listView.VirtualListSize == 0)
1676 switch (listScroll.ScrollLockMode)
1678 case ScrollLockMode.FixedToTop:
1679 listView.EnsureVisible(0);
1681 case ScrollLockMode.FixedToBottom:
1682 listView.EnsureVisible(listView.VirtualListSize - 1);
1684 case ScrollLockMode.FixedToItem:
1685 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1688 var topItem = listView.Items[topIndex];
1691 listView.TopItem = topItem;
1693 catch (NullReferenceException)
1695 listView.EnsureVisible(listView.VirtualListSize - 1);
1696 listView.EnsureVisible(topIndex);
1700 case ScrollLockMode.None:
1707 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1709 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1711 // status_id から ListView 上のインデックスに変換
1712 int[]? selectedIndices = null;
1713 if (listSelection.SelectedStatusIds != null)
1714 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1716 var focusedIndex = -1;
1717 if (listSelection.FocusedStatusId != null)
1718 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1720 var selectionMarkIndex = -1;
1721 if (listSelection.SelectionMarkStatusId != null)
1722 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1724 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1727 private bool BalloonRequired()
1729 var ev = new Twitter.FormattedEvent
1731 Eventtype = MyCommon.EVENTTYPE.None,
1734 return BalloonRequired(ev);
1737 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1739 if (type == MyCommon.EVENTTYPE.None)
1742 if (!SettingManager.Common.EventNotifyEnabled)
1745 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1748 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1753 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1756 private bool BalloonRequired(Twitter.FormattedEvent ev)
1761 if (NativeMethods.IsScreenSaverRunning())
1765 if (!this.NewPostPopMenuItem.Checked)
1767 // 「新着通知が無効でもイベントを通知する」にも該当しない
1768 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1772 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1773 if (SettingManager.Common.LimitBalloon)
1775 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1779 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1782 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1784 if (SettingManager.Common.ReadOwnPost)
1786 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1791 if (BalloonRequired())
1793 if (notifyPosts != null && notifyPosts.Length > 0)
1795 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1796 if (SettingManager.Common.IsUseNotifyGrowl)
1798 var sb = new StringBuilder();
1802 foreach (var post in notifyPosts)
1804 if (!(notifyPosts.Length > 3))
1810 if (post.IsReply && !post.IsExcludeReply) reply = true;
1811 if (post.IsDm) dm = true;
1812 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1813 switch (SettingManager.Common.NameBalloon)
1815 case MyCommon.NameBalloonEnum.UserID:
1816 sb.Append(post.ScreenName).Append(" : ");
1818 case MyCommon.NameBalloonEnum.NickName:
1819 sb.Append(post.Nickname).Append(" : ");
1822 sb.Append(post.TextFromApi);
1823 if (notifyPosts.Length > 3)
1825 if (notifyPosts.Last() != post) continue;
1828 var title = new StringBuilder();
1829 GrowlHelper.NotifyType nt;
1830 if (SettingManager.Common.DispUsername)
1832 title.Append(tw.Username);
1833 title.Append(" - ");
1841 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1842 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1843 title.Append(ApplicationSettings.ApplicationName);
1844 title.Append(" [DM] ");
1845 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1846 nt = GrowlHelper.NotifyType.DirectMessage;
1850 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1851 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1852 title.Append(ApplicationSettings.ApplicationName);
1853 title.Append(" [Reply!] ");
1854 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1855 nt = GrowlHelper.NotifyType.Reply;
1859 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1860 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1861 title.Append(ApplicationSettings.ApplicationName);
1863 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1864 nt = GrowlHelper.NotifyType.Notify;
1866 var bText = sb.ToString();
1867 if (string.IsNullOrEmpty(bText)) return;
1869 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1870 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1875 var sb = new StringBuilder();
1878 foreach (var post in notifyPosts)
1880 if (post.IsReply && !post.IsExcludeReply) reply = true;
1881 if (post.IsDm) dm = true;
1882 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1883 switch (SettingManager.Common.NameBalloon)
1885 case MyCommon.NameBalloonEnum.UserID:
1886 sb.Append(post.ScreenName).Append(" : ");
1888 case MyCommon.NameBalloonEnum.NickName:
1889 sb.Append(post.Nickname).Append(" : ");
1892 sb.Append(post.TextFromApi);
1895 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1896 var title = new StringBuilder();
1898 if (SettingManager.Common.DispUsername)
1900 title.Append(tw.Username);
1901 title.Append(" - ");
1909 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1910 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1911 ntIcon = ToolTipIcon.Warning;
1912 title.Append(ApplicationSettings.ApplicationName);
1913 title.Append(" [DM] ");
1914 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1918 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1919 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1920 ntIcon = ToolTipIcon.Warning;
1921 title.Append(ApplicationSettings.ApplicationName);
1922 title.Append(" [Reply!] ");
1923 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1927 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1928 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1929 ntIcon = ToolTipIcon.Info;
1930 title.Append(ApplicationSettings.ApplicationName);
1932 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1934 var bText = sb.ToString();
1935 if (string.IsNullOrEmpty(bText)) return;
1936 //NotifyIcon1.BalloonTipText = sb.ToString();
1937 //NotifyIcon1.ShowBalloonTip(500);
1938 NotifyIcon1.BalloonTipTitle = title.ToString();
1939 NotifyIcon1.BalloonTipText = bText;
1940 NotifyIcon1.BalloonTipIcon = ntIcon;
1941 NotifyIcon1.ShowBalloonTip(500);
1947 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1951 var dir = Application.StartupPath;
1952 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1954 dir = Path.Combine(dir, "Sounds");
1956 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1964 //mentions新着時に画面ブリンク
1965 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1967 NativeMethods.FlashMyWindow(this.Handle, 3);
1971 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1973 var listView = this.CurrentListView;
1974 if (listView != sender)
1977 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1978 this.CurrentTab.SelectPosts(indices);
1980 if (listView.SelectedIndices.Count != 1)
1983 var index = listView.SelectedIndices[0];
1984 if (index > listView.VirtualListSize - 1) return;
1986 this.PushSelectPostChain();
1988 var post = this.CurrentPost!;
1989 this._statuses.SetReadAllTab(post.StatusId, read: true);
1992 ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1994 this.colorizeDebouncer.Call();
1995 this.selectionDebouncer.Call();
1998 private void ChangeCacheStyleRead(bool Read, int Index)
2000 var tabInfo = this.CurrentTab;
2001 //Read:true=既読 false=未読
2002 //未読管理していなかったら既読として扱う
2003 if (!tabInfo.UnreadManage ||
2004 !SettingManager.Common.UnreadManage) Read = true;
2006 var listCache = this._listItemCache;
2007 if (listCache == null)
2010 // キャッシュに含まれていないアイテムは対象外
2011 if (!listCache.TryGetValue(Index, out var itm, out var post))
2014 ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
2017 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView? DList)
2032 if (Item.SubItems[5].Text != star)
2033 Item.SubItems[5].Text = star;
2039 else if (Post.RetweetedId != null)
2041 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
2043 else if (Read || !SettingManager.Common.UseUnreadStyle)
2048 if (DList == null || Item.Index == -1)
2050 Item.ForeColor = cl;
2051 if (SettingManager.Common.UseUnreadStyle)
2057 if (SettingManager.Common.UseUnreadStyle)
2058 DList.ChangeItemFontAndColor(Item, cl, fnt);
2060 DList.ChangeItemForeColor(Item, cl);
2061 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2065 private void ColorizeList()
2067 //Index:更新対象のListviewItem.Index。Colorを返す。
2068 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2071 _post = _anchorPost;
2073 _post = this.CurrentPost;
2075 if (_post == null) return;
2077 var listCache = this._listItemCache;
2078 if (listCache == null)
2081 var listView = (DetailsListView)listCache.TargetList;
2083 // ValidateRectが呼ばれる前に選択色などの描画を済ませておく
2086 foreach (var (listViewItem, cachedPost) in listCache.Cache)
2088 var backColor = this.JudgeColor(_post, cachedPost);
2089 listView.ChangeItemBackColor(listViewItem, backColor);
2093 private void ColorizeList(ListViewItem Item, PostClass post)
2095 //Index:更新対象のListviewItem.Index。Colorを返す。
2096 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2099 _post = _anchorPost;
2101 _post = this.CurrentPost;
2103 if (_post == null) return;
2105 if (Item.Index == -1)
2106 Item.BackColor = JudgeColor(_post, post);
2108 this.CurrentListView.ChangeItemBackColor(Item, JudgeColor(_post, post));
2111 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2114 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2117 else if (TargetPost.IsMe)
2120 else if (TargetPost.IsReply)
2123 else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2125 cl = _clAtFromTarget;
2126 else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2129 else if (TargetPost.UserId == BasePost.UserId)
2134 cl = _clListBackcolor;
2139 private void StatusTextHistoryBack()
2141 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2142 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2145 if (this._hisIdx < 0)
2148 var historyItem = this._history[this._hisIdx];
2149 this.inReplyTo = historyItem.inReplyTo;
2150 this.StatusText.Text = historyItem.status;
2151 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2154 private void StatusTextHistoryForward()
2156 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2157 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2160 if (this._hisIdx > this._history.Count - 1)
2161 this._hisIdx = this._history.Count - 1;
2163 var historyItem = this._history[this._hisIdx];
2164 this.inReplyTo = historyItem.inReplyTo;
2165 this.StatusText.Text = historyItem.status;
2166 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2169 private async void PostButton_Click(object sender, EventArgs e)
2171 if (StatusText.Text.Trim().Length == 0)
2173 if (!ImageSelector.Enabled)
2175 await this.DoRefresh();
2180 var currentPost = this.CurrentPost;
2181 if (this.ExistCurrentPost && currentPost != null && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2183 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2185 MessageBoxButtons.YesNoCancel,
2186 MessageBoxIcon.Question);
2189 case DialogResult.Yes:
2190 StatusText.Text = "";
2191 await this.doReTweetOfficial(false);
2193 case DialogResult.Cancel:
2198 if (TextContainsOnlyMentions(this.StatusText.Text))
2200 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2201 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2203 if (ret != DialogResult.OK)
2207 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2209 if (SettingManager.Common.Nicoms)
2211 StatusText.SelectionStart = StatusText.Text.Length;
2212 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2214 //if (SettingDialog.UrlConvertAuto)
2216 // StatusText.SelectionStart = StatusText.Text.Length;
2217 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2219 //else if (SettingDialog.Nicoms)
2221 // StatusText.SelectionStart = StatusText.Text.Length;
2222 // UrlConvert(UrlConverter.Nicoms);
2224 StatusText.SelectionStart = StatusText.Text.Length;
2225 CheckReplyTo(StatusText.Text);
2227 var status = new PostStatusParams();
2229 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2230 if (this.GetRestStatusCount(statusTextCompat) >= 0)
2232 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2233 // 収まる場合はこれらのオプションを使用せずに投稿する
2234 status.Text = statusTextCompat;
2235 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2239 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2240 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2242 status.AttachmentUrl = attachmentUrl;
2244 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2246 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2247 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2249 status.AutoPopulateReplyMetadata = true;
2251 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2252 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2257 if (this.GetRestStatusCount(status.Text) < 0)
2259 // 文字数制限を超えているが強制的に投稿するか
2260 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2261 if (ret != DialogResult.OK)
2265 IMediaUploadService? uploadService = null;
2266 IMediaItem[]? uploadItems = null;
2267 if (ImageSelector.Visible)
2270 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2273 uploadService = this.ImageSelector.GetService(serviceName);
2276 this.inReplyTo = null;
2277 StatusText.Text = "";
2278 _history.Add(new StatusTextHistory());
2279 _hisIdx = _history.Count - 1;
2280 if (!SettingManager.Common.FocusLockToStatusText)
2281 this.CurrentListView.Focus();
2282 urlUndoBuffer = null;
2283 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2286 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2288 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2289 await this.OpenUriInBrowserAsync(tmp);
2292 await this.PostMessageAsync(status, uploadService, uploadItems);
2295 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2297 MyCommon._endingFlag = true;
2301 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2303 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2305 //_endingFlag=false:フォームの×ボタン
2307 this.Visible = false;
2311 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2312 _ignoreConfigSave = true;
2313 MyCommon._endingFlag = true;
2314 this.timelineScheduler.Enabled = false;
2315 TimerRefreshIcon.Enabled = false;
2319 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2321 this.Visible = true;
2322 if (this.WindowState == FormWindowState.Minimized)
2324 this.WindowState = FormWindowState.Normal;
2327 this.BringToFront();
2330 private static int errorCount = 0;
2332 private static bool CheckAccountValid()
2334 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2340 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2349 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2350 private Task RefreshTabAsync<T>() where T : TabModel
2351 => this.RefreshTabAsync<T>(backward: false);
2353 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2354 private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2357 from tab in this._statuses.GetTabsByType<T>()
2358 select this.RefreshTabAsync(tab, backward);
2360 return Task.WhenAll(loadTasks);
2363 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2364 private Task RefreshTabAsync(TabModel tab)
2365 => this.RefreshTabAsync(tab, backward: false);
2367 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2368 private async Task RefreshTabAsync(TabModel tab, bool backward)
2370 await this.workerSemaphore.WaitAsync();
2371 this.RefreshTasktrayIcon();
2375 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2376 this.RefreshTimeline();
2378 catch (WebApiException ex)
2380 this._myStatusError = true;
2385 case HomeTabModel _:
2386 tabType = "GetTimeline";
2388 case MentionsTabModel _:
2389 tabType = "GetTimeline";
2391 case DirectMessagesTabModel _:
2392 tabType = "GetDirectMessage";
2394 case FavoritesTabModel _:
2395 tabType = "GetFavorites";
2397 case PublicSearchTabModel _:
2398 tabType = "GetSearch";
2400 case UserTimelineTabModel _:
2401 tabType = "GetUserTimeline";
2403 case ListTimelineTabModel _:
2404 tabType = "GetListStatus";
2406 case RelatedPostsTabModel _:
2407 tabType = "GetRelatedTweets";
2410 tabType = tab.GetType().Name.Replace("Model", "");
2414 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2418 this.workerSemaphore.Release();
2422 private async Task FavAddAsync(long statusId, TabModel tab)
2424 await this.workerSemaphore.WaitAsync();
2425 this.RefreshTasktrayIcon();
2429 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2431 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2433 catch (WebApiException ex)
2435 this._myStatusError = true;
2436 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2440 this.workerSemaphore.Release();
2444 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2446 if (ct.IsCancellationRequested)
2449 if (!CheckAccountValid())
2450 throw new WebApiException("Auth error. Check your account");
2452 if (!tab.Posts.TryGetValue(statusId, out var post))
2458 await Task.Run(async () =>
2460 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2466 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2468 .ConfigureAwait(false);
2470 catch (TwitterApiException ex)
2471 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2473 // エラーコード 139 のみの場合は成功と見なす
2476 if (SettingManager.Common.RestrictFavCheck)
2478 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2479 .ConfigureAwait(false);
2481 if (status.Favorited != true)
2482 throw new WebApiException("NG(Restricted?)");
2485 this._favTimestamps.Add(DateTimeUtc.Now);
2488 if (this._statuses.Posts.TryGetValue(statusId, out var postTl))
2490 postTl.IsFav = true;
2492 var favTab = this._statuses.FavoriteTab;
2493 favTab.AddPostQueue(postTl);
2496 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2497 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2499 if (tb.Contains(statusId))
2500 tb.Posts[statusId].IsFav = true;
2503 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2505 catch (WebApiException)
2507 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2512 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2513 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2515 if (this._favTimestamps[i] < oneHour)
2516 this._favTimestamps.RemoveAt(i);
2519 this._statuses.DistributePosts();
2522 if (ct.IsCancellationRequested)
2525 this.RefreshTimeline();
2527 if (this.CurrentTabName == tab.TabName)
2529 using (ControlTransaction.Update(this.CurrentListView))
2531 var idx = tab.IndexOf(statusId);
2533 this.ChangeCacheStyleRead(post.IsRead, idx);
2536 var currentPost = this.CurrentPost;
2537 if (currentPost != null && statusId == currentPost.StatusId)
2538 this.DispSelectedPost(true); // 選択アイテム再表示
2542 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2544 await this.workerSemaphore.WaitAsync();
2545 this.RefreshTasktrayIcon();
2549 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2551 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2553 catch (WebApiException ex)
2555 this._myStatusError = true;
2556 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2560 this.workerSemaphore.Release();
2564 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2566 if (ct.IsCancellationRequested)
2569 if (!CheckAccountValid())
2570 throw new WebApiException("Auth error. Check your account");
2572 var successIds = new List<long>();
2574 await Task.Run(async () =>
2578 var failedCount = 0;
2579 foreach (var statusId in statusIds)
2583 var post = tab.Posts[statusId];
2585 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2592 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2594 .ConfigureAwait(false);
2596 catch (WebApiException)
2602 successIds.Add(statusId);
2603 post.IsFav = false; // リスト再描画必要
2605 if (this._statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
2606 tabinfoPost.IsFav = false;
2608 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2609 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2611 if (tb.Contains(statusId))
2612 tb.Posts[statusId].IsFav = false;
2617 if (ct.IsCancellationRequested)
2620 var favTab = this._statuses.FavoriteTab;
2621 foreach (var statusId in successIds)
2623 // ツイートが削除された訳ではないので IsDeleted はセットしない
2624 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2627 this.RefreshTimeline();
2629 if (this.CurrentTabName == tab.TabName)
2631 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2637 using (ControlTransaction.Update(this.CurrentListView))
2639 foreach (var statusId in successIds)
2641 var idx = tab.IndexOf(statusId);
2645 var post = tab.Posts[statusId];
2646 this.ChangeCacheStyleRead(post.IsRead, idx);
2650 var currentPost = this.CurrentPost;
2651 if (currentPost != null && successIds.Contains(currentPost.StatusId))
2652 this.DispSelectedPost(true); // 選択アイテム再表示
2657 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2659 await this.workerSemaphore.WaitAsync();
2660 this.RefreshTasktrayIcon();
2664 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2666 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2668 catch (WebApiException ex)
2670 this._myStatusError = true;
2671 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2675 this.workerSemaphore.Release();
2679 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2680 IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2682 if (ct.IsCancellationRequested)
2685 if (!CheckAccountValid())
2686 throw new WebApiException("Auth error. Check your account");
2688 p.Report("Posting...");
2690 PostClass? post = null;
2695 await Task.Run(async () =>
2697 var postParamsWithMedia = postParams;
2699 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2701 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2702 .ConfigureAwait(false);
2705 post = await this.tw.PostStatus(postParamsWithMedia)
2706 .ConfigureAwait(false);
2709 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2711 catch (WebApiException ex)
2713 // 処理は中断せずエラーの表示のみ行う
2714 errMsg = $"Err:{ex.Message}(PostMessage)";
2716 this._myStatusError = true;
2718 catch (UnauthorizedAccessException ex)
2720 // アップロード対象のファイルが開けなかった場合など
2721 errMsg = $"Err:{ex.Message}(PostMessage)";
2723 this._myStatusError = true;
2727 // 使い終わった MediaItem は破棄する
2728 if (uploadItems != null)
2730 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2732 disposableItem.Dispose();
2737 if (ct.IsCancellationRequested)
2740 if (!string.IsNullOrEmpty(errMsg) &&
2741 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2742 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2744 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2746 var ret = MessageBox.Show(
2748 "Failed to update status",
2749 MessageBoxButtons.RetryCancel,
2750 MessageBoxIcon.Question);
2752 if (ret == DialogResult.Retry)
2754 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2758 this.StatusTextHistoryBack();
2759 this.StatusText.Focus();
2761 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2762 if (SettingManager.Common.FocusLockToStatusText)
2763 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2768 this._postTimestamps.Add(DateTimeUtc.Now);
2770 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2771 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2773 if (this._postTimestamps[i] < oneHour)
2774 this._postTimestamps.RemoveAt(i);
2777 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2779 this.HashMgr.ClearHashtag();
2780 this.HashStripSplitButton.Text = "#[-]";
2781 this.HashTogglePullDownMenuItem.Checked = false;
2782 this.HashToggleMenuItem.Checked = false;
2785 this.SetMainWindowTitle();
2788 if (!this.tw.UserStreamActive)
2790 if (SettingManager.Common.PostAndGet)
2791 await this.RefreshTabAsync<HomeTabModel>();
2796 this._statuses.AddPost(post);
2797 this._statuses.DistributePosts();
2799 this.RefreshTimeline();
2804 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2806 await this.workerSemaphore.WaitAsync();
2807 this.RefreshTasktrayIcon();
2811 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2813 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2815 catch (WebApiException ex)
2817 this._myStatusError = true;
2818 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2822 this.workerSemaphore.Release();
2826 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2828 if (ct.IsCancellationRequested)
2831 if (!CheckAccountValid())
2832 throw new WebApiException("Auth error. Check your account");
2835 if (!SettingManager.Common.UnreadManage)
2838 read = this._initial && SettingManager.Common.Read;
2840 p.Report("Posting...");
2842 var posts = new List<PostClass>();
2844 await Task.Run(async () =>
2846 foreach (var statusId in statusIds)
2848 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2849 if (post != null) posts.Add(post);
2853 if (ct.IsCancellationRequested)
2856 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2858 this._postTimestamps.Add(DateTimeUtc.Now);
2860 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2861 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2863 if (this._postTimestamps[i] < oneHour)
2864 this._postTimestamps.RemoveAt(i);
2868 if (!this.tw.UserStreamActive)
2870 // 自分のRTはTLの更新では取得できない場合があるので、
2871 // 投稿時取得の有無に関わらず追加しておく
2872 posts.ForEach(post => this._statuses.AddPost(post));
2874 if (SettingManager.Common.PostAndGet)
2875 await this.RefreshTabAsync<HomeTabModel>();
2878 this._statuses.DistributePosts();
2879 this.RefreshTimeline();
2884 private async Task RefreshFollowerIdsAsync()
2886 await this.workerSemaphore.WaitAsync();
2887 this.RefreshTasktrayIcon();
2891 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2893 await this.tw.RefreshFollowerIds();
2895 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2897 this.RefreshTimeline();
2898 this.PurgeListViewItemCache();
2899 this.CurrentListView.Refresh();
2901 catch (WebApiException ex)
2903 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2907 this.workerSemaphore.Release();
2911 private async Task RefreshNoRetweetIdsAsync()
2913 await this.workerSemaphore.WaitAsync();
2914 this.RefreshTasktrayIcon();
2918 await this.tw.RefreshNoRetweetIds();
2920 this.StatusLabel.Text = "NoRetweetIds refreshed";
2922 catch (WebApiException ex)
2924 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2928 this.workerSemaphore.Release();
2932 private async Task RefreshBlockIdsAsync()
2934 await this.workerSemaphore.WaitAsync();
2935 this.RefreshTasktrayIcon();
2939 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2941 await this.tw.RefreshBlockIds();
2943 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2945 catch (WebApiException ex)
2947 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2951 this.workerSemaphore.Release();
2955 private async Task RefreshTwitterConfigurationAsync()
2957 await this.workerSemaphore.WaitAsync();
2958 this.RefreshTasktrayIcon();
2962 await this.tw.RefreshConfiguration();
2964 if (this.tw.Configuration.PhotoSizeLimit != 0)
2966 foreach (var service in this.ImageSelector.GetServices())
2968 service.UpdateTwitterConfiguration(this.tw.Configuration);
2972 this.PurgeListViewItemCache();
2973 this.CurrentListView.Refresh();
2975 catch (WebApiException ex)
2977 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2981 this.workerSemaphore.Release();
2985 private async Task RefreshMuteUserIdsAsync()
2987 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2991 await tw.RefreshMuteUserIdsAsync();
2993 catch (WebApiException ex)
2995 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2999 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3002 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3004 if (e.Button == MouseButtons.Left)
3006 this.Visible = true;
3007 if (this.WindowState == FormWindowState.Minimized)
3009 this.WindowState = _formWindowState;
3012 this.BringToFront();
3016 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3018 switch (SettingManager.Common.ListDoubleClickAction)
3021 MakeReplyOrDirectStatus();
3024 await this.FavoriteChange(true);
3027 var post = this.CurrentPost;
3029 await this.ShowUserStatus(post.ScreenName, false);
3032 await ShowUserTimeline();
3035 ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
3038 MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty);
3041 StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
3049 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3050 => await this.FavoriteChange(true);
3052 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3053 => await this.FavoriteChange(false);
3056 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3057 => await this.FavoritesRetweetOfficial();
3059 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3060 => await this.FavoritesRetweetUnofficial();
3062 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3064 var tab = this.CurrentTab;
3065 var posts = tab.SelectedPosts;
3067 //trueでFavAdd,falseでFavRemove
3068 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
3069 || !this.ExistCurrentPost) return;
3071 if (posts.Length > 1)
3076 // https://support.twitter.com/articles/76915#favoriting
3077 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3078 _DoFavRetweetFlags = false;
3083 if (multiFavoriteChangeDialogEnable)
3085 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3086 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3087 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3089 if (confirm == DialogResult.Cancel)
3097 var selectedPost = posts.Single();
3098 if (selectedPost.IsFav)
3100 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3104 await this.FavAddAsync(selectedPost.StatusId, tab);
3108 var selectedPosts = posts.Where(x => x.IsFav);
3109 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3110 if (statusIds.Length == 0)
3112 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3116 await this.FavRemoveAsync(statusIds, tab);
3120 private PostClass GetCurTabPost(int Index)
3122 var listCache = this._listItemCache;
3123 if (listCache != null)
3125 if (listCache.TryGetValue(Index, out _, out var post))
3129 return this.CurrentTab[Index];
3132 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3134 var post = this.CurrentPost;
3136 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3138 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3141 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3143 var post = this.CurrentPost;
3145 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3148 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3150 if ((!_initialLayout) && this.Visible)
3152 if (this.WindowState == FormWindowState.Normal)
3154 _mySize = this.ClientSize;
3155 _mySpDis = this.SplitContainer1.SplitterDistance;
3156 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3157 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3158 this.MarkSettingLocalModified();
3163 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3165 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3166 if (comparerMode == null)
3169 this.SetSortColumn(comparerMode.Value);
3173 /// 列インデックスからソートを行う ComparerMode を求める
3175 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3176 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3177 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3180 return ComparerMode.Id;
3182 switch (columnIndex)
3185 return ComparerMode.Nickname;
3187 return ComparerMode.Data;
3189 return ComparerMode.Id;
3191 return ComparerMode.Name;
3193 return ComparerMode.Source;
3195 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3201 /// 発言一覧の指定した位置の列でソートする
3203 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3204 private void SetSortColumnByDisplayIndex(int columnIndex)
3206 // 表示上の列の位置から ColumnHeader を求める
3207 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3208 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3213 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3214 if (comparerMode == null)
3217 this.SetSortColumn(comparerMode.Value);
3221 /// 発言一覧の最後列の項目でソートする
3223 private void SetSortLastColumn()
3225 // 表示上の最後列にある ColumnHeader を求める
3226 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3227 .OrderByDescending(x => x.DisplayIndex)
3230 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3231 if (comparerMode == null)
3234 this.SetSortColumn(comparerMode.Value);
3238 /// 発言一覧を指定された ComparerMode に基づいてソートする
3240 private void SetSortColumn(ComparerMode sortColumn)
3242 if (SettingManager.Common.SortOrderLock)
3245 this._statuses.ToggleSortOrder(sortColumn);
3246 this.InitColumnText();
3248 var list = this.CurrentListView;
3251 list.Columns[0].Text = this.ColumnText[0];
3252 list.Columns[1].Text = this.ColumnText[2];
3256 for (var i = 0; i <= 7; i++)
3258 list.Columns[i].Text = this.ColumnText[i];
3262 this.PurgeListViewItemCache();
3264 var tab = this.CurrentTab;
3265 var post = this.CurrentPost;
3266 if (tab.AllCount > 0 && post != null)
3268 var idx = tab.IndexOf(post.StatusId);
3271 this.SelectListItem(list, idx);
3272 list.EnsureVisible(idx);
3277 this.MarkSettingCommonModified();
3280 private void TweenMain_LocationChanged(object sender, EventArgs e)
3282 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3284 _myLoc = this.DesktopLocation;
3285 this.MarkSettingLocalModified();
3289 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3291 if (!this.ExistCurrentPost)
3293 ReplyStripMenuItem.Enabled = false;
3294 ReplyAllStripMenuItem.Enabled = false;
3295 DMStripMenuItem.Enabled = false;
3296 ShowProfileMenuItem.Enabled = false;
3297 ShowUserTimelineContextMenuItem.Enabled = false;
3298 ListManageUserContextToolStripMenuItem2.Enabled = false;
3299 MoveToFavToolStripMenuItem.Enabled = false;
3300 TabMenuItem.Enabled = false;
3301 IDRuleMenuItem.Enabled = false;
3302 SourceRuleMenuItem.Enabled = false;
3303 ReadedStripMenuItem.Enabled = false;
3304 UnreadStripMenuItem.Enabled = false;
3308 ShowProfileMenuItem.Enabled = true;
3309 ListManageUserContextToolStripMenuItem2.Enabled = true;
3310 ReplyStripMenuItem.Enabled = true;
3311 ReplyAllStripMenuItem.Enabled = true;
3312 DMStripMenuItem.Enabled = true;
3313 ShowUserTimelineContextMenuItem.Enabled = true;
3314 MoveToFavToolStripMenuItem.Enabled = true;
3315 TabMenuItem.Enabled = true;
3316 IDRuleMenuItem.Enabled = true;
3317 SourceRuleMenuItem.Enabled = true;
3318 ReadedStripMenuItem.Enabled = true;
3319 UnreadStripMenuItem.Enabled = true;
3321 var tab = this.CurrentTab;
3322 var post = this.CurrentPost;
3323 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
3325 FavAddToolStripMenuItem.Enabled = false;
3326 FavRemoveToolStripMenuItem.Enabled = false;
3327 StatusOpenMenuItem.Enabled = false;
3328 ShowRelatedStatusesMenuItem.Enabled = false;
3330 ReTweetStripMenuItem.Enabled = false;
3331 ReTweetUnofficialStripMenuItem.Enabled = false;
3332 QuoteStripMenuItem.Enabled = false;
3333 FavoriteRetweetContextMenu.Enabled = false;
3334 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3338 FavAddToolStripMenuItem.Enabled = true;
3339 FavRemoveToolStripMenuItem.Enabled = true;
3340 StatusOpenMenuItem.Enabled = true;
3341 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3343 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3345 ReTweetStripMenuItem.Enabled = false;
3346 ReTweetUnofficialStripMenuItem.Enabled = false;
3347 QuoteStripMenuItem.Enabled = false;
3348 FavoriteRetweetContextMenu.Enabled = false;
3349 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3353 ReTweetStripMenuItem.Enabled = true;
3354 ReTweetUnofficialStripMenuItem.Enabled = true;
3355 QuoteStripMenuItem.Enabled = true;
3356 FavoriteRetweetContextMenu.Enabled = true;
3357 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3360 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3362 // RefreshMoreStripMenuItem.Enabled = true;
3366 // RefreshMoreStripMenuItem.Enabled = false;
3368 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
3370 RepliedStatusOpenMenuItem.Enabled = false;
3374 RepliedStatusOpenMenuItem.Enabled = true;
3376 if (!this.ExistCurrentPost || post == null || string.IsNullOrEmpty(post.RetweetedBy))
3378 MoveToRTHomeMenuItem.Enabled = false;
3382 MoveToRTHomeMenuItem.Enabled = true;
3385 if (this.ExistCurrentPost && post != null)
3387 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3388 if (post.RetweetedByUserId == this.tw.UserId)
3389 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3391 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3395 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3396 => this.MakeReplyOrDirectStatus(false, true);
3398 private void DMStripMenuItem_Click(object sender, EventArgs e)
3399 => this.MakeReplyOrDirectStatus(false, false);
3401 private async Task doStatusDelete()
3403 var posts = this.CurrentTab.SelectedPosts;
3404 if (posts.Length == 0)
3407 // 選択されたツイートの中に削除可能なものが一つでもあるか
3408 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3411 var ret = MessageBox.Show(this,
3412 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3413 Properties.Resources.DeleteStripMenuItem_ClickText2,
3414 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3416 if (ret != DialogResult.OK)
3419 var currentListView = this.CurrentListView;
3420 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3422 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3424 Exception? lastException = null;
3425 foreach (var post in posts)
3427 if (!post.CanDeleteBy(this.tw.UserId))
3434 await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3438 if (post.RetweetedByUserId == this.tw.UserId)
3440 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3442 await this.twitterApi.StatusesDestroy(post.StatusId)
3447 if (post.UserId == this.tw.UserId)
3449 if (post.RetweetedId != null)
3450 // 他人に RT された自分のツイート
3451 // => RT 元の自分のツイートを削除
3452 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3457 await this.twitterApi.StatusesDestroy(post.StatusId)
3463 catch (WebApiException ex)
3469 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3472 if (lastException == null)
3473 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3475 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3477 this.PurgeListViewItemCache();
3479 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3481 var tabPage = this.ListTab.TabPages[index];
3482 var listView = (DetailsListView)tabPage.Tag;
3484 using (ControlTransaction.Update(listView))
3486 listView.VirtualListSize = tab.AllCount;
3488 if (tab.TabName == this.CurrentTabName)
3490 listView.SelectedIndices.Clear();
3492 if (tab.AllCount != 0)
3495 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3496 selectedIndex = focusedIndex;
3498 selectedIndex = tab.AllCount - 1;
3500 listView.SelectedIndices.Add(selectedIndex);
3501 listView.EnsureVisible(selectedIndex);
3502 listView.FocusedItem = listView.Items[selectedIndex];
3507 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3509 if (tabPage.ImageIndex == 0)
3510 tabPage.ImageIndex = -1; // タブアイコン
3514 if (!SettingManager.Common.TabIconDisp)
3515 this.ListTab.Refresh();
3519 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3520 => await this.doStatusDelete();
3522 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3524 using (ControlTransaction.Update(this.CurrentListView))
3526 var tab = this.CurrentTab;
3527 foreach (var statusId in tab.SelectedStatusIds)
3529 this._statuses.SetReadAllTab(statusId, read: true);
3530 var idx = tab.IndexOf(statusId);
3531 ChangeCacheStyleRead(true, idx);
3535 if (SettingManager.Common.TabIconDisp)
3537 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3539 if (tab.UnreadCount == 0)
3541 var tabPage = this.ListTab.TabPages[index];
3542 if (tabPage.ImageIndex == 0)
3543 tabPage.ImageIndex = -1; // タブアイコン
3547 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3550 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3552 using (ControlTransaction.Update(this.CurrentListView))
3554 var tab = this.CurrentTab;
3555 foreach (var statusId in tab.SelectedStatusIds)
3557 this._statuses.SetReadAllTab(statusId, read: false);
3558 var idx = tab.IndexOf(statusId);
3559 ChangeCacheStyleRead(false, idx);
3563 if (SettingManager.Common.TabIconDisp)
3565 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3567 if (tab.UnreadCount > 0)
3569 var tabPage = this.ListTab.TabPages[index];
3570 if (tabPage.ImageIndex == -1)
3571 tabPage.ImageIndex = 0; // タブアイコン
3575 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3578 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3579 => await this.DoRefresh();
3581 private async Task DoRefresh()
3582 => await this.RefreshTabAsync(this.CurrentTab);
3584 private async Task DoRefreshMore()
3585 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3587 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3589 var result = DialogResult.Abort;
3591 using var settingDialog = new AppendSettingDialog();
3592 settingDialog.Icon = this.MainIcon;
3593 settingDialog.Owner = this;
3594 settingDialog.ShowInTaskbar = showTaskbarIcon;
3595 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3597 settingDialog.tw = this.tw;
3598 settingDialog.twitterApi = this.twitterApi;
3600 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3604 result = settingDialog.ShowDialog(this);
3608 return DialogResult.Abort;
3611 if (result == DialogResult.OK)
3615 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3622 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3625 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3627 var oldIconSz = SettingManager.Common.IconSize;
3629 if (ShowSettingDialog() == DialogResult.OK)
3633 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3634 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3635 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3636 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3637 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3638 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3639 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3641 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3642 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3643 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3644 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3645 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3646 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3648 ImageSelector.Reset(tw, this.tw.Configuration);
3652 if (SettingManager.Common.TabIconDisp)
3654 ListTab.DrawItem -= ListTab_DrawItem;
3655 ListTab.DrawMode = TabDrawMode.Normal;
3656 ListTab.ImageList = this.TabImage;
3660 ListTab.DrawItem -= ListTab_DrawItem;
3661 ListTab.DrawItem += ListTab_DrawItem;
3662 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3663 ListTab.ImageList = null;
3666 catch (Exception ex)
3668 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3669 ex.Data["IsTerminatePermission"] = false;
3675 if (!SettingManager.Common.UnreadManage)
3677 ReadedStripMenuItem.Enabled = false;
3678 UnreadStripMenuItem.Enabled = false;
3679 if (SettingManager.Common.TabIconDisp)
3681 foreach (TabPage myTab in ListTab.TabPages)
3683 myTab.ImageIndex = -1;
3689 ReadedStripMenuItem.Enabled = true;
3690 UnreadStripMenuItem.Enabled = true;
3693 catch (Exception ex)
3695 ex.Data["Instance"] = "ListTab(UnreadManage)";
3696 ex.Data["IsTerminatePermission"] = false;
3703 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3705 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3706 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3707 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3709 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3710 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3711 _fntUnread = SettingManager.Local.FontUnread;
3712 _clUnread = SettingManager.Local.ColorUnread;
3713 _fntReaded = SettingManager.Local.FontRead;
3714 _clReaded = SettingManager.Local.ColorRead;
3715 _clFav = SettingManager.Local.ColorFav;
3716 _clOWL = SettingManager.Local.ColorOWL;
3717 _clRetweet = SettingManager.Local.ColorRetweet;
3718 _fntDetail = SettingManager.Local.FontDetail;
3719 _clDetail = SettingManager.Local.ColorDetail;
3720 _clDetailLink = SettingManager.Local.ColorDetailLink;
3721 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3722 _clSelf = SettingManager.Local.ColorSelf;
3723 _clAtSelf = SettingManager.Local.ColorAtSelf;
3724 _clTarget = SettingManager.Local.ColorTarget;
3725 _clAtTarget = SettingManager.Local.ColorAtTarget;
3726 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3727 _clAtTo = SettingManager.Local.ColorAtTo;
3728 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3729 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3730 _clInputFont = SettingManager.Local.ColorInputFont;
3731 _fntInputFont = SettingManager.Local.FontInputFont;
3732 _brsBackColorMine.Dispose();
3733 _brsBackColorAt.Dispose();
3734 _brsBackColorYou.Dispose();
3735 _brsBackColorAtYou.Dispose();
3736 _brsBackColorAtFromTarget.Dispose();
3737 _brsBackColorAtTo.Dispose();
3738 _brsBackColorNone.Dispose();
3739 _brsBackColorMine = new SolidBrush(_clSelf);
3740 _brsBackColorAt = new SolidBrush(_clAtSelf);
3741 _brsBackColorYou = new SolidBrush(_clTarget);
3742 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3743 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3744 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3745 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3749 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3750 StatusText.Font = _fntInputFont;
3751 StatusText.ForeColor = _clInputFont;
3753 catch (Exception ex)
3755 MessageBox.Show(ex.Message);
3760 InitDetailHtmlFormat();
3762 catch (Exception ex)
3764 ex.Data["Instance"] = "Font";
3765 ex.Data["IsTerminatePermission"] = false;
3771 if (SettingManager.Common.TabIconDisp)
3773 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3775 var tabPage = this.ListTab.TabPages[index];
3776 if (tab.UnreadCount == 0)
3777 tabPage.ImageIndex = -1;
3779 tabPage.ImageIndex = 0;
3783 catch (Exception ex)
3785 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3786 ex.Data["IsTerminatePermission"] = false;
3792 var oldIconCol = _iconCol;
3794 if (SettingManager.Common.IconSize != oldIconSz)
3795 ApplyListViewIconSize(SettingManager.Common.IconSize);
3797 foreach (TabPage tp in ListTab.TabPages)
3799 var lst = (DetailsListView)tp.Tag;
3801 using (ControlTransaction.Update(lst))
3803 lst.GridLines = SettingManager.Common.ShowGrid;
3804 lst.Font = _fntReaded;
3805 lst.BackColor = _clListBackcolor;
3807 if (_iconCol != oldIconCol)
3812 catch (Exception ex)
3814 ex.Data["Instance"] = "ListView(IconSize)";
3815 ex.Data["IsTerminatePermission"] = false;
3819 SetMainWindowTitle();
3820 SetNotifyIconText();
3822 this.PurgeListViewItemCache();
3823 this.CurrentListView.Refresh();
3826 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3827 if (SettingManager.Common.HotkeyEnabled)
3829 ///グローバルホットキーの登録。設定で変更可能にするかも
3830 var modKey = HookGlobalHotkey.ModKeys.None;
3831 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3832 modKey |= HookGlobalHotkey.ModKeys.Alt;
3833 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3834 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3835 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3836 modKey |= HookGlobalHotkey.ModKeys.Shift;
3837 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3838 modKey |= HookGlobalHotkey.ModKeys.Win;
3840 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3843 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3846 StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3855 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3856 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3859 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3861 this.TopMost = SettingManager.Common.AlwaysTop;
3862 SaveConfigsAll(false);
3864 if (tw.UserId != oldUser.UserId)
3865 await this.doGetFollowersMenu();
3871 private void SetTabAlignment()
3873 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3874 if (ListTab.Alignment == newAlignment) return;
3876 // 各タブのリスト上の選択位置などを退避
3877 var listSelections = this.SaveListViewSelection();
3879 ListTab.Alignment = newAlignment;
3881 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3883 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3884 using (ControlTransaction.Update(lst))
3887 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3892 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3898 case MyCommon.IconSizes.IconNone:
3901 case MyCommon.IconSizes.Icon16:
3904 case MyCommon.IconSizes.Icon24:
3907 case MyCommon.IconSizes.Icon48:
3910 case MyCommon.IconSizes.Icon48_2:
3918 // ディスプレイの DPI 設定を考慮したサイズを設定する
3919 _listViewImageList.ImageSize = new Size(
3921 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3925 _listViewImageList.ImageSize = new Size(1, 1);
3929 private void ResetColumns(DetailsListView list)
3931 using (ControlTransaction.Update(list))
3932 using (ControlTransaction.Layout(list, false))
3935 list.ColumnClick -= MyList_ColumnClick;
3936 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3937 list.ColumnReordered -= MyList_ColumnReordered;
3938 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3940 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3941 list.Columns.Clear();
3942 cols.ForEach(col => col.Dispose());
3945 InitColumns(list, true);
3947 list.ColumnClick += MyList_ColumnClick;
3948 list.DrawColumnHeader += MyList_DrawColumnHeader;
3949 list.ColumnReordered += MyList_ColumnReordered;
3950 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3954 public void AddNewTabForSearch(string searchWord)
3956 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3957 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3959 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
3961 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3962 this.ListTab.SelectedIndex = tabIndex;
3967 var tabName = searchWord;
3968 for (var i = 0; i <= 100; i++)
3970 if (_statuses.ContainsTab(tabName))
3976 var tab = new PublicSearchTabModel(tabName);
3977 _statuses.AddTab(tab);
3978 AddNewTab(tab, startup: false);
3980 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3982 var tabPage = this.CurrentTabPage;
3983 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3984 cmb.Items.Add(searchWord);
3985 cmb.Text = searchWord;
3988 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
3991 private async Task ShowUserTimeline()
3993 var post = this.CurrentPost;
3994 if (post == null || !this.ExistCurrentPost) return;
3995 await this.AddNewTabForUserTimeline(post.ScreenName);
3998 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4000 if (e.KeyCode == Keys.Escape)
4002 RemoveSpecifiedTab(this.CurrentTabName, false);
4004 e.SuppressKeyPress = true;
4008 public async Task AddNewTabForUserTimeline(string user)
4010 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4011 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4013 if (tb.ScreenName == user)
4015 var tabIndex = this._statuses.Tabs.IndexOf(tb);
4016 this.ListTab.SelectedIndex = tabIndex;
4021 var tabName = "user:" + user;
4022 while (_statuses.ContainsTab(tabName))
4027 var tab = new UserTimelineTabModel(tabName, user);
4028 this._statuses.AddTab(tab);
4029 this.AddNewTab(tab, startup: false);
4031 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
4034 await this.RefreshTabAsync(tab);
4037 public bool AddNewTab(TabModel tab, bool startup)
4040 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
4044 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4046 var _tabPage = new TabPage();
4047 var _listCustom = new DetailsListView();
4049 var cnt = this._statuses.Tabs.Count;
4051 ///ToDo:Create and set controls follow tabtypes
4053 using (ControlTransaction.Update(_listCustom))
4054 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4055 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4056 using (ControlTransaction.Layout(this.SplitContainer1, false))
4057 using (ControlTransaction.Layout(this.ListTab, false))
4058 using (ControlTransaction.Layout(this))
4059 using (ControlTransaction.Layout(_tabPage, false))
4061 _tabPage.Controls.Add(_listCustom);
4064 var userTab = tab as UserTimelineTabModel;
4065 var listTab = tab as ListTimelineTabModel;
4066 var searchTab = tab as PublicSearchTabModel;
4068 if (userTab != null || listTab != null)
4070 var label = new Label
4072 Dock = DockStyle.Top,
4077 if (listTab != null)
4079 label.Text = listTab.ListInfo.ToString();
4081 else if (userTab != null)
4083 label.Text = userTab.ScreenName + "'s Timeline";
4085 label.TextAlign = ContentAlignment.MiddleLeft;
4086 using (var tmpComboBox = new ComboBox())
4088 label.Height = tmpComboBox.Height;
4090 _tabPage.Controls.Add(label);
4093 else if (searchTab != null)
4095 var pnl = new Panel();
4097 var lbl = new Label();
4098 var cmb = new ComboBox();
4099 var btn = new Button();
4100 var cmbLang = new ComboBox();
4102 using (ControlTransaction.Layout(pnl, false))
4104 pnl.Controls.Add(cmb);
4105 pnl.Controls.Add(cmbLang);
4106 pnl.Controls.Add(btn);
4107 pnl.Controls.Add(lbl);
4108 pnl.Name = "panelSearch";
4110 pnl.Dock = DockStyle.Top;
4111 pnl.Height = cmb.Height;
4112 pnl.Enter += SearchControls_Enter;
4113 pnl.Leave += SearchControls_Leave;
4116 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4117 cmb.Dock = DockStyle.Fill;
4118 cmb.Name = "comboSearch";
4119 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4120 cmb.ImeMode = ImeMode.NoControl;
4121 cmb.TabStop = false;
4123 cmb.AutoCompleteMode = AutoCompleteMode.None;
4124 cmb.KeyDown += SearchComboBox_KeyDown;
4127 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4128 cmbLang.Dock = DockStyle.Right;
4130 cmbLang.Name = "comboLang";
4131 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4132 cmbLang.TabStop = false;
4133 cmbLang.TabIndex = 2;
4134 cmbLang.Items.Add("");
4135 cmbLang.Items.Add("ja");
4136 cmbLang.Items.Add("en");
4137 cmbLang.Items.Add("ar");
4138 cmbLang.Items.Add("da");
4139 cmbLang.Items.Add("nl");
4140 cmbLang.Items.Add("fa");
4141 cmbLang.Items.Add("fi");
4142 cmbLang.Items.Add("fr");
4143 cmbLang.Items.Add("de");
4144 cmbLang.Items.Add("hu");
4145 cmbLang.Items.Add("is");
4146 cmbLang.Items.Add("it");
4147 cmbLang.Items.Add("no");
4148 cmbLang.Items.Add("pl");
4149 cmbLang.Items.Add("pt");
4150 cmbLang.Items.Add("ru");
4151 cmbLang.Items.Add("es");
4152 cmbLang.Items.Add("sv");
4153 cmbLang.Items.Add("th");
4155 lbl.Text = "Search(C-S-f)";
4156 lbl.Name = "label1";
4157 lbl.Dock = DockStyle.Left;
4159 lbl.Height = cmb.Height;
4160 lbl.TextAlign = ContentAlignment.MiddleLeft;
4163 btn.Text = "Search";
4164 btn.Name = "buttonSearch";
4165 btn.UseVisualStyleBackColor = true;
4166 btn.Dock = DockStyle.Right;
4167 btn.TabStop = false;
4169 btn.Click += SearchButton_Click;
4171 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4173 cmb.Items.Add(searchTab.SearchWords);
4174 cmb.Text = searchTab.SearchWords;
4177 cmbLang.Text = searchTab.SearchLang;
4179 _tabPage.Controls.Add(pnl);
4183 _tabPage.Tag = _listCustom;
4184 this.ListTab.Controls.Add(_tabPage);
4186 _tabPage.Location = new Point(4, 4);
4187 _tabPage.Name = "CTab" + cnt;
4188 _tabPage.Size = new Size(380, 260);
4189 _tabPage.TabIndex = 2 + cnt;
4190 _tabPage.Text = tab.TabName;
4191 _tabPage.UseVisualStyleBackColor = true;
4192 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4194 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4195 _listCustom.TabIndex = 1;
4196 _listCustom.AllowColumnReorder = true;
4197 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4198 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4199 _listCustom.Dock = DockStyle.Fill;
4200 _listCustom.FullRowSelect = true;
4201 _listCustom.HideSelection = false;
4202 _listCustom.Location = new Point(0, 0);
4203 _listCustom.Margin = new Padding(0);
4204 _listCustom.Name = "CList" + Environment.TickCount;
4205 _listCustom.ShowItemToolTips = true;
4206 _listCustom.Size = new Size(380, 260);
4207 _listCustom.UseCompatibleStateImageBehavior = false;
4208 _listCustom.View = View.Details;
4209 _listCustom.OwnerDraw = true;
4210 _listCustom.VirtualMode = true;
4211 _listCustom.Font = _fntReaded;
4212 _listCustom.BackColor = _clListBackcolor;
4214 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4215 _listCustom.AllowDrop = true;
4217 _listCustom.SmallImageList = _listViewImageList;
4219 InitColumns(_listCustom, startup);
4221 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4222 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4223 _listCustom.ColumnClick += MyList_ColumnClick;
4224 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4225 _listCustom.DragDrop += TweenMain_DragDrop;
4226 _listCustom.DragEnter += TweenMain_DragEnter;
4227 _listCustom.DragOver += TweenMain_DragOver;
4228 _listCustom.DrawItem += MyList_DrawItem;
4229 _listCustom.MouseClick += MyList_MouseClick;
4230 _listCustom.ColumnReordered += MyList_ColumnReordered;
4231 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4232 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4233 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4234 _listCustom.DrawSubItem += MyList_DrawSubItem;
4235 _listCustom.HScrolled += MyList_HScrolled;
4241 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4243 var tabInfo = _statuses.GetTabByName(TabName);
4244 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
4249 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4250 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4251 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4257 var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4261 var _tabPage = this.ListTab.TabPages[tabIndex];
4263 SetListProperty(); //他のタブに列幅等を反映
4266 var _listCustom = (DetailsListView)_tabPage.Tag;
4267 _tabPage.Tag = null;
4269 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4270 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4271 using (ControlTransaction.Layout(this.SplitContainer1, false))
4272 using (ControlTransaction.Layout(this.ListTab, false))
4273 using (ControlTransaction.Layout(this))
4274 using (ControlTransaction.Layout(_tabPage, false))
4276 if (this.CurrentTabName == TabName)
4278 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4279 this._beforeSelectedTab = null;
4281 this.ListTab.Controls.Remove(_tabPage);
4284 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4286 using var label = _tabPage.Controls["labelUser"];
4287 _tabPage.Controls.Remove(label);
4289 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4291 using var pnl = _tabPage.Controls["panelSearch"];
4293 pnl.Enter -= SearchControls_Enter;
4294 pnl.Leave -= SearchControls_Leave;
4295 _tabPage.Controls.Remove(pnl);
4297 foreach (Control ctrl in pnl.Controls)
4299 if (ctrl.Name == "buttonSearch")
4301 ctrl.Click -= SearchButton_Click;
4303 else if (ctrl.Name == "comboSearch")
4305 ctrl.KeyDown -= SearchComboBox_KeyDown;
4307 pnl.Controls.Remove(ctrl);
4312 _tabPage.Controls.Remove(_listCustom);
4314 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4315 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4316 _listCustom.ColumnClick -= MyList_ColumnClick;
4317 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4318 _listCustom.DragDrop -= TweenMain_DragDrop;
4319 _listCustom.DragEnter -= TweenMain_DragEnter;
4320 _listCustom.DragOver -= TweenMain_DragOver;
4321 _listCustom.DrawItem -= MyList_DrawItem;
4322 _listCustom.MouseClick -= MyList_MouseClick;
4323 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4324 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4325 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4326 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4327 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4328 _listCustom.HScrolled -= MyList_HScrolled;
4330 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4331 _listCustom.Columns.Clear();
4332 cols.ForEach(col => col.Dispose());
4335 _listCustom.ContextMenuStrip = null;
4336 _listCustom.ColumnHeaderContextMenuStrip = null;
4337 _listCustom.Font = null;
4339 _listCustom.SmallImageList = null;
4340 _listCustom.ListViewItemSorter = null;
4343 this.PurgeListViewItemCache();
4347 _listCustom.Dispose();
4348 _statuses.RemoveTab(TabName);
4350 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4352 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4353 lst.VirtualListSize = tab.AllCount;
4359 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4361 this.PurgeListViewItemCache();
4362 _beforeSelectedTab = e.TabPage;
4365 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4369 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4372 var dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4373 if (!dragEnableRectangle.Contains(e.Location))
4375 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4376 tn = this.CurrentTabName;
4379 if (string.IsNullOrEmpty(tn)) return;
4381 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4384 var tabPage = this.ListTab.TabPages[tabIndex];
4385 ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4393 var cpos = new Point(e.X, e.Y);
4394 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4396 var rect = ListTab.GetTabRect(index);
4397 if (rect.Contains(cpos))
4399 _rclickTabName = tab.TabName;
4405 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4407 //_curList.Refresh();
4408 SetMainWindowTitle();
4409 SetStatusLabelUrl();
4410 SetApiStatusLabel();
4411 if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4412 this.Tag = ListTab.Tag;
4413 TabMenuControl(this.CurrentTabName);
4414 this.PushSelectPostChain();
4418 private void SetListProperty()
4420 if (!_isColumnChanged) return;
4422 var currentListView = this.CurrentListView;
4424 var dispOrder = new int[currentListView.Columns.Count];
4425 for (var i = 0; i < currentListView.Columns.Count; i++)
4427 for (var j = 0; j < currentListView.Columns.Count; j++)
4429 if (currentListView.Columns[j].DisplayIndex == i)
4438 foreach (TabPage tb in ListTab.TabPages)
4440 if (tb.Text == this.CurrentTabName)
4443 if (tb.Tag != null && tb.Controls.Count > 0)
4445 var lst = (DetailsListView)tb.Tag;
4446 for (var i = 0; i < lst.Columns.Count; i++)
4448 lst.Columns[dispOrder[i]].DisplayIndex = i;
4449 lst.Columns[i].Width = currentListView.Columns[i].Width;
4454 _isColumnChanged = false;
4457 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4459 if (e.KeyChar == '@')
4461 if (!SettingManager.Common.UseAtIdSupplement) return;
4463 var cnt = AtIdSupl.ItemCount;
4464 ShowSuplDialog(StatusText, AtIdSupl);
4465 if (cnt != AtIdSupl.ItemCount)
4466 this.MarkSettingAtIdModified();
4469 else if (e.KeyChar == '#')
4471 if (!SettingManager.Common.UseHashSupplement) return;
4472 ShowSuplDialog(StatusText, HashSupl);
4477 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4478 => this.ShowSuplDialog(owner, dialog, 0, "");
4480 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4481 => this.ShowSuplDialog(owner, dialog, offset, "");
4483 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4485 dialog.StartsWith = startswith;
4492 dialog.ShowDialog();
4494 this.TopMost = SettingManager.Common.AlwaysTop;
4495 var selStart = owner.SelectionStart;
4498 if (dialog.DialogResult == DialogResult.OK)
4500 if (!string.IsNullOrEmpty(dialog.inputText))
4504 fHalf = owner.Text.Substring(0, selStart - offset);
4506 if (selStart < owner.Text.Length)
4508 eHalf = owner.Text.Substring(selStart);
4510 owner.Text = fHalf + dialog.inputText + eHalf;
4511 owner.SelectionStart = selStart + dialog.inputText.Length;
4518 fHalf = owner.Text.Substring(0, selStart);
4520 if (selStart < owner.Text.Length)
4522 eHalf = owner.Text.Substring(selStart);
4524 owner.Text = fHalf + eHalf;
4527 owner.SelectionStart = selStart;
4533 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4536 if (!e.Alt && !e.Control && !e.Shift)
4538 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4540 var isSpace = false;
4541 foreach (var c in StatusText.Text)
4543 if (c == ' ' || c == ' ')
4556 StatusText.Text = "";
4557 JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4561 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
4564 private void StatusText_TextChanged(object sender, EventArgs e)
4567 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4568 lblLen.Text = pLen.ToString();
4571 StatusText.ForeColor = Color.Red;
4575 StatusText.ForeColor = _clInputFont;
4578 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4580 if (string.IsNullOrEmpty(StatusText.Text))
4582 this.inReplyTo = null;
4587 /// メンション以外の文字列が含まれていないテキストであるか判定します
4589 internal static bool TextContainsOnlyMentions(string text)
4591 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4594 foreach (var mention in mentions)
4596 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4598 if (!string.IsNullOrWhiteSpace(textPart))
4601 startIndex = mention.Indices[1];
4604 var textPartLast = text.Substring(startIndex);
4606 if (!string.IsNullOrWhiteSpace(textPartLast))
4613 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4615 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4617 var _autoPopulatedUserIds = new List<long>();
4619 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4620 if (replyToPost != null)
4622 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4624 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4625 _autoPopulatedUserIds.Add(replyToPost.UserId);
4627 foreach (var (userId, screenName) in replyToPost.ReplyToList)
4629 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4631 statusText = statusText.Substring(screenName.Length + 2);
4632 _autoPopulatedUserIds.Add(userId);
4638 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4644 /// attachment_url に指定可能な URL が含まれていれば除去
4646 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
4648 attachmentUrl = null;
4650 // attachment_url は media_id と同時に使用できない
4651 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4654 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4658 attachmentUrl = match.Value;
4661 statusText = statusText.Substring(0, match.Index);
4663 // テキストと URL の間にスペースが含まれていれば除去
4664 return statusText.TrimEnd(' ');
4667 private string FormatStatusTextExtended(string statusText)
4668 => this.FormatStatusTextExtended(statusText, out _, out _);
4671 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4673 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
4675 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4677 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4679 return this.FormatStatusText(statusText);
4683 /// ツイート投稿前のフッター付与などの前処理を行います
4685 private string FormatStatusText(string statusText)
4687 statusText = statusText.Replace("\r\n", "\n");
4689 if (this.urlMultibyteSplit)
4692 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4695 if (SettingManager.Common.WideSpaceConvert)
4697 // 文中の全角スペースを半角スペース1個にする
4698 statusText = statusText.Replace(" ", " ");
4701 // DM の場合はこれ以降の処理を行わない
4702 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4706 if (SettingManager.Common.PostShiftEnter)
4708 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4712 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4713 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4715 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4718 if (statusText.Contains("RT @"))
4719 disableFooter = true;
4721 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4722 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4724 var mentionSelf = $"@{this.tw.Username} ";
4725 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4727 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4728 statusText = statusText.Substring(mentionSelf.Length);
4735 var hashtag = this.HashMgr.UseHash;
4736 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4739 header = HashMgr.UseHash + " ";
4741 footer = " " + HashMgr.UseHash;
4746 if (SettingManager.Local.UseRecommendStatus)
4749 footer += this.recommendedStatusFooter;
4751 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4753 // テキストボックスに入力されている文字列を使用する
4754 footer += " " + SettingManager.Local.StatusText.Trim();
4758 statusText = header + statusText + footer;
4760 if (this.preventSmsCommand)
4762 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4763 // 参照: https://support.twitter.com/articles/14020
4765 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4766 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4768 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4769 statusText = '\u200b' + statusText;
4777 /// 投稿欄に表示する入力可能な文字数を計算します
4779 private int GetRestStatusCount(string statusText)
4781 var remainCount = this.tw.GetTextLengthRemain(statusText);
4783 var uploadService = this.GetSelectedImageService();
4784 if (uploadService != null)
4786 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4787 remainCount -= uploadService.GetReservedTextLength(1);
4793 private IMediaUploadService? GetSelectedImageService()
4794 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4796 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4798 if (sender != this.CurrentListView)
4801 var listCache = this._listItemCache;
4802 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4804 // If the newly requested cache is a subset of the old cache,
4805 // no need to rebuild everything, so do nothing.
4809 // Now we need to rebuild the cache.
4810 this.CreateCache(e.StartIndex, e.EndIndex);
4813 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4815 var listCache = this._listItemCache;
4816 if (listCache?.TargetList == sender)
4818 if (listCache.TryGetValue(e.ItemIndex, out var item, out _))
4825 // A cache miss, so create a new ListViewItem and pass it back.
4826 var tabPage = (TabPage)((DetailsListView)sender).Parent;
4827 var tab = this._statuses.Tabs[tabPage.Text];
4830 e.Item = this.CreateItem(tab, tab[e.ItemIndex]);
4834 // 不正な要求に対する間に合わせの応答
4835 string[] sitem = {"", "", "", "", "", "", "", ""};
4836 e.Item = new ImageListViewItem(sitem);
4840 private void CreateCache(int startIndex, int endIndex)
4842 var tabInfo = this.CurrentTab;
4844 if (tabInfo.AllCount == 0)
4847 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4848 int FilterRange(int index)
4849 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4851 // キャッシュ要求(要求範囲±30を作成)
4852 startIndex = FilterRange(startIndex - 30);
4853 endIndex = FilterRange(endIndex + 30);
4855 var cacheLength = endIndex - startIndex + 1;
4857 var tab = this.CurrentTab;
4858 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4859 var listItems = Enumerable.Range(0, cacheLength)
4860 .Select(x => this.CreateItem(tab, posts[x]))
4863 var listCache = new ListViewItemCache
4865 TargetList = this.CurrentListView,
4866 StartIndex = startIndex,
4867 EndIndex = endIndex,
4868 Cache = Enumerable.Zip(listItems, posts, (x, y) => (x, y)).ToArray(),
4871 Interlocked.Exchange(ref this._listItemCache, listCache);
4875 /// DetailsListView のための ListViewItem のキャッシュを消去する
4877 private void PurgeListViewItemCache()
4878 => Interlocked.Exchange(ref this._listItemCache, null);
4880 private ListViewItem CreateItem(TabModel tab, PostClass Post)
4882 var mk = new StringBuilder();
4883 //if (Post.IsDeleted) mk.Append("×");
4884 //if (Post.IsMark) mk.Append("♪");
4885 //if (Post.IsProtect) mk.Append("Ю");
4886 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4887 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4888 ImageListViewItem itm;
4889 if (Post.RetweetedId == null)
4891 string[] sitem= {"",
4893 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4894 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4899 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4903 string[] sitem = {"",
4905 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4906 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4907 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4911 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4913 itm.StateIndex = Post.StateIndex;
4916 var read = Post.IsRead;
4917 // 未読管理していなかったら既読として扱う
4918 if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4921 ChangeItemStyleRead(read, itm, Post, null);
4923 if (tab.TabName == this.CurrentTabName)
4924 this.ColorizeList(itm, Post);
4930 /// 全てのタブの振り分けルールを反映し直します
4932 private void ApplyPostFilters()
4934 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4936 this.PurgeListViewItemCache();
4937 this._statuses.FilterAll();
4939 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4941 var tabPage = this.ListTab.TabPages[index];
4942 var listview = (DetailsListView)tabPage.Tag;
4943 using (ControlTransaction.Update(listview))
4945 listview.VirtualListSize = tab.AllCount;
4948 if (SettingManager.Common.TabIconDisp)
4950 if (tab.UnreadCount > 0)
4951 tabPage.ImageIndex = 0;
4953 tabPage.ImageIndex = -1;
4957 if (!SettingManager.Common.TabIconDisp)
4958 this.ListTab.Refresh();
4960 SetMainWindowTitle();
4961 SetStatusLabelUrl();
4965 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4966 => e.DrawDefault = true;
4968 private void MyList_HScrolled(object sender, EventArgs e)
4969 => ((DetailsListView)sender).Refresh();
4971 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4973 if (e.State == 0) return;
4974 e.DrawDefault = false;
4977 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4979 if (e.Item.BackColor == _clSelf)
4980 brs2 = _brsBackColorMine;
4981 else if (e.Item.BackColor == _clAtSelf)
4982 brs2 = _brsBackColorAt;
4983 else if (e.Item.BackColor == _clTarget)
4984 brs2 = _brsBackColorYou;
4985 else if (e.Item.BackColor == _clAtTarget)
4986 brs2 = _brsBackColorAtYou;
4987 else if (e.Item.BackColor == _clAtFromTarget)
4988 brs2 = _brsBackColorAtFromTarget;
4989 else if (e.Item.BackColor == _clAtTo)
4990 brs2 = _brsBackColorAtTo;
4992 brs2 = _brsBackColorNone;
4997 if (((Control)sender).Focused)
4998 brs2 = _brsHighLight;
5000 brs2 = _brsDeactiveSelection;
5002 e.Graphics.FillRectangle(brs2, e.Bounds);
5003 e.DrawFocusRectangle();
5004 this.DrawListViewItemIcon(e);
5007 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5009 if (e.ItemState == 0) return;
5011 if (e.ColumnIndex > 0)
5014 var post = (PostClass)e.Item.Tag;
5016 RectangleF rct = e.Bounds;
5017 rct.Width = e.Header.Width;
5018 var fontHeight = e.Item.Font.Height;
5021 rct.Y += fontHeight;
5022 rct.Height -= fontHeight;
5025 var drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5027 //if (heightDiff > fontHeight * 0.7)
5029 // rct.Height += fontHeight;
5030 // drawLineCount += 1;
5033 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5034 if (!_iconCol && drawLineCount <= 1)
5036 //rct.Inflate(0, heightDiff / -2);
5037 //rct.Height += fontHeight / 2;
5039 else if (heightDiff < fontHeight * 0.7)
5041 //最終行が70%以上欠けていたら、最終行は表示しない
5042 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5043 rct.Height = (fontHeight * drawLineCount) - 1;
5050 //if (!_iconCol && drawLineCount > 1)
5052 // rct.Y += fontHeight * 0.2;
5053 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5058 var color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5059 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5064 var rctB = e.Bounds;
5065 rctB.Width = e.Header.Width;
5066 rctB.Height = fontHeight;
5068 using var fnt = new Font(e.Item.Font, FontStyle.Bold);
5070 TextRenderer.DrawText(e.Graphics,
5071 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5073 Rectangle.Round(rct),
5075 TextFormatFlags.WordBreak |
5076 TextFormatFlags.EndEllipsis |
5077 TextFormatFlags.GlyphOverhangPadding |
5078 TextFormatFlags.NoPrefix);
5079 TextRenderer.DrawText(e.Graphics,
5080 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 + "]",
5084 TextFormatFlags.SingleLine |
5085 TextFormatFlags.EndEllipsis |
5086 TextFormatFlags.GlyphOverhangPadding |
5087 TextFormatFlags.NoPrefix);
5092 if (e.ColumnIndex != 2)
5093 text = e.SubItem.Text;
5095 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5097 if (drawLineCount == 1)
5099 TextRenderer.DrawText(e.Graphics,
5102 Rectangle.Round(rct),
5104 TextFormatFlags.SingleLine |
5105 TextFormatFlags.EndEllipsis |
5106 TextFormatFlags.GlyphOverhangPadding |
5107 TextFormatFlags.NoPrefix |
5108 TextFormatFlags.VerticalCenter);
5112 TextRenderer.DrawText(e.Graphics,
5115 Rectangle.Round(rct),
5117 TextFormatFlags.WordBreak |
5118 TextFormatFlags.EndEllipsis |
5119 TextFormatFlags.GlyphOverhangPadding |
5120 TextFormatFlags.NoPrefix);
5123 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5128 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5130 if (_iconSz == 0) return;
5132 var item = (ImageListViewItem)e.Item;
5134 //e.Bounds.Leftが常に0を指すから自前で計算
5135 var itemRect = item.Bounds;
5136 var col0 = e.Item.ListView.Columns[0];
5137 itemRect.Width = col0.Width;
5139 if (col0.DisplayIndex > 0)
5141 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5143 if (clm.DisplayIndex < col0.DisplayIndex)
5144 itemRect.X += clm.Width;
5148 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5149 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5150 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5153 var img = item.Image;
5156 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5157 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5159 if (iconRect.Width > 0)
5161 e.Graphics.FillRectangle(Brushes.White, iconRect);
5162 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5165 e.Graphics.DrawImage(img.Image, iconRect);
5167 catch (ArgumentException)
5169 item.RefreshImageAsync();
5175 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5176 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5178 item.GetImageAsync();
5181 if (item.StateIndex > -1)
5183 var stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5184 if (stateRect.Width > 0)
5186 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5187 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5188 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5193 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5195 base.ScaleControl(factor, specified);
5197 ScaleChildControl(this.TabImage, factor);
5199 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5200 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5202 foreach (var listview in listviews)
5204 ScaleChildControl(listview, factor);
5208 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5210 // ImageListViewItem item = (ImageListViewItem)e.Item;
5211 // if (item.StateImageIndex > -1)
5213 // ////e.Bounds.Leftが常に0を指すから自前で計算
5214 // //Rectangle itemRect = item.Bounds;
5215 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5217 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5219 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5221 // // itemRect.X += clm.Width;
5225 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5226 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5228 // if (rct.Width > 0)
5230 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5231 // //e.Graphics.FillRectangle(Brushes.White, rct);
5232 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5233 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5238 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5240 var tab = this.CurrentTab;
5242 if (tab.AllCount == 0)
5244 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5248 var selectedIndex = tab.SelectedIndex;
5253 case SEARCHTYPE.NextSearch: // 次を検索
5254 if (selectedIndex != -1)
5255 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5259 case SEARCHTYPE.PrevSearch: // 前を検索
5260 if (selectedIndex != -1)
5261 startIndex = Math.Max(selectedIndex - 1, 0);
5263 startIndex = tab.AllCount - 1;
5265 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5267 if (selectedIndex != -1)
5268 startIndex = selectedIndex;
5274 Func<string, bool> stringComparer;
5277 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5279 catch (ArgumentException)
5281 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5285 var reverse = searchType == SEARCHTYPE.PrevSearch;
5286 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5287 .DefaultIfEmpty(-1).First();
5289 if (foundIndex == -1)
5291 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5295 var listView = this.CurrentListView;
5296 this.SelectListItem(listView, foundIndex);
5297 listView.EnsureVisible(foundIndex);
5300 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5301 => this.ShowSearchDialog(); // 検索メニュー
5303 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5305 var previousSearch = this.SearchDialog.ResultOptions;
5306 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5308 this.SearchDialog.Reset();
5309 this.ShowSearchDialog();
5315 previousSearch.Query,
5316 previousSearch.CaseSensitive,
5317 previousSearch.UseRegex,
5318 SEARCHTYPE.NextSearch);
5321 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5323 var previousSearch = this.SearchDialog.ResultOptions;
5324 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5326 this.SearchDialog.Reset();
5327 this.ShowSearchDialog();
5333 previousSearch.Query,
5334 previousSearch.CaseSensitive,
5335 previousSearch.UseRegex,
5336 SEARCHTYPE.PrevSearch);
5340 /// 検索ダイアログを表示し、検索を実行します
5342 private void ShowSearchDialog()
5344 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5346 this.TopMost = SettingManager.Common.AlwaysTop;
5349 this.TopMost = SettingManager.Common.AlwaysTop;
5351 var searchOptions = this.SearchDialog.ResultOptions!;
5352 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5354 if (searchOptions.NewTab)
5356 var tabName = Properties.Resources.SearchResults_TabName;
5360 tabName = this._statuses.MakeTabName(tabName);
5362 catch (TabException ex)
5364 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5367 var resultTab = new LocalSearchTabModel(tabName);
5368 this.AddNewTab(resultTab, startup: false);
5369 this._statuses.AddTab(resultTab);
5371 var targetTab = this.CurrentTab;
5373 Func<string, bool> stringComparer;
5376 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5378 catch (ArgumentException)
5380 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5384 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5385 if (foundIndices.Length == 0)
5387 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5391 var foundPosts = foundIndices.Select(x => targetTab[x]);
5392 foreach (var post in foundPosts)
5394 resultTab.AddPostQueue(post);
5397 this._statuses.DistributePosts();
5398 this.RefreshTimeline();
5400 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5401 this.ListTab.SelectedIndex = tabIndex;
5406 searchOptions.Query,
5407 searchOptions.CaseSensitive,
5408 searchOptions.UseRegex,
5409 SEARCHTYPE.DialogSearch);
5412 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5414 this.AddNewTabForSearch(searchOptions.Query);
5418 /// <summary>発言検索に使用するメソッドを生成します</summary>
5419 /// <exception cref="ArgumentException">
5420 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5422 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5426 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5427 var regex = new Regex(query, regexOption);
5429 return x => regex.IsMatch(x);
5433 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5435 return x => x.IndexOf(query, comparisonType) != -1;
5439 private void AboutMenuItem_Click(object sender, EventArgs e)
5441 using (var about = new TweenAboutBox())
5443 about.ShowDialog(this);
5445 this.TopMost = SettingManager.Common.AlwaysTop;
5448 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5450 var bgnIdx = this._statuses.SelectedTabIndex;
5452 if (ImageSelector.Enabled)
5455 TabModel? foundTab = null;
5459 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5461 var unreadIndex = tab.NextUnreadIndex;
5462 if (unreadIndex != -1)
5464 ListTab.SelectedIndex = index;
5466 foundIndex = unreadIndex;
5471 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5472 if (foundTab == null && bgnIdx > 0)
5474 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5476 var unreadIndex = tab.NextUnreadIndex;
5477 if (unreadIndex != -1)
5479 ListTab.SelectedIndex = index;
5481 foundIndex = unreadIndex;
5487 DetailsListView lst;
5489 if (foundTab == null)
5491 //全部調べたが未読見つからず→先頭タブの最新発言へ
5492 ListTab.SelectedIndex = 0;
5493 var tabPage = this.ListTab.TabPages[0];
5494 var tab = this._statuses.Tabs[0];
5496 if (tab.AllCount == 0)
5499 if (_statuses.SortOrder == SortOrder.Ascending)
5500 foundIndex = tab.AllCount - 1;
5504 lst = (DetailsListView)tabPage.Tag;
5508 var foundTabIndex = this._statuses.Tabs.IndexOf(foundTab);
5509 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
5512 SelectListItem(lst, foundIndex);
5514 if (_statuses.SortMode == ComparerMode.Id)
5516 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5517 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5523 lst.EnsureVisible(foundIndex);
5528 lst.EnsureVisible(foundIndex);
5534 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5536 var tab = this.CurrentTab;
5537 var post = this.CurrentPost;
5538 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5539 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5542 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5543 => await this.CheckNewVersion(false);
5545 private void RunTweenUp()
5547 var pinfo = new ProcessStartInfo
5549 UseShellExecute = true,
5550 WorkingDirectory = MyCommon.settingPath,
5551 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5552 Arguments = "\"" + Application.StartupPath + "\"",
5557 Process.Start(pinfo);
5561 MessageBox.Show("Failed to execute TweenUp3.exe.");
5565 public class VersionInfo
5567 public Version Version { get; }
5568 public Uri DownloadUri { get; }
5569 public string ReleaseNote { get; }
5571 public VersionInfo(Version version, Uri downloadUri, string releaseNote)
5572 => (this.Version, this.DownloadUri, this.ReleaseNote) = (version, downloadUri, releaseNote);
5576 /// OpenTween の最新バージョンの情報を取得します
5578 public async Task<VersionInfo> GetVersionInfoAsync()
5580 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5581 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5583 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5584 .ConfigureAwait(false);
5586 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5587 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5589 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5590 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5592 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5594 return new VersionInfo(
5595 version: Version.Parse(msgHeader[0]),
5596 downloadUri: new Uri(msgHeader[1]),
5597 releaseNote: msgBody
5601 private async Task CheckNewVersion(bool startup = false)
5603 if (ApplicationSettings.VersionInfoUrl == null)
5604 return; // 更新チェック無効化
5608 var versionInfo = await this.GetVersionInfoAsync();
5610 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5615 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5616 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5617 msgtext = MyCommon.ReplaceAppName(msgtext);
5619 MessageBox.Show(msgtext,
5620 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5621 MessageBoxButtons.OK, MessageBoxIcon.Information);
5626 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5629 using var dialog = new UpdateDialog();
5631 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5632 MyCommon.GetReadableVersion(versionInfo.Version));
5633 dialog.DetailsText = versionInfo.ReleaseNote;
5635 if (dialog.ShowDialog(this) == DialogResult.Yes)
5637 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5639 else if (dialog.SkipButtonPressed)
5641 SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5642 this.MarkSettingCommonModified();
5647 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5650 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5651 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5652 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5657 private void UpdateSelectedPost()
5659 //件数関連の場合、タイトル即時書き換え
5660 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5661 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5662 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5663 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5665 SetMainWindowTitle();
5667 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5668 SetStatusLabelUrl();
5670 if (SettingManager.Common.TabIconDisp)
5672 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5674 if (tab.UnreadCount == 0)
5676 var tabPage = this.ListTab.TabPages[index];
5677 if (tabPage.ImageIndex == 0)
5678 tabPage.ImageIndex = -1;
5684 this.ListTab.Refresh();
5687 this.DispSelectedPost();
5690 public string createDetailHtml(string orgdata)
5691 => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5693 private void DispSelectedPost()
5694 => this.DispSelectedPost(false);
5696 private PostClass displayPost = new PostClass();
5699 /// サムネイル表示に使用する CancellationToken の生成元
5701 private CancellationTokenSource? thumbnailTokenSource = null;
5703 private void DispSelectedPost(bool forceupdate)
5705 var currentPost = this.CurrentPost;
5706 if (currentPost == null)
5709 var oldDisplayPost = this.displayPost;
5710 this.displayPost = currentPost;
5712 if (!forceupdate && currentPost.Equals(oldDisplayPost))
5715 var loadTasks = new List<Task>
5717 this.tweetDetailsView.ShowPostDetails(currentPost),
5720 this.SplitContainer3.Panel2Collapsed = true;
5722 if (SettingManager.Common.PreviewEnable)
5724 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5725 oldTokenSource?.Cancel();
5727 var token = this.thumbnailTokenSource!.Token;
5728 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5731 async Task delayedTasks()
5735 await Task.WhenAll(loadTasks);
5737 catch (OperationCanceledException) { }
5740 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
5744 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5745 => await this.OpenApplicationWebsite();
5747 private async Task OpenApplicationWebsite()
5748 => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5750 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5751 => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5753 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5755 var tab = this.CurrentTab;
5756 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5758 var pnl = this.CurrentTabPage.Controls["panelSearch"];
5759 if (pnl.Controls["comboSearch"].Focused ||
5760 pnl.Controls["comboLang"].Focused ||
5761 pnl.Controls["buttonSearch"].Focused) return;
5764 if (e.Control || e.Shift || e.Alt)
5765 this._anchorFlag = false;
5767 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5770 e.SuppressKeyPress = true;
5773 if (asyncTask != null)
5777 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5779 private void InitializeShortcuts()
5781 this.shortcutCommands = new[]
5783 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5784 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5785 .FocusedOn(FocusedControl.ListTab)
5786 .Do(() => SendKeys.Send("{DOWN}")),
5788 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5789 .FocusedOn(FocusedControl.ListTab)
5790 .Do(() => SendKeys.Send("{UP}")),
5792 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5793 .FocusedOn(FocusedControl.ListTab)
5794 .Do(() => SendKeys.Send("{PGDN}")),
5796 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5797 .FocusedOn(FocusedControl.ListTab)
5798 .Do(() => SendKeys.Send("{PGUP}")),
5800 ShortcutCommand.Create(Keys.F1)
5801 .Do(() => this.OpenApplicationWebsite()),
5803 ShortcutCommand.Create(Keys.F3)
5804 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
5806 ShortcutCommand.Create(Keys.F5)
5807 .Do(() => this.DoRefresh()),
5809 ShortcutCommand.Create(Keys.F6)
5810 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5812 ShortcutCommand.Create(Keys.F7)
5813 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5815 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5816 .NotFocusedOn(FocusedControl.StatusText)
5817 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty); }),
5819 ShortcutCommand.Create(Keys.G)
5820 .NotFocusedOn(FocusedControl.StatusText)
5821 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty); }),
5823 ShortcutCommand.Create(Keys.Right, Keys.N)
5824 .FocusedOn(FocusedControl.ListTab)
5825 .Do(() => this.GoRelPost(forward: true)),
5827 ShortcutCommand.Create(Keys.Left, Keys.P)
5828 .FocusedOn(FocusedControl.ListTab)
5829 .Do(() => this.GoRelPost(forward: false)),
5831 ShortcutCommand.Create(Keys.OemPeriod)
5832 .FocusedOn(FocusedControl.ListTab)
5833 .Do(() => this.GoAnchor()),
5835 ShortcutCommand.Create(Keys.I)
5836 .FocusedOn(FocusedControl.ListTab)
5837 .OnlyWhen(() => this.StatusText.Enabled)
5838 .Do(() => this.StatusText.Focus()),
5840 ShortcutCommand.Create(Keys.Enter)
5841 .FocusedOn(FocusedControl.ListTab)
5842 .Do(() => this.MakeReplyOrDirectStatus()),
5844 ShortcutCommand.Create(Keys.R)
5845 .FocusedOn(FocusedControl.ListTab)
5846 .Do(() => this.DoRefresh()),
5848 ShortcutCommand.Create(Keys.L)
5849 .FocusedOn(FocusedControl.ListTab)
5850 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5852 ShortcutCommand.Create(Keys.H)
5853 .FocusedOn(FocusedControl.ListTab)
5854 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5856 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5857 .FocusedOn(FocusedControl.ListTab)
5858 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5860 ShortcutCommand.Create(Keys.S)
5861 .FocusedOn(FocusedControl.ListTab)
5862 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5864 ShortcutCommand.Create(Keys.A)
5865 .FocusedOn(FocusedControl.ListTab)
5866 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5868 // ] in_reply_to参照元へ戻る
5869 ShortcutCommand.Create(Keys.Oem4)
5870 .FocusedOn(FocusedControl.ListTab)
5871 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5873 // [ in_reply_toへジャンプ
5874 ShortcutCommand.Create(Keys.Oem6)
5875 .FocusedOn(FocusedControl.ListTab)
5876 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5878 ShortcutCommand.Create(Keys.Escape)
5879 .FocusedOn(FocusedControl.ListTab)
5881 this._anchorFlag = false;
5882 var tab = this.CurrentTab;
5883 var tabtype = tab.TabType;
5884 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5886 RemoveSpecifiedTab(tab.TabName, false);
5891 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5892 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5893 .FocusedOn(FocusedControl.ListTab)
5894 .Do(() => this._anchorFlag = false, preventDefault: false),
5896 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5897 ShortcutCommand.Create(Keys.Up, Keys.Down)
5898 .FocusedOn(FocusedControl.PostBrowser)
5901 ShortcutCommand.Create(Keys.Control | Keys.R)
5902 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5904 ShortcutCommand.Create(Keys.Control | Keys.D)
5905 .Do(() => this.doStatusDelete()),
5907 ShortcutCommand.Create(Keys.Control | Keys.M)
5908 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5910 ShortcutCommand.Create(Keys.Control | Keys.S)
5911 .Do(() => this.FavoriteChange(FavAdd: true)),
5913 ShortcutCommand.Create(Keys.Control | Keys.I)
5914 .Do(() => this.doRepliedStatusOpen()),
5916 ShortcutCommand.Create(Keys.Control | Keys.Q)
5917 .Do(() => this.doQuoteOfficial()),
5919 ShortcutCommand.Create(Keys.Control | Keys.B)
5920 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
5922 ShortcutCommand.Create(Keys.Control | Keys.T)
5923 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
5925 ShortcutCommand.Create(Keys.Control | Keys.L)
5926 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
5928 ShortcutCommand.Create(Keys.Control | Keys.Y)
5929 .NotFocusedOn(FocusedControl.PostBrowser)
5930 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
5932 ShortcutCommand.Create(Keys.Control | Keys.F)
5933 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
5935 ShortcutCommand.Create(Keys.Control | Keys.U)
5936 .Do(() => this.ShowUserTimeline()),
5938 ShortcutCommand.Create(Keys.Control | Keys.H)
5939 .Do(() => this.MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty)),
5941 ShortcutCommand.Create(Keys.Control | Keys.G)
5942 .Do(() => this.MoveToFavToolStripMenuItem_Click(this.MoveToFavToolStripMenuItem, EventArgs.Empty)),
5944 ShortcutCommand.Create(Keys.Control | Keys.O)
5945 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
5947 ShortcutCommand.Create(Keys.Control | Keys.E)
5948 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
5950 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5951 .FocusedOn(FocusedControl.ListTab)
5952 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
5954 ShortcutCommand.Create(Keys.Control | Keys.N)
5955 .FocusedOn(FocusedControl.ListTab)
5956 .Do(() => this.GoNextTab(forward: true)),
5958 ShortcutCommand.Create(Keys.Control | Keys.P)
5959 .FocusedOn(FocusedControl.ListTab)
5960 .Do(() => this.GoNextTab(forward: false)),
5962 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5963 .FocusedOn(FocusedControl.ListTab)
5964 .Do(() => this.CopyStot()),
5966 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5967 ShortcutCommand.Create(Keys.Control | Keys.D1)
5968 .FocusedOn(FocusedControl.ListTab)
5969 .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5970 .Do(() => this.ListTab.SelectedIndex = 0),
5972 ShortcutCommand.Create(Keys.Control | Keys.D2)
5973 .FocusedOn(FocusedControl.ListTab)
5974 .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5975 .Do(() => this.ListTab.SelectedIndex = 1),
5977 ShortcutCommand.Create(Keys.Control | Keys.D3)
5978 .FocusedOn(FocusedControl.ListTab)
5979 .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5980 .Do(() => this.ListTab.SelectedIndex = 2),
5982 ShortcutCommand.Create(Keys.Control | Keys.D4)
5983 .FocusedOn(FocusedControl.ListTab)
5984 .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5985 .Do(() => this.ListTab.SelectedIndex = 3),
5987 ShortcutCommand.Create(Keys.Control | Keys.D5)
5988 .FocusedOn(FocusedControl.ListTab)
5989 .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5990 .Do(() => this.ListTab.SelectedIndex = 4),
5992 ShortcutCommand.Create(Keys.Control | Keys.D6)
5993 .FocusedOn(FocusedControl.ListTab)
5994 .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5995 .Do(() => this.ListTab.SelectedIndex = 5),
5997 ShortcutCommand.Create(Keys.Control | Keys.D7)
5998 .FocusedOn(FocusedControl.ListTab)
5999 .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
6000 .Do(() => this.ListTab.SelectedIndex = 6),
6002 ShortcutCommand.Create(Keys.Control | Keys.D8)
6003 .FocusedOn(FocusedControl.ListTab)
6004 .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
6005 .Do(() => this.ListTab.SelectedIndex = 7),
6007 ShortcutCommand.Create(Keys.Control | Keys.D9)
6008 .FocusedOn(FocusedControl.ListTab)
6009 .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
6011 ShortcutCommand.Create(Keys.Control | Keys.A)
6012 .FocusedOn(FocusedControl.StatusText)
6013 .Do(() => this.StatusText.SelectAll()),
6015 ShortcutCommand.Create(Keys.Control | Keys.V)
6016 .FocusedOn(FocusedControl.StatusText)
6017 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6019 ShortcutCommand.Create(Keys.Control | Keys.Up)
6020 .FocusedOn(FocusedControl.StatusText)
6021 .Do(() => this.StatusTextHistoryBack()),
6023 ShortcutCommand.Create(Keys.Control | Keys.Down)
6024 .FocusedOn(FocusedControl.StatusText)
6025 .Do(() => this.StatusTextHistoryForward()),
6027 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6028 .FocusedOn(FocusedControl.StatusText)
6030 if (ListTab.SelectedIndex == 0)
6032 ListTab.SelectedIndex = ListTab.TabCount - 1;
6036 ListTab.SelectedIndex -= 1;
6041 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6042 .FocusedOn(FocusedControl.StatusText)
6044 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6046 ListTab.SelectedIndex = 0;
6050 ListTab.SelectedIndex += 1;
6055 ShortcutCommand.Create(Keys.Control | Keys.Y)
6056 .FocusedOn(FocusedControl.PostBrowser)
6058 var multiline = !SettingManager.Local.StatusMultiline;
6059 SettingManager.Local.StatusMultiline = multiline;
6060 MultiLineMenuItem.Checked = multiline;
6061 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6064 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6065 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
6067 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6068 .Do(() => this.DoRefreshMore()),
6070 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6071 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
6073 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6074 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
6076 ShortcutCommand.Create(Keys.Shift | Keys.R)
6077 .NotFocusedOn(FocusedControl.StatusText)
6078 .Do(() => this.DoRefreshMore()),
6080 ShortcutCommand.Create(Keys.Shift | Keys.H)
6081 .FocusedOn(FocusedControl.ListTab)
6082 .Do(() => this.GoTopEnd(GoTop: true)),
6084 ShortcutCommand.Create(Keys.Shift | Keys.L)
6085 .FocusedOn(FocusedControl.ListTab)
6086 .Do(() => this.GoTopEnd(GoTop: false)),
6088 ShortcutCommand.Create(Keys.Shift | Keys.M)
6089 .FocusedOn(FocusedControl.ListTab)
6090 .Do(() => this.GoMiddle()),
6092 ShortcutCommand.Create(Keys.Shift | Keys.G)
6093 .FocusedOn(FocusedControl.ListTab)
6094 .Do(() => this.GoLast()),
6096 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6097 .FocusedOn(FocusedControl.ListTab)
6098 .Do(() => this.MoveMiddle()),
6100 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6101 .FocusedOn(FocusedControl.ListTab)
6102 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6104 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6105 .FocusedOn(FocusedControl.ListTab)
6106 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6108 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6109 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6110 .FocusedOn(FocusedControl.ListTab)
6111 .Do(() => this.GoFav(forward: true)),
6113 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6114 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6115 .FocusedOn(FocusedControl.ListTab)
6116 .Do(() => this.GoFav(forward: false)),
6118 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6119 .FocusedOn(FocusedControl.ListTab)
6120 .Do(() => this.GoBackSelectPostChain()),
6122 ShortcutCommand.Create(Keys.Alt | Keys.R)
6123 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6125 ShortcutCommand.Create(Keys.Alt | Keys.P)
6126 .OnlyWhen(() => this.CurrentPost != null)
6127 .Do(() => this.doShowUserStatus(this.CurrentPost!.ScreenName, ShowInputDialog: false)),
6129 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6130 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6132 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6133 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6135 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6136 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6138 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6139 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6141 // 別タブの同じ書き込みへ(ALT+←/→)
6142 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6143 .FocusedOn(FocusedControl.ListTab)
6144 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6146 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6147 .FocusedOn(FocusedControl.ListTab)
6148 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6150 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6151 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6153 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6154 .Do(() => this.CopyIdUri()),
6156 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6157 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6158 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6160 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6161 .Do(() => this.FavoriteChange(FavAdd: false)),
6163 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6164 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
6166 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6167 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
6169 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6170 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
6172 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6173 .Do(() => this.doMoveToRTHome()),
6175 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6176 .FocusedOn(FocusedControl.StatusText)
6178 var tab = this.CurrentTab;
6179 var selectedIndex = tab.SelectedIndex;
6180 if (selectedIndex != -1 && selectedIndex > 0)
6182 var listView = this.CurrentListView;
6183 var idx = selectedIndex - 1;
6184 SelectListItem(listView, idx);
6185 listView.EnsureVisible(idx);
6189 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6190 .FocusedOn(FocusedControl.StatusText)
6192 var tab = this.CurrentTab;
6193 var selectedIndex = tab.SelectedIndex;
6194 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6196 var listView = this.CurrentListView;
6197 var idx = selectedIndex + 1;
6198 SelectListItem(listView, idx);
6199 listView.EnsureVisible(idx);
6203 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6204 .FocusedOn(FocusedControl.StatusText)
6206 if (StatusText.SelectionStart > 0)
6208 var endidx = StatusText.SelectionStart - 1;
6210 for (var i = StatusText.SelectionStart - 1; i >= 0; i--)
6212 var c = StatusText.Text[i];
6213 if (char.IsLetterOrDigit(c) || c == '_')
6219 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6220 var cnt = AtIdSupl.ItemCount;
6221 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6222 if (AtIdSupl.ItemCount != cnt)
6223 this.MarkSettingAtIdModified();
6227 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6228 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6238 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6239 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6240 .FocusedOn(FocusedControl.ListTab)
6241 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6243 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6244 .FocusedOn(FocusedControl.ListTab)
6245 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6247 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6248 .FocusedOn(FocusedControl.ListTab)
6249 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6251 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6252 .FocusedOn(FocusedControl.ListTab)
6253 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6255 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6256 .FocusedOn(FocusedControl.ListTab)
6257 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6259 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6260 .FocusedOn(FocusedControl.ListTab)
6261 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6263 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6264 .FocusedOn(FocusedControl.ListTab)
6265 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6267 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6268 .FocusedOn(FocusedControl.ListTab)
6269 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6271 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6272 .FocusedOn(FocusedControl.ListTab)
6273 .Do(() => this.SetSortLastColumn()),
6275 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6276 .FocusedOn(FocusedControl.ListTab)
6277 .Do(() => this.FavoritesRetweetOfficial()),
6279 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6280 .FocusedOn(FocusedControl.ListTab)
6281 .Do(() => this.FavoritesRetweetUnofficial()),
6283 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6284 .FocusedOn(FocusedControl.ListTab)
6285 .Do(() => this.OpenUserAppointUrl()),
6287 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6288 .FocusedOn(FocusedControl.PostBrowser)
6289 .Do(() => this.doReTweetUnofficial()),
6291 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6292 .OnlyWhen(() => this.ExistCurrentPost)
6293 .Do(() => this.tweetDetailsView.DoTranslation()),
6295 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6296 .Do(() => this.doReTweetUnofficial()),
6298 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6299 .Do(() => this.CopyUserId()),
6301 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6302 .Do(() => this.tweetThumbnail1.ScrollUp()),
6304 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6305 .Do(() => this.tweetThumbnail1.ScrollDown()),
6307 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6308 .FocusedOn(FocusedControl.ListTab)
6309 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6310 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6314 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
6316 // Task を返す非同期処理があれば asyncTask に代入する
6319 // ShortcutCommand に対応しているコマンドはここで処理される
6320 foreach (var command in this.shortcutCommands)
6322 if (command.IsMatch(keyData, focusedOn))
6324 asyncTask = command.RunCommand();
6325 return command.PreventDefault;
6332 private void GoNextTab(bool forward)
6334 var idx = this._statuses.SelectedTabIndex;
6335 var tabCount = this._statuses.Tabs.Count;
6339 if (idx > tabCount - 1) idx = 0;
6344 if (idx < 0) idx = tabCount - 1;
6346 ListTab.SelectedIndex = idx;
6349 private void CopyStot()
6351 var sb = new StringBuilder();
6352 var tab = this.CurrentTab;
6353 var IsProtected = false;
6354 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6355 foreach (var post in tab.SelectedPosts)
6357 if (post.IsDeleted) continue;
6360 if (post.RetweetedId != null)
6361 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6363 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6367 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6372 MessageBox.Show(Properties.Resources.CopyStotText1);
6376 var clstr = sb.ToString();
6379 Clipboard.SetDataObject(clstr, false, 5, 100);
6381 catch (Exception ex)
6383 MessageBox.Show(ex.Message);
6388 private void CopyIdUri()
6390 var tab = this.CurrentTab;
6391 if (tab == null || tab is DirectMessagesTabModel)
6394 var copyUrls = new List<string>();
6395 foreach (var post in tab.SelectedPosts)
6396 copyUrls.Add(MyCommon.GetStatusUrl(post));
6398 if (copyUrls.Count == 0)
6403 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6405 catch (ExternalException ex)
6407 MessageBox.Show(ex.Message);
6411 private void GoFav(bool forward)
6413 var tab = this.CurrentTab;
6414 if (tab.AllCount == 0)
6417 var selectedIndex = tab.SelectedIndex;
6425 if (selectedIndex == -1)
6431 fIdx = selectedIndex + 1;
6432 if (fIdx > tab.AllCount - 1)
6435 toIdx = tab.AllCount;
6440 if (selectedIndex == -1)
6442 fIdx = tab.AllCount - 1;
6446 fIdx = selectedIndex - 1;
6454 for (var idx = fIdx; idx != toIdx; idx += stp)
6458 var listView = this.CurrentListView;
6459 SelectListItem(listView, idx);
6460 listView.EnsureVisible(idx);
6466 private void GoSamePostToAnotherTab(bool left)
6468 var tab = this.CurrentTab;
6470 // Directタブは対象外(見つかるはずがない)
6471 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6474 var selectedStatusId = tab.SelectedStatusId;
6475 if (selectedStatusId == -1)
6478 int fIdx, toIdx, stp;
6483 if (ListTab.SelectedIndex == 0)
6489 fIdx = ListTab.SelectedIndex - 1;
6497 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6503 fIdx = ListTab.SelectedIndex + 1;
6505 toIdx = ListTab.TabCount;
6509 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6511 var targetTab = this._statuses.Tabs[tabidx];
6514 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6517 var foundIndex = targetTab.IndexOf(selectedStatusId);
6518 if (foundIndex != -1)
6520 ListTab.SelectedIndex = tabidx;
6521 var listView = this.CurrentListView;
6522 SelectListItem(listView, foundIndex);
6523 listView.EnsureVisible(foundIndex);
6529 private void GoPost(bool forward)
6531 var tab = this.CurrentTab;
6532 var currentPost = this.CurrentPost;
6534 if (currentPost == null)
6537 var selectedIndex = tab.SelectedIndex;
6539 int fIdx, toIdx, stp;
6543 fIdx = selectedIndex + 1;
6544 if (fIdx > tab.AllCount - 1) return;
6545 toIdx = tab.AllCount;
6550 fIdx = selectedIndex - 1;
6551 if (fIdx < 0) return;
6557 if (currentPost.RetweetedBy == null)
6559 name = currentPost.ScreenName;
6563 name = currentPost.RetweetedBy;
6565 for (var idx = fIdx; idx != toIdx; idx += stp)
6567 var post = tab[idx];
6568 if (post.RetweetedId == null)
6570 if (post.ScreenName == name)
6572 var listView = this.CurrentListView;
6573 SelectListItem(listView, idx);
6574 listView.EnsureVisible(idx);
6580 if (post.RetweetedBy == name)
6582 var listView = this.CurrentListView;
6583 SelectListItem(listView, idx);
6584 listView.EnsureVisible(idx);
6591 private void GoRelPost(bool forward)
6593 var tab = this.CurrentTab;
6594 var selectedIndex = tab.SelectedIndex;
6596 if (selectedIndex == -1)
6599 int fIdx, toIdx, stp;
6603 fIdx = selectedIndex + 1;
6604 if (fIdx > tab.AllCount - 1) return;
6605 toIdx = tab.AllCount;
6610 fIdx = selectedIndex - 1;
6611 if (fIdx < 0) return;
6618 var currentPost = this.CurrentPost;
6619 if (currentPost == null) return;
6620 _anchorPost = currentPost;
6625 if (_anchorPost == null) return;
6628 for (var idx = fIdx; idx != toIdx; idx += stp)
6630 var post = tab[idx];
6631 if (post.ScreenName == _anchorPost.ScreenName ||
6632 post.RetweetedBy == _anchorPost.ScreenName ||
6633 post.ScreenName == _anchorPost.RetweetedBy ||
6634 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6635 _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6636 _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6637 post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6638 post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6640 var listView = this.CurrentListView;
6641 SelectListItem(listView, idx);
6642 listView.EnsureVisible(idx);
6648 private void GoAnchor()
6650 if (_anchorPost == null) return;
6651 var idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6652 if (idx == -1) return;
6654 var listView = this.CurrentListView;
6655 SelectListItem(listView, idx);
6656 listView.EnsureVisible(idx);
6659 private void GoTopEnd(bool GoTop)
6661 var listView = this.CurrentListView;
6662 if (listView.VirtualListSize == 0)
6670 _item = listView.GetItemAt(0, 25);
6678 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6680 idx = listView.VirtualListSize - 1;
6684 SelectListItem(listView, idx);
6687 private void GoMiddle()
6689 var listView = this.CurrentListView;
6690 if (listView.VirtualListSize == 0)
6698 _item = listView.GetItemAt(0, 0);
6708 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6711 idx2 = listView.VirtualListSize - 1;
6717 idx3 = (idx1 + idx2) / 2;
6719 SelectListItem(listView, idx3);
6722 private void GoLast()
6724 var listView = this.CurrentListView;
6725 if (listView.VirtualListSize == 0) return;
6727 if (_statuses.SortOrder == SortOrder.Ascending)
6729 SelectListItem(listView, listView.VirtualListSize - 1);
6730 listView.EnsureVisible(listView.VirtualListSize - 1);
6734 SelectListItem(listView, 0);
6735 listView.EnsureVisible(0);
6739 private void MoveTop()
6741 var listView = this.CurrentListView;
6742 if (listView.SelectedIndices.Count == 0) return;
6743 var idx = listView.SelectedIndices[0];
6744 if (_statuses.SortOrder == SortOrder.Ascending)
6746 listView.EnsureVisible(listView.VirtualListSize - 1);
6750 listView.EnsureVisible(0);
6752 listView.EnsureVisible(idx);
6755 private async Task GoInReplyToPostTree()
6757 var curTabClass = this.CurrentTab;
6758 var currentPost = this.CurrentPost;
6760 if (currentPost == null)
6763 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6767 var post = await tw.GetStatusApi(false, currentPost.StatusId);
6769 currentPost.InReplyToStatusId = post.InReplyToStatusId;
6770 currentPost.InReplyToUser = post.InReplyToUser;
6771 currentPost.IsReply = post.IsReply;
6772 this.PurgeListViewItemCache();
6774 var index = curTabClass.SelectedIndex;
6775 this.CurrentListView.RedrawItems(index, index, false);
6777 catch (WebApiException ex)
6779 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6783 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6785 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6787 replyChains = new Stack<ReplyChain>();
6789 replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6792 string inReplyToTabName;
6793 var inReplyToId = currentPost.InReplyToStatusId.Value;
6794 var inReplyToUser = currentPost.InReplyToUser;
6796 var inReplyToPosts = from tab in _statuses.Tabs
6797 orderby tab != curTabClass
6798 from post in tab.Posts.Values
6799 where post.StatusId == inReplyToId
6800 let index = tab.IndexOf(post.StatusId)
6802 select new {Tab = tab, Index = index};
6804 var inReplyPost = inReplyToPosts.FirstOrDefault();
6805 if (inReplyPost == null)
6809 await Task.Run(async () =>
6811 var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6812 .ConfigureAwait(false);
6815 _statuses.AddPost(post);
6816 _statuses.DistributePosts();
6819 catch (WebApiException ex)
6821 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6822 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6826 this.RefreshTimeline();
6828 inReplyPost = inReplyToPosts.FirstOrDefault();
6829 if (inReplyPost == null)
6831 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6835 inReplyToTabName = inReplyPost.Tab.TabName;
6836 inReplyToIndex = inReplyPost.Index;
6838 var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6839 var tabPage = this.ListTab.TabPages[tabIndex];
6840 var listView = (DetailsListView)tabPage.Tag;
6842 if (this.CurrentTabName != inReplyToTabName)
6844 this.ListTab.SelectedIndex = tabIndex;
6847 this.SelectListItem(listView, inReplyToIndex);
6848 listView.EnsureVisible(inReplyToIndex);
6851 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6853 var curTabClass = this.CurrentTab;
6854 var currentPost = this.CurrentPost;
6856 if (currentPost == null)
6861 if (currentPost.InReplyToStatusId != null)
6863 var posts = from t in _statuses.Tabs
6865 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6866 let indexOf = t.IndexOf(p.Value.StatusId)
6868 orderby isForward ? indexOf : indexOf * -1
6869 orderby t != curTabClass
6870 select new {Tab = t, Post = p.Value, Index = indexOf};
6873 var postList = posts.ToList();
6874 for (var i = postList.Count - 1; i >= 0; i--)
6877 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
6879 postList.RemoveAt(index);
6882 var currentIndex = this.CurrentTab.SelectedIndex;
6883 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
6884 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
6885 if (post == null) post = postList.First();
6886 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6887 this.ListTab.SelectedIndex = tabIndex;
6888 var listView = this.CurrentListView;
6889 SelectListItem(listView, post.Index);
6890 listView.EnsureVisible(post.Index);
6892 catch (InvalidOperationException)
6900 if (replyChains == null || replyChains.Count < 1)
6902 var posts = from t in _statuses.Tabs
6904 where p.Value.InReplyToStatusId == currentPost.StatusId
6905 let indexOf = t.IndexOf(p.Value.StatusId)
6908 orderby t != curTabClass
6909 select new {Tab = t, Index = indexOf};
6912 var post = posts.First();
6913 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6914 this.ListTab.SelectedIndex = tabIndex;
6915 var listView = this.CurrentListView;
6916 SelectListItem(listView, post.Index);
6917 listView.EnsureVisible(post.Index);
6919 catch (InvalidOperationException)
6926 var chainHead = replyChains.Pop();
6927 if (chainHead.InReplyToId == currentPost.StatusId)
6929 var tab = chainHead.OriginalTab;
6930 if (!this._statuses.Tabs.Contains(tab))
6936 var idx = tab.IndexOf(chainHead.OriginalId);
6943 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6946 this.ListTab.SelectedIndex = tabIndex;
6952 var listView = this.CurrentListView;
6953 SelectListItem(listView, idx);
6954 listView.EnsureVisible(idx);
6961 this.GoBackInReplyToPostTree(parallel);
6967 private void GoBackSelectPostChain()
6969 if (this.selectPostChains.Count > 1)
6972 TabModel? foundTab = null;
6978 this.selectPostChains.Pop();
6979 var (tab, post) = this.selectPostChains.Peek();
6981 if (!this._statuses.Tabs.Contains(tab))
6982 continue; // 該当タブが存在しないので無視
6986 idx = tab.IndexOf(post.StatusId);
6987 if (idx == -1) continue; //該当ポストが存在しないので無視
6992 this.selectPostChains.Pop();
6994 catch (InvalidOperationException)
7000 while (this.selectPostChains.Count > 1);
7002 if (foundTab == null)
7005 //履歴が残り1つであればクリアしておく
7006 if (this.selectPostChains.Count == 1)
7007 this.selectPostChains.Clear();
7011 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
7012 var tabPage = this.ListTab.TabPages[tabIndex];
7013 var lst = (DetailsListView)tabPage.Tag;
7014 this.ListTab.SelectedIndex = tabIndex;
7018 SelectListItem(lst, idx);
7019 lst.EnsureVisible(idx);
7025 private void PushSelectPostChain()
7027 var currentTab = this.CurrentTab;
7028 var currentPost = this.CurrentPost;
7030 var count = this.selectPostChains.Count;
7033 var (tab, post) = this.selectPostChains.Peek();
7034 if (tab == currentTab)
7036 if (post == currentPost) return; //最新の履歴と同一
7037 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7040 if (count >= 2500) TrimPostChain();
7041 this.selectPostChains.Push((currentTab, currentPost));
7044 private void TrimPostChain()
7046 if (this.selectPostChains.Count <= 2000) return;
7047 var p = new Stack<(TabModel, PostClass?)>(2000);
7048 for (var i = 0; i < 2000; i++)
7050 p.Push(this.selectPostChains.Pop());
7052 this.selectPostChains.Clear();
7053 for (var i = 0; i < 2000; i++)
7055 this.selectPostChains.Push(p.Pop());
7059 private bool GoStatus(long statusId)
7061 if (statusId == 0) return false;
7063 var tab = this._statuses.Tabs
7064 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
7065 .Where(x => x.Contains(statusId))
7071 var index = tab.IndexOf(statusId);
7073 var tabIndex = this._statuses.Tabs.IndexOf(tab);
7074 this.ListTab.SelectedIndex = tabIndex;
7076 var listView = this.CurrentListView;
7077 this.SelectListItem(listView, index);
7078 listView.EnsureVisible(index);
7083 private bool GoDirectMessage(long statusId)
7085 if (statusId == 0) return false;
7087 var tab = this._statuses.DirectMessageTab;
7088 var index = tab.IndexOf(statusId);
7093 var tabIndex = this._statuses.Tabs.IndexOf(tab);
7094 this.ListTab.SelectedIndex = tabIndex;
7096 var listView = this.CurrentListView;
7097 this.SelectListItem(listView, index);
7098 listView.EnsureVisible(index);
7103 private void MyList_MouseClick(object sender, MouseEventArgs e)
7104 => this._anchorFlag = false;
7106 private void StatusText_Enter(object sender, EventArgs e)
7108 // フォーカスの戻り先を StatusText に設定
7109 this.Tag = StatusText;
7110 StatusText.BackColor = _clInputBackcolor;
7113 public Color InputBackColor
7115 get => _clInputBackcolor;
7116 set => _clInputBackcolor = value;
7119 private void StatusText_Leave(object sender, EventArgs e)
7121 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7122 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7123 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7126 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7128 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7131 e.SuppressKeyPress = true;
7134 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
7136 if (asyncTask != null)
7140 private void SaveConfigsAll(bool ifModified)
7144 SaveConfigsCommon();
7151 if (ModifySettingCommon) SaveConfigsCommon();
7152 if (ModifySettingLocal) SaveConfigsLocal();
7153 if (ModifySettingAtId) SaveConfigsAtId();
7157 private void SaveConfigsAtId()
7159 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7161 ModifySettingAtId = false;
7162 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7163 SettingManager.SaveAtIdList();
7166 private void SaveConfigsCommon()
7168 if (_ignoreConfigSave) return;
7170 ModifySettingCommon = false;
7173 SettingManager.Common.UserName = tw.Username;
7174 SettingManager.Common.UserId = tw.UserId;
7175 SettingManager.Common.Token = tw.AccessToken;
7176 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7177 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7178 switch (_statuses.SortMode)
7180 case ComparerMode.Nickname: //ニックネーム
7181 SettingManager.Common.SortColumn = 1;
7183 case ComparerMode.Data: //本文
7184 SettingManager.Common.SortColumn = 2;
7186 case ComparerMode.Id: //時刻=発言Id
7187 SettingManager.Common.SortColumn = 3;
7189 case ComparerMode.Name: //名前
7190 SettingManager.Common.SortColumn = 4;
7192 case ComparerMode.Source: //Source
7193 SettingManager.Common.SortColumn = 7;
7197 SettingManager.Common.HashTags = HashMgr.HashHistories;
7198 if (HashMgr.IsPermanent)
7200 SettingManager.Common.HashSelected = HashMgr.UseHash;
7204 SettingManager.Common.HashSelected = "";
7206 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7207 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7208 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7209 SettingManager.Common.TrackWord = tw.TrackWord;
7210 SettingManager.Common.AllAtReply = tw.AllAtReply;
7211 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7212 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7214 SettingManager.SaveCommon();
7218 private void SaveConfigsLocal()
7220 if (_ignoreConfigSave) return;
7223 ModifySettingLocal = false;
7224 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7225 SettingManager.Local.FormSize = _mySize;
7226 SettingManager.Local.FormLocation = _myLoc;
7227 SettingManager.Local.SplitterDistance = _mySpDis;
7228 SettingManager.Local.PreviewDistance = _mySpDis3;
7229 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7230 SettingManager.Local.StatusTextHeight = _mySpDis2;
7232 SettingManager.Local.FontUnread = _fntUnread;
7233 SettingManager.Local.ColorUnread = _clUnread;
7234 SettingManager.Local.FontRead = _fntReaded;
7235 SettingManager.Local.ColorRead = _clReaded;
7236 SettingManager.Local.FontDetail = _fntDetail;
7237 SettingManager.Local.ColorDetail = _clDetail;
7238 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7239 SettingManager.Local.ColorDetailLink = _clDetailLink;
7240 SettingManager.Local.ColorFav = _clFav;
7241 SettingManager.Local.ColorOWL = _clOWL;
7242 SettingManager.Local.ColorRetweet = _clRetweet;
7243 SettingManager.Local.ColorSelf = _clSelf;
7244 SettingManager.Local.ColorAtSelf = _clAtSelf;
7245 SettingManager.Local.ColorTarget = _clTarget;
7246 SettingManager.Local.ColorAtTarget = _clAtTarget;
7247 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7248 SettingManager.Local.ColorAtTo = _clAtTo;
7249 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7250 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7251 SettingManager.Local.ColorInputFont = _clInputFont;
7252 SettingManager.Local.FontInputFont = _fntInputFont;
7254 if (_ignoreConfigSave) return;
7255 SettingManager.SaveLocal();
7259 private void SaveConfigsTabs()
7261 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7263 var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7265 foreach (var tab in tabs)
7267 if (!tab.IsPermanentTabType)
7270 var tabSetting = new SettingTabs.SettingTabItem
7272 TabName = tab.TabName,
7273 TabType = tab.TabType,
7274 UnreadManage = tab.UnreadManage,
7275 Protected = tab.Protected,
7276 Notify = tab.Notify,
7277 SoundFile = tab.SoundFile,
7282 case FilterTabModel filterTab:
7283 tabSetting.FilterArray = filterTab.FilterArray;
7285 case UserTimelineTabModel userTab:
7286 tabSetting.User = userTab.ScreenName;
7288 case PublicSearchTabModel searchTab:
7289 tabSetting.SearchWords = searchTab.SearchWords;
7290 tabSetting.SearchLang = searchTab.SearchLang;
7292 case ListTimelineTabModel listTab:
7293 tabSetting.ListInfo = listTab.ListInfo;
7297 tabSettingList.Add(tabSetting);
7300 SettingManager.Tabs.Tabs = tabSettingList;
7301 SettingManager.SaveTabs();
7304 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7306 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7307 if (ret != DialogResult.OK)
7310 var match = Twitter.StatusUrlRegex.Match(inputText);
7313 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7314 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7320 var statusId = long.Parse(match.Groups["StatusId"].Value);
7321 await this.OpenRelatedTab(statusId);
7323 catch (TabException ex)
7325 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7329 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7331 var tab = this.CurrentTab;
7333 var rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7334 Properties.Resources.SaveLogMenuItem_ClickText2,
7335 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7336 if (rslt == DialogResult.Cancel) return;
7338 SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7339 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7340 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7341 SaveFileDialog1.FilterIndex = 0;
7342 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7343 SaveFileDialog1.RestoreDirectory = true;
7345 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7347 if (!SaveFileDialog1.ValidateNames) return;
7348 using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
7349 if (rslt == DialogResult.Yes)
7352 for (var idx = 0; idx < tab.AllCount; idx++)
7354 var post = tab[idx];
7357 protect = "Protect";
7358 sw.WriteLine(post.Nickname + "\t" +
7359 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7360 post.CreatedAt.ToLocalTimeString() + "\t" +
7361 post.ScreenName + "\t" +
7362 post.StatusId + "\t" +
7363 post.ImageUrl + "\t" +
7364 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7370 foreach (var post in this.CurrentTab.SelectedPosts)
7374 protect = "Protect";
7375 sw.WriteLine(post.Nickname + "\t" +
7376 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7377 post.CreatedAt.ToLocalTimeString() + "\t" +
7378 post.ScreenName + "\t" +
7379 post.StatusId + "\t" +
7380 post.ImageUrl + "\t" +
7381 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7386 this.TopMost = SettingManager.Common.AlwaysTop;
7389 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
7393 using (var inputName = new InputTabName())
7395 inputName.TabName = origTabName;
7396 inputName.ShowDialog();
7397 if (inputName.DialogResult == DialogResult.Cancel) return false;
7398 newTabName = inputName.TabName;
7400 this.TopMost = SettingManager.Common.AlwaysTop;
7401 if (!string.IsNullOrEmpty(newTabName))
7404 if (this._statuses.ContainsTab(newTabName))
7406 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7407 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7411 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7412 var tabPage = this.ListTab.TabPages[tabIndex];
7415 if (tabPage != null)
7416 tabPage.Text = newTabName;
7418 _statuses.RenameTab(origTabName, newTabName);
7420 SaveConfigsCommon();
7422 _rclickTabName = newTabName;
7431 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7433 if (e.Button == MouseButtons.Middle)
7435 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7437 if (this.ListTab.GetTabRect(index).Contains(e.Location))
7439 this.RemoveSpecifiedTab(tab.TabName, true);
7440 this.SaveConfigsTabs();
7447 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7448 => this.TabRename(this.CurrentTabName, out _);
7450 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7452 if (SettingManager.Common.TabMouseLock) return;
7453 if (e.Button == MouseButtons.Left)
7455 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7457 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7460 _tabMouseDownPoint = e.Location;
7471 private void ListTab_DragEnter(object sender, DragEventArgs e)
7473 if (e.Data.GetDataPresent(typeof(TabPage)))
7474 e.Effect = DragDropEffects.Move;
7476 e.Effect = DragDropEffects.None;
7479 private void ListTab_DragDrop(object sender, DragEventArgs e)
7481 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7486 var cpos = new Point(e.X, e.Y);
7487 var spos = ListTab.PointToClient(cpos);
7488 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7490 var rect = ListTab.GetTabRect(index);
7491 if (rect.Contains(spos))
7494 if (spos.X <= (rect.Left + rect.Right) / 2)
7503 //タブのないところにドロップ->最後尾へ移動
7504 if (string.IsNullOrEmpty(tn))
7506 var lastTab = this._statuses.Tabs.Last();
7507 tn = lastTab.TabName;
7511 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
7512 if (tp.Text == tn) return;
7514 ReOrderTab(tp.Text, tn, bef);
7517 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7519 var baseIndex = this.GetTabPageIndex(baseTabText);
7520 if (baseIndex == -1)
7523 var targetIndex = this.GetTabPageIndex(targetTabText);
7524 if (targetIndex == -1)
7527 using (ControlTransaction.Layout(this.ListTab))
7529 var tab = this._statuses.Tabs[targetIndex];
7530 var tabPage = this.ListTab.TabPages[targetIndex];
7532 this.ListTab.TabPages.Remove(tabPage);
7534 if (targetIndex < baseIndex)
7537 if (!isBeforeBaseTab)
7540 this._statuses.MoveTab(baseIndex, tab);
7542 ListTab.TabPages.Insert(baseIndex, tabPage);
7548 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7550 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7551 //isReply:true=@,false=DM
7552 if (!StatusText.Enabled) return;
7553 if (!this.ExistCurrentPost) return;
7555 var tab = this.CurrentTab;
7556 var selectedPosts = tab.SelectedPosts;
7558 // 複数あてリプライはReplyではなく通常ポスト
7559 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7560 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7561 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7563 if (selectedPosts.Length > 0)
7566 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7568 var post = selectedPosts.Single();
7571 if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7574 this.inReplyTo = null;
7575 StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7576 StatusText.SelectionStart = StatusText.Text.Length;
7580 if (string.IsNullOrEmpty(StatusText.Text))
7583 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7584 var inReplyToScreenName = post.ScreenName;
7585 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7587 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7588 StatusText.Text = "@" + post.ScreenName + " ";
7596 //1件選んでEnter or DoubleClick
7597 if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7599 if (this.inReplyTo?.ScreenName == post.ScreenName)
7602 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7603 var inReplyToScreenName = post.ScreenName;
7604 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7608 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7611 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7614 this.inReplyTo = null;
7615 StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7620 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7621 var inReplyToScreenName = post.ScreenName;
7622 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7623 StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7630 this.inReplyTo = null;
7631 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7636 //1件選んでCtrl-Rの場合(返信先操作せず)
7637 var sidx = StatusText.SelectionStart;
7638 var id = "@" + post.ScreenName + " ";
7641 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7646 StatusText.Text = StatusText.Text.Insert(sidx, id);
7648 //if (StatusText.Text.StartsWith("@"))
7651 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7652 // sidx += 5 + _curPost.ScreenName.Length;
7657 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7658 // sidx += 3 + _curPost.ScreenName.Length;
7660 StatusText.SelectionStart = sidx;
7663 //_reply_to_name = null;
7671 if (!isAuto && !isReply) return;
7673 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7677 //Enter or DoubleClick
7679 var sTxt = StatusText.Text;
7680 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7683 this.inReplyTo = null;
7685 foreach (var post in selectedPosts)
7687 if (!sTxt.Contains("@" + post.ScreenName + " "))
7689 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7690 //sTxt = "@" + post.ScreenName + " " + sTxt;
7693 StatusText.Text = sTxt;
7699 if (selectedPosts.Length > 1)
7704 var sidx = StatusText.SelectionStart;
7705 foreach (var post in selectedPosts)
7707 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7709 ids += "@" + post.ScreenName + " ";
7713 foreach (var (_, screenName) in post.ReplyToList)
7715 if (!ids.Contains("@" + screenName + " ") &&
7716 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7718 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7720 ids += "@" + m.Result("${id}") + " ";
7722 ids += "@" + screenName + " ";
7727 if (ids.Length == 0) return;
7728 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7730 this.inReplyTo = null;
7731 StatusText.Text = ". " + StatusText.Text;
7736 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7741 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7743 //if (StatusText.Text.StartsWith("@"))
7745 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7746 // sidx += 2 + ids.Length;
7750 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7751 // sidx += 1 + ids.Length;
7753 StatusText.SelectionStart = sidx;
7759 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7762 var sidx = StatusText.SelectionStart;
7763 var post = selectedPosts.Single();
7764 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7766 ids += "@" + post.ScreenName + " ";
7768 foreach (var (_, screenName) in post.ReplyToList)
7770 if (!ids.Contains("@" + screenName + " ") &&
7771 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7773 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7775 ids += "@" + m.Result("${id}") + " ";
7777 ids += "@" + screenName + " ";
7780 if (!string.IsNullOrEmpty(post.RetweetedBy))
7782 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7784 ids += "@" + post.RetweetedBy + " ";
7787 if (ids.Length == 0) return;
7788 if (string.IsNullOrEmpty(StatusText.Text))
7791 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7792 var inReplyToScreenName = post.ScreenName;
7793 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7795 StatusText.Text = ids;
7796 StatusText.SelectionStart = ids.Length;
7803 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7808 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7810 StatusText.SelectionStart = sidx;
7816 StatusText.SelectionStart = StatusText.Text.Length;
7821 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7822 => this._tabDrag = false;
7824 private int iconCnt = 0;
7825 private int blinkCnt = 0;
7826 private bool blink = false;
7828 private void RefreshTasktrayIcon()
7830 void EnableTasktrayAnimation()
7831 => this.TimerRefreshIcon.Enabled = true;
7833 void DisableTasktrayAnimation()
7834 => this.TimerRefreshIcon.Enabled = false;
7836 var busyTasks = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7840 if (iconCnt >= this.NIconRefresh.Length)
7843 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7844 _myStatusError = false;
7845 EnableTasktrayAnimation();
7849 var replyIconType = SettingManager.Common.ReplyIconState;
7851 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
7853 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
7854 if (replyTab != null && replyTab.UnreadCount > 0)
7858 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
7867 NotifyIcon1.Icon = blink ? ReplyIconBlink : ReplyIcon;
7868 EnableTasktrayAnimation();
7872 DisableTasktrayAnimation();
7878 // 優先度:リプライ→エラー→オフライン→アイドル
7879 // エラーは更新アイコンでクリアされる
7880 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
7881 NotifyIcon1.Icon = ReplyIcon;
7882 else if (_myStatusError)
7883 NotifyIcon1.Icon = NIconAtRed;
7884 else if (_myStatusOnline)
7885 NotifyIcon1.Icon = NIconAt;
7887 NotifyIcon1.Icon = NIconAtSmoke;
7890 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
7891 => this.RefreshTasktrayIcon(); // 200ms
7893 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7895 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7896 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7897 _rclickTabName = this.CurrentTabName;
7899 if (_statuses == null) return;
7900 if (_statuses.Tabs == null) return;
7902 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7905 NotifyDispMenuItem.Checked = tb.Notify;
7906 this.NotifyTbMenuItem.Checked = tb.Notify;
7908 soundfileListup = true;
7909 SoundFileComboBox.Items.Clear();
7910 this.SoundFileTbComboBox.Items.Clear();
7911 SoundFileComboBox.Items.Add("");
7912 this.SoundFileTbComboBox.Items.Add("");
7913 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7914 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7916 oDir = oDir.GetDirectories("Sounds")[0];
7918 foreach (var oFile in oDir.GetFiles("*.wav"))
7920 SoundFileComboBox.Items.Add(oFile.Name);
7921 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7923 var idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7924 if (idx == -1) idx = 0;
7925 SoundFileComboBox.SelectedIndex = idx;
7926 this.SoundFileTbComboBox.SelectedIndex = idx;
7927 soundfileListup = false;
7928 UreadManageMenuItem.Checked = tb.UnreadManage;
7929 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7931 TabMenuControl(_rclickTabName);
7934 private void TabMenuControl(string tabName)
7936 var tabInfo = _statuses.GetTabByName(tabName)!;
7938 this.FilterEditMenuItem.Enabled = true;
7939 this.EditRuleTbMenuItem.Enabled = true;
7941 if (tabInfo.IsDefaultTabType)
7943 this.ProtectTabMenuItem.Enabled = false;
7944 this.ProtectTbMenuItem.Enabled = false;
7948 this.ProtectTabMenuItem.Enabled = true;
7949 this.ProtectTbMenuItem.Enabled = true;
7952 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7954 this.ProtectTabMenuItem.Checked = true;
7955 this.ProtectTbMenuItem.Checked = true;
7956 this.DeleteTabMenuItem.Enabled = false;
7957 this.DeleteTbMenuItem.Enabled = false;
7961 this.ProtectTabMenuItem.Checked = false;
7962 this.ProtectTbMenuItem.Checked = false;
7963 this.DeleteTabMenuItem.Enabled = true;
7964 this.DeleteTbMenuItem.Enabled = true;
7968 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7970 var checkState = ((ToolStripMenuItem)sender).Checked;
7973 this.ProtectTbMenuItem.Checked = checkState;
7974 this.ProtectTabMenuItem.Checked = checkState;
7977 this.DeleteTabMenuItem.Enabled = !checkState;
7978 this.DeleteTbMenuItem.Enabled = !checkState;
7980 if (string.IsNullOrEmpty(_rclickTabName)) return;
7981 _statuses.Tabs[_rclickTabName].Protected = checkState;
7986 private void UreadManageMenuItem_Click(object sender, EventArgs e)
7988 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7989 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7991 if (string.IsNullOrEmpty(_rclickTabName)) return;
7992 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7997 public void ChangeTabUnreadManage(string tabName, bool isManage)
7999 var idx = this.GetTabPageIndex(tabName);
8003 var tab = this._statuses.Tabs[tabName];
8004 tab.UnreadManage = isManage;
8006 if (SettingManager.Common.TabIconDisp)
8008 var tabPage = this.ListTab.TabPages[idx];
8009 if (tab.UnreadCount > 0)
8010 tabPage.ImageIndex = 0;
8012 tabPage.ImageIndex = -1;
8015 if (this.CurrentTabName == tabName)
8017 this.PurgeListViewItemCache();
8018 this.CurrentListView.Refresh();
8021 SetMainWindowTitle();
8022 SetStatusLabelUrl();
8023 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8026 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8028 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8029 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8031 if (string.IsNullOrEmpty(_rclickTabName)) return;
8033 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8038 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8040 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8042 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8047 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8049 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
8050 _rclickTabName = this.CurrentTabName;
8052 RemoveSpecifiedTab(_rclickTabName, true);
8056 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8058 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.HomeTab.TabName;
8060 using (var fltDialog = new FilterDialog())
8062 fltDialog.Owner = this;
8063 fltDialog.SetCurrent(_rclickTabName);
8064 fltDialog.ShowDialog(this);
8066 this.TopMost = SettingManager.Common.AlwaysTop;
8068 this.ApplyPostFilters();
8072 private async void AddTabMenuItem_Click(object sender, EventArgs e)
8074 string? tabName = null;
8075 MyCommon.TabUsageType tabUsage;
8076 using (var inputName = new InputTabName())
8078 inputName.TabName = _statuses.MakeTabName("MyTab");
8079 inputName.IsShowUsage = true;
8080 inputName.ShowDialog();
8081 if (inputName.DialogResult == DialogResult.Cancel) return;
8082 tabName = inputName.TabName;
8083 tabUsage = inputName.Usage;
8085 this.TopMost = SettingManager.Common.AlwaysTop;
8086 if (!string.IsNullOrEmpty(tabName))
8089 ListElement? list = null;
8090 if (tabUsage == MyCommon.TabUsageType.Lists)
8092 using var listAvail = new ListAvailable();
8093 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
8095 if (listAvail.SelectedList == null)
8097 list = listAvail.SelectedList;
8103 case MyCommon.TabUsageType.UserDefined:
8104 tab = new FilterTabModel(tabName);
8106 case MyCommon.TabUsageType.PublicSearch:
8107 tab = new PublicSearchTabModel(tabName);
8109 case MyCommon.TabUsageType.Lists:
8110 tab = new ListTimelineTabModel(tabName, list!);
8116 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8118 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8119 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8126 var tabIndex = this._statuses.Tabs.Count - 1;
8128 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8130 ListTab.SelectedIndex = tabIndex;
8131 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8133 if (tabUsage == MyCommon.TabUsageType.Lists)
8135 ListTab.SelectedIndex = tabIndex;
8136 await this.RefreshTabAsync(this.CurrentTab);
8142 private void TabMenuItem_Click(object sender, EventArgs e)
8144 using (var fltDialog = new FilterDialog())
8146 fltDialog.Owner = this;
8149 foreach (var post in this.CurrentTab.SelectedPosts)
8152 if (!SelectTab(out var tabName)) return;
8154 fltDialog.SetCurrent(tabName);
8156 if (post.RetweetedBy == null)
8158 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
8162 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
8164 fltDialog.ShowDialog(this);
8165 this.TopMost = SettingManager.Common.AlwaysTop;
8169 this.ApplyPostFilters();
8173 protected override bool ProcessDialogKey(Keys keyData)
8175 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8176 if ((keyData & Keys.KeyCode) == Keys.Enter)
8178 if (StatusText.Focused)
8180 var _NewLine = false;
8183 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8185 if (StatusText.Multiline)
8187 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8189 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8193 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8197 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8199 if (StatusText.Multiline)
8201 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8203 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8207 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8213 if (StatusText.Multiline)
8215 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8217 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8218 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8222 if (((keyData & Keys.Shift) == Keys.Shift) ||
8223 (((keyData & Keys.Control) != Keys.Control) &&
8224 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8230 var pos1 = StatusText.SelectionStart;
8231 if (StatusText.SelectionLength > 0)
8233 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8235 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8236 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8241 PostButton_Click(this.PostButton, EventArgs.Empty);
8247 var tab = this.CurrentTab;
8248 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8250 var tabPage = this.CurrentTabPage;
8251 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8252 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8254 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
8261 return base.ProcessDialogKey(keyData);
8264 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8265 => this.MakeReplyOrDirectStatus(false, true, true);
8267 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8269 var tab = this.CurrentTab;
8270 var selectedPosts = tab.SelectedPosts;
8273 if (selectedPosts.Length == 0)
8276 var screenNameArray = selectedPosts
8277 .Select(x => x.RetweetedBy ?? x.ScreenName)
8280 this.AddFilterRuleByScreenName(screenNameArray);
8282 if (screenNameArray.Length != 0)
8284 var atids = new List<string>();
8285 foreach (var screenName in screenNameArray)
8287 atids.Add("@" + screenName);
8289 var cnt = AtIdSupl.ItemCount;
8290 AtIdSupl.AddRangeItem(atids.ToArray());
8291 if (AtIdSupl.ItemCount != cnt)
8292 this.MarkSettingAtIdModified();
8296 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8298 var tab = this.CurrentTab;
8299 var selectedPosts = tab.SelectedPosts;
8301 if (selectedPosts.Length == 0)
8304 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8306 this.AddFilterRuleBySource(sourceArray);
8309 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8312 if (!SelectTab(out var tabName)) return;
8314 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8318 if (tab.TabType != MyCommon.TabUsageType.Mute)
8320 this.MoveOrCopy(out mv, out mk);
8324 // ミュートタブでは常に MoveMatches を true にする
8329 foreach (var screenName in screenNameArray)
8331 tab.AddFilter(new PostFilterRule
8333 FilterName = screenName,
8334 UseNameField = true,
8338 FilterByUrl = false,
8342 this.ApplyPostFilters();
8346 public void AddFilterRuleBySource(params string[] sourceArray)
8348 // タブ選択ダイアログを表示(or追加)
8349 if (!this.SelectTab(out var tabName))
8352 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8356 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8358 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8359 this.MoveOrCopy(out mv, out mk);
8363 // ミュートタブでは常に MoveMatches を true にする
8368 // 振り分けルールに追加するSource
8369 foreach (var source in sourceArray)
8371 filterTab.AddFilter(new PostFilterRule
8373 FilterSource = source,
8377 FilterByUrl = false,
8381 this.ApplyPostFilters();
8382 this.SaveConfigsTabs();
8385 private bool SelectTab([NotNullWhen(true)] out string? tabName)
8392 using (var dialog = new TabsDialog(_statuses))
8394 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8396 tabName = dialog.SelectedTab?.TabName;
8399 this.CurrentTabPage.Focus();
8401 if (tabName == null)
8403 using (var inputName = new InputTabName())
8405 inputName.TabName = _statuses.MakeTabName("MyTab");
8406 inputName.ShowDialog();
8407 if (inputName.DialogResult == DialogResult.Cancel) return false;
8408 tabName = inputName.TabName;
8410 this.TopMost = SettingManager.Common.AlwaysTop;
8411 if (!string.IsNullOrEmpty(tabName))
8413 var tab = new FilterTabModel(tabName);
8414 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8416 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8417 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8435 private void MoveOrCopy(out bool move, out bool mark)
8439 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8440 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8448 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8449 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8460 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8463 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8464 => this.CopyIdUri();
8466 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8468 if (StatusText.Focused)
8471 StatusText.SelectAll();
8475 // ListView上でのCtrl+A
8476 NativeMethods.SelectAllItems(this.CurrentListView);
8480 private void MoveMiddle()
8486 var listView = this.CurrentListView;
8487 if (listView.SelectedIndices.Count == 0) return;
8489 var idx = listView.SelectedIndices[0];
8491 _item = listView.GetItemAt(0, 25);
8497 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8499 idx2 = listView.VirtualListSize - 1;
8503 idx -= Math.Abs(idx1 - idx2) / 2;
8504 if (idx < 0) idx = 0;
8506 listView.EnsureVisible(listView.VirtualListSize - 1);
8507 listView.EnsureVisible(idx);
8510 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8512 var linkElements = this.tweetDetailsView.GetLinkElements();
8514 if (linkElements.Length == 0)
8517 var links = new List<OpenUrlItem>(linkElements.Length);
8519 foreach (var linkElm in linkElements)
8521 var displayUrl = linkElm.GetAttribute("title");
8522 var href = linkElm.GetAttribute("href");
8523 var linkedText = linkElm.InnerText;
8525 if (string.IsNullOrEmpty(displayUrl))
8528 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
8532 bool isReverseSettings;
8534 if (links.Count == 1)
8536 // ツイートに含まれる URL が 1 つのみの場合
8537 // => OpenURL ダイアログを表示せずにリンクを開く
8538 selectedUrl = links[0].Href;
8540 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8541 isReverseSettings = false;
8545 // ツイートに含まれる URL が複数ある場合
8546 // => OpenURL を表示しユーザーが選択したリンクを開く
8547 this.UrlDialog.ClearUrl();
8549 foreach (var link in links)
8550 this.UrlDialog.AddUrl(link);
8552 if (this.UrlDialog.ShowDialog(this) != DialogResult.OK)
8555 this.TopMost = SettingManager.Common.AlwaysTop;
8557 selectedUrl = this.UrlDialog.SelectedUrl;
8559 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8560 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
8563 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
8566 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8568 if (string.IsNullOrEmpty(_rclickTabName)) return;
8569 ClearTab(_rclickTabName, true);
8572 private void ClearTab(string tabName, bool showWarning)
8576 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8577 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8583 _statuses.ClearTabIds(tabName);
8584 if (this.CurrentTabName == tabName)
8587 _anchorFlag = false;
8588 this.PurgeListViewItemCache();
8591 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8592 var tabPage = this.ListTab.TabPages[tabIndex];
8593 tabPage.ImageIndex = -1;
8595 var listView = (DetailsListView)tabPage.Tag;
8596 listView.VirtualListSize = 0;
8598 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8600 SetMainWindowTitle();
8601 SetStatusLabelUrl();
8604 private static long followers = 0;
8606 private void SetMainWindowTitle()
8609 var ttl = new StringBuilder(256);
8612 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8613 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8614 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8615 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8617 foreach (var tab in _statuses.Tabs)
8619 ur += tab.UnreadCount;
8624 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8625 ttl.Append(ApplicationSettings.ApplicationName);
8627 switch (SettingManager.Common.DispLatestPost)
8629 case MyCommon.DispTitleEnum.Ver:
8630 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8632 case MyCommon.DispTitleEnum.Post:
8633 if (_history != null && _history.Count > 1)
8634 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8636 case MyCommon.DispTitleEnum.UnreadRepCount:
8637 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8639 case MyCommon.DispTitleEnum.UnreadAllCount:
8640 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8642 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8643 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8645 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8646 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8648 case MyCommon.DispTitleEnum.OwnStatus:
8649 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8650 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8656 this.Text = ttl.ToString();
8658 catch (AccessViolationException)
8660 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8664 private string GetStatusLabelText()
8667 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8668 if (_statuses == null) return "";
8669 var tbRep = _statuses.MentionTab;
8670 var tbDm = _statuses.DirectMessageTab;
8671 if (tbRep == null || tbDm == null) return "";
8672 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
8677 var slbl = new StringBuilder(256);
8680 foreach (var tab in _statuses.Tabs)
8682 ur += tab.UnreadCount;
8684 if (tab.TabName == this.CurrentTabName)
8686 tur = tab.UnreadCount;
8697 UnreadAtCounter = urat;
8699 var homeTab = this._statuses.HomeTab;
8701 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8702 if (SettingManager.Common.TimelinePeriod == 0)
8704 slbl.Append(Properties.Resources.SetStatusLabelText2);
8708 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8710 return slbl.ToString();
8713 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8717 if (this.InvokeRequired && !this.IsDisposed)
8719 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8723 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
8724 SetApiStatusLabel(endpointName);
8727 catch (ObjectDisposedException)
8731 catch (InvalidOperationException)
8737 private void SetApiStatusLabel(string? endpointName = null)
8739 var tabType = this.CurrentTab.TabType;
8741 if (endpointName == null)
8746 case MyCommon.TabUsageType.Home:
8747 case MyCommon.TabUsageType.UserDefined:
8748 endpointName = "/statuses/home_timeline";
8751 case MyCommon.TabUsageType.Mentions:
8752 endpointName = "/statuses/mentions_timeline";
8755 case MyCommon.TabUsageType.Favorites:
8756 endpointName = "/favorites/list";
8759 case MyCommon.TabUsageType.DirectMessage:
8760 endpointName = "/direct_messages/events/list";
8763 case MyCommon.TabUsageType.UserTimeline:
8764 endpointName = "/statuses/user_timeline";
8767 case MyCommon.TabUsageType.Lists:
8768 endpointName = "/lists/statuses";
8771 case MyCommon.TabUsageType.PublicSearch:
8772 endpointName = "/search/tweets";
8775 case MyCommon.TabUsageType.Related:
8776 endpointName = "/statuses/show/:id";
8783 this.toolStripApiGauge.ApiEndpoint = endpointName;
8787 // 表示中のタブに関連する endpoint であれば更新
8790 switch (endpointName)
8792 case "/statuses/home_timeline":
8793 update = tabType == MyCommon.TabUsageType.Home ||
8794 tabType == MyCommon.TabUsageType.UserDefined;
8797 case "/statuses/mentions_timeline":
8798 update = tabType == MyCommon.TabUsageType.Mentions;
8801 case "/favorites/list":
8802 update = tabType == MyCommon.TabUsageType.Favorites;
8805 case "/direct_messages/events/list":
8806 update = tabType == MyCommon.TabUsageType.DirectMessage;
8809 case "/statuses/user_timeline":
8810 update = tabType == MyCommon.TabUsageType.UserTimeline;
8813 case "/lists/statuses":
8814 update = tabType == MyCommon.TabUsageType.Lists;
8817 case "/search/tweets":
8818 update = tabType == MyCommon.TabUsageType.PublicSearch;
8821 case "/statuses/show/:id":
8822 update = tabType == MyCommon.TabUsageType.Related;
8831 this.toolStripApiGauge.ApiEndpoint = endpointName;
8836 private void SetStatusLabelUrl()
8837 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8839 public void SetStatusLabel(string text)
8840 => this.StatusLabel.Text = text;
8842 private void SetNotifyIconText()
8844 var ur = new StringBuilder(64);
8846 // タスクトレイアイコンのツールチップテキスト書き換え
8848 ur.Remove(0, ur.Length);
8849 if (SettingManager.Common.DispUsername)
8851 ur.Append(tw.Username);
8854 ur.Append(ApplicationSettings.ApplicationName);
8856 ur.Append("(Debug Build)");
8858 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8861 ur.Append(UnreadCounter);
8863 ur.Append(UnreadAtCounter);
8866 NotifyIcon1.Text = ur.ToString();
8869 internal void CheckReplyTo(string StatusText)
8873 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8875 foreach (Match hm in m)
8877 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8879 hstr += "#" + hm.Result("$3") + " ";
8880 HashSupl.AddItem("#" + hm.Result("$3"));
8883 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8885 hstr += HashMgr.UseHash;
8887 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8889 // 本当にリプライ先指定すべきかどうかの判定
8890 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8892 if (SettingManager.Common.UseAtIdSupplement)
8894 var bCnt = AtIdSupl.ItemCount;
8895 foreach (Match mid in m)
8897 AtIdSupl.AddItem(mid.Result("${id}"));
8899 if (bCnt != AtIdSupl.ItemCount)
8900 this.MarkSettingAtIdModified();
8903 // リプライ先ステータスIDの指定がない場合は指定しない
8904 if (this.inReplyTo == null)
8908 // 次の条件を満たす場合に in_reply_to_status_id 指定
8909 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8910 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8911 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8915 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8916 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8918 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8922 foreach (Match mid in m)
8924 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8929 this.inReplyTo = null;
8932 private void TweenMain_Resize(object sender, EventArgs e)
8934 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8936 this.Visible = false;
8938 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8940 // 現在の DPI と設定保存時の DPI との比を取得する
8941 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8943 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8946 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8947 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8948 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8950 this.SplitContainer1.SplitterDistance = splitterDistance;
8954 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8955 if (StatusText.Multiline)
8957 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8958 var dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8959 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8961 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8963 StatusText.Height = statusTextHeight;
8967 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8969 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8973 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8974 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8976 this.SplitContainer3.SplitterDistance = previewDistance;
8979 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8980 this.SplitContainer3.Panel2Collapsed = true;
8982 _initialLayout = false;
8984 if (this.WindowState != FormWindowState.Minimized)
8986 _formWindowState = this.WindowState;
8990 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8992 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8993 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8994 if (PlaySoundMenuItem.Checked)
8996 SettingManager.Common.PlaySound = true;
9000 SettingManager.Common.PlaySound = false;
9002 this.MarkSettingCommonModified();
9005 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9007 if (this._initialLayout)
9010 int splitterDistance;
9011 switch (this.WindowState)
9013 case FormWindowState.Normal:
9014 splitterDistance = this.SplitContainer1.SplitterDistance;
9016 case FormWindowState.Maximized:
9017 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9018 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9019 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9020 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9026 this._mySpDis = splitterDistance;
9027 this.MarkSettingLocalModified();
9030 private async Task doRepliedStatusOpen()
9032 var currentPost = this.CurrentPost;
9033 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
9035 if (MyCommon.IsKeyDown(Keys.Shift))
9037 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9040 if (this._statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
9042 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9046 foreach (var tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9048 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
9049 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
9050 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9053 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9058 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9059 => await this.doRepliedStatusOpen();
9061 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9063 if (this._initialLayout)
9064 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9066 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9067 if (multiline != this.StatusText.Multiline)
9069 this.StatusText.Multiline = multiline;
9070 SettingManager.Local.StatusMultiline = multiline;
9071 this.MarkSettingLocalModified();
9075 private void StatusText_MultilineChanged(object sender, EventArgs e)
9077 if (this.StatusText.Multiline)
9078 this.StatusText.ScrollBars = ScrollBars.Vertical;
9080 this.StatusText.ScrollBars = ScrollBars.None;
9082 if (!this._initialLayout)
9083 this.MarkSettingLocalModified();
9086 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9089 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9090 StatusText.Multiline = menuItemChecked;
9091 SettingManager.Local.StatusMultiline = menuItemChecked;
9092 if (menuItemChecked)
9094 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9095 SplitContainer2.SplitterDistance = 0;
9097 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9101 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9103 this.MarkSettingLocalModified();
9106 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9108 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9110 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9111 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9112 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9114 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9119 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9120 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9122 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9123 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9124 //Appendix A. Collected ABNF for URI
9125 //http://www.ietf.org/rfc/rfc3986.txt
9127 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9130 if (StatusText.SelectionLength > 0)
9132 var tmp = StatusText.SelectedText;
9133 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9134 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9136 // 文字列が選択されている場合はその文字列について処理
9138 //nico.ms使用、nicovideoにマッチしたら変換
9139 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9141 result = nicoms.Shorten(tmp);
9143 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9148 var srcUri = new Uri(tmp);
9149 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9150 result = resultUri.AbsoluteUri;
9152 catch (WebApiException e)
9154 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9157 catch (UriFormatException e)
9159 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9168 if (!string.IsNullOrEmpty(result))
9170 var undotmp = new urlUndo();
9172 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9173 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9174 if (origUrlIndex == -1)
9177 StatusText.Select(origUrlIndex, tmp.Length);
9178 StatusText.SelectedText = result;
9181 undotmp.Before = tmp;
9182 undotmp.After = result;
9184 if (urlUndoBuffer == null)
9186 urlUndoBuffer = new List<urlUndo>();
9187 UrlUndoToolStripMenuItem.Enabled = true;
9190 urlUndoBuffer.Add(undotmp);
9196 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9197 @"(?<url>(?<protocol>https?://)" +
9198 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9199 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9200 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9201 // 正規表現にマッチしたURL文字列をtinyurl化
9202 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9204 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
9206 var tmp = mt.Result("${url}");
9207 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
9208 tmp = "http://" + tmp;
9209 var undotmp = new urlUndo();
9212 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9214 //nico.ms使用、nicovideoにマッチしたら変換
9215 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9217 result = nicoms.Shorten(tmp);
9219 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9224 var srcUri = new Uri(tmp);
9225 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9226 result = resultUri.AbsoluteUri;
9228 catch (HttpRequestException e)
9230 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9231 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9232 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9234 this.StatusLabel.Text = Converter_Type + ":" + message;
9237 catch (WebApiException e)
9239 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9242 catch (UriFormatException e)
9244 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9253 if (!string.IsNullOrEmpty(result))
9255 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9256 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9257 if (origUrlIndex == -1)
9260 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9261 StatusText.SelectedText = result;
9263 undotmp.Before = mt.Result("${url}");
9264 undotmp.After = result;
9266 if (urlUndoBuffer == null)
9268 urlUndoBuffer = new List<urlUndo>();
9269 UrlUndoToolStripMenuItem.Enabled = true;
9272 urlUndoBuffer.Add(undotmp);
9280 private void doUrlUndo()
9282 if (urlUndoBuffer != null)
9284 var tmp = StatusText.Text;
9285 foreach (var data in urlUndoBuffer)
9287 tmp = tmp.Replace(data.After, data.Before);
9289 StatusText.Text = tmp;
9290 urlUndoBuffer = null;
9291 UrlUndoToolStripMenuItem.Enabled = false;
9292 StatusText.SelectionStart = 0;
9293 StatusText.SelectionLength = 0;
9297 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9298 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9300 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9301 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9303 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9304 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9306 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9308 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9310 var rnd = new Random();
9312 MyCommon.UrlConverter svc;
9313 // 前回使用した短縮URLサービス以外を選択する
9316 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9318 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9319 await UrlConvertAsync(svc);
9323 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9324 => this.doUrlUndo();
9326 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9328 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9329 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9330 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9331 this.MarkSettingCommonModified();
9334 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9336 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9337 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9338 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9339 this.MarkSettingCommonModified();
9342 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9344 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9345 MenuStrip1.Tag = new object();
9346 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9349 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9351 var currentTabPage = this.CurrentTabPage;
9352 if (this.Tag != null) // 設定された戻り先へ遷移
9354 if (this.Tag == currentTabPage)
9355 ((Control)currentTabPage.Tag).Select();
9357 ((Control)this.Tag).Select();
9359 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9361 this.Tag = currentTabPage.Tag;
9362 ((Control)this.Tag).Select();
9364 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9365 MenuStrip1.Tag = null;
9368 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9370 var lst = (DetailsListView)sender;
9371 if (SettingManager.Local == null) return;
9375 SettingManager.Local.Width1 = lst.Columns[0].Width;
9376 SettingManager.Local.Width3 = lst.Columns[1].Width;
9380 var darr = new int[lst.Columns.Count];
9381 for (var i = 0; i < lst.Columns.Count; i++)
9383 darr[lst.Columns[i].DisplayIndex] = i;
9385 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9387 for (var i = 0; i < lst.Columns.Count; i++)
9392 SettingManager.Local.DisplayIndex1 = i;
9395 SettingManager.Local.DisplayIndex2 = i;
9398 SettingManager.Local.DisplayIndex3 = i;
9401 SettingManager.Local.DisplayIndex4 = i;
9404 SettingManager.Local.DisplayIndex5 = i;
9407 SettingManager.Local.DisplayIndex6 = i;
9410 SettingManager.Local.DisplayIndex7 = i;
9413 SettingManager.Local.DisplayIndex8 = i;
9417 SettingManager.Local.Width1 = lst.Columns[0].Width;
9418 SettingManager.Local.Width2 = lst.Columns[1].Width;
9419 SettingManager.Local.Width3 = lst.Columns[2].Width;
9420 SettingManager.Local.Width4 = lst.Columns[3].Width;
9421 SettingManager.Local.Width5 = lst.Columns[4].Width;
9422 SettingManager.Local.Width6 = lst.Columns[5].Width;
9423 SettingManager.Local.Width7 = lst.Columns[6].Width;
9424 SettingManager.Local.Width8 = lst.Columns[7].Width;
9426 this.MarkSettingLocalModified();
9427 _isColumnChanged = true;
9430 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9432 var lst = (DetailsListView)sender;
9433 if (SettingManager.Local == null) return;
9435 var modified = false;
9438 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9440 SettingManager.Local.Width1 = lst.Columns[0].Width;
9443 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9445 SettingManager.Local.Width3 = lst.Columns[1].Width;
9451 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9453 SettingManager.Local.Width1 = lst.Columns[0].Width;
9456 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9458 SettingManager.Local.Width2 = lst.Columns[1].Width;
9461 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9463 SettingManager.Local.Width3 = lst.Columns[2].Width;
9466 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9468 SettingManager.Local.Width4 = lst.Columns[3].Width;
9471 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9473 SettingManager.Local.Width5 = lst.Columns[4].Width;
9476 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9478 SettingManager.Local.Width6 = lst.Columns[5].Width;
9481 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9483 SettingManager.Local.Width7 = lst.Columns[6].Width;
9486 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9488 SettingManager.Local.Width8 = lst.Columns[7].Width;
9494 this.MarkSettingLocalModified();
9495 this._isColumnChanged = true;
9497 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9500 // SaveConfigsLocal();
9504 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9506 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9507 this.MarkSettingLocalModified();
9510 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9512 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9514 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9516 SelectMedia_DragDrop(e);
9519 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9521 var (url, title) = GetUrlFromDataObject(e.Data);
9527 appendText = title + " " + url;
9529 if (this.StatusText.TextLength == 0)
9530 this.StatusText.Text = appendText;
9532 this.StatusText.Text += " " + appendText;
9534 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9536 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9538 this.StatusText.Text += text;
9540 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9542 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9543 if (data != null) StatusText.Text += data;
9548 /// IDataObject から URL とタイトルの対を取得します
9551 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9553 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9554 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9555 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
9557 if (data.GetDataPresent("text/x-moz-url"))
9559 // Firefox, Google Chrome で利用可能
9560 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9562 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
9563 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9564 if (lines.Length < 2)
9565 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9567 return (lines[0], lines[1]);
9569 else if (data.GetDataPresent("IESiteModeToUrl"))
9571 // Internet Exproler 用
9572 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9574 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
9575 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9576 if (lines.Length < 2)
9577 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9579 return (lines[0], lines[1]);
9581 else if (data.GetDataPresent("UniformResourceLocatorW"))
9585 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
9586 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9590 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9593 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9595 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9597 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9599 SelectMedia_DragEnter(e);
9603 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9605 e.Effect = DragDropEffects.Copy;
9608 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9610 e.Effect = DragDropEffects.Copy;
9613 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9615 e.Effect = DragDropEffects.Copy;
9619 e.Effect = DragDropEffects.None;
9622 private void TweenMain_DragOver(object sender, DragEventArgs e)
9626 public bool IsNetworkAvailable()
9628 var nw = MyCommon.IsNetworkAvailable();
9629 _myStatusOnline = nw;
9633 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9635 var uriStr = uri.AbsoluteUri;
9637 // OpenTween 内部で使用する URL
9638 if (uri.Authority == "opentween")
9640 await this.OpenInternalUriAsync(uri);
9644 // ハッシュタグを含む Twitter 検索
9645 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9648 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9649 var pos = unescapedQuery.IndexOf('#');
9650 if (pos == -1) return;
9652 var hash = unescapedQuery.Substring(pos);
9653 this.HashSupl.AddItem(hash);
9654 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9655 this.AddNewTabForSearch(hash);
9660 // フラグが立っている場合は設定と逆の動作をする
9661 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9662 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9664 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9665 if (userUriMatch.Success)
9667 var screenName = userUriMatch.Groups["ScreenName"].Value;
9668 if (this.IsTwitterId(screenName))
9670 await this.AddNewTabForUserTimeline(screenName);
9677 await this.OpenUriInBrowserAsync(uriStr);
9681 /// OpenTween 内部の機能を呼び出すための URL を開きます
9683 private async Task OpenInternalUriAsync(Uri uri)
9685 // ツイートを開く (//opentween/status/:status_id)
9686 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9689 var statusId = long.Parse(match.Groups[1].Value);
9690 await this.OpenRelatedTab(statusId);
9695 public Task OpenUriInBrowserAsync(string UriString)
9697 return Task.Run(() =>
9699 var myPath = UriString;
9703 var configBrowserPath = SettingManager.Local.BrowserPath;
9704 if (!string.IsNullOrEmpty(configBrowserPath))
9706 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9708 var sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9709 var browserPath = configBrowserPath.Substring(1, sep - 1);
9711 if (sep < configBrowserPath.Length - 1)
9713 arg = configBrowserPath.Substring(sep + 1);
9715 myPath = arg + " " + myPath;
9716 System.Diagnostics.Process.Start(browserPath, myPath);
9720 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9725 System.Diagnostics.Process.Start(myPath);
9730 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9735 private void ListTabSelect(TabPage _tab)
9739 this.PurgeListViewItemCache();
9741 this._statuses.SelectTab(_tab.Text);
9743 var listView = this.CurrentListView;
9746 _anchorFlag = false;
9750 listView.Columns[1].Text = ColumnText[2];
9754 for (var i = 0; i < listView.Columns.Count; i++)
9756 listView.Columns[i].Text = ColumnText[i];
9761 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9762 => this.ListTabSelect(e.TabPage);
9764 private void SelectListItem(DetailsListView LView, int Index)
9767 var bnd = new Rectangle();
9769 var item = LView.FocusedItem;
9778 LView.SelectedIndices.Clear();
9780 while (LView.SelectedIndices.Count > 0);
9781 item = LView.Items[Index];
9782 item.Selected = true;
9783 item.Focused = true;
9785 if (flg) LView.Invalidate(bnd);
9788 private void SelectListItem(DetailsListView LView , int[]? Index, int focusedIndex, int selectionMarkIndex)
9791 var bnd = new Rectangle();
9793 var item = LView.FocusedItem;
9804 LView.SelectedIndices.Clear();
9806 while (LView.SelectedIndices.Count > 0);
9807 LView.SelectItems(Index);
9809 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9811 LView.SelectionMark = selectionMarkIndex;
9813 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9815 LView.Items[focusedIndex].Focused = true;
9817 else if (Index != null && Index.Length != 0)
9819 LView.Items[Index.Last()].Focused = true;
9822 if (flg) LView.Invalidate(bnd);
9825 private void StartUserStream()
9827 tw.NewPostFromStream += tw_NewPostFromStream;
9828 tw.UserStreamStarted += tw_UserStreamStarted;
9829 tw.UserStreamStopped += tw_UserStreamStopped;
9830 tw.PostDeleted += tw_PostDeleted;
9831 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9833 this.RefreshUserStreamsMenu();
9835 if (SettingManager.Common.UserstreamStartup)
9836 tw.StartUserStream();
9839 private async void TweenMain_Shown(object sender, EventArgs e)
9841 NotifyIcon1.Visible = true;
9843 if (this.IsNetworkAvailable())
9847 var loadTasks = new List<Task>
9849 this.RefreshMuteUserIdsAsync(),
9850 this.RefreshBlockIdsAsync(),
9851 this.RefreshNoRetweetIdsAsync(),
9852 this.RefreshTwitterConfigurationAsync(),
9853 this.RefreshTabAsync<HomeTabModel>(),
9854 this.RefreshTabAsync<MentionsTabModel>(),
9855 this.RefreshTabAsync<DirectMessagesTabModel>(),
9856 this.RefreshTabAsync<PublicSearchTabModel>(),
9857 this.RefreshTabAsync<UserTimelineTabModel>(),
9858 this.RefreshTabAsync<ListTimelineTabModel>(),
9861 if (SettingManager.Common.StartupFollowers)
9862 loadTasks.Add(this.RefreshFollowerIdsAsync());
9864 if (SettingManager.Common.GetFav)
9865 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9867 var allTasks = Task.WhenAll(loadTasks);
9872 var timeout = Task.Delay(5000);
9873 if (await Task.WhenAny(allTasks, timeout) != timeout)
9877 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9879 if (MyCommon._endingFlag)
9883 if (MyCommon._endingFlag) return;
9885 if (ApplicationSettings.VersionInfoUrl != null)
9887 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9888 if (SettingManager.Common.StartupVersion)
9889 await this.CheckNewVersion(true);
9893 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9894 this.VerUpMenuItem.Enabled = false;
9895 this.VerUpMenuItem.Available = false;
9896 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9899 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9900 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9902 MessageBox.Show(Properties.Resources.ReAuthorizeText);
9903 SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
9907 var reloadTasks = new List<Task>();
9909 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9910 reloadTasks.Add(this.RefreshFollowerIdsAsync());
9912 if (!tw.GetNoRetweetSuccess)
9913 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9915 if (this.tw.Configuration.PhotoSizeLimit == 0)
9916 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9918 await Task.WhenAll(reloadTasks);
9923 this.timelineScheduler.Enabled = true;
9926 private async Task doGetFollowersMenu()
9928 await this.RefreshFollowerIdsAsync();
9929 this.DispSelectedPost(true);
9932 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9933 => await this.doGetFollowersMenu();
9935 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9936 => this.doReTweetUnofficial();
9938 private async Task doReTweetOfficial(bool isConfirm)
9941 if (this.ExistCurrentPost)
9943 var selectedPosts = this.CurrentTab.SelectedPosts;
9945 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9947 if (selectedPosts.Any(x => x.IsProtect))
9948 MessageBox.Show("Protected.");
9950 _DoFavRetweetFlags = false;
9954 if (selectedPosts.Length > 15)
9956 MessageBox.Show(Properties.Resources.RetweetLimitText);
9957 _DoFavRetweetFlags = false;
9960 else if (selectedPosts.Length > 1)
9962 var QuestionText = Properties.Resources.RetweetQuestion2;
9963 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9964 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9966 case DialogResult.Cancel:
9967 case DialogResult.No:
9968 _DoFavRetweetFlags = false;
9974 if (!SettingManager.Common.RetweetNoConfirm)
9976 var Questiontext = Properties.Resources.RetweetQuestion1;
9977 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9978 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9980 _DoFavRetweetFlags = false;
9986 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9988 await this.RetweetAsync(statusIds);
9992 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9993 => await this.doReTweetOfficial(true);
9995 private async Task FavoritesRetweetOfficial()
9997 if (!this.ExistCurrentPost) return;
9998 _DoFavRetweetFlags = true;
9999 var retweetTask = this.doReTweetOfficial(true);
10000 if (_DoFavRetweetFlags)
10002 _DoFavRetweetFlags = false;
10003 var favoriteTask = this.FavoriteChange(true, false);
10005 await Task.WhenAll(retweetTask, favoriteTask);
10013 private async Task FavoritesRetweetUnofficial()
10015 var post = this.CurrentPost;
10016 if (this.ExistCurrentPost && post != null && !post.IsDm)
10018 _DoFavRetweetFlags = true;
10019 var favoriteTask = this.FavoriteChange(true);
10020 if (!post.IsProtect && _DoFavRetweetFlags)
10022 _DoFavRetweetFlags = false;
10023 doReTweetUnofficial();
10026 await favoriteTask;
10031 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10033 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10034 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10035 /// <returns>復元されたツイート本文</returns>
10036 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10038 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10041 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10043 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10045 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10047 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
10051 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10053 statusHtml = statusHtml.Replace("<br>", " ");
10055 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10056 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10057 statusHtml = statusHtml.Replace(" ", " ");
10059 return WebUtility.HtmlDecode(statusHtml);
10062 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10064 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10066 if (this.CurrentPost != null)
10067 this.DispSelectedPost(true);
10070 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10072 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10073 DebugModeToolStripMenuItem.Visible = true;
10075 DebugModeToolStripMenuItem.Visible = false;
10078 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10079 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10081 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10082 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10084 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10085 => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10087 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10089 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10090 this.MarkSettingCommonModified();
10093 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10095 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10096 this.MarkSettingCommonModified();
10099 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10101 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10102 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10103 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10104 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10105 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10106 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10109 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10111 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10112 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10113 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10114 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10115 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10116 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10119 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10121 if (TraceOutToolStripMenuItem.Checked)
10122 MyCommon.TraceFlag = true;
10124 MyCommon.TraceFlag = false;
10127 private void TweenMain_Deactivate(object sender, EventArgs e)
10128 => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10130 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10132 if (string.IsNullOrEmpty(_rclickTabName)) return;
10134 _ = TabRename(_rclickTabName, out _);
10137 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10138 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10140 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10141 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10143 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10145 TwitterApiStatus? apiStatus;
10147 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10149 var cancellationToken = dialog.EnableCancellation();
10153 var task = this.tw.GetInfoApi();
10154 apiStatus = await dialog.WaitForAsync(this, task);
10156 catch (WebApiException)
10161 if (cancellationToken.IsCancellationRequested)
10164 if (apiStatus == null)
10166 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10171 using var apiDlg = new ApiInfoDialog();
10172 apiDlg.ShowDialog(this);
10175 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10177 var id = this.CurrentPost?.ScreenName ?? "";
10179 await this.FollowCommand(id);
10182 internal async Task FollowCommand(string id)
10184 using (var inputName = new InputTabName())
10186 inputName.FormTitle = "Follow";
10187 inputName.FormDescription = Properties.Resources.FRMessage1;
10188 inputName.TabName = id;
10190 if (inputName.ShowDialog(this) != DialogResult.OK)
10192 if (string.IsNullOrWhiteSpace(inputName.TabName))
10195 id = inputName.TabName.Trim();
10198 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10202 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10203 await dialog.WaitForAsync(this, task);
10205 catch (WebApiException ex)
10207 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10212 MessageBox.Show(Properties.Resources.FRMessage3);
10215 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10217 var id = this.CurrentPost?.ScreenName ?? "";
10219 await this.RemoveCommand(id, false);
10222 internal async Task RemoveCommand(string id, bool skipInput)
10226 using var inputName = new InputTabName();
10227 inputName.FormTitle = "Unfollow";
10228 inputName.FormDescription = Properties.Resources.FRMessage1;
10229 inputName.TabName = id;
10231 if (inputName.ShowDialog(this) != DialogResult.OK)
10233 if (string.IsNullOrWhiteSpace(inputName.TabName))
10236 id = inputName.TabName.Trim();
10239 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10243 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10244 await dialog.WaitForAsync(this, task);
10246 catch (WebApiException ex)
10248 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10253 MessageBox.Show(Properties.Resources.FRMessage3);
10256 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10258 var id = this.CurrentPost?.ScreenName ?? "";
10260 await this.ShowFriendship(id);
10263 internal async Task ShowFriendship(string id)
10265 using (var inputName = new InputTabName())
10267 inputName.FormTitle = "Show Friendships";
10268 inputName.FormDescription = Properties.Resources.FRMessage1;
10269 inputName.TabName = id;
10271 if (inputName.ShowDialog(this) != DialogResult.OK)
10273 if (string.IsNullOrWhiteSpace(inputName.TabName))
10276 id = inputName.TabName.Trim();
10279 bool isFollowing, isFollowed;
10281 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10283 var cancellationToken = dialog.EnableCancellation();
10287 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10288 var friendship = await dialog.WaitForAsync(this, task);
10290 isFollowing = friendship.Relationship.Source.Following;
10291 isFollowed = friendship.Relationship.Source.FollowedBy;
10293 catch (WebApiException ex)
10295 if (!cancellationToken.IsCancellationRequested)
10296 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10300 if (cancellationToken.IsCancellationRequested)
10307 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10311 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10315 result += Properties.Resources.GetFriendshipInfo3;
10319 result += Properties.Resources.GetFriendshipInfo4;
10321 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10322 MessageBox.Show(result);
10325 internal async Task ShowFriendship(string[] ids)
10327 foreach (var id in ids)
10329 bool isFollowing, isFollowed;
10331 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10333 var cancellationToken = dialog.EnableCancellation();
10337 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10338 var friendship = await dialog.WaitForAsync(this, task);
10340 isFollowing = friendship.Relationship.Source.Following;
10341 isFollowed = friendship.Relationship.Source.FollowedBy;
10343 catch (WebApiException ex)
10345 if (!cancellationToken.IsCancellationRequested)
10346 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10350 if (cancellationToken.IsCancellationRequested)
10360 ff += Properties.Resources.GetFriendshipInfo1;
10364 ff += Properties.Resources.GetFriendshipInfo2;
10367 ff += System.Environment.NewLine + " ";
10370 ff += Properties.Resources.GetFriendshipInfo3;
10374 ff += Properties.Resources.GetFriendshipInfo4;
10376 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10379 if (MessageBox.Show(
10380 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10381 MessageBoxButtons.YesNo,
10382 MessageBoxIcon.Question,
10383 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10385 await this.RemoveCommand(id, true);
10390 MessageBox.Show(result);
10395 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10396 => await this.doShowUserStatus(tw.Username, false);
10398 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10399 // URLから切り出した文字列を渡す
10401 public bool IsTwitterId(string name)
10403 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10404 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10406 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10409 private void doQuoteOfficial()
10411 var post = this.CurrentPost;
10412 if (this.ExistCurrentPost && post != null)
10414 if (post.IsDm || !StatusText.Enabled)
10417 if (post.IsProtect)
10419 MessageBox.Show("Protected.");
10423 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10425 this.inReplyTo = null;
10427 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10429 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10430 StatusText.Focus();
10434 private void doReTweetUnofficial()
10437 var post = this.CurrentPost;
10438 if (this.ExistCurrentPost && post != null)
10440 if (post.IsDm || !StatusText.Enabled)
10443 if (post.IsProtect)
10445 MessageBox.Show("Protected.");
10448 var rtdata = post.Text;
10449 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10451 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10453 // 投稿時に in_reply_to_status_id を付加する
10454 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10455 var inReplyToScreenName = post.ScreenName;
10456 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10458 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10460 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10461 StatusText.Focus();
10465 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10466 => this.doQuoteOfficial();
10468 private async void SearchButton_Click(object sender, EventArgs e)
10471 var pnl = ((Control)sender).Parent;
10472 if (pnl == null) return;
10473 var tbName = pnl.Parent.Text;
10474 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10475 var cmb = (ComboBox)pnl.Controls["comboSearch"];
10476 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
10477 cmb.Text = cmb.Text.Trim();
10478 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10480 var buf = new StringBuilder();
10481 var c = cmb.Text.ToCharArray();
10482 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
10484 if (cnt > cmb.Text.Length - 4)
10486 buf.Append(cmb.Text.Substring(cnt));
10495 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10497 buf.Append(" OR ");
10502 buf.Append(c[cnt]);
10504 cmb.Text = buf.ToString();
10506 var listView = (DetailsListView)pnl.Parent.Tag;
10508 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10510 tb.SearchWords = cmb.Text;
10511 tb.SearchLang = cmbLang.Text;
10512 if (string.IsNullOrEmpty(cmb.Text))
10520 var idx = cmb.Items.IndexOf(tb.SearchWords);
10521 if (idx > -1) cmb.Items.RemoveAt(idx);
10522 cmb.Items.Insert(0, tb.SearchWords);
10523 cmb.Text = tb.SearchWords;
10525 this.PurgeListViewItemCache();
10526 listView.VirtualListSize = 0;
10527 _statuses.ClearTabIds(tbName);
10528 SaveConfigsTabs(); //検索条件の保存
10532 await this.RefreshTabAsync(tb);
10535 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10536 => await this.DoRefreshMore(); // もっと前を取得
10539 /// 指定されたタブのListTabにおける位置を返します
10542 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10544 public int GetTabPageIndex(string tabName)
10545 => this._statuses.Tabs.IndexOf(tabName);
10547 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10549 if (_statuses.RemovedTab.Count == 0)
10551 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10556 DetailsListView? listView;
10558 var tb = _statuses.RemovedTab.Pop();
10559 if (tb.TabType == MyCommon.TabUsageType.Related)
10561 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10562 if (relatedTab != null)
10564 // 関連発言なら既存のタブを置き換える
10565 tb.TabName = relatedTab.TabName;
10566 this.ClearTab(tb.TabName, false);
10568 this._statuses.ReplaceTab(tb);
10570 var tabIndex = this._statuses.Tabs.IndexOf(tb);
10571 var tabPage = this.ListTab.TabPages[tabIndex];
10572 listView = (DetailsListView)tabPage.Tag;
10573 this.ListTab.SelectedIndex = tabIndex;
10577 const string TabName = "Related Tweets";
10578 var renamed = TabName;
10579 for (var i = 2; i <= 100; i++)
10581 if (!_statuses.ContainsTab(renamed))
10583 renamed = TabName + i;
10585 tb.TabName = renamed;
10587 _statuses.AddTab(tb);
10588 AddNewTab(tb, startup: false);
10590 var tabIndex = this._statuses.Tabs.Count - 1;
10591 var tabPage = this.ListTab.TabPages[tabIndex];
10593 listView = (DetailsListView)tabPage.Tag;
10594 this.ListTab.SelectedIndex = tabIndex;
10599 var renamed = tb.TabName;
10600 for (var i = 1; i < int.MaxValue; i++)
10602 if (!_statuses.ContainsTab(renamed))
10604 renamed = tb.TabName + "(" + i + ")";
10606 tb.TabName = renamed;
10608 _statuses.AddTab(tb);
10609 AddNewTab(tb, startup: false);
10611 var tabIndex = this._statuses.Tabs.Count - 1;
10612 var tabPage = this.ListTab.TabPages[tabIndex];
10614 listView = (DetailsListView)tabPage.Tag;
10615 this.ListTab.SelectedIndex = tabIndex;
10619 if (listView != null)
10621 using (ControlTransaction.Update(listView))
10623 listView.VirtualListSize = tb.AllCount;
10629 private async Task doMoveToRTHome()
10631 var post = this.CurrentPost;
10632 if (post != null && post.RetweetedId != null)
10633 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10636 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10637 => await this.doMoveToRTHome();
10639 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10641 var screenName = this.CurrentPost?.ScreenName;
10642 if (screenName != null)
10643 this.ListManageUserContext(screenName);
10646 public void ListManageUserContext(string screenName)
10648 using var listSelectForm = new MyLists(screenName, this.twitterApi);
10649 listSelectForm.ShowDialog(this);
10652 private void SearchControls_Enter(object sender, EventArgs e)
10654 var pnl = (Control)sender;
10655 foreach (Control ctl in pnl.Controls)
10657 ctl.TabStop = true;
10661 private void SearchControls_Leave(object sender, EventArgs e)
10663 var pnl = (Control)sender;
10664 foreach (Control ctl in pnl.Controls)
10666 ctl.TabStop = false;
10670 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10672 var tab = this.CurrentTab;
10673 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10674 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10677 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10678 => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10680 private void HashManageMenuItem_Click(object sender, EventArgs e)
10685 rslt = HashMgr.ShowDialog();
10691 this.TopMost = SettingManager.Common.AlwaysTop;
10692 if (rslt == DialogResult.Cancel) return;
10693 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10695 HashStripSplitButton.Text = HashMgr.UseHash;
10696 HashTogglePullDownMenuItem.Checked = true;
10697 HashToggleMenuItem.Checked = true;
10701 HashStripSplitButton.Text = "#[-]";
10702 HashTogglePullDownMenuItem.Checked = false;
10703 HashToggleMenuItem.Checked = false;
10705 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10707 // int sidx = StatusText.SelectionStart;
10708 // string hash = HashMgr.UseHash + " ";
10711 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10712 // hash = " " + hash;
10714 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10715 // sidx += hash.Length;
10716 // StatusText.SelectionStart = sidx;
10717 // StatusText.Focus();
10719 this.MarkSettingCommonModified();
10720 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10723 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10725 HashMgr.ToggleHash();
10726 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10728 HashStripSplitButton.Text = HashMgr.UseHash;
10729 HashToggleMenuItem.Checked = true;
10730 HashTogglePullDownMenuItem.Checked = true;
10734 HashStripSplitButton.Text = "#[-]";
10735 HashToggleMenuItem.Checked = false;
10736 HashTogglePullDownMenuItem.Checked = false;
10738 this.MarkSettingCommonModified();
10739 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10742 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10743 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
10745 public void SetPermanentHashtag(string hashtag)
10747 HashMgr.SetPermanentHash("#" + hashtag);
10748 HashStripSplitButton.Text = HashMgr.UseHash;
10749 HashTogglePullDownMenuItem.Checked = true;
10750 HashToggleMenuItem.Checked = true;
10752 this.MarkSettingCommonModified();
10755 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10757 if (!this.ExistCurrentPost)
10759 this.ReplyOpMenuItem.Enabled = false;
10760 this.ReplyAllOpMenuItem.Enabled = false;
10761 this.DmOpMenuItem.Enabled = false;
10762 this.ShowProfMenuItem.Enabled = false;
10763 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10764 this.ListManageMenuItem.Enabled = false;
10765 this.OpenFavOpMenuItem.Enabled = false;
10766 this.CreateTabRuleOpMenuItem.Enabled = false;
10767 this.CreateIdRuleOpMenuItem.Enabled = false;
10768 this.CreateSourceRuleOpMenuItem.Enabled = false;
10769 this.ReadOpMenuItem.Enabled = false;
10770 this.UnreadOpMenuItem.Enabled = false;
10774 this.ReplyOpMenuItem.Enabled = true;
10775 this.ReplyAllOpMenuItem.Enabled = true;
10776 this.DmOpMenuItem.Enabled = true;
10777 this.ShowProfMenuItem.Enabled = true;
10778 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10779 this.ListManageMenuItem.Enabled = true;
10780 this.OpenFavOpMenuItem.Enabled = true;
10781 this.CreateTabRuleOpMenuItem.Enabled = true;
10782 this.CreateIdRuleOpMenuItem.Enabled = true;
10783 this.CreateSourceRuleOpMenuItem.Enabled = true;
10784 this.ReadOpMenuItem.Enabled = true;
10785 this.UnreadOpMenuItem.Enabled = true;
10788 var tab = this.CurrentTab;
10789 var post = this.CurrentPost;
10790 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
10792 this.FavOpMenuItem.Enabled = false;
10793 this.UnFavOpMenuItem.Enabled = false;
10794 this.OpenStatusOpMenuItem.Enabled = false;
10795 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10796 this.RtOpMenuItem.Enabled = false;
10797 this.RtUnOpMenuItem.Enabled = false;
10798 this.QtOpMenuItem.Enabled = false;
10799 this.FavoriteRetweetMenuItem.Enabled = false;
10800 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10804 this.FavOpMenuItem.Enabled = true;
10805 this.UnFavOpMenuItem.Enabled = true;
10806 this.OpenStatusOpMenuItem.Enabled = true;
10807 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10809 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10811 this.RtOpMenuItem.Enabled = false;
10812 this.RtUnOpMenuItem.Enabled = false;
10813 this.QtOpMenuItem.Enabled = false;
10814 this.FavoriteRetweetMenuItem.Enabled = false;
10815 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10819 this.RtOpMenuItem.Enabled = true;
10820 this.RtUnOpMenuItem.Enabled = true;
10821 this.QtOpMenuItem.Enabled = true;
10822 this.FavoriteRetweetMenuItem.Enabled = true;
10823 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10827 if (tab.TabType != MyCommon.TabUsageType.Favorites)
10829 this.RefreshPrevOpMenuItem.Enabled = true;
10833 this.RefreshPrevOpMenuItem.Enabled = false;
10835 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
10837 OpenRepSourceOpMenuItem.Enabled = false;
10841 OpenRepSourceOpMenuItem.Enabled = true;
10843 if (!this.ExistCurrentPost || post == null || string.IsNullOrEmpty(post.RetweetedBy))
10845 OpenRterHomeMenuItem.Enabled = false;
10849 OpenRterHomeMenuItem.Enabled = true;
10852 if (this.ExistCurrentPost && post != null)
10854 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10858 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10859 => this.ContextMenuTabProperty_Opening(sender, null!);
10861 public Twitter TwitterInstance
10864 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10866 if (this._initialLayout)
10869 int splitterDistance;
10870 switch (this.WindowState)
10872 case FormWindowState.Normal:
10873 splitterDistance = this.SplitContainer3.SplitterDistance;
10875 case FormWindowState.Maximized:
10876 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10877 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10878 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10879 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10885 this._mySpDis3 = splitterDistance;
10886 this.MarkSettingLocalModified();
10889 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10891 if (_statuses.RemovedTab.Count == 0)
10893 UndoRemoveTabMenuItem.Enabled = false;
10897 UndoRemoveTabMenuItem.Enabled = true;
10900 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10901 PublicSearchQueryMenuItem.Enabled = true;
10903 PublicSearchQueryMenuItem.Enabled = false;
10905 var post = this.CurrentPost;
10906 if (!this.ExistCurrentPost || post == null)
10908 this.CopySTOTMenuItem.Enabled = false;
10909 this.CopyURLMenuItem.Enabled = false;
10910 this.CopyUserIdStripMenuItem.Enabled = false;
10914 this.CopySTOTMenuItem.Enabled = true;
10915 this.CopyURLMenuItem.Enabled = true;
10916 this.CopyUserIdStripMenuItem.Enabled = true;
10918 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10919 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10923 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10924 => this.SetNotifyIconText();
10926 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10927 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10929 private async Task doShowUserStatus(string id, bool ShowInputDialog)
10931 TwitterUser? user = null;
10933 if (ShowInputDialog)
10935 using var inputName = new InputTabName();
10936 inputName.FormTitle = "Show UserStatus";
10937 inputName.FormDescription = Properties.Resources.FRMessage1;
10938 inputName.TabName = id;
10940 if (inputName.ShowDialog(this) != DialogResult.OK)
10942 if (string.IsNullOrWhiteSpace(inputName.TabName))
10945 id = inputName.TabName.Trim();
10948 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10950 var cancellationToken = dialog.EnableCancellation();
10954 var task = this.twitterApi.UsersShow(id);
10955 user = await dialog.WaitForAsync(this, task);
10957 catch (WebApiException ex)
10959 if (!cancellationToken.IsCancellationRequested)
10960 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10964 if (cancellationToken.IsCancellationRequested)
10968 await this.doShowUserStatus(user);
10971 private async Task doShowUserStatus(TwitterUser user)
10973 using var userDialog = new UserInfoDialog(this, this.twitterApi);
10974 var showUserTask = userDialog.ShowUserAsync(user);
10975 userDialog.ShowDialog(this);
10978 this.BringToFront();
10980 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10981 await showUserTask;
10984 internal Task ShowUserStatus(string id, bool ShowInputDialog)
10985 => this.doShowUserStatus(id, ShowInputDialog);
10987 internal Task ShowUserStatus(string id)
10988 => this.doShowUserStatus(id, true);
10990 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10992 var post = this.CurrentPost;
10995 await this.ShowUserStatus(post.ScreenName, false);
10999 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11001 var post = this.CurrentPost;
11002 if (!this.ExistCurrentPost || post == null)
11005 var statusId = post.RetweetedId ?? post.StatusId;
11006 TwitterStatus status;
11008 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11010 var cancellationToken = dialog.EnableCancellation();
11014 var task = this.twitterApi.StatusesShow(statusId);
11015 status = await dialog.WaitForAsync(this, task);
11017 catch (WebApiException ex)
11019 if (!cancellationToken.IsCancellationRequested)
11020 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11024 if (cancellationToken.IsCancellationRequested)
11028 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11031 private readonly HookGlobalHotkey _hookGlobalHotkey;
11034 _hookGlobalHotkey = new HookGlobalHotkey(this);
11036 // この呼び出しは、Windows フォーム デザイナで必要です。
11037 InitializeComponent();
11039 // InitializeComponent() 呼び出しの後で初期化を追加します。
11041 if (!this.DesignMode)
11043 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11044 this.StatusText.Dock = DockStyle.Fill;
11047 this.tweetDetailsView.Owner = this;
11049 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11050 this.gh.NotifyClicked += GrowlHelper_Callback;
11052 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11053 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11055 this.ImageSelector.Visible = false;
11056 this.ImageSelector.Enabled = false;
11057 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11059 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11061 this.ReplaceAppName();
11062 this.InitializeShortcuts();
11065 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11067 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11070 this.Visible = false;
11072 else if (Form.ActiveForm == null)
11074 this.Visible = true;
11075 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11077 this.BringToFront();
11078 this.StatusText.Focus();
11082 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11083 => this.MultiLinePullDownMenuItem.PerformClick();
11086 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11088 if (ImageSelector.Visible)
11089 ImageSelector.EndSelection();
11091 ImageSelector.BeginSelection();
11094 private void SelectMedia_DragEnter(DragEventArgs e)
11096 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11098 e.Effect = DragDropEffects.Copy;
11101 e.Effect = DragDropEffects.None;
11104 private void SelectMedia_DragDrop(DragEventArgs e)
11107 this.BringToFront();
11108 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11109 StatusText.Focus();
11112 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11114 TimelinePanel.Visible = false;
11115 TimelinePanel.Enabled = false;
11118 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11120 TimelinePanel.Visible = true;
11121 TimelinePanel.Enabled = true;
11122 this.CurrentListView.Focus();
11125 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11126 => this.AllowDrop = false;
11128 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11129 => this.AllowDrop = true;
11131 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11133 if (ImageSelector.Visible)
11135 this.MarkSettingCommonModified();
11136 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
11140 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11141 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
11144 /// StatusTextでCtrl+Vが押下された時の処理
11146 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11150 if (Clipboard.ContainsText())
11152 // clipboardにテキストがある場合は貼り付け処理
11153 this.StatusText.Paste(Clipboard.GetText());
11155 else if (Clipboard.ContainsImage())
11158 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11159 Properties.Resources.PostPictureWarn4,
11160 MessageBoxButtons.OKCancel,
11161 MessageBoxIcon.Question,
11162 MessageBoxDefaultButton.Button2)
11163 == DialogResult.OK)
11165 // clipboardから画像を取得
11166 using var image = Clipboard.GetImage();
11167 this.ImageSelector.BeginSelection(image);
11171 catch (ExternalException ex)
11173 MessageBox.Show(ex.Message);
11178 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11180 using var form = new ListManage(tw);
11181 form.ShowDialog(this);
11184 private bool ModifySettingCommon { get; set; }
11185 private bool ModifySettingLocal { get; set; }
11186 private bool ModifySettingAtId { get; set; }
11188 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11190 var post = this.CurrentPost;
11191 if (this.ExistCurrentPost && post != null && !post.IsDm)
11192 RtCountMenuItem.Enabled = true;
11194 RtCountMenuItem.Enabled = false;
11196 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11197 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11199 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11202 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11203 => this.CopyUserId();
11205 private void CopyUserId()
11207 var post = this.CurrentPost;
11208 if (post == null) return;
11209 var clstr = post.ScreenName;
11212 Clipboard.SetDataObject(clstr, false, 5, 100);
11214 catch (Exception ex)
11216 MessageBox.Show(ex.Message);
11220 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11222 var post = this.CurrentPost;
11223 if (this.ExistCurrentPost && post != null && !post.IsDm)
11227 await this.OpenRelatedTab(post);
11229 catch (TabException ex)
11231 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11237 /// 指定されたツイートに対する関連発言タブを開きます
11239 /// <param name="statusId">表示するツイートのID</param>
11240 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11241 public async Task OpenRelatedTab(long statusId)
11243 var post = this._statuses[statusId];
11248 post = await this.tw.GetStatusApi(false, statusId);
11250 catch (WebApiException ex)
11252 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11257 await this.OpenRelatedTab(post);
11261 /// 指定されたツイートに対する関連発言タブを開きます
11263 /// <param name="post">表示する対象となるツイート</param>
11264 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11265 private async Task OpenRelatedTab(PostClass post)
11267 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11268 if (tabRelated != null)
11270 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11273 var tabName = this._statuses.MakeTabName("Related Tweets");
11275 tabRelated = new RelatedPostsTabModel(tabName, post)
11277 UnreadManage = false,
11281 this._statuses.AddTab(tabRelated);
11282 this.AddNewTab(tabRelated, startup: false);
11284 this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11286 await this.RefreshTabAsync(tabRelated);
11288 var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11290 if (tabIndex != -1)
11292 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11294 var tabPage = this.ListTab.TabPages[tabIndex];
11295 var listView = (DetailsListView)tabPage.Tag;
11296 var targetPost = tabRelated.TargetPost;
11297 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11299 if (index != -1 && index < listView.Items.Count)
11301 listView.SelectedIndices.Add(index);
11302 listView.Items[index].Focused = true;
11307 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11309 var buf = new StringBuilder();
11310 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11311 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11312 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11313 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11314 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11317 #region "Userstream"
11318 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11322 if (InvokeRequired && !IsDisposed)
11324 await this.InvokeAsync(() =>
11326 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11327 if (this.CurrentTab.Contains(e.StatusId))
11329 this.PurgeListViewItemCache();
11330 this.CurrentListView.Update();
11331 var post = this.CurrentPost;
11332 if (post != null && post.StatusId == e.StatusId)
11333 this.DispSelectedPost(true);
11339 catch (ObjectDisposedException)
11343 catch (InvalidOperationException)
11349 private void tw_NewPostFromStream(object sender, EventArgs e)
11351 if (SettingManager.Common.ReadOldPosts)
11353 _statuses.SetReadHomeTab(); //新着時未読クリア
11356 this._statuses.DistributePosts();
11358 this.RefreshThrottlingTimer.Call();
11361 private async void tw_UserStreamStarted(object sender, EventArgs e)
11365 if (InvokeRequired && !IsDisposed)
11367 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11371 catch (ObjectDisposedException)
11375 catch (InvalidOperationException)
11380 this.RefreshUserStreamsMenu();
11381 this.MenuItemUserStream.Enabled = true;
11383 StatusLabel.Text = "UserStream Started.";
11386 private async void tw_UserStreamStopped(object sender, EventArgs e)
11390 if (InvokeRequired && !IsDisposed)
11392 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11396 catch (ObjectDisposedException)
11400 catch (InvalidOperationException)
11405 this.RefreshUserStreamsMenu();
11406 this.MenuItemUserStream.Enabled = true;
11408 StatusLabel.Text = "UserStream Stopped.";
11411 private void RefreshUserStreamsMenu()
11413 if (this.tw.UserStreamActive)
11415 this.MenuItemUserStream.Text = "&UserStream ▶";
11416 this.StopToolStripMenuItem.Text = "&Stop";
11420 this.MenuItemUserStream.Text = "&UserStream ■";
11421 this.StopToolStripMenuItem.Text = "&Start";
11425 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11429 if (InvokeRequired && !IsDisposed)
11431 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11435 catch (ObjectDisposedException)
11439 catch (InvalidOperationException)
11443 var ev = e.EventData;
11444 StatusLabel.Text = "Event: " + ev.Event;
11445 //if (ev.Event == "favorite")
11447 // NotifyFavorite(ev);
11450 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11452 if (this.CurrentTab.Contains(ev.Id))
11454 this.PurgeListViewItemCache();
11455 this.CurrentListView.Update();
11457 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11459 var favTab = this._statuses.FavoriteTab;
11460 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11465 private void NotifyEvent(Twitter.FormattedEvent ev)
11468 if (BalloonRequired(ev))
11470 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11471 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11472 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11473 var title = new StringBuilder();
11474 if (SettingManager.Common.DispUsername)
11476 title.Append(tw.Username);
11477 title.Append(" - ");
11483 title.Append(ApplicationSettings.ApplicationName);
11484 title.Append(" [");
11485 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11486 title.Append("] by ");
11487 if (!string.IsNullOrEmpty(ev.Username))
11489 title.Append(ev.Username);
11493 //title.Append("");
11496 if (!string.IsNullOrEmpty(ev.Target))
11498 //NotifyIcon1.BalloonTipText = ev.Target;
11503 //NotifyIcon1.BalloonTipText = " ";
11506 //NotifyIcon1.ShowBalloonTip(500);
11507 if (SettingManager.Common.IsUseNotifyGrowl)
11509 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11510 ev.Id.ToString(), title.ToString(), text);
11514 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11515 NotifyIcon1.BalloonTipTitle = title.ToString();
11516 NotifyIcon1.BalloonTipText = text;
11517 NotifyIcon1.ShowBalloonTip(500);
11522 var snd = SettingManager.Common.EventSoundFile;
11523 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11525 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11529 var dir = Application.StartupPath;
11530 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11532 dir = Path.Combine(dir, "Sounds");
11534 using var player = new SoundPlayer(Path.Combine(dir, snd));
11544 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11546 MenuItemUserStream.Enabled = false;
11547 if (StopRefreshAllMenuItem.Checked)
11549 StopRefreshAllMenuItem.Checked = false;
11552 if (this.tw.UserStreamActive)
11554 tw.StopUserStream();
11558 tw.StartUserStream();
11562 private static string inputTrack = "";
11564 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11566 if (TrackToolStripMenuItem.Checked)
11568 using (var inputForm = new InputTabName())
11570 inputForm.TabName = inputTrack;
11571 inputForm.FormTitle = "Input track word";
11572 inputForm.FormDescription = "Track word";
11573 if (inputForm.ShowDialog() != DialogResult.OK)
11575 TrackToolStripMenuItem.Checked = false;
11578 inputTrack = inputForm.TabName.Trim();
11580 if (!inputTrack.Equals(tw.TrackWord))
11582 tw.TrackWord = inputTrack;
11583 this.MarkSettingCommonModified();
11584 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11585 tw.ReconnectUserStream();
11591 tw.ReconnectUserStream();
11593 this.MarkSettingCommonModified();
11596 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11598 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11599 this.MarkSettingCommonModified();
11600 tw.ReconnectUserStream();
11603 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11605 if (evtDialog == null || evtDialog.IsDisposed)
11607 this.evtDialog = new EventViewerDialog
11613 this.evtDialog.Location = new Point
11615 X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11616 Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11619 evtDialog.EventSource = tw.StoredEvent;
11620 if (!evtDialog.Visible)
11622 evtDialog.Show(this);
11626 evtDialog.Activate();
11628 this.TopMost = SettingManager.Common.AlwaysTop;
11632 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11634 MyCommon._endingFlag = true;
11638 Application.Restart();
11642 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11646 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11647 => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11649 private bool ExistCurrentPost
11653 var post = this.CurrentPost;
11654 return post != null && !post.IsDeleted;
11658 private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11659 => await this.ShowUserTimeline();
11661 private string GetUserIdFromCurPostOrInput(string caption)
11663 var id = this.CurrentPost?.ScreenName ?? "";
11665 using var inputName = new InputTabName();
11666 inputName.FormTitle = caption;
11667 inputName.FormDescription = Properties.Resources.FRMessage1;
11668 inputName.TabName = id;
11670 if (inputName.ShowDialog() == DialogResult.OK &&
11671 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11673 id = inputName.TabName.Trim();
11682 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11684 var 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)
11694 this.timelineScheduler.SystemResumed();
11697 private void SystemEvents_TimeChanged(object sender, EventArgs e)
11699 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11701 TimeZoneInfo.ClearCachedData();
11703 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11705 if (curTimeOffset != prevTimeOffset)
11708 this.PurgeListViewItemCache();
11709 this.CurrentListView.Refresh();
11711 this.DispSelectedPost(forceupdate: true);
11715 private void TimelineRefreshEnableChange(bool isEnable)
11719 tw.StartUserStream();
11723 tw.StopUserStream();
11725 this.timelineScheduler.Enabled = isEnable;
11728 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11729 => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11731 private async Task OpenUserAppointUrl()
11733 if (SettingManager.Common.UserAppointUrl != null)
11735 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11737 var post = this.CurrentPost;
11740 var xUrl = SettingManager.Common.UserAppointUrl;
11741 xUrl = xUrl.Replace("{ID}", post.ScreenName);
11743 var statusId = post.RetweetedId ?? post.StatusId;
11744 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11746 await this.OpenUriInBrowserAsync(xUrl);
11751 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11756 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11757 => await this.OpenUserAppointUrl();
11759 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11761 if (Form.ActiveForm == null)
11763 await this.InvokeAsync(() =>
11765 this.Visible = true;
11766 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11768 this.BringToFront();
11769 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11771 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11775 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11781 private void ReplaceAppName()
11783 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11784 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11787 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11788 => this.SplitContainer3.Panel2Collapsed = false;
11790 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11791 => await this.OpenThumbnailPicture(e.Thumbnail);
11793 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11794 => await this.OpenUriInBrowserAsync(e.ImageUrl);
11796 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11798 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11800 await this.OpenUriInBrowserAsync(url);
11803 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11804 => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11806 private void PostButton_KeyDown(object sender, KeyEventArgs e)
11808 if (e.KeyCode == Keys.Space)
11810 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
11812 e.SuppressKeyPress = true;
11816 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11818 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11819 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11820 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11821 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11822 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11824 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11827 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11828 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11830 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11831 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11833 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11834 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11836 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11837 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11839 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11840 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11842 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11844 if (SettingManager.Common.IconSize == iconSize) return;
11846 var oldIconCol = _iconCol;
11848 SettingManager.Common.IconSize = iconSize;
11849 ApplyListViewIconSize(iconSize);
11851 if (_iconCol != oldIconCol)
11853 foreach (TabPage tp in ListTab.TabPages)
11855 ResetColumns((DetailsListView)tp.Tag);
11859 this.CurrentListView.Refresh();
11860 this.MarkSettingCommonModified();
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;
11869 this.MarkSettingCommonModified();
11872 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11874 if (!string.IsNullOrEmpty(e.StatusText))
11876 this.StatusLabelUrl.Text = e.StatusText;
11880 this.SetStatusLabelUrl();