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.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.Thumbnail;
66 public partial class TweenMain : OTBaseForm
70 /// <summary>画面サイズ</summary>
73 /// <summary>画面位置</summary>
76 /// <summary>区切り位置</summary>
79 /// <summary>発言欄区切り位置</summary>
82 /// <summary>プレビュー区切り位置</summary>
86 private bool initial; // true:起動時処理中
87 private bool initialLayout = true;
88 private bool ignoreConfigSave; // true:起動時処理中
90 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
93 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
94 private Point tabMouseDownPoint;
96 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
97 private string? rclickTabName;
99 private readonly object syncObject = new(); // ロック用
101 private readonly DetailsHtmlBuilder detailsHtmlBuilder = new();
103 private bool myStatusError = false;
104 private bool myStatusOnline = false;
105 private bool soundfileListup = false;
106 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
109 private readonly SettingManager settings;
112 private readonly Twitter tw;
115 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
119 /// <summary>検索画面インスタンス</summary>
120 internal SearchWordDialog SearchDialog = new();
122 private readonly OpenURL urlDialog = new();
124 /// <summary>@id補助</summary>
125 public AtIdSupplement AtIdSupl = null!;
127 /// <summary>Hashtag補助</summary>
128 public AtIdSupplement HashSupl = null!;
130 public HashtagManage HashMgr = null!;
133 private ThemeManager themeManager;
135 /// <summary>アイコン画像リスト</summary>
136 private readonly ImageCache iconCache;
138 private readonly IconAssetsManager iconAssets;
140 private readonly ThumbnailGenerator thumbGenerator;
142 /// <summary>発言履歴</summary>
143 private readonly StatusTextHistory history = new();
145 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
147 /// <summary>リプライ先のステータスID・スクリーン名</summary>
148 private (PostId StatusId, string ScreenName)? inReplyTo = null;
151 private readonly List<DateTimeUtc> postTimestamps = new();
152 private readonly List<DateTimeUtc> favTimestamps = new();
155 private readonly StringFormat sfTab = new();
157 //////////////////////////////////////////////////////////////////////////////////////////////////////////
159 /// <summary>発言保持クラス</summary>
160 private readonly TabInformations statuses;
162 private TimelineListViewCache? listCache;
163 private TimelineListViewDrawer? listDrawer;
164 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
166 private bool isColumnChanged = false;
168 private const int MaxWorderThreads = 20;
169 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
170 private readonly CancellationTokenSource workerCts = new();
171 private readonly IProgress<string> workerProgress = null!;
173 private int unreadCounter = -1;
174 private int unreadAtCounter = -1;
176 private readonly string[] columnOrgText = new string[9];
177 private readonly string[] columnText = new string[9];
179 private bool doFavRetweetFlags = false;
181 //////////////////////////////////////////////////////////////////////////////////////////////////////////
183 private readonly TimelineScheduler timelineScheduler = new();
184 private readonly DebounceTimer selectionDebouncer;
185 private readonly DebounceTimer saveConfigDebouncer;
187 private readonly string recommendedStatusFooter;
189 internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
191 private bool preventSmsCommand = true;
194 private readonly record struct UrlUndo(
199 private List<UrlUndo>? urlUndoBuffer = null;
201 private readonly record struct ReplyChain(
207 /// <summary>[, ]でのリプライ移動の履歴</summary>
208 private Stack<ReplyChain>? replyChains;
210 /// <summary>ポスト選択履歴</summary>
211 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
213 public TabModel CurrentTab
214 => this.statuses.SelectedTab;
216 public string CurrentTabName
217 => this.statuses.SelectedTabName;
219 public TabPage CurrentTabPage
220 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
222 public DetailsListView CurrentListView
223 => (DetailsListView)this.CurrentTabPage.Tag;
225 public PostClass? CurrentPost
226 => this.CurrentTab.SelectedPost;
228 public bool Use2ColumnsMode
229 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
231 /// <summary>検索処理タイプ</summary>
232 internal enum SEARCHTYPE
239 private readonly HookGlobalHotkey hookGlobalHotkey;
242 SettingManager settingManager,
243 TabInformations tabInfo,
245 ImageCache imageCache,
246 IconAssetsManager iconAssets,
247 ThumbnailGenerator thumbGenerator
250 this.settings = settingManager;
251 this.statuses = tabInfo;
253 this.iconCache = imageCache;
254 this.iconAssets = iconAssets;
255 this.thumbGenerator = thumbGenerator;
257 this.InitializeComponent();
259 if (!this.DesignMode)
261 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
262 this.StatusText.Dock = DockStyle.Fill;
265 this.hookGlobalHotkey = new HookGlobalHotkey(this);
267 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
268 this.gh.NotifyClicked += this.GrowlHelper_Callback;
270 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
271 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
273 this.ImageSelector.Visible = false;
274 this.ImageSelector.Enabled = false;
275 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
277 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
279 this.ReplaceAppName();
280 this.InitializeShortcuts();
282 this.ignoreConfigSave = true;
284 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
286 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
288 Regex.CacheSize = 100;
291 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
292 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
293 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
295 // <<<<<<<<<設定関連>>>>>>>>>
299 // 現在の DPI と設定保存時の DPI との比を取得する
300 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
305 // プロキシ設定等の通信まわりの初期化が済んでから処理する
306 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
307 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
308 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
310 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
313 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
314 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
316 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
319 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
320 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
321 this.HashMgr = new HashtagManage(this.HashSupl,
322 this.settings.Common.HashTags.ToArray(),
323 this.settings.Common.HashSelected,
324 this.settings.Common.HashIsPermanent,
325 this.settings.Common.HashIsHead,
326 this.settings.Common.HashIsNotAddToAtReply);
327 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
330 this.themeManager = new(this.settings.Local);
331 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager, this.detailsHtmlBuilder);
333 // StringFormatオブジェクトへの事前設定
334 this.sfTab.Alignment = StringAlignment.Center;
335 this.sfTab.LineAlignment = StringAlignment.Center;
337 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
338 this.tweetDetailsView.ClearPostBrowser();
340 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
342 this.inReplyTo = null;
345 this.SearchDialog.Owner = this;
346 this.urlDialog.Owner = this;
349 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
350 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
352 // 新着取得時のリストスクロールをするか。trueならスクロールしない
353 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
354 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
356 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
357 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
360 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
361 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
362 this.myLoc = this.settings.Local.FormLocation;
364 if (this.WindowState != FormWindowState.Minimized)
366 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
367 var outOfScreen = true;
368 if (Screen.AllScreens.Length == 1) // ハングするとの報告
370 foreach (var scr in Screen.AllScreens)
372 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
380 this.myLoc = new Point(0, 0);
382 this.DesktopLocation = this.myLoc;
384 this.TopMost = this.settings.Common.AlwaysTop;
385 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
386 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
387 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
389 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
390 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
392 this.StatusText.Font = this.themeManager.FontInputFont;
393 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
395 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
396 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
397 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
399 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
400 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
402 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
403 if (this.settings.Common.UnreadManage == false)
405 this.ReadedStripMenuItem.Enabled = false;
406 this.UnreadStripMenuItem.Enabled = false;
409 // リンク先URL表示部の初期化(画面左下)
410 this.StatusLabelUrl.Text = "";
412 this.StatusLabel.Text = "";
413 this.StatusLabel.AutoToolTip = false;
414 this.StatusLabel.ToolTipText = "";
416 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
418 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
419 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
420 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
421 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
423 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
424 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
425 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
426 this.SplitContainer2.Panel2.AccessibleName = "";
428 ////////////////////////////////////////////////////////////////////////////////
429 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
430 var mode = this.settings.Common.SortColumn switch
432 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
433 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
434 1 => ComparerMode.Nickname, // ニックネーム
435 2 => ComparerMode.Data, // 本文
436 3 => ComparerMode.Id, // 時刻=発言Id
437 4 => ComparerMode.Name, // 名前
438 7 => ComparerMode.Source, // Source
439 _ => ComparerMode.Id,
441 this.statuses.SetSortMode(mode, sortOrder);
442 ////////////////////////////////////////////////////////////////////////////////
444 this.ApplyListViewIconSize(this.settings.Common.IconSize);
446 // <<<<<<<<タブ関連>>>>>>>
447 foreach (var tab in this.statuses.Tabs)
449 if (!this.AddNewTab(tab, startup: true))
450 throw new TabException(Properties.Resources.TweenMain_LoadText1);
453 this.ListTabSelect(this.ListTab.SelectedTab);
456 this.SetTabAlignment();
458 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
459 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
461 if (this.settings.Common.TabIconDisp)
463 this.ListTab.DrawMode = TabDrawMode.Normal;
467 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
468 this.ListTab.DrawItem += this.ListTab_DrawItem;
469 this.ListTab.ImageList = null;
472 if (this.settings.Common.HotkeyEnabled)
475 var modKey = HookGlobalHotkey.ModKeys.None;
476 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
477 modKey |= HookGlobalHotkey.ModKeys.Alt;
478 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
479 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
480 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
481 modKey |= HookGlobalHotkey.ModKeys.Shift;
482 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
483 modKey |= HookGlobalHotkey.ModKeys.Win;
485 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
488 if (this.settings.Common.IsUseNotifyGrowl)
489 this.gh.RegisterGrowl();
491 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
493 this.SetMainWindowTitle();
494 this.SetNotifyIconText();
496 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
498 this.Visible = false;
503 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
504 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
505 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
506 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
507 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
508 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
509 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
511 this.DoGetFollowersMenu(),
512 this.RefreshBlockIdsAsync(),
513 this.RefreshMuteUserIdsAsync(),
514 this.RefreshNoRetweetIdsAsync(),
515 this.RefreshTwitterConfigurationAsync(),
517 this.RefreshTimelineScheduler();
519 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
520 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
523 this.TimerRefreshIcon.Interval = 200;
524 this.TimerRefreshIcon.Enabled = false;
526 this.ignoreConfigSave = false;
527 this.ApplyLayoutFromSettings();
530 private void TweenMain_Activated(object sender, EventArgs e)
532 // 画面がアクティブになったら、発言欄の背景色戻す
533 if (this.StatusText.Focused)
535 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
539 private bool disposed = false;
542 /// 使用中のリソースをすべてクリーンアップします。
544 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
545 protected override void Dispose(bool disposing)
547 base.Dispose(disposing);
554 this.components?.Dispose();
557 this.SearchDialog.Dispose();
558 this.urlDialog.Dispose();
559 this.themeManager.Dispose();
560 this.sfTab.Dispose();
562 this.timelineScheduler.Dispose();
563 this.workerCts.Cancel();
564 this.thumbnailTokenSource?.Dispose();
566 this.hookGlobalHotkey.Dispose();
569 // 終了時にRemoveHandlerしておかないとメモリリークする
570 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
571 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
572 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
573 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
575 this.disposed = true;
578 private void InitColumns(ListView list, bool startup)
580 this.InitColumnText();
582 ColumnHeader[]? columns = null;
585 if (this.Use2ColumnsMode)
589 new ColumnHeader(), // アイコン
590 new ColumnHeader(), // 本文
593 columns[0].Text = this.columnText[0];
594 columns[1].Text = this.columnText[2];
598 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
600 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
601 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
602 columns[0].DisplayIndex = 0;
603 columns[1].DisplayIndex = 1;
608 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
610 columns[idx].Width = curListColumn.Width;
611 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
620 new ColumnHeader(), // アイコン
621 new ColumnHeader(), // ニックネーム
622 new ColumnHeader(), // 本文
623 new ColumnHeader(), // 日付
624 new ColumnHeader(), // ユーザID
625 new ColumnHeader(), // 未読
626 new ColumnHeader(), // マーク&プロテクト
627 new ColumnHeader(), // ソース
630 foreach (var i in Enumerable.Range(0, columns.Length))
631 columns[i].Text = this.columnText[i];
635 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
637 foreach (var (column, index) in columns.WithIndex())
639 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
640 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
646 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
648 columns[idx].Width = curListColumn.Width;
649 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
655 list.Columns.AddRange(columns);
663 foreach (var column in columns)
669 private void InitColumnText()
671 this.columnText[0] = "";
672 this.columnText[1] = Properties.Resources.AddNewTabText2;
673 this.columnText[2] = Properties.Resources.AddNewTabText3;
674 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
675 this.columnText[4] = Properties.Resources.AddNewTabText5;
676 this.columnText[5] = "";
677 this.columnText[6] = "";
678 this.columnText[7] = "Source";
680 this.columnOrgText[0] = "";
681 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
682 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
683 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
684 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
685 this.columnOrgText[5] = "";
686 this.columnOrgText[6] = "";
687 this.columnOrgText[7] = "Source";
689 var c = this.statuses.SortMode switch
691 ComparerMode.Nickname => 1, // ニックネーム
692 ComparerMode.Data => 2, // 本文
693 ComparerMode.Id => 3, // 時刻=発言Id
694 ComparerMode.Name => 4, // 名前
695 ComparerMode.Source => 7, // Source
699 if (this.Use2ColumnsMode)
701 if (this.statuses.SortOrder == SortOrder.Descending)
703 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
704 this.columnText[2] = this.columnOrgText[2] + "▾";
708 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
709 this.columnText[2] = this.columnOrgText[2] + "▴";
714 if (this.statuses.SortOrder == SortOrder.Descending)
716 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
717 this.columnText[c] = this.columnOrgText[c] + "▾";
721 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
722 this.columnText[c] = this.columnOrgText[c] + "▴";
727 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
732 txt = this.statuses.Tabs[e.Index].TabName;
739 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
740 if (e.State == DrawItemState.Selected)
742 e.DrawFocusRectangle();
747 if (this.statuses.Tabs[txt].UnreadCount > 0)
750 fore = System.Drawing.SystemBrushes.ControlText;
754 fore = System.Drawing.SystemBrushes.ControlText;
756 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
759 private void LoadConfig()
761 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
762 this.statuses.AddDefaultTabs();
765 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
767 this.RefreshTimelineScheduler();
770 private void RefreshTimelineScheduler()
772 static TimeSpan IntervalSecondsOrDisabled(int seconds)
773 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
775 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
776 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
777 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
778 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
779 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
780 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
781 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
782 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
784 this.timelineScheduler.RefreshSchedule();
787 private void MarkSettingCommonModified()
789 if (this.saveConfigDebouncer == null)
792 this.ModifySettingCommon = true;
793 _ = this.saveConfigDebouncer.Call();
796 private void MarkSettingLocalModified()
798 if (this.saveConfigDebouncer == null)
801 this.ModifySettingLocal = true;
802 _ = this.saveConfigDebouncer.Call();
805 internal void MarkSettingAtIdModified()
807 if (this.saveConfigDebouncer == null)
810 this.ModifySettingAtId = true;
811 _ = this.saveConfigDebouncer.Call();
814 private void RefreshTimeline()
816 var curListView = this.CurrentListView;
818 // 現在表示中のタブのスクロール位置を退避
819 var currentListViewState = this.listViewState[this.CurrentTabName];
820 currentListViewState.Save(this.ListLockMenuItem.Checked);
824 addCount = this.statuses.SubmitUpdate(
827 out var newMentionOrDm,
830 if (MyCommon.EndingFlag) return;
833 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
835 using (ControlTransaction.Update(curListView))
837 this.listCache.PurgeCache();
838 this.listCache.UpdateListSize();
841 currentListViewState.RestoreSelection();
847 if (this.settings.Common.TabIconDisp)
849 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
851 var tabPage = this.ListTab.TabPages[index];
852 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
853 tabPage.ImageIndex = 0; // 未読アイコン
858 this.ListTab.Refresh();
863 currentListViewState.RestoreScroll();
866 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
868 this.SetMainWindowTitle();
869 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
871 this.HashSupl.AddRangeItem(this.tw.GetHashList());
874 private bool BalloonRequired()
879 if (NativeMethods.IsScreenSaverRunning())
883 if (!this.NewPostPopMenuItem.Checked)
886 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
887 if (this.settings.Common.LimitBalloon)
889 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
896 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
898 if (this.settings.Common.ReadOwnPost)
900 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
905 if (this.BalloonRequired())
907 if (notifyPosts != null && notifyPosts.Length > 0)
909 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
910 if (this.settings.Common.IsUseNotifyGrowl)
912 var sb = new StringBuilder();
916 foreach (var post in notifyPosts)
918 if (!(notifyPosts.Length > 3))
924 if (post.IsReply && !post.IsExcludeReply) reply = true;
925 if (post.IsDm) dm = true;
926 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
927 switch (this.settings.Common.NameBalloon)
929 case MyCommon.NameBalloonEnum.UserID:
930 sb.Append(post.ScreenName).Append(" : ");
932 case MyCommon.NameBalloonEnum.NickName:
933 sb.Append(post.Nickname).Append(" : ");
936 sb.Append(post.TextFromApi);
937 if (notifyPosts.Length > 3)
939 if (notifyPosts.Last() != post) continue;
942 var title = new StringBuilder();
943 GrowlHelper.NotifyType nt;
944 if (this.settings.Common.DispUsername)
946 title.Append(this.tw.Username);
952 title.Append(ApplicationSettings.ApplicationName);
953 title.Append(" [DM] ");
954 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
955 nt = GrowlHelper.NotifyType.DirectMessage;
959 title.Append(ApplicationSettings.ApplicationName);
960 title.Append(" [Reply!] ");
961 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
962 nt = GrowlHelper.NotifyType.Reply;
966 title.Append(ApplicationSettings.ApplicationName);
968 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
969 nt = GrowlHelper.NotifyType.Notify;
971 var bText = sb.ToString();
972 if (MyCommon.IsNullOrEmpty(bText)) return;
974 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
975 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
980 var sb = new StringBuilder();
983 foreach (var post in notifyPosts)
985 if (post.IsReply && !post.IsExcludeReply) reply = true;
986 if (post.IsDm) dm = true;
987 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
988 switch (this.settings.Common.NameBalloon)
990 case MyCommon.NameBalloonEnum.UserID:
991 sb.Append(post.ScreenName).Append(" : ");
993 case MyCommon.NameBalloonEnum.NickName:
994 sb.Append(post.Nickname).Append(" : ");
997 sb.Append(post.TextFromApi);
1000 var title = new StringBuilder();
1002 if (this.settings.Common.DispUsername)
1004 title.Append(this.tw.Username);
1005 title.Append(" - ");
1010 ntIcon = ToolTipIcon.Warning;
1011 title.Append(ApplicationSettings.ApplicationName);
1012 title.Append(" [DM] ");
1013 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1017 ntIcon = ToolTipIcon.Warning;
1018 title.Append(ApplicationSettings.ApplicationName);
1019 title.Append(" [Reply!] ");
1020 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1024 ntIcon = ToolTipIcon.Info;
1025 title.Append(ApplicationSettings.ApplicationName);
1027 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1029 var bText = sb.ToString();
1030 if (MyCommon.IsNullOrEmpty(bText)) return;
1032 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1033 this.NotifyIcon1.BalloonTipText = bText;
1034 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1035 this.NotifyIcon1.ShowBalloonTip(500);
1041 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1045 var dir = Application.StartupPath;
1046 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1048 dir = Path.Combine(dir, "Sounds");
1050 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1058 // mentions新着時に画面ブリンク
1059 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1061 NativeMethods.FlashMyWindow(this.Handle, 3);
1065 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1067 var listView = this.CurrentListView;
1068 if (listView != sender)
1071 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1072 this.CurrentTab.SelectPosts(indices);
1074 if (indices.Length != 1)
1077 var index = indices[0];
1078 if (index > listView.VirtualListSize - 1) return;
1080 this.PushSelectPostChain();
1082 var post = this.CurrentPost!;
1083 this.statuses.SetReadAllTab(post.StatusId, read: true);
1085 this.listCache?.RefreshStyle();
1086 await this.selectionDebouncer.Call();
1089 private void StatusTextHistoryBack()
1091 var historyItem = this.history.Back(this.StatusText.Text, this.inReplyTo);
1092 this.inReplyTo = historyItem.InReplyTo;
1093 this.StatusText.Text = historyItem.Status;
1094 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1097 private void StatusTextHistoryForward()
1099 var historyItem = this.history.Forward(this.StatusText.Text, this.inReplyTo);
1100 this.inReplyTo = historyItem.InReplyTo;
1101 this.StatusText.Text = historyItem.Status;
1102 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1105 private async void PostButton_Click(object sender, EventArgs e)
1107 if (this.StatusText.Text.Trim().Length == 0)
1109 if (!this.ImageSelector.Enabled)
1111 await this.DoRefresh();
1116 var currentPost = this.CurrentPost;
1117 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1119 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1121 MessageBoxButtons.YesNoCancel,
1122 MessageBoxIcon.Question);
1125 case DialogResult.Yes:
1126 this.StatusText.Text = "";
1127 await this.DoReTweetOfficial(false);
1129 case DialogResult.Cancel:
1134 if (TextContainsOnlyMentions(this.StatusText.Text))
1136 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1137 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1139 if (ret != DialogResult.OK)
1143 if (this.settings.Common.Nicoms)
1145 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1146 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1149 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1150 this.CheckReplyTo(this.StatusText.Text);
1152 var status = new PostStatusParams();
1154 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1155 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1157 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1158 // 収まる場合はこれらのオプションを使用せずに投稿する
1159 status.Text = statusTextCompat;
1160 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1164 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1165 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1167 status.AttachmentUrl = attachmentUrl;
1169 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1171 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1172 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1174 status.AutoPopulateReplyMetadata = true;
1176 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1177 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1182 if (this.GetRestStatusCount(status.Text) < 0)
1184 // 文字数制限を超えているが強制的に投稿するか
1185 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1186 if (ret != DialogResult.OK)
1190 IMediaUploadService? uploadService = null;
1191 IMediaItem[]? uploadItems = null;
1192 if (this.ImageSelector.Visible)
1195 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1198 this.ImageSelector.EndSelection();
1199 uploadService = this.ImageSelector.Model.GetService(serviceName);
1202 this.history.AddLast(this.StatusText.Text, this.inReplyTo);
1204 this.inReplyTo = null;
1205 this.StatusText.Text = "";
1206 if (!this.settings.Common.FocusLockToStatusText)
1207 this.CurrentListView.Focus();
1208 this.urlUndoBuffer = null;
1209 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1212 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1214 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1215 await MyCommon.OpenInBrowserAsync(this, tmp);
1218 await this.PostMessageAsync(status, uploadService, uploadItems);
1221 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1223 MyCommon.EndingFlag = true;
1227 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1229 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1231 // _endingFlag=false:フォームの×ボタン
1233 this.Visible = false;
1237 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1238 this.ignoreConfigSave = true;
1239 MyCommon.EndingFlag = true;
1240 this.timelineScheduler.Enabled = false;
1241 this.TimerRefreshIcon.Enabled = false;
1245 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1247 this.Visible = true;
1248 if (this.WindowState == FormWindowState.Minimized)
1250 this.WindowState = FormWindowState.Normal;
1253 this.BringToFront();
1256 private static int errorCount = 0;
1258 private static bool CheckAccountValid()
1260 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1266 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1275 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1276 private Task RefreshTabAsync<T>()
1278 => this.RefreshTabAsync<T>(backward: false);
1280 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1281 private Task RefreshTabAsync<T>(bool backward)
1285 from tab in this.statuses.GetTabsByType<T>()
1286 select this.RefreshTabAsync(tab, backward);
1288 return Task.WhenAll(loadTasks);
1291 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1292 private Task RefreshTabAsync(TabModel tab)
1293 => this.RefreshTabAsync(tab, backward: false);
1295 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1296 private async Task RefreshTabAsync(TabModel tab, bool backward)
1298 await this.workerSemaphore.WaitAsync();
1302 this.RefreshTasktrayIcon();
1303 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1305 catch (WebApiException ex)
1307 this.myStatusError = true;
1308 var tabType = tab switch
1310 HomeTabModel => "GetTimeline",
1311 MentionsTabModel => "GetTimeline",
1312 DirectMessagesTabModel => "GetDirectMessage",
1313 FavoritesTabModel => "GetFavorites",
1314 PublicSearchTabModel => "GetSearch",
1315 UserTimelineTabModel => "GetUserTimeline",
1316 ListTimelineTabModel => "GetListStatus",
1317 RelatedPostsTabModel => "GetRelatedTweets",
1318 _ => tab.GetType().Name.Replace("Model", ""),
1320 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1324 this.RefreshTimeline();
1325 this.workerSemaphore.Release();
1329 private async Task FavAddAsync(PostId statusId, TabModel tab)
1331 await this.workerSemaphore.WaitAsync();
1335 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1337 this.RefreshTasktrayIcon();
1338 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1340 catch (WebApiException ex)
1342 this.myStatusError = true;
1343 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1347 this.workerSemaphore.Release();
1351 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1353 if (ct.IsCancellationRequested)
1356 if (!CheckAccountValid())
1357 throw new WebApiException("Auth error. Check your account");
1359 if (!tab.Posts.TryGetValue(statusId, out var post))
1365 await Task.Run(async () =>
1367 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1371 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1374 await this.tw.Api.FavoritesCreate(twitterStatusId)
1376 .ConfigureAwait(false);
1378 catch (TwitterApiException ex)
1379 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1381 // エラーコード 139 のみの場合は成功と見なす
1384 if (this.settings.Common.RestrictFavCheck)
1386 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1387 .ConfigureAwait(false);
1389 if (status.Favorited != true)
1390 throw new WebApiException("NG(Restricted?)");
1393 this.favTimestamps.Add(DateTimeUtc.Now);
1396 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1398 postTl.IsFav = true;
1400 var favTab = this.statuses.FavoriteTab;
1401 favTab.AddPostQueue(postTl);
1404 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1405 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1407 if (tb.Contains(statusId))
1408 tb.Posts[statusId].IsFav = true;
1411 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1413 catch (WebApiException)
1415 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1420 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1421 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1423 if (this.favTimestamps[i] < oneHour)
1424 this.favTimestamps.RemoveAt(i);
1427 this.statuses.DistributePosts();
1430 if (ct.IsCancellationRequested)
1433 this.RefreshTimeline();
1435 if (this.CurrentTabName == tab.TabName)
1437 using (ControlTransaction.Update(this.CurrentListView))
1439 var idx = tab.IndexOf(statusId);
1441 this.listCache?.RefreshStyle(idx);
1444 var currentPost = this.CurrentPost;
1445 if (currentPost != null && statusId == currentPost.StatusId)
1446 this.DispSelectedPost(true); // 選択アイテム再表示
1450 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1452 await this.workerSemaphore.WaitAsync();
1456 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1458 this.RefreshTasktrayIcon();
1459 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1461 catch (WebApiException ex)
1463 this.myStatusError = true;
1464 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1468 this.workerSemaphore.Release();
1472 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1474 if (ct.IsCancellationRequested)
1477 if (!CheckAccountValid())
1478 throw new WebApiException("Auth error. Check your account");
1480 var successIds = new List<PostId>();
1482 await Task.Run(async () =>
1486 var failedCount = 0;
1487 foreach (var statusId in statusIds)
1491 var post = tab.Posts[statusId];
1493 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1498 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1502 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1504 .ConfigureAwait(false);
1506 catch (WebApiException)
1512 successIds.Add(statusId);
1513 post.IsFav = false; // リスト再描画必要
1515 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1516 tabinfoPost.IsFav = false;
1518 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1519 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1521 if (tb.Contains(statusId))
1522 tb.Posts[statusId].IsFav = false;
1527 if (ct.IsCancellationRequested)
1530 var favTab = this.statuses.FavoriteTab;
1531 foreach (var statusId in successIds)
1533 // ツイートが削除された訳ではないので IsDeleted はセットしない
1534 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1537 this.RefreshTimeline();
1539 if (this.CurrentTabName == tab.TabName)
1541 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1547 using (ControlTransaction.Update(this.CurrentListView))
1549 foreach (var statusId in successIds)
1551 var idx = tab.IndexOf(statusId);
1553 this.listCache?.RefreshStyle(idx);
1557 var currentPost = this.CurrentPost;
1558 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1559 this.DispSelectedPost(true); // 選択アイテム再表示
1564 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1566 await this.workerSemaphore.WaitAsync();
1570 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1572 this.RefreshTasktrayIcon();
1573 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1575 catch (WebApiException ex)
1577 this.myStatusError = true;
1578 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1582 this.workerSemaphore.Release();
1586 private async Task PostMessageAsyncInternal(
1587 IProgress<string> p,
1588 CancellationToken ct,
1589 PostStatusParams postParams,
1590 IMediaUploadService? uploadService,
1591 IMediaItem[]? uploadItems)
1593 if (ct.IsCancellationRequested)
1596 if (!CheckAccountValid())
1597 throw new WebApiException("Auth error. Check your account");
1599 p.Report("Posting...");
1601 PostClass? post = null;
1606 await Task.Run(async () =>
1608 var postParamsWithMedia = postParams;
1610 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1612 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1613 .ConfigureAwait(false);
1616 post = await this.tw.PostStatus(postParamsWithMedia)
1617 .ConfigureAwait(false);
1620 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1622 catch (WebApiException ex)
1624 // 処理は中断せずエラーの表示のみ行う
1625 errMsg = $"Err:{ex.Message}(PostMessage)";
1627 this.myStatusError = true;
1629 catch (UnauthorizedAccessException ex)
1631 // アップロード対象のファイルが開けなかった場合など
1632 errMsg = $"Err:{ex.Message}(PostMessage)";
1634 this.myStatusError = true;
1638 // 使い終わった MediaItem は破棄する
1639 if (uploadItems != null)
1641 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1643 disposableItem.Dispose();
1648 if (ct.IsCancellationRequested)
1651 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1652 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1653 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1655 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1657 var ret = MessageBox.Show(
1659 "Failed to update status",
1660 MessageBoxButtons.RetryCancel,
1661 MessageBoxIcon.Question);
1663 if (ret == DialogResult.Retry)
1665 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1669 this.StatusTextHistoryBack();
1670 this.StatusText.Focus();
1672 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1673 if (this.settings.Common.FocusLockToStatusText)
1674 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1679 this.postTimestamps.Add(DateTimeUtc.Now);
1681 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1682 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1684 if (this.postTimestamps[i] < oneHour)
1685 this.postTimestamps.RemoveAt(i);
1688 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1690 this.HashMgr.ClearHashtag();
1691 this.HashStripSplitButton.Text = "#[-]";
1692 this.HashTogglePullDownMenuItem.Checked = false;
1693 this.HashToggleMenuItem.Checked = false;
1696 this.SetMainWindowTitle();
1701 this.statuses.AddPost(post);
1702 this.statuses.DistributePosts();
1703 this.RefreshTimeline();
1706 if (this.settings.Common.PostAndGet)
1707 await this.RefreshTabAsync<HomeTabModel>();
1710 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1712 await this.workerSemaphore.WaitAsync();
1716 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1718 this.RefreshTasktrayIcon();
1719 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1721 catch (WebApiException ex)
1723 this.myStatusError = true;
1724 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1728 this.workerSemaphore.Release();
1732 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1734 if (ct.IsCancellationRequested)
1737 if (!CheckAccountValid())
1738 throw new WebApiException("Auth error. Check your account");
1741 if (!this.settings.Common.UnreadManage)
1744 read = this.initial && this.settings.Common.Read;
1746 p.Report("Posting...");
1748 var posts = new List<PostClass>();
1750 await Task.Run(async () =>
1752 foreach (var statusId in statusIds)
1754 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1755 if (post != null) posts.Add(post);
1759 if (ct.IsCancellationRequested)
1762 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1764 this.postTimestamps.Add(DateTimeUtc.Now);
1766 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1767 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1769 if (this.postTimestamps[i] < oneHour)
1770 this.postTimestamps.RemoveAt(i);
1773 // 自分のRTはTLの更新では取得できない場合があるので、
1774 // 投稿時取得の有無に関わらず追加しておく
1775 posts.ForEach(post => this.statuses.AddPost(post));
1777 if (this.settings.Common.PostAndGet)
1779 await this.RefreshTabAsync<HomeTabModel>();
1783 this.statuses.DistributePosts();
1784 this.RefreshTimeline();
1788 private async Task RefreshFollowerIdsAsync()
1790 await this.workerSemaphore.WaitAsync();
1794 this.RefreshTasktrayIcon();
1795 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1797 await this.tw.RefreshFollowerIds();
1799 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1801 this.RefreshTimeline();
1802 this.listCache?.PurgeCache();
1803 this.CurrentListView.Refresh();
1805 catch (WebApiException ex)
1807 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1811 this.workerSemaphore.Release();
1815 private async Task RefreshNoRetweetIdsAsync()
1817 await this.workerSemaphore.WaitAsync();
1821 this.RefreshTasktrayIcon();
1822 await this.tw.RefreshNoRetweetIds();
1824 this.StatusLabel.Text = "NoRetweetIds refreshed";
1826 catch (WebApiException ex)
1828 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1832 this.workerSemaphore.Release();
1836 private async Task RefreshBlockIdsAsync()
1838 await this.workerSemaphore.WaitAsync();
1842 this.RefreshTasktrayIcon();
1843 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1845 await this.tw.RefreshBlockIds();
1847 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1849 catch (WebApiException ex)
1851 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1855 this.workerSemaphore.Release();
1859 private async Task RefreshTwitterConfigurationAsync()
1861 await this.workerSemaphore.WaitAsync();
1865 this.RefreshTasktrayIcon();
1866 await this.tw.RefreshConfiguration();
1868 if (this.tw.Configuration.PhotoSizeLimit != 0)
1870 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1872 service.UpdateTwitterConfiguration(this.tw.Configuration);
1876 this.listCache?.PurgeCache();
1877 this.CurrentListView.Refresh();
1879 catch (WebApiException ex)
1881 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1885 this.workerSemaphore.Release();
1889 private async Task RefreshMuteUserIdsAsync()
1891 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1895 await this.tw.RefreshMuteUserIdsAsync();
1897 catch (WebApiException ex)
1899 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1903 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1906 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1908 if (e.Button == MouseButtons.Left)
1910 this.Visible = true;
1911 if (this.WindowState == FormWindowState.Minimized)
1913 this.WindowState = this.formWindowState;
1916 this.BringToFront();
1920 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1921 => await this.ListItemDoubleClickAction();
1923 private async Task ListItemDoubleClickAction()
1925 switch (this.settings.Common.ListDoubleClickAction)
1927 case MyCommon.ListItemDoubleClickActionType.Reply:
1928 this.MakeReplyText();
1930 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1931 this.MakeReplyText(atAll: true);
1933 case MyCommon.ListItemDoubleClickActionType.Favorite:
1934 await this.FavoriteChange(true);
1936 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1937 var post = this.CurrentPost;
1939 await this.ShowUserStatus(post.ScreenName, false);
1941 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
1942 await this.ShowUserTimeline();
1944 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
1945 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
1947 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
1948 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
1950 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
1951 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
1953 case MyCommon.ListItemDoubleClickActionType.None:
1960 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
1961 => await this.FavoriteChange(true);
1963 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
1964 => await this.FavoriteChange(false);
1966 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
1967 => await this.FavoritesRetweetOfficial();
1969 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
1970 => await this.FavoritesRetweetUnofficial();
1972 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
1974 var tab = this.CurrentTab;
1975 var posts = tab.SelectedPosts;
1977 // trueでFavAdd,falseでFavRemove
1978 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
1979 || !this.ExistCurrentPost) return;
1981 if (posts.Length > 1)
1986 // https://support.twitter.com/articles/76915#favoriting
1987 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
1988 this.doFavRetweetFlags = false;
1993 if (multiFavoriteChangeDialogEnable)
1995 var confirm = MessageBox.Show(
1996 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
1997 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
1998 MessageBoxButtons.OKCancel,
1999 MessageBoxIcon.Question);
2001 if (confirm == DialogResult.Cancel)
2009 var selectedPost = posts.Single();
2010 if (selectedPost.IsFav)
2012 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2016 await this.FavAddAsync(selectedPost.StatusId, tab);
2020 var selectedPosts = posts.Where(x => x.IsFav);
2021 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2022 if (statusIds.Length == 0)
2024 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2028 await this.FavRemoveAsync(statusIds, tab);
2032 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2034 var post = this.CurrentPost;
2036 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2038 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2041 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2043 if ((!this.initialLayout) && this.Visible)
2045 if (this.WindowState == FormWindowState.Normal)
2047 this.mySize = this.ClientSize;
2048 this.mySpDis = this.SplitContainer1.SplitterDistance;
2049 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2050 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2051 this.MarkSettingLocalModified();
2056 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2058 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2059 if (comparerMode == null)
2062 this.SetSortColumn(comparerMode.Value);
2066 /// 列インデックスからソートを行う ComparerMode を求める
2068 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2069 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2070 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2072 if (this.Use2ColumnsMode)
2073 return ComparerMode.Id;
2075 return columnIndex switch
2077 1 => ComparerMode.Nickname, // ニックネーム
2078 2 => ComparerMode.Data, // 本文
2079 3 => ComparerMode.Id, // 時刻=発言Id
2080 4 => ComparerMode.Name, // 名前
2081 7 => ComparerMode.Source, // Source
2082 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2087 /// 発言一覧の指定した位置の列でソートする
2089 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2090 private void SetSortColumnByDisplayIndex(int columnIndex)
2092 // 表示上の列の位置から ColumnHeader を求める
2093 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2094 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2099 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2100 if (comparerMode == null)
2103 this.SetSortColumn(comparerMode.Value);
2107 /// 発言一覧の最後列の項目でソートする
2109 private void SetSortLastColumn()
2111 // 表示上の最後列にある ColumnHeader を求める
2112 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2113 .OrderByDescending(x => x.DisplayIndex)
2116 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2117 if (comparerMode == null)
2120 this.SetSortColumn(comparerMode.Value);
2124 /// 発言一覧を指定された ComparerMode に基づいてソートする
2126 private void SetSortColumn(ComparerMode sortColumn)
2128 if (this.settings.Common.SortOrderLock)
2131 this.statuses.ToggleSortOrder(sortColumn);
2132 this.InitColumnText();
2134 var list = this.CurrentListView;
2135 if (this.Use2ColumnsMode)
2137 list.Columns[0].Text = this.columnText[0];
2138 list.Columns[1].Text = this.columnText[2];
2142 for (var i = 0; i <= 7; i++)
2144 list.Columns[i].Text = this.columnText[i];
2148 this.listCache?.PurgeCache();
2150 var tab = this.CurrentTab;
2151 var post = this.CurrentPost;
2152 if (tab.AllCount > 0 && post != null)
2154 var idx = tab.IndexOf(post.StatusId);
2157 this.SelectListItem(list, idx);
2158 list.EnsureVisible(idx);
2163 this.MarkSettingCommonModified();
2166 private void TweenMain_LocationChanged(object sender, EventArgs e)
2168 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2170 this.myLoc = this.DesktopLocation;
2171 this.MarkSettingLocalModified();
2175 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2177 var post = this.CurrentPost;
2178 if (!this.ExistCurrentPost)
2180 this.ReplyStripMenuItem.Enabled = false;
2181 this.ReplyAllStripMenuItem.Enabled = false;
2182 this.DMStripMenuItem.Enabled = false;
2183 this.TabMenuItem.Enabled = false;
2184 this.IDRuleMenuItem.Enabled = false;
2185 this.SourceRuleMenuItem.Enabled = false;
2186 this.ReadedStripMenuItem.Enabled = false;
2187 this.UnreadStripMenuItem.Enabled = false;
2188 this.AuthorContextMenuItem.Visible = false;
2189 this.RetweetedByContextMenuItem.Visible = false;
2193 this.ReplyStripMenuItem.Enabled = true;
2194 this.ReplyAllStripMenuItem.Enabled = true;
2195 this.DMStripMenuItem.Enabled = true;
2196 this.TabMenuItem.Enabled = true;
2197 this.IDRuleMenuItem.Enabled = true;
2198 this.SourceRuleMenuItem.Enabled = true;
2199 this.ReadedStripMenuItem.Enabled = true;
2200 this.UnreadStripMenuItem.Enabled = true;
2201 this.AuthorContextMenuItem.Visible = true;
2202 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2203 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2204 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2206 var tab = this.CurrentTab;
2207 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2209 this.FavAddToolStripMenuItem.Enabled = false;
2210 this.FavRemoveToolStripMenuItem.Enabled = false;
2211 this.StatusOpenMenuItem.Enabled = false;
2212 this.ShowRelatedStatusesMenuItem.Enabled = false;
2214 this.ReTweetStripMenuItem.Enabled = false;
2215 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2216 this.QuoteStripMenuItem.Enabled = false;
2217 this.FavoriteRetweetContextMenu.Enabled = false;
2218 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2222 this.FavAddToolStripMenuItem.Enabled = true;
2223 this.FavRemoveToolStripMenuItem.Enabled = true;
2224 this.StatusOpenMenuItem.Enabled = true;
2225 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2227 if (!post.CanRetweetBy(this.tw.UserId))
2229 this.ReTweetStripMenuItem.Enabled = false;
2230 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2231 this.QuoteStripMenuItem.Enabled = false;
2232 this.FavoriteRetweetContextMenu.Enabled = false;
2233 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2237 this.ReTweetStripMenuItem.Enabled = true;
2238 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2239 this.QuoteStripMenuItem.Enabled = true;
2240 this.FavoriteRetweetContextMenu.Enabled = true;
2241 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2245 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2247 this.RepliedStatusOpenMenuItem.Enabled = false;
2251 this.RepliedStatusOpenMenuItem.Enabled = true;
2254 if (this.ExistCurrentPost && post != null)
2256 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2257 if (post.RetweetedByUserId == this.tw.UserId)
2258 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2260 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2264 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2265 => this.MakeReplyText();
2267 private void DMStripMenuItem_Click(object sender, EventArgs e)
2268 => this.MakeDirectMessageText();
2270 private async Task DoStatusDelete()
2272 var posts = this.CurrentTab.SelectedPosts;
2273 if (posts.Length == 0)
2276 // 選択されたツイートの中に削除可能なものが一つでもあるか
2277 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2280 var ret = MessageBox.Show(
2282 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2283 Properties.Resources.DeleteStripMenuItem_ClickText2,
2284 MessageBoxButtons.OKCancel,
2285 MessageBoxIcon.Question);
2287 if (ret != DialogResult.OK)
2290 var currentListView = this.CurrentListView;
2291 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2293 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2295 Exception? lastException = null;
2296 foreach (var post in posts)
2298 if (!post.CanDeleteBy(this.tw.UserId))
2303 if (post.StatusId is TwitterDirectMessageId dmId)
2305 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2309 if (post.RetweetedByUserId == this.tw.UserId)
2311 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2313 await this.tw.DeleteRetweet(post);
2317 if (post.UserId == this.tw.UserId)
2319 if (post.RetweetedId != null)
2321 // 他人に RT された自分のツイート
2322 // => RT 元の自分のツイートを削除
2323 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2329 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2335 catch (WebApiException ex)
2341 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2344 if (lastException == null)
2345 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2347 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2349 using (ControlTransaction.Update(currentListView))
2351 this.listCache?.PurgeCache();
2352 this.listCache?.UpdateListSize();
2354 currentListView.SelectedIndices.Clear();
2356 var currentTab = this.CurrentTab;
2357 if (currentTab.AllCount != 0)
2360 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2361 selectedIndex = focusedIndex;
2363 selectedIndex = currentTab.AllCount - 1;
2365 currentListView.SelectedIndices.Add(selectedIndex);
2366 currentListView.EnsureVisible(selectedIndex);
2367 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2371 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2373 var tabPage = this.ListTab.TabPages[index];
2374 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2376 if (tabPage.ImageIndex == 0)
2377 tabPage.ImageIndex = -1; // タブアイコン
2381 if (!this.settings.Common.TabIconDisp)
2382 this.ListTab.Refresh();
2386 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2387 => await this.DoStatusDelete();
2389 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2391 using (ControlTransaction.Update(this.CurrentListView))
2393 var tab = this.CurrentTab;
2394 foreach (var statusId in tab.SelectedStatusIds)
2396 this.statuses.SetReadAllTab(statusId, read: true);
2397 var idx = tab.IndexOf(statusId);
2398 this.listCache?.RefreshStyle(idx);
2401 if (this.settings.Common.TabIconDisp)
2403 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2405 if (tab.UnreadCount == 0)
2407 var tabPage = this.ListTab.TabPages[index];
2408 if (tabPage.ImageIndex == 0)
2409 tabPage.ImageIndex = -1; // タブアイコン
2413 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2416 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2418 using (ControlTransaction.Update(this.CurrentListView))
2420 var tab = this.CurrentTab;
2421 foreach (var statusId in tab.SelectedStatusIds)
2423 this.statuses.SetReadAllTab(statusId, read: false);
2424 var idx = tab.IndexOf(statusId);
2425 this.listCache?.RefreshStyle(idx);
2428 if (this.settings.Common.TabIconDisp)
2430 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2432 if (tab.UnreadCount > 0)
2434 var tabPage = this.ListTab.TabPages[index];
2435 if (tabPage.ImageIndex == -1)
2436 tabPage.ImageIndex = 0; // タブアイコン
2440 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2443 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2444 => await this.DoRefresh();
2446 private async Task DoRefresh()
2447 => await this.RefreshTabAsync(this.CurrentTab);
2449 private async Task DoRefreshMore()
2450 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2452 private DialogResult ShowSettingDialog()
2454 using var settingDialog = new AppendSettingDialog();
2455 settingDialog.Icon = this.iconAssets.IconMain;
2456 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2458 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2460 DialogResult result;
2463 result = settingDialog.ShowDialog(this);
2467 return DialogResult.Abort;
2470 if (result == DialogResult.OK)
2472 lock (this.syncObject)
2474 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2481 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2484 var previousUserId = this.settings.Common.UserId;
2485 var oldIconCol = this.Use2ColumnsMode;
2487 if (this.ShowSettingDialog() == DialogResult.OK)
2489 lock (this.syncObject)
2491 this.settings.ApplySettings();
2493 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2494 this.tw.ClearAuthInfo();
2496 var account = this.settings.Common.SelectedAccount;
2497 if (account != null)
2498 this.tw.Initialize(account.GetTwitterCredential(), account.Username, account.UserId);
2500 this.tw.Initialize(new TwitterCredentialNone(), "", 0L);
2502 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2503 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2505 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2509 if (this.settings.Common.TabIconDisp)
2511 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2512 this.ListTab.DrawMode = TabDrawMode.Normal;
2513 this.ListTab.ImageList = this.TabImage;
2517 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2518 this.ListTab.DrawItem += this.ListTab_DrawItem;
2519 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2520 this.ListTab.ImageList = null;
2523 catch (Exception ex)
2525 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2526 ex.Data["IsTerminatePermission"] = false;
2532 if (!this.settings.Common.UnreadManage)
2534 this.ReadedStripMenuItem.Enabled = false;
2535 this.UnreadStripMenuItem.Enabled = false;
2536 if (this.settings.Common.TabIconDisp)
2538 foreach (TabPage myTab in this.ListTab.TabPages)
2540 myTab.ImageIndex = -1;
2546 this.ReadedStripMenuItem.Enabled = true;
2547 this.UnreadStripMenuItem.Enabled = true;
2550 catch (Exception ex)
2552 ex.Data["Instance"] = "ListTab(UnreadManage)";
2553 ex.Data["IsTerminatePermission"] = false;
2558 this.SetTabAlignment();
2560 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2562 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2563 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2564 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2566 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2567 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2568 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2569 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2571 var newTheme = new ThemeManager(this.settings.Local);
2572 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2573 this.tweetDetailsView.Theme = this.themeManager;
2574 if (this.listDrawer != null)
2575 this.listDrawer.Theme = this.themeManager;
2580 if (this.StatusText.Focused)
2581 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2583 this.StatusText.Font = this.themeManager.FontInputFont;
2584 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2586 catch (Exception ex)
2588 MessageBox.Show(ex.Message);
2593 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
2595 catch (Exception ex)
2597 ex.Data["Instance"] = "Font";
2598 ex.Data["IsTerminatePermission"] = false;
2604 if (this.settings.Common.TabIconDisp)
2606 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2608 var tabPage = this.ListTab.TabPages[index];
2609 if (tab.UnreadCount == 0)
2610 tabPage.ImageIndex = -1;
2612 tabPage.ImageIndex = 0;
2616 catch (Exception ex)
2618 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2619 ex.Data["IsTerminatePermission"] = false;
2625 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2627 foreach (TabPage tp in this.ListTab.TabPages)
2629 var lst = (DetailsListView)tp.Tag;
2631 using (ControlTransaction.Update(lst))
2633 lst.GridLines = this.settings.Common.ShowGrid;
2635 if (this.Use2ColumnsMode != oldIconCol)
2636 this.ResetColumns(lst);
2640 catch (Exception ex)
2642 ex.Data["Instance"] = "ListView(IconSize)";
2643 ex.Data["IsTerminatePermission"] = false;
2647 this.SetMainWindowTitle();
2648 this.SetNotifyIconText();
2650 this.listCache?.PurgeCache();
2651 this.CurrentListView.Refresh();
2652 this.ListTab.Refresh();
2654 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2655 if (this.settings.Common.HotkeyEnabled)
2657 // グローバルホットキーの登録。設定で変更可能にするかも
2658 var modKey = HookGlobalHotkey.ModKeys.None;
2659 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2660 modKey |= HookGlobalHotkey.ModKeys.Alt;
2661 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2662 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2663 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2664 modKey |= HookGlobalHotkey.ModKeys.Shift;
2665 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2666 modKey |= HookGlobalHotkey.ModKeys.Win;
2668 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2671 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2674 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2682 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2684 this.TopMost = this.settings.Common.AlwaysTop;
2685 this.SaveConfigsAll(false);
2687 if (this.tw.UserId != previousUserId)
2688 await this.DoGetFollowersMenu();
2694 private void SetTabAlignment()
2696 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2697 if (this.ListTab.Alignment == newAlignment) return;
2700 var currentListViewState = this.listViewState[this.CurrentTabName];
2701 currentListViewState.Save(this.ListLockMenuItem.Checked);
2703 this.ListTab.Alignment = newAlignment;
2705 currentListViewState.Restore(forceScroll: true);
2708 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2711 if (this.listDrawer != null)
2713 this.listDrawer.IconSize = iconSz;
2714 this.listDrawer.UpdateItemHeight();
2717 this.listCache?.PurgeCache();
2720 private void ResetColumns(DetailsListView list)
2722 using (ControlTransaction.Update(list))
2723 using (ControlTransaction.Layout(list, false))
2726 list.ColumnClick -= this.MyList_ColumnClick;
2727 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2728 list.ColumnReordered -= this.MyList_ColumnReordered;
2729 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2731 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2732 list.Columns.Clear();
2733 cols.ForEach(col => col.Dispose());
2736 this.InitColumns(list, true);
2738 list.ColumnClick += this.MyList_ColumnClick;
2739 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2740 list.ColumnReordered += this.MyList_ColumnReordered;
2741 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2745 public void AddNewTabForSearch(string searchWord)
2747 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2748 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2750 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2752 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2753 this.ListTab.SelectedIndex = tabIndex;
2758 var tabName = searchWord;
2759 for (var i = 0; i <= 100; i++)
2761 if (this.statuses.ContainsTab(tabName))
2767 var tab = new PublicSearchTabModel(tabName);
2768 this.statuses.AddTab(tab);
2769 this.AddNewTab(tab, startup: false);
2771 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2773 var tabPage = this.CurrentTabPage;
2774 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2775 cmb.Items.Add(searchWord);
2776 cmb.Text = searchWord;
2777 this.SaveConfigsTabs();
2779 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2782 private async Task ShowUserTimeline()
2784 var post = this.CurrentPost;
2785 if (post == null || !this.ExistCurrentPost) return;
2786 await this.AddNewTabForUserTimeline(post.ScreenName);
2789 private async Task ShowRetweeterTimeline()
2791 var retweetedBy = this.CurrentPost?.RetweetedBy;
2792 if (retweetedBy == null || !this.ExistCurrentPost) return;
2793 await this.AddNewTabForUserTimeline(retweetedBy);
2796 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2798 if (e.KeyCode == Keys.Escape)
2800 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2801 this.SaveConfigsTabs();
2802 e.SuppressKeyPress = true;
2806 public async Task AddNewTabForUserTimeline(string user)
2808 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2809 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2811 if (tb.ScreenName == user)
2813 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2814 this.ListTab.SelectedIndex = tabIndex;
2819 var tabName = "user:" + user;
2820 while (this.statuses.ContainsTab(tabName))
2825 var tab = new UserTimelineTabModel(tabName, user);
2826 this.statuses.AddTab(tab);
2827 this.AddNewTab(tab, startup: false);
2829 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2830 this.SaveConfigsTabs();
2832 await this.RefreshTabAsync(tab);
2835 public bool AddNewTab(TabModel tab, bool startup)
2838 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2842 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2844 var tabPage = new TabPage();
2845 var listCustom = new DetailsListView();
2847 var cnt = this.statuses.Tabs.Count;
2849 // ToDo:Create and set controls follow tabtypes
2851 using (ControlTransaction.Update(listCustom))
2852 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2853 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2854 using (ControlTransaction.Layout(this.SplitContainer1, false))
2855 using (ControlTransaction.Layout(this.ListTab, false))
2856 using (ControlTransaction.Layout(this))
2857 using (ControlTransaction.Layout(tabPage, false))
2859 tabPage.Controls.Add(listCustom);
2862 var userTab = tab as UserTimelineTabModel;
2863 var listTab = tab as ListTimelineTabModel;
2864 var searchTab = tab as PublicSearchTabModel;
2866 if (userTab != null || listTab != null)
2868 var label = new Label
2870 Dock = DockStyle.Top,
2875 if (listTab != null)
2877 label.Text = listTab.ListInfo.ToString();
2879 else if (userTab != null)
2881 label.Text = userTab.ScreenName + "'s Timeline";
2883 label.TextAlign = ContentAlignment.MiddleLeft;
2884 using (var tmpComboBox = new ComboBox())
2886 label.Height = tmpComboBox.Height;
2888 tabPage.Controls.Add(label);
2891 else if (searchTab != null)
2893 var pnl = new Panel();
2895 var lbl = new Label();
2896 var cmb = new ComboBox();
2897 var btn = new Button();
2898 var cmbLang = new ComboBox();
2900 using (ControlTransaction.Layout(pnl, false))
2902 pnl.Controls.Add(cmb);
2903 pnl.Controls.Add(cmbLang);
2904 pnl.Controls.Add(btn);
2905 pnl.Controls.Add(lbl);
2906 pnl.Name = "panelSearch";
2908 pnl.Dock = DockStyle.Top;
2909 pnl.Height = cmb.Height;
2910 pnl.Enter += this.SearchControls_Enter;
2911 pnl.Leave += this.SearchControls_Leave;
2914 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2915 cmb.Dock = DockStyle.Fill;
2916 cmb.Name = "comboSearch";
2917 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2918 cmb.ImeMode = ImeMode.NoControl;
2919 cmb.TabStop = false;
2921 cmb.AutoCompleteMode = AutoCompleteMode.None;
2922 cmb.KeyDown += this.SearchComboBox_KeyDown;
2925 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2926 cmbLang.Dock = DockStyle.Right;
2928 cmbLang.Name = "comboLang";
2929 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2930 cmbLang.TabStop = false;
2931 cmbLang.TabIndex = 2;
2932 cmbLang.Items.Add("");
2933 cmbLang.Items.Add("ja");
2934 cmbLang.Items.Add("en");
2935 cmbLang.Items.Add("ar");
2936 cmbLang.Items.Add("da");
2937 cmbLang.Items.Add("nl");
2938 cmbLang.Items.Add("fa");
2939 cmbLang.Items.Add("fi");
2940 cmbLang.Items.Add("fr");
2941 cmbLang.Items.Add("de");
2942 cmbLang.Items.Add("hu");
2943 cmbLang.Items.Add("is");
2944 cmbLang.Items.Add("it");
2945 cmbLang.Items.Add("no");
2946 cmbLang.Items.Add("pl");
2947 cmbLang.Items.Add("pt");
2948 cmbLang.Items.Add("ru");
2949 cmbLang.Items.Add("es");
2950 cmbLang.Items.Add("sv");
2951 cmbLang.Items.Add("th");
2953 lbl.Text = "Search(C-S-f)";
2954 lbl.Name = "label1";
2955 lbl.Dock = DockStyle.Left;
2957 lbl.Height = cmb.Height;
2958 lbl.TextAlign = ContentAlignment.MiddleLeft;
2961 btn.Text = "Search";
2962 btn.Name = "buttonSearch";
2963 btn.UseVisualStyleBackColor = true;
2964 btn.Dock = DockStyle.Right;
2965 btn.TabStop = false;
2967 btn.Click += this.SearchButton_Click;
2969 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
2971 cmb.Items.Add(searchTab.SearchWords);
2972 cmb.Text = searchTab.SearchWords;
2975 cmbLang.Text = searchTab.SearchLang;
2977 tabPage.Controls.Add(pnl);
2981 tabPage.Tag = listCustom;
2982 this.ListTab.Controls.Add(tabPage);
2984 tabPage.Location = new Point(4, 4);
2985 tabPage.Name = "CTab" + cnt;
2986 tabPage.Size = new Size(380, 260);
2987 tabPage.TabIndex = 2 + cnt;
2988 tabPage.Text = tab.TabName;
2989 tabPage.UseVisualStyleBackColor = true;
2990 tabPage.AccessibleRole = AccessibleRole.PageTab;
2992 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
2993 listCustom.TabIndex = 1;
2994 listCustom.AllowColumnReorder = true;
2995 listCustom.ContextMenuStrip = this.ContextMenuOperate;
2996 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
2997 listCustom.Dock = DockStyle.Fill;
2998 listCustom.FullRowSelect = true;
2999 listCustom.HideSelection = false;
3000 listCustom.Location = new Point(0, 0);
3001 listCustom.Margin = new Padding(0);
3002 listCustom.Name = "CList" + Environment.TickCount;
3003 listCustom.ShowItemToolTips = true;
3004 listCustom.Size = new Size(380, 260);
3005 listCustom.UseCompatibleStateImageBehavior = false;
3006 listCustom.View = View.Details;
3007 listCustom.OwnerDraw = true;
3008 listCustom.VirtualMode = true;
3010 listCustom.GridLines = this.settings.Common.ShowGrid;
3011 listCustom.AllowDrop = true;
3013 this.InitColumns(listCustom, startup);
3015 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3016 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3017 listCustom.ColumnClick += this.MyList_ColumnClick;
3018 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3019 listCustom.DragDrop += this.TweenMain_DragDrop;
3020 listCustom.DragEnter += this.TweenMain_DragEnter;
3021 listCustom.DragOver += this.TweenMain_DragOver;
3022 listCustom.MouseClick += this.MyList_MouseClick;
3023 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3024 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3025 listCustom.HScrolled += this.MyList_HScrolled;
3028 var state = new TimelineListViewState(listCustom, tab);
3029 this.listViewState[tab.TabName] = state;
3034 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3036 var tabInfo = this.statuses.GetTabByName(tabName);
3037 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3042 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3043 var result = MessageBox.Show(
3045 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3046 MessageBoxButtons.OKCancel,
3047 MessageBoxIcon.Question,
3048 MessageBoxDefaultButton.Button2);
3049 if (result == DialogResult.Cancel)
3055 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3059 var tabPage = this.ListTab.TabPages[tabIndex];
3061 this.SetListProperty(); // 他のタブに列幅等を反映
3063 this.listViewState.Remove(tabName);
3066 var listCustom = (DetailsListView)tabPage.Tag;
3069 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3070 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3071 using (ControlTransaction.Layout(this.SplitContainer1, false))
3072 using (ControlTransaction.Layout(this.ListTab, false))
3073 using (ControlTransaction.Layout(this))
3074 using (ControlTransaction.Layout(tabPage, false))
3076 if (this.CurrentTabName == tabName)
3078 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3079 this.beforeSelectedTab = null;
3081 this.ListTab.Controls.Remove(tabPage);
3084 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3086 using var label = tabPage.Controls["labelUser"];
3087 tabPage.Controls.Remove(label);
3089 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3091 using var pnl = tabPage.Controls["panelSearch"];
3093 pnl.Enter -= this.SearchControls_Enter;
3094 pnl.Leave -= this.SearchControls_Leave;
3095 tabPage.Controls.Remove(pnl);
3097 foreach (Control ctrl in pnl.Controls)
3099 if (ctrl.Name == "buttonSearch")
3101 ctrl.Click -= this.SearchButton_Click;
3103 else if (ctrl.Name == "comboSearch")
3105 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3107 pnl.Controls.Remove(ctrl);
3112 tabPage.Controls.Remove(listCustom);
3114 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3115 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3116 listCustom.ColumnClick -= this.MyList_ColumnClick;
3117 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3118 listCustom.DragDrop -= this.TweenMain_DragDrop;
3119 listCustom.DragEnter -= this.TweenMain_DragEnter;
3120 listCustom.DragOver -= this.TweenMain_DragOver;
3121 listCustom.MouseClick -= this.MyList_MouseClick;
3122 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3123 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3124 listCustom.HScrolled -= this.MyList_HScrolled;
3126 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3127 listCustom.Columns.Clear();
3128 cols.ForEach(col => col.Dispose());
3131 listCustom.ContextMenuStrip = null;
3132 listCustom.ColumnHeaderContextMenuStrip = null;
3133 listCustom.Font = null;
3135 listCustom.SmallImageList = null;
3136 listCustom.ListViewItemSorter = null;
3139 this.listCache?.PurgeCache();
3143 listCustom.Dispose();
3144 this.statuses.RemoveTab(tabName);
3149 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3151 this.listCache?.PurgeCache();
3152 this.beforeSelectedTab = e.TabPage;
3155 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3159 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3162 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3163 if (!dragEnableRectangle.Contains(e.Location))
3165 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3166 tn = this.CurrentTabName;
3169 if (MyCommon.IsNullOrEmpty(tn)) return;
3171 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3174 var tabPage = this.ListTab.TabPages[tabIndex];
3175 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3180 this.tabDrag = false;
3183 var cpos = new Point(e.X, e.Y);
3184 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3186 var rect = this.ListTab.GetTabRect(index);
3187 if (rect.Contains(cpos))
3189 this.rclickTabName = tab.TabName;
3195 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3197 this.SetMainWindowTitle();
3198 this.SetStatusLabelUrl();
3199 this.SetApiStatusLabel();
3200 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3201 this.Tag = this.ListTab.Tag;
3202 this.TabMenuControl(this.CurrentTabName);
3203 this.PushSelectPostChain();
3204 this.DispSelectedPost();
3207 private void SetListProperty()
3209 if (!this.isColumnChanged) return;
3211 var currentListView = this.CurrentListView;
3213 var dispOrder = new int[currentListView.Columns.Count];
3214 for (var i = 0; i < currentListView.Columns.Count; i++)
3216 for (var j = 0; j < currentListView.Columns.Count; j++)
3218 if (currentListView.Columns[j].DisplayIndex == i)
3227 foreach (TabPage tb in this.ListTab.TabPages)
3229 if (tb.Text == this.CurrentTabName)
3232 if (tb.Tag != null && tb.Controls.Count > 0)
3234 var lst = (DetailsListView)tb.Tag;
3235 for (var i = 0; i < lst.Columns.Count; i++)
3237 lst.Columns[dispOrder[i]].DisplayIndex = i;
3238 lst.Columns[i].Width = currentListView.Columns[i].Width;
3243 this.isColumnChanged = false;
3246 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3248 if (e.KeyChar == '@')
3250 if (!this.settings.Common.UseAtIdSupplement) return;
3252 var cnt = this.AtIdSupl.ItemCount;
3253 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3254 if (cnt != this.AtIdSupl.ItemCount)
3255 this.MarkSettingAtIdModified();
3258 else if (e.KeyChar == '#')
3260 if (!this.settings.Common.UseHashSupplement) return;
3261 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3266 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3267 => this.ShowSuplDialog(owner, dialog, 0, "");
3269 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3270 => this.ShowSuplDialog(owner, dialog, offset, "");
3272 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3274 dialog.StartsWith = startswith;
3281 dialog.ShowDialog();
3283 this.TopMost = this.settings.Common.AlwaysTop;
3284 var selStart = owner.SelectionStart;
3287 if (dialog.DialogResult == DialogResult.OK)
3289 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3293 fHalf = owner.Text.Substring(0, selStart - offset);
3295 if (selStart < owner.Text.Length)
3297 eHalf = owner.Text.Substring(selStart);
3299 owner.Text = fHalf + dialog.InputText + eHalf;
3300 owner.SelectionStart = selStart + dialog.InputText.Length;
3307 fHalf = owner.Text.Substring(0, selStart);
3309 if (selStart < owner.Text.Length)
3311 eHalf = owner.Text.Substring(selStart);
3313 owner.Text = fHalf + eHalf;
3316 owner.SelectionStart = selStart;
3322 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3325 if (!e.Alt && !e.Control && !e.Shift)
3327 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3329 var isSpace = false;
3330 foreach (var c in this.StatusText.Text)
3332 if (c == ' ' || c == ' ')
3345 this.StatusText.Text = "";
3346 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3350 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3353 private void StatusText_TextChanged(object sender, EventArgs e)
3356 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3357 this.lblLen.Text = pLen.ToString();
3360 this.StatusText.ForeColor = Color.Red;
3364 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3367 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3369 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3371 this.inReplyTo = null;
3376 /// メンション以外の文字列が含まれていないテキストであるか判定します
3378 internal static bool TextContainsOnlyMentions(string text)
3380 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3383 foreach (var mention in mentions)
3385 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3387 if (!string.IsNullOrWhiteSpace(textPart))
3390 startIndex = mention.Indices[1];
3393 var textPartLast = text.Substring(startIndex);
3395 if (!string.IsNullOrWhiteSpace(textPartLast))
3402 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3404 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3406 var autoPopulatedUserIdList = new List<long>();
3408 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3409 if (replyToPost != null)
3411 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3413 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3414 autoPopulatedUserIdList.Add(replyToPost.UserId);
3416 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3418 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3420 statusText = statusText.Substring(screenName.Length + 2);
3421 autoPopulatedUserIdList.Add(userId);
3427 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3433 /// attachment_url に指定可能な URL が含まれていれば除去
3435 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3437 attachmentUrl = null;
3439 // attachment_url は media_id と同時に使用できない
3440 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3443 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3447 attachmentUrl = match.Value;
3450 statusText = statusText.Substring(0, match.Index);
3452 // テキストと URL の間にスペースが含まれていれば除去
3453 return statusText.TrimEnd(' ');
3456 private string FormatStatusTextExtended(string statusText)
3457 => this.FormatStatusTextExtended(statusText, out _, out _);
3460 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3462 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3464 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3466 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3468 return this.FormatStatusText(statusText);
3471 internal string FormatStatusText(string statusText)
3472 => this.FormatStatusText(statusText, Control.ModifierKeys);
3475 /// ツイート投稿前のフッター付与などの前処理を行います
3477 internal string FormatStatusText(string statusText, Keys modifierKeys)
3479 statusText = statusText.Replace("\r\n", "\n");
3481 if (this.SeparateUrlAndFullwidthCharacter)
3484 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3487 if (this.settings.Common.WideSpaceConvert)
3489 // 文中の全角スペースを半角スペース1個にする
3490 statusText = statusText.Replace(" ", " ");
3493 // DM の場合はこれ以降の処理を行わない
3494 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3498 if (this.settings.Common.PostShiftEnter)
3500 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3504 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3505 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3507 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3510 if (statusText.Contains("RT @"))
3511 disableFooter = true;
3513 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3514 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3516 var mentionSelf = $"@{this.tw.Username} ";
3517 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3519 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3520 statusText = statusText.Substring(mentionSelf.Length);
3527 var hashtag = this.HashMgr.UseHash;
3528 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3530 if (this.HashMgr.IsHead)
3531 header = this.HashMgr.UseHash + " ";
3533 footer = " " + this.HashMgr.UseHash;
3538 if (this.settings.Local.UseRecommendStatus)
3541 footer += this.recommendedStatusFooter;
3543 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3545 // テキストボックスに入力されている文字列を使用する
3546 footer += " " + this.settings.Local.StatusText.Trim();
3550 statusText = header + statusText + footer;
3552 if (this.preventSmsCommand)
3554 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3555 // 参照: https://support.twitter.com/articles/14020
3557 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3558 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3560 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3561 statusText = '\u200b' + statusText;
3569 /// 投稿欄に表示する入力可能な文字数を計算します
3571 private int GetRestStatusCount(string statusText)
3573 var remainCount = this.tw.GetTextLengthRemain(statusText);
3575 var uploadService = this.GetSelectedImageService();
3576 if (uploadService != null)
3578 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3579 remainCount -= uploadService.GetReservedTextLength(1);
3585 private IMediaUploadService? GetSelectedImageService()
3586 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3589 /// 全てのタブの振り分けルールを反映し直します
3591 private void ApplyPostFilters()
3593 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3595 this.statuses.FilterAll();
3597 var listView = this.CurrentListView;
3598 using (ControlTransaction.Update(listView))
3600 this.listCache?.PurgeCache();
3601 this.listCache?.UpdateListSize();
3604 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3606 var tabPage = this.ListTab.TabPages[index];
3608 if (this.settings.Common.TabIconDisp)
3610 if (tab.UnreadCount > 0)
3611 tabPage.ImageIndex = 0;
3613 tabPage.ImageIndex = -1;
3617 if (!this.settings.Common.TabIconDisp)
3618 this.ListTab.Refresh();
3620 this.SetMainWindowTitle();
3621 this.SetStatusLabelUrl();
3625 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3626 => e.DrawDefault = true;
3628 private void MyList_HScrolled(object sender, EventArgs e)
3629 => ((DetailsListView)sender).Refresh();
3631 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3633 base.ScaleControl(factor, specified);
3635 ScaleChildControl(this.TabImage, factor);
3637 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3638 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3640 foreach (var listview in listviews)
3642 ScaleChildControl(listview, factor);
3646 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3648 var tab = this.CurrentTab;
3650 if (tab.AllCount == 0)
3652 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3656 var selectedIndex = tab.SelectedIndex;
3661 case SEARCHTYPE.NextSearch: // 次を検索
3662 if (selectedIndex != -1)
3663 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3667 case SEARCHTYPE.PrevSearch: // 前を検索
3668 if (selectedIndex != -1)
3669 startIndex = Math.Max(selectedIndex - 1, 0);
3671 startIndex = tab.AllCount - 1;
3673 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3675 if (selectedIndex != -1)
3676 startIndex = selectedIndex;
3682 Func<string, bool> stringComparer;
3685 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3687 catch (ArgumentException)
3689 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3693 var reverse = searchType == SEARCHTYPE.PrevSearch;
3694 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3695 .DefaultIfEmpty(-1).First();
3697 if (foundIndex == -1)
3699 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3703 var listView = this.CurrentListView;
3704 this.SelectListItem(listView, foundIndex);
3705 listView.EnsureVisible(foundIndex);
3708 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3709 => this.ShowSearchDialog(); // 検索メニュー
3711 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3713 var previousSearch = this.SearchDialog.ResultOptions;
3714 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3716 this.SearchDialog.Reset();
3717 this.ShowSearchDialog();
3723 previousSearch.Query,
3724 previousSearch.CaseSensitive,
3725 previousSearch.UseRegex,
3726 SEARCHTYPE.NextSearch);
3729 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3731 var previousSearch = this.SearchDialog.ResultOptions;
3732 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3734 this.SearchDialog.Reset();
3735 this.ShowSearchDialog();
3741 previousSearch.Query,
3742 previousSearch.CaseSensitive,
3743 previousSearch.UseRegex,
3744 SEARCHTYPE.PrevSearch);
3748 /// 検索ダイアログを表示し、検索を実行します
3750 private void ShowSearchDialog()
3752 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3754 this.TopMost = this.settings.Common.AlwaysTop;
3757 this.TopMost = this.settings.Common.AlwaysTop;
3759 var searchOptions = this.SearchDialog.ResultOptions!;
3760 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3762 if (searchOptions.NewTab)
3764 var tabName = Properties.Resources.SearchResults_TabName;
3768 tabName = this.statuses.MakeTabName(tabName);
3770 catch (TabException ex)
3772 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3775 var resultTab = new LocalSearchTabModel(tabName);
3776 this.AddNewTab(resultTab, startup: false);
3777 this.statuses.AddTab(resultTab);
3779 var targetTab = this.CurrentTab;
3781 Func<string, bool> stringComparer;
3784 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3786 catch (ArgumentException)
3788 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3792 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3793 if (foundIndices.Length == 0)
3795 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3799 var foundPosts = foundIndices.Select(x => targetTab[x]);
3800 foreach (var post in foundPosts)
3802 resultTab.AddPostQueue(post);
3805 this.statuses.DistributePosts();
3806 this.RefreshTimeline();
3808 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3809 this.ListTab.SelectedIndex = tabIndex;
3814 searchOptions.Query,
3815 searchOptions.CaseSensitive,
3816 searchOptions.UseRegex,
3817 SEARCHTYPE.DialogSearch);
3820 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3822 this.AddNewTabForSearch(searchOptions.Query);
3826 /// <summary>発言検索に使用するメソッドを生成します</summary>
3827 /// <exception cref="ArgumentException">
3828 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3830 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3834 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3835 var regex = new Regex(query, regexOption);
3837 return x => regex.IsMatch(x);
3841 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3843 return x => x.IndexOf(query, comparisonType) != -1;
3847 private void AboutMenuItem_Click(object sender, EventArgs e)
3849 using (var about = new TweenAboutBox())
3851 about.ShowDialog(this);
3853 this.TopMost = this.settings.Common.AlwaysTop;
3856 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3858 var bgnIdx = this.statuses.SelectedTabIndex;
3860 if (this.ImageSelector.Enabled)
3863 TabModel? foundTab = null;
3867 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3869 var unreadIndex = tab.NextUnreadIndex;
3870 if (unreadIndex != -1)
3872 this.ListTab.SelectedIndex = index;
3874 foundIndex = unreadIndex;
3879 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3880 if (foundTab == null && bgnIdx > 0)
3882 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3884 var unreadIndex = tab.NextUnreadIndex;
3885 if (unreadIndex != -1)
3887 this.ListTab.SelectedIndex = index;
3889 foundIndex = unreadIndex;
3895 DetailsListView lst;
3897 if (foundTab == null)
3899 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3900 this.ListTab.SelectedIndex = 0;
3901 var tabPage = this.ListTab.TabPages[0];
3902 var tab = this.statuses.Tabs[0];
3904 if (tab.AllCount == 0)
3907 if (this.statuses.SortOrder == SortOrder.Ascending)
3908 foundIndex = tab.AllCount - 1;
3912 lst = (DetailsListView)tabPage.Tag;
3916 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3917 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3920 this.SelectListItem(lst, foundIndex);
3922 if (this.statuses.SortMode == ComparerMode.Id)
3924 var rowHeight = lst.SmallImageList.ImageSize.Height;
3925 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3926 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3932 lst.EnsureVisible(foundIndex);
3937 lst.EnsureVisible(foundIndex);
3943 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
3945 var tab = this.CurrentTab;
3946 var post = this.CurrentPost;
3947 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
3948 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
3951 private async void VerUpMenuItem_Click(object sender, EventArgs e)
3952 => await this.CheckNewVersion(false);
3954 private void RunTweenUp()
3956 var pinfo = new ProcessStartInfo
3958 UseShellExecute = true,
3959 WorkingDirectory = this.settings.SettingsPath,
3960 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
3961 Arguments = "\"" + Application.StartupPath + "\"",
3966 Process.Start(pinfo);
3970 MessageBox.Show("Failed to execute TweenUp3.exe.");
3974 public readonly record struct VersionInfo(
3981 /// OpenTween の最新バージョンの情報を取得します
3983 public async Task<VersionInfo> GetVersionInfoAsync()
3985 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
3986 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
3988 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
3989 .ConfigureAwait(false);
3991 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
3992 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
3994 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
3995 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
3997 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
3999 return new VersionInfo
4001 Version = Version.Parse(msgHeader[0]),
4002 DownloadUri = new Uri(msgHeader[1]),
4003 ReleaseNote = msgBody,
4007 private async Task CheckNewVersion(bool startup = false)
4009 if (ApplicationSettings.VersionInfoUrl == null)
4010 return; // 更新チェック無効化
4014 var versionInfo = await this.GetVersionInfoAsync();
4016 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4021 var msgtext = string.Format(
4022 Properties.Resources.CheckNewVersionText7,
4023 MyCommon.GetReadableVersion(),
4024 MyCommon.GetReadableVersion(versionInfo.Version));
4025 msgtext = MyCommon.ReplaceAppName(msgtext);
4029 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4030 MessageBoxButtons.OK,
4031 MessageBoxIcon.Information);
4036 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4039 using var dialog = new UpdateDialog();
4041 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4042 MyCommon.GetReadableVersion(versionInfo.Version));
4043 dialog.DetailsText = versionInfo.ReleaseNote;
4045 if (dialog.ShowDialog(this) == DialogResult.Yes)
4047 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4049 else if (dialog.SkipButtonPressed)
4051 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4052 this.MarkSettingCommonModified();
4057 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4061 Properties.Resources.CheckNewVersionText10,
4062 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4063 MessageBoxButtons.OK,
4064 MessageBoxIcon.Exclamation,
4065 MessageBoxDefaultButton.Button2);
4070 private void UpdateSelectedPost()
4072 // 件数関連の場合、タイトル即時書き換え
4073 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4074 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4075 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4076 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4078 this.SetMainWindowTitle();
4080 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4081 this.SetStatusLabelUrl();
4083 if (this.settings.Common.TabIconDisp)
4085 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4087 if (tab.UnreadCount == 0)
4089 var tabPage = this.ListTab.TabPages[index];
4090 if (tabPage.ImageIndex == 0)
4091 tabPage.ImageIndex = -1;
4097 this.ListTab.Refresh();
4100 this.DispSelectedPost();
4103 private void DispSelectedPost()
4104 => this.DispSelectedPost(false);
4106 private PostClass displayPost = new();
4109 /// サムネイル表示に使用する CancellationToken の生成元
4111 private CancellationTokenSource? thumbnailTokenSource = null;
4113 private void DispSelectedPost(bool forceupdate)
4115 var currentPost = this.CurrentPost;
4116 if (currentPost == null)
4119 var oldDisplayPost = this.displayPost;
4120 this.displayPost = currentPost;
4122 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4125 var loadTasks = new TaskCollection();
4126 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4128 if (this.settings.Common.PreviewEnable)
4130 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4131 oldTokenSource?.Cancel();
4133 var token = this.thumbnailTokenSource!.Token;
4134 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4138 this.SplitContainer3.Panel2Collapsed = true;
4141 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4143 .IgnoreException(x => x is OperationCanceledException)
4147 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4149 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4151 var timeout = Task.Delay(100);
4152 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4154 token.ThrowIfCancellationRequested();
4156 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4157 this.SplitContainer3.Panel2Collapsed = true;
4161 token.ThrowIfCancellationRequested();
4163 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4166 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4167 => await this.OpenApplicationWebsite();
4169 private async Task OpenApplicationWebsite()
4170 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4172 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4173 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4175 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4177 var tab = this.CurrentTab;
4178 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4180 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4181 if (pnl.Controls["comboSearch"].Focused ||
4182 pnl.Controls["comboLang"].Focused ||
4183 pnl.Controls["buttonSearch"].Focused) return;
4186 if (e.Control || e.Shift || e.Alt)
4189 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4192 e.SuppressKeyPress = true;
4195 if (asyncTask != null)
4199 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4201 private void InitializeShortcuts()
4203 this.shortcutCommands = new[]
4205 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4206 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4207 .FocusedOn(FocusedControl.ListTab)
4208 .Do(() => SendKeys.Send("{DOWN}")),
4210 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4211 .FocusedOn(FocusedControl.ListTab)
4212 .Do(() => SendKeys.Send("{UP}")),
4214 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4215 .FocusedOn(FocusedControl.ListTab)
4216 .Do(() => SendKeys.Send("{PGDN}")),
4218 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4219 .FocusedOn(FocusedControl.ListTab)
4220 .Do(() => SendKeys.Send("{PGUP}")),
4222 ShortcutCommand.Create(Keys.F1)
4223 .Do(() => this.OpenApplicationWebsite()),
4225 ShortcutCommand.Create(Keys.F3)
4226 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4228 ShortcutCommand.Create(Keys.F5)
4229 .Do(() => this.DoRefresh()),
4231 ShortcutCommand.Create(Keys.F6)
4232 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4234 ShortcutCommand.Create(Keys.F7)
4235 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4237 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4238 .NotFocusedOn(FocusedControl.StatusText)
4241 this.CurrentTab.ClearAnchor();
4242 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4245 ShortcutCommand.Create(Keys.G)
4246 .NotFocusedOn(FocusedControl.StatusText)
4249 this.CurrentTab.ClearAnchor();
4250 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4253 ShortcutCommand.Create(Keys.Right, Keys.N)
4254 .FocusedOn(FocusedControl.ListTab)
4255 .Do(() => this.GoRelPost(forward: true)),
4257 ShortcutCommand.Create(Keys.Left, Keys.P)
4258 .FocusedOn(FocusedControl.ListTab)
4259 .Do(() => this.GoRelPost(forward: false)),
4261 ShortcutCommand.Create(Keys.OemPeriod)
4262 .FocusedOn(FocusedControl.ListTab)
4263 .Do(() => this.GoAnchor()),
4265 ShortcutCommand.Create(Keys.I)
4266 .FocusedOn(FocusedControl.ListTab)
4267 .OnlyWhen(() => this.StatusText.Enabled)
4268 .Do(() => this.StatusText.Focus()),
4270 ShortcutCommand.Create(Keys.Enter)
4271 .FocusedOn(FocusedControl.ListTab)
4272 .Do(() => this.ListItemDoubleClickAction()),
4274 ShortcutCommand.Create(Keys.R)
4275 .FocusedOn(FocusedControl.ListTab)
4276 .Do(() => this.DoRefresh()),
4278 ShortcutCommand.Create(Keys.L)
4279 .FocusedOn(FocusedControl.ListTab)
4282 this.CurrentTab.ClearAnchor();
4283 this.GoPost(forward: true);
4286 ShortcutCommand.Create(Keys.H)
4287 .FocusedOn(FocusedControl.ListTab)
4290 this.CurrentTab.ClearAnchor();
4291 this.GoPost(forward: false);
4294 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4295 .FocusedOn(FocusedControl.ListTab)
4298 this.CurrentTab.ClearAnchor();
4302 ShortcutCommand.Create(Keys.S)
4303 .FocusedOn(FocusedControl.ListTab)
4306 this.CurrentTab.ClearAnchor();
4307 this.GoNextTab(forward: true);
4310 ShortcutCommand.Create(Keys.A)
4311 .FocusedOn(FocusedControl.ListTab)
4314 this.CurrentTab.ClearAnchor();
4315 this.GoNextTab(forward: false);
4318 // ] in_reply_to参照元へ戻る
4319 ShortcutCommand.Create(Keys.Oem4)
4320 .FocusedOn(FocusedControl.ListTab)
4323 this.CurrentTab.ClearAnchor();
4324 return this.GoInReplyToPostTree();
4327 // [ in_reply_toへジャンプ
4328 ShortcutCommand.Create(Keys.Oem6)
4329 .FocusedOn(FocusedControl.ListTab)
4332 this.CurrentTab.ClearAnchor();
4333 this.GoBackInReplyToPostTree();
4336 ShortcutCommand.Create(Keys.Escape)
4337 .FocusedOn(FocusedControl.ListTab)
4340 this.CurrentTab.ClearAnchor();
4341 var tab = this.CurrentTab;
4342 var tabtype = tab.TabType;
4343 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4345 this.RemoveSpecifiedTab(tab.TabName, false);
4346 this.SaveConfigsTabs();
4350 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4351 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4352 .FocusedOn(FocusedControl.ListTab)
4353 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4355 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4356 ShortcutCommand.Create(Keys.Up, Keys.Down)
4357 .FocusedOn(FocusedControl.PostBrowser)
4360 ShortcutCommand.Create(Keys.Control | Keys.R)
4361 .Do(() => this.MakeReplyText()),
4363 ShortcutCommand.Create(Keys.Control | Keys.D)
4364 .Do(() => this.DoStatusDelete()),
4366 ShortcutCommand.Create(Keys.Control | Keys.M)
4367 .Do(() => this.MakeDirectMessageText()),
4369 ShortcutCommand.Create(Keys.Control | Keys.S)
4370 .Do(() => this.FavoriteChange(favAdd: true)),
4372 ShortcutCommand.Create(Keys.Control | Keys.I)
4373 .Do(() => this.DoRepliedStatusOpen()),
4375 ShortcutCommand.Create(Keys.Control | Keys.Q)
4376 .Do(() => this.DoQuoteOfficial()),
4378 ShortcutCommand.Create(Keys.Control | Keys.B)
4379 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4381 ShortcutCommand.Create(Keys.Control | Keys.T)
4382 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4384 ShortcutCommand.Create(Keys.Control | Keys.L)
4385 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4387 ShortcutCommand.Create(Keys.Control | Keys.Y)
4388 .NotFocusedOn(FocusedControl.PostBrowser)
4389 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4391 ShortcutCommand.Create(Keys.Control | Keys.F)
4392 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4394 ShortcutCommand.Create(Keys.Control | Keys.U)
4395 .Do(() => this.ShowUserTimeline()),
4397 ShortcutCommand.Create(Keys.Control | Keys.H)
4398 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4400 ShortcutCommand.Create(Keys.Control | Keys.O)
4401 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4403 ShortcutCommand.Create(Keys.Control | Keys.E)
4404 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4406 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4407 .FocusedOn(FocusedControl.ListTab)
4408 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4410 ShortcutCommand.Create(Keys.Control | Keys.N)
4411 .FocusedOn(FocusedControl.ListTab)
4412 .Do(() => this.GoNextTab(forward: true)),
4414 ShortcutCommand.Create(Keys.Control | Keys.P)
4415 .FocusedOn(FocusedControl.ListTab)
4416 .Do(() => this.GoNextTab(forward: false)),
4418 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4419 .FocusedOn(FocusedControl.ListTab)
4420 .Do(() => this.CopyStot()),
4422 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4423 ShortcutCommand.Create(Keys.Control | Keys.D1)
4424 .FocusedOn(FocusedControl.ListTab)
4425 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4426 .Do(() => this.ListTab.SelectedIndex = 0),
4428 ShortcutCommand.Create(Keys.Control | Keys.D2)
4429 .FocusedOn(FocusedControl.ListTab)
4430 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4431 .Do(() => this.ListTab.SelectedIndex = 1),
4433 ShortcutCommand.Create(Keys.Control | Keys.D3)
4434 .FocusedOn(FocusedControl.ListTab)
4435 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4436 .Do(() => this.ListTab.SelectedIndex = 2),
4438 ShortcutCommand.Create(Keys.Control | Keys.D4)
4439 .FocusedOn(FocusedControl.ListTab)
4440 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4441 .Do(() => this.ListTab.SelectedIndex = 3),
4443 ShortcutCommand.Create(Keys.Control | Keys.D5)
4444 .FocusedOn(FocusedControl.ListTab)
4445 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4446 .Do(() => this.ListTab.SelectedIndex = 4),
4448 ShortcutCommand.Create(Keys.Control | Keys.D6)
4449 .FocusedOn(FocusedControl.ListTab)
4450 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4451 .Do(() => this.ListTab.SelectedIndex = 5),
4453 ShortcutCommand.Create(Keys.Control | Keys.D7)
4454 .FocusedOn(FocusedControl.ListTab)
4455 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4456 .Do(() => this.ListTab.SelectedIndex = 6),
4458 ShortcutCommand.Create(Keys.Control | Keys.D8)
4459 .FocusedOn(FocusedControl.ListTab)
4460 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4461 .Do(() => this.ListTab.SelectedIndex = 7),
4463 ShortcutCommand.Create(Keys.Control | Keys.D9)
4464 .FocusedOn(FocusedControl.ListTab)
4465 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4467 ShortcutCommand.Create(Keys.Control | Keys.A)
4468 .FocusedOn(FocusedControl.StatusText)
4469 .Do(() => this.StatusText.SelectAll()),
4471 ShortcutCommand.Create(Keys.Control | Keys.V)
4472 .FocusedOn(FocusedControl.StatusText)
4473 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4475 ShortcutCommand.Create(Keys.Control | Keys.Up)
4476 .FocusedOn(FocusedControl.StatusText)
4477 .Do(() => this.StatusTextHistoryBack()),
4479 ShortcutCommand.Create(Keys.Control | Keys.Down)
4480 .FocusedOn(FocusedControl.StatusText)
4481 .Do(() => this.StatusTextHistoryForward()),
4483 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4484 .FocusedOn(FocusedControl.StatusText)
4487 if (this.ListTab.SelectedIndex == 0)
4489 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4493 this.ListTab.SelectedIndex -= 1;
4495 this.StatusText.Focus();
4498 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4499 .FocusedOn(FocusedControl.StatusText)
4502 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4504 this.ListTab.SelectedIndex = 0;
4508 this.ListTab.SelectedIndex += 1;
4510 this.StatusText.Focus();
4513 ShortcutCommand.Create(Keys.Control | Keys.Y)
4514 .FocusedOn(FocusedControl.PostBrowser)
4517 var multiline = !this.settings.Local.StatusMultiline;
4518 this.settings.Local.StatusMultiline = multiline;
4519 this.MultiLineMenuItem.Checked = multiline;
4520 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4523 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4524 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4526 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4527 .Do(() => this.DoRefreshMore()),
4529 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4530 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4532 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4533 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4535 ShortcutCommand.Create(Keys.Shift | Keys.R)
4536 .NotFocusedOn(FocusedControl.StatusText)
4537 .Do(() => this.DoRefreshMore()),
4539 ShortcutCommand.Create(Keys.Shift | Keys.H)
4540 .FocusedOn(FocusedControl.ListTab)
4541 .Do(() => this.GoTopEnd(goTop: true)),
4543 ShortcutCommand.Create(Keys.Shift | Keys.L)
4544 .FocusedOn(FocusedControl.ListTab)
4545 .Do(() => this.GoTopEnd(goTop: false)),
4547 ShortcutCommand.Create(Keys.Shift | Keys.M)
4548 .FocusedOn(FocusedControl.ListTab)
4549 .Do(() => this.GoMiddle()),
4551 ShortcutCommand.Create(Keys.Shift | Keys.G)
4552 .FocusedOn(FocusedControl.ListTab)
4553 .Do(() => this.GoLast()),
4555 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4556 .FocusedOn(FocusedControl.ListTab)
4557 .Do(() => this.MoveMiddle()),
4559 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4560 .FocusedOn(FocusedControl.ListTab)
4561 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4563 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4564 .FocusedOn(FocusedControl.ListTab)
4565 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4567 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4568 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4569 .FocusedOn(FocusedControl.ListTab)
4570 .Do(() => this.GoFav(forward: true)),
4572 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4573 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4574 .FocusedOn(FocusedControl.ListTab)
4575 .Do(() => this.GoFav(forward: false)),
4577 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4578 .FocusedOn(FocusedControl.ListTab)
4579 .Do(() => this.GoBackSelectPostChain()),
4581 ShortcutCommand.Create(Keys.Alt | Keys.R)
4582 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4584 ShortcutCommand.Create(Keys.Alt | Keys.P)
4585 .OnlyWhen(() => this.CurrentPost != null)
4586 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4588 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4589 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4591 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4592 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4594 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4595 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4597 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4598 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4600 // 別タブの同じ書き込みへ(ALT+←/→)
4601 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4602 .FocusedOn(FocusedControl.ListTab)
4603 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4605 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4606 .FocusedOn(FocusedControl.ListTab)
4607 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4609 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4610 .Do(() => this.MakeReplyText(atAll: true)),
4612 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4613 .Do(() => this.CopyIdUri()),
4615 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4616 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4617 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4619 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4620 .Do(() => this.DoQuoteOfficial()),
4622 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4623 .Do(() => this.FavoriteChange(favAdd: false)),
4625 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4626 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4628 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4629 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4631 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4632 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4634 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4635 .Do(() => this.DoMoveToRTHome()),
4637 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4638 .FocusedOn(FocusedControl.StatusText)
4641 var tab = this.CurrentTab;
4642 var selectedIndex = tab.SelectedIndex;
4643 if (selectedIndex != -1 && selectedIndex > 0)
4645 var listView = this.CurrentListView;
4646 var idx = selectedIndex - 1;
4647 this.SelectListItem(listView, idx);
4648 listView.EnsureVisible(idx);
4652 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4653 .FocusedOn(FocusedControl.StatusText)
4656 var tab = this.CurrentTab;
4657 var selectedIndex = tab.SelectedIndex;
4658 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4660 var listView = this.CurrentListView;
4661 var idx = selectedIndex + 1;
4662 this.SelectListItem(listView, idx);
4663 listView.EnsureVisible(idx);
4667 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4668 .FocusedOn(FocusedControl.StatusText)
4671 if (this.StatusText.SelectionStart > 0)
4673 var endidx = this.StatusText.SelectionStart - 1;
4675 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4677 var c = this.StatusText.Text[i];
4678 if (char.IsLetterOrDigit(c) || c == '_')
4684 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4685 var cnt = this.AtIdSupl.ItemCount;
4686 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4687 if (this.AtIdSupl.ItemCount != cnt)
4688 this.MarkSettingAtIdModified();
4692 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4693 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4703 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4704 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4705 .FocusedOn(FocusedControl.ListTab)
4706 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4708 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4709 .FocusedOn(FocusedControl.ListTab)
4710 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4712 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4713 .FocusedOn(FocusedControl.ListTab)
4714 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4716 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4717 .FocusedOn(FocusedControl.ListTab)
4718 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4720 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4721 .FocusedOn(FocusedControl.ListTab)
4722 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4724 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4725 .FocusedOn(FocusedControl.ListTab)
4726 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4728 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4729 .FocusedOn(FocusedControl.ListTab)
4730 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4732 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4733 .FocusedOn(FocusedControl.ListTab)
4734 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4736 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4737 .FocusedOn(FocusedControl.ListTab)
4738 .Do(() => this.SetSortLastColumn()),
4740 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4741 .FocusedOn(FocusedControl.ListTab)
4742 .Do(() => this.FavoritesRetweetOfficial()),
4744 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4745 .FocusedOn(FocusedControl.ListTab)
4746 .Do(() => this.FavoritesRetweetUnofficial()),
4748 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4749 .FocusedOn(FocusedControl.ListTab)
4750 .Do(() => this.OpenUserAppointUrl()),
4752 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4753 .FocusedOn(FocusedControl.PostBrowser)
4754 .Do(() => this.DoReTweetUnofficial()),
4756 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4757 .OnlyWhen(() => this.ExistCurrentPost)
4758 .Do(() => this.tweetDetailsView.DoTranslation()),
4760 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4761 .Do(() => this.DoReTweetUnofficial()),
4763 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4764 .Do(() => this.CopyUserId()),
4766 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4767 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4769 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4770 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4772 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4773 .FocusedOn(FocusedControl.ListTab)
4774 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4775 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4779 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4781 // Task を返す非同期処理があれば asyncTask に代入する
4784 // ShortcutCommand に対応しているコマンドはここで処理される
4785 foreach (var command in this.shortcutCommands)
4787 if (command.IsMatch(keyData, focusedOn))
4789 asyncTask = command.RunCommand();
4790 return command.PreventDefault;
4797 private void GoNextTab(bool forward)
4799 var idx = this.statuses.SelectedTabIndex;
4800 var tabCount = this.statuses.Tabs.Count;
4804 if (idx > tabCount - 1) idx = 0;
4809 if (idx < 0) idx = tabCount - 1;
4811 this.ListTab.SelectedIndex = idx;
4814 private void CopyStot()
4816 var sb = new StringBuilder();
4817 var tab = this.CurrentTab;
4818 var isProtected = false;
4819 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4820 foreach (var post in tab.SelectedPosts)
4822 if (post.IsDeleted) continue;
4825 if (post.RetweetedId != null)
4826 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4828 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4832 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4837 MessageBox.Show(Properties.Resources.CopyStotText1);
4841 var clstr = sb.ToString();
4844 Clipboard.SetDataObject(clstr, false, 5, 100);
4846 catch (Exception ex)
4848 MessageBox.Show(ex.Message);
4853 private void CopyIdUri()
4855 var tab = this.CurrentTab;
4856 if (tab == null || tab is DirectMessagesTabModel)
4859 var copyUrls = new List<string>();
4860 foreach (var post in tab.SelectedPosts)
4861 copyUrls.Add(MyCommon.GetStatusUrl(post));
4863 if (copyUrls.Count == 0)
4868 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4870 catch (ExternalException ex)
4872 MessageBox.Show(ex.Message);
4876 private void GoFav(bool forward)
4878 var tab = this.CurrentTab;
4879 if (tab.AllCount == 0)
4882 var selectedIndex = tab.SelectedIndex;
4890 if (selectedIndex == -1)
4896 fIdx = selectedIndex + 1;
4897 if (fIdx > tab.AllCount - 1)
4900 toIdx = tab.AllCount;
4905 if (selectedIndex == -1)
4907 fIdx = tab.AllCount - 1;
4911 fIdx = selectedIndex - 1;
4919 for (var idx = fIdx; idx != toIdx; idx += stp)
4923 var listView = this.CurrentListView;
4924 this.SelectListItem(listView, idx);
4925 listView.EnsureVisible(idx);
4931 private void GoSamePostToAnotherTab(bool left)
4933 var tab = this.CurrentTab;
4935 // Directタブは対象外(見つかるはずがない)
4936 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4939 var selectedStatusId = tab.SelectedStatusId;
4940 if (selectedStatusId == null)
4943 int fIdx, toIdx, stp;
4948 if (this.ListTab.SelectedIndex == 0)
4954 fIdx = this.ListTab.SelectedIndex - 1;
4962 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4968 fIdx = this.ListTab.SelectedIndex + 1;
4970 toIdx = this.ListTab.TabCount;
4974 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
4976 var targetTab = this.statuses.Tabs[tabidx];
4979 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
4982 var foundIndex = targetTab.IndexOf(selectedStatusId);
4983 if (foundIndex != -1)
4985 this.ListTab.SelectedIndex = tabidx;
4986 var listView = this.CurrentListView;
4987 this.SelectListItem(listView, foundIndex);
4988 listView.EnsureVisible(foundIndex);
4994 private void GoPost(bool forward)
4996 var tab = this.CurrentTab;
4997 var currentPost = this.CurrentPost;
4999 if (currentPost == null)
5002 var selectedIndex = tab.SelectedIndex;
5004 int fIdx, toIdx, stp;
5008 fIdx = selectedIndex + 1;
5009 if (fIdx > tab.AllCount - 1) return;
5010 toIdx = tab.AllCount;
5015 fIdx = selectedIndex - 1;
5016 if (fIdx < 0) return;
5022 if (currentPost.RetweetedBy == null)
5024 name = currentPost.ScreenName;
5028 name = currentPost.RetweetedBy;
5030 for (var idx = fIdx; idx != toIdx; idx += stp)
5032 var post = tab[idx];
5033 if (post.RetweetedId == null)
5035 if (post.ScreenName == name)
5037 var listView = this.CurrentListView;
5038 this.SelectListItem(listView, idx);
5039 listView.EnsureVisible(idx);
5045 if (post.RetweetedBy == name)
5047 var listView = this.CurrentListView;
5048 this.SelectListItem(listView, idx);
5049 listView.EnsureVisible(idx);
5056 private void GoRelPost(bool forward)
5058 var tab = this.CurrentTab;
5059 var selectedIndex = tab.SelectedIndex;
5061 if (selectedIndex == -1)
5064 int fIdx, toIdx, stp;
5068 fIdx = selectedIndex + 1;
5069 if (fIdx > tab.AllCount - 1) return;
5070 toIdx = tab.AllCount;
5075 fIdx = selectedIndex - 1;
5076 if (fIdx < 0) return;
5081 var anchorPost = tab.AnchorPost;
5082 if (anchorPost == null)
5084 var currentPost = this.CurrentPost;
5085 if (currentPost == null)
5088 anchorPost = currentPost;
5089 tab.AnchorPost = currentPost;
5092 for (var idx = fIdx; idx != toIdx; idx += stp)
5094 var post = tab[idx];
5095 if (post.ScreenName == anchorPost.ScreenName ||
5096 post.RetweetedBy == anchorPost.ScreenName ||
5097 post.ScreenName == anchorPost.RetweetedBy ||
5098 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5099 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5100 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5101 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5102 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5104 var listView = this.CurrentListView;
5105 this.SelectListItem(listView, idx);
5106 listView.EnsureVisible(idx);
5112 private void GoAnchor()
5114 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5115 if (anchorStatusId == null)
5118 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5122 var listView = this.CurrentListView;
5123 this.SelectListItem(listView, idx);
5124 listView.EnsureVisible(idx);
5127 private void GoTopEnd(bool goTop)
5129 var listView = this.CurrentListView;
5130 if (listView.VirtualListSize == 0)
5138 item = listView.GetItemAt(0, 25);
5146 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5148 idx = listView.VirtualListSize - 1;
5152 this.SelectListItem(listView, idx);
5155 private void GoMiddle()
5157 var listView = this.CurrentListView;
5158 if (listView.VirtualListSize == 0)
5166 item = listView.GetItemAt(0, 0);
5176 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5179 idx2 = listView.VirtualListSize - 1;
5185 idx3 = (idx1 + idx2) / 2;
5187 this.SelectListItem(listView, idx3);
5190 private void GoLast()
5192 var listView = this.CurrentListView;
5193 if (listView.VirtualListSize == 0) return;
5195 if (this.statuses.SortOrder == SortOrder.Ascending)
5197 this.SelectListItem(listView, listView.VirtualListSize - 1);
5198 listView.EnsureVisible(listView.VirtualListSize - 1);
5202 this.SelectListItem(listView, 0);
5203 listView.EnsureVisible(0);
5207 private void MoveTop()
5209 var listView = this.CurrentListView;
5210 if (listView.SelectedIndices.Count == 0) return;
5211 var idx = listView.SelectedIndices[0];
5212 if (this.statuses.SortOrder == SortOrder.Ascending)
5214 listView.EnsureVisible(listView.VirtualListSize - 1);
5218 listView.EnsureVisible(0);
5220 listView.EnsureVisible(idx);
5223 private async Task GoInReplyToPostTree()
5225 var curTabClass = this.CurrentTab;
5226 var currentPost = this.CurrentPost;
5228 if (currentPost == null)
5231 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5235 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5237 currentPost = currentPost with
5239 InReplyToStatusId = post.InReplyToStatusId,
5240 InReplyToUser = post.InReplyToUser,
5241 IsReply = post.IsReply,
5243 curTabClass.ReplacePost(currentPost);
5244 this.listCache?.PurgeCache();
5246 var index = curTabClass.SelectedIndex;
5247 this.CurrentListView.RedrawItems(index, index, false);
5249 catch (WebApiException ex)
5251 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5255 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5257 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5259 this.replyChains = new Stack<ReplyChain>();
5261 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5264 string inReplyToTabName;
5265 var inReplyToId = currentPost.InReplyToStatusId;
5266 var inReplyToUser = currentPost.InReplyToUser;
5268 var inReplyToPosts = from tab in this.statuses.Tabs
5269 orderby tab != curTabClass
5270 from post in tab.Posts.Values
5271 where post.StatusId == inReplyToId
5272 let index = tab.IndexOf(post.StatusId)
5274 select new { Tab = tab, Index = index };
5276 var inReplyPost = inReplyToPosts.FirstOrDefault();
5277 if (inReplyPost == null)
5281 await Task.Run(async () =>
5283 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5284 .ConfigureAwait(false);
5287 this.statuses.AddPost(post);
5288 this.statuses.DistributePosts();
5291 catch (WebApiException ex)
5293 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5294 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5298 this.RefreshTimeline();
5300 inReplyPost = inReplyToPosts.FirstOrDefault();
5301 if (inReplyPost == null)
5303 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5307 inReplyToTabName = inReplyPost.Tab.TabName;
5308 inReplyToIndex = inReplyPost.Index;
5310 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5311 var tabPage = this.ListTab.TabPages[tabIndex];
5312 var listView = (DetailsListView)tabPage.Tag;
5314 if (this.CurrentTabName != inReplyToTabName)
5316 this.ListTab.SelectedIndex = tabIndex;
5319 this.SelectListItem(listView, inReplyToIndex);
5320 listView.EnsureVisible(inReplyToIndex);
5323 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5325 var curTabClass = this.CurrentTab;
5326 var currentPost = this.CurrentPost;
5328 if (currentPost == null)
5333 if (currentPost.InReplyToStatusId != null)
5335 var posts = from t in this.statuses.Tabs
5337 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5338 let indexOf = t.IndexOf(p.Value.StatusId)
5340 orderby isForward ? indexOf : indexOf * -1
5341 orderby t != curTabClass
5342 select new { Tab = t, Post = p.Value, Index = indexOf };
5345 var postList = posts.ToList();
5346 for (var i = postList.Count - 1; i >= 0; i--)
5349 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5351 postList.RemoveAt(index);
5354 var currentIndex = this.CurrentTab.SelectedIndex;
5355 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5356 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5357 if (post == null) post = postList.First();
5358 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5359 this.ListTab.SelectedIndex = tabIndex;
5360 var listView = this.CurrentListView;
5361 this.SelectListItem(listView, post.Index);
5362 listView.EnsureVisible(post.Index);
5364 catch (InvalidOperationException)
5372 if (this.replyChains == null || this.replyChains.Count < 1)
5374 var posts = from t in this.statuses.Tabs
5376 where p.Value.InReplyToStatusId == currentPost.StatusId
5377 let indexOf = t.IndexOf(p.Value.StatusId)
5380 orderby t != curTabClass
5381 select new { Tab = t, Index = indexOf };
5384 var post = posts.First();
5385 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5386 this.ListTab.SelectedIndex = tabIndex;
5387 var listView = this.CurrentListView;
5388 this.SelectListItem(listView, post.Index);
5389 listView.EnsureVisible(post.Index);
5391 catch (InvalidOperationException)
5398 var chainHead = this.replyChains.Pop();
5399 if (chainHead.InReplyToId == currentPost.StatusId)
5401 var tab = chainHead.OriginalTab;
5402 if (!this.statuses.Tabs.Contains(tab))
5404 this.replyChains = null;
5408 var idx = tab.IndexOf(chainHead.OriginalId);
5411 this.replyChains = null;
5415 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5418 this.ListTab.SelectedIndex = tabIndex;
5422 this.replyChains = null;
5424 var listView = this.CurrentListView;
5425 this.SelectListItem(listView, idx);
5426 listView.EnsureVisible(idx);
5432 this.replyChains = null;
5433 this.GoBackInReplyToPostTree(parallel);
5439 private void GoBackSelectPostChain()
5441 if (this.selectPostChains.Count > 1)
5444 TabModel? foundTab = null;
5450 this.selectPostChains.Pop();
5451 var (tab, post) = this.selectPostChains.Peek();
5453 if (!this.statuses.Tabs.Contains(tab))
5454 continue; // 該当タブが存在しないので無視
5458 idx = tab.IndexOf(post.StatusId);
5459 if (idx == -1) continue; // 該当ポストが存在しないので無視
5464 this.selectPostChains.Pop();
5466 catch (InvalidOperationException)
5472 while (this.selectPostChains.Count > 1);
5474 if (foundTab == null)
5477 // 履歴が残り1つであればクリアしておく
5478 if (this.selectPostChains.Count == 1)
5479 this.selectPostChains.Clear();
5483 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5484 var tabPage = this.ListTab.TabPages[tabIndex];
5485 var lst = (DetailsListView)tabPage.Tag;
5486 this.ListTab.SelectedIndex = tabIndex;
5490 this.SelectListItem(lst, idx);
5491 lst.EnsureVisible(idx);
5497 private void PushSelectPostChain()
5499 var currentTab = this.CurrentTab;
5500 var currentPost = this.CurrentPost;
5502 var count = this.selectPostChains.Count;
5505 var (tab, post) = this.selectPostChains.Peek();
5506 if (tab == currentTab)
5508 if (post == currentPost) return; // 最新の履歴と同一
5509 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5512 if (count >= 2500) this.TrimPostChain();
5513 this.selectPostChains.Push((currentTab, currentPost));
5516 private void TrimPostChain()
5518 if (this.selectPostChains.Count <= 2000) return;
5519 var p = new Stack<(TabModel, PostClass?)>(2000);
5520 for (var i = 0; i < 2000; i++)
5522 p.Push(this.selectPostChains.Pop());
5524 this.selectPostChains.Clear();
5525 for (var i = 0; i < 2000; i++)
5527 this.selectPostChains.Push(p.Pop());
5531 private bool GoStatus(PostId statusId)
5533 var tab = this.statuses.Tabs
5534 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5535 .Where(x => x.Contains(statusId))
5541 var index = tab.IndexOf(statusId);
5543 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5544 this.ListTab.SelectedIndex = tabIndex;
5546 var listView = this.CurrentListView;
5547 this.SelectListItem(listView, index);
5548 listView.EnsureVisible(index);
5553 private bool GoDirectMessage(PostId statusId)
5555 var tab = this.statuses.DirectMessageTab;
5556 var index = tab.IndexOf(statusId);
5561 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5562 this.ListTab.SelectedIndex = tabIndex;
5564 var listView = this.CurrentListView;
5565 this.SelectListItem(listView, index);
5566 listView.EnsureVisible(index);
5571 private void MyList_MouseClick(object sender, MouseEventArgs e)
5572 => this.CurrentTab.ClearAnchor();
5574 private void StatusText_Enter(object sender, EventArgs e)
5576 // フォーカスの戻り先を StatusText に設定
5577 this.Tag = this.StatusText;
5578 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5581 public Color InputBackColor
5582 => this.themeManager.ColorInputBackcolor;
5584 private void StatusText_Leave(object sender, EventArgs e)
5586 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5587 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5588 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5591 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5593 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5596 e.SuppressKeyPress = true;
5599 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5601 if (asyncTask != null)
5605 private void SaveConfigsAll(bool ifModified)
5609 this.SaveConfigsCommon();
5610 this.SaveConfigsLocal();
5611 this.SaveConfigsTabs();
5612 this.SaveConfigsAtId();
5616 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5617 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5618 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5622 private void SaveConfigsAtId()
5624 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5626 this.ModifySettingAtId = false;
5627 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5628 this.settings.SaveAtIdList();
5631 private void SaveConfigsCommon()
5633 if (this.ignoreConfigSave) return;
5635 this.ModifySettingCommon = false;
5636 lock (this.syncObject)
5638 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5639 this.settings.Common.SortColumn = this.statuses.SortMode switch
5641 ComparerMode.Nickname => 1, // ニックネーム
5642 ComparerMode.Data => 2, // 本文
5643 ComparerMode.Id => 3, // 時刻=発言Id
5644 ComparerMode.Name => 4, // 名前
5645 ComparerMode.Source => 7, // Source
5646 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5648 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5649 if (this.HashMgr.IsPermanent)
5651 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5655 this.settings.Common.HashSelected = "";
5657 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5658 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5659 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5660 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5661 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5663 this.settings.SaveCommon();
5667 private void SaveConfigsLocal()
5669 if (this.ignoreConfigSave) return;
5670 lock (this.syncObject)
5672 this.ModifySettingLocal = false;
5673 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5674 this.settings.Local.FormSize = this.mySize;
5675 this.settings.Local.FormLocation = this.myLoc;
5676 this.settings.Local.SplitterDistance = this.mySpDis;
5677 this.settings.Local.PreviewDistance = this.mySpDis3;
5678 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5679 this.settings.Local.StatusTextHeight = this.mySpDis2;
5681 if (this.ignoreConfigSave) return;
5682 this.settings.SaveLocal();
5686 private void SaveConfigsTabs()
5688 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5690 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5692 foreach (var tab in tabs)
5694 if (!tab.IsPermanentTabType)
5697 var tabSetting = new SettingTabs.SettingTabItem
5699 TabName = tab.TabName,
5700 TabType = tab.TabType,
5701 UnreadManage = tab.UnreadManage,
5702 Protected = tab.Protected,
5703 Notify = tab.Notify,
5704 SoundFile = tab.SoundFile,
5709 case FilterTabModel filterTab:
5710 tabSetting.FilterArray = filterTab.FilterArray;
5712 case UserTimelineTabModel userTab:
5713 tabSetting.User = userTab.ScreenName;
5714 tabSetting.UserId = userTab.UserId;
5716 case PublicSearchTabModel searchTab:
5717 tabSetting.SearchWords = searchTab.SearchWords;
5718 tabSetting.SearchLang = searchTab.SearchLang;
5720 case ListTimelineTabModel listTab:
5721 tabSetting.ListInfo = listTab.ListInfo;
5725 tabSettingList.Add(tabSetting);
5728 this.settings.Tabs.Tabs = tabSettingList;
5729 this.settings.SaveTabs();
5732 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5734 static void ShowFormatErrorDialog(IWin32Window owner)
5738 Properties.Resources.OpenURL_InvalidFormat,
5739 Properties.Resources.OpenURL_Caption,
5740 MessageBoxButtons.OK,
5741 MessageBoxIcon.Error
5745 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5746 if (ret != DialogResult.OK)
5749 var match = Twitter.StatusUrlRegex.Match(inputText);
5752 ShowFormatErrorDialog(this);
5758 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5759 await this.OpenRelatedTab(statusId);
5761 catch (OverflowException)
5763 ShowFormatErrorDialog(this);
5765 catch (TabException ex)
5767 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5771 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5773 var tab = this.CurrentTab;
5775 var rslt = MessageBox.Show(
5776 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5777 Properties.Resources.SaveLogMenuItem_ClickText2,
5778 MessageBoxButtons.YesNoCancel,
5779 MessageBoxIcon.Question);
5780 if (rslt == DialogResult.Cancel) return;
5782 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5783 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5784 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5785 this.SaveFileDialog1.FilterIndex = 0;
5786 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5787 this.SaveFileDialog1.RestoreDirectory = true;
5789 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5791 if (!this.SaveFileDialog1.ValidateNames) return;
5792 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5793 if (rslt == DialogResult.Yes)
5796 for (var idx = 0; idx < tab.AllCount; idx++)
5798 var post = tab[idx];
5801 protect = "Protect";
5802 sw.WriteLine(post.Nickname + "\t" +
5803 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5804 post.CreatedAt.ToLocalTimeString() + "\t" +
5805 post.ScreenName + "\t" +
5806 post.StatusId.Id + "\t" +
5807 post.ImageUrl + "\t" +
5808 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5814 foreach (var post in this.CurrentTab.SelectedPosts)
5818 protect = "Protect";
5819 sw.WriteLine(post.Nickname + "\t" +
5820 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5821 post.CreatedAt.ToLocalTimeString() + "\t" +
5822 post.ScreenName + "\t" +
5823 post.StatusId.Id + "\t" +
5824 post.ImageUrl + "\t" +
5825 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5830 this.TopMost = this.settings.Common.AlwaysTop;
5833 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5837 using (var inputName = new InputTabName())
5839 inputName.TabName = origTabName;
5840 inputName.ShowDialog();
5841 if (inputName.DialogResult == DialogResult.Cancel) return false;
5842 newTabName = inputName.TabName;
5844 this.TopMost = this.settings.Common.AlwaysTop;
5845 if (!MyCommon.IsNullOrEmpty(newTabName))
5848 if (this.statuses.ContainsTab(newTabName))
5850 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5851 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5855 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5856 var tabPage = this.ListTab.TabPages[tabIndex];
5859 if (tabPage != null)
5860 tabPage.Text = newTabName;
5862 this.statuses.RenameTab(origTabName, newTabName);
5864 var state = this.listViewState[origTabName];
5865 this.listViewState.Remove(origTabName);
5866 this.listViewState[newTabName] = state;
5868 this.SaveConfigsCommon();
5869 this.SaveConfigsTabs();
5870 this.rclickTabName = newTabName;
5879 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5881 if (e.Button == MouseButtons.Middle)
5883 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5885 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5887 this.RemoveSpecifiedTab(tab.TabName, true);
5888 this.SaveConfigsTabs();
5895 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5896 => this.TabRename(this.CurrentTabName, out _);
5898 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5900 if (this.settings.Common.TabMouseLock) return;
5901 if (e.Button == MouseButtons.Left)
5903 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5905 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5907 this.tabDrag = true;
5908 this.tabMouseDownPoint = e.Location;
5915 this.tabDrag = false;
5919 private void ListTab_DragEnter(object sender, DragEventArgs e)
5921 if (e.Data.GetDataPresent(typeof(TabPage)))
5922 e.Effect = DragDropEffects.Move;
5924 e.Effect = DragDropEffects.None;
5927 private void ListTab_DragDrop(object sender, DragEventArgs e)
5929 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5931 this.tabDrag = false;
5934 var cpos = new Point(e.X, e.Y);
5935 var spos = this.ListTab.PointToClient(cpos);
5936 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5938 var rect = this.ListTab.GetTabRect(index);
5939 if (rect.Contains(spos))
5942 if (spos.X <= (rect.Left + rect.Right) / 2)
5951 // タブのないところにドロップ->最後尾へ移動
5952 if (MyCommon.IsNullOrEmpty(tn))
5954 var lastTab = this.statuses.Tabs.Last();
5955 tn = lastTab.TabName;
5959 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
5960 if (tp.Text == tn) return;
5962 this.ReOrderTab(tp.Text, tn, bef);
5965 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
5967 var baseIndex = this.GetTabPageIndex(baseTabText);
5968 if (baseIndex == -1)
5971 var targetIndex = this.GetTabPageIndex(targetTabText);
5972 if (targetIndex == -1)
5975 using (ControlTransaction.Layout(this.ListTab))
5977 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
5978 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
5979 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
5980 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
5982 var tab = this.statuses.Tabs[targetIndex];
5983 var tabPage = this.ListTab.TabPages[targetIndex];
5985 this.ListTab.TabPages.Remove(tabPage);
5987 if (targetIndex < baseIndex)
5990 if (!isBeforeBaseTab)
5993 this.statuses.MoveTab(baseIndex, tab);
5995 this.ListTab.TabPages.Insert(baseIndex, tabPage);
5998 this.SaveConfigsTabs();
6001 private void MakeDirectMessageText()
6003 var selectedPosts = this.CurrentTab.SelectedPosts;
6004 if (selectedPosts.Length > 1)
6007 var post = selectedPosts.Single();
6008 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6010 this.inReplyTo = null;
6011 this.StatusText.Text = text;
6012 this.StatusText.SelectionStart = text.Length;
6013 this.StatusText.Focus();
6016 private void MakeReplyText(bool atAll = false)
6018 var selectedPosts = this.CurrentTab.SelectedPosts;
6019 if (selectedPosts.Any(x => x.IsDm))
6021 this.MakeDirectMessageText();
6025 if (selectedPosts.Length == 1)
6027 var post = selectedPosts.Single();
6028 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6029 var inReplyToScreenName = post.ScreenName;
6030 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6034 this.inReplyTo = null;
6037 var selfScreenName = this.tw.Username;
6038 var targetScreenNames = new List<string>();
6039 foreach (var post in selectedPosts)
6041 if (post.ScreenName != selfScreenName)
6042 targetScreenNames.Add(post.ScreenName);
6046 foreach (var (_, screenName) in post.ReplyToList)
6048 if (screenName != selfScreenName)
6049 targetScreenNames.Add(screenName);
6054 if (this.inReplyTo != null)
6056 var (_, screenName) = this.inReplyTo.Value;
6057 if (screenName == selfScreenName)
6058 targetScreenNames.Insert(0, screenName);
6061 var text = this.StatusText.Text;
6062 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6064 var atText = $"@{screenName} ";
6065 if (!text.Contains(atText))
6066 text = atText + text;
6069 this.StatusText.Text = text;
6070 this.StatusText.SelectionStart = text.Length;
6071 this.StatusText.Focus();
6074 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6075 => this.tabDrag = false;
6077 private int iconCnt = 0;
6078 private int blinkCnt = 0;
6079 private bool blink = false;
6081 private void RefreshTasktrayIcon()
6083 void EnableTasktrayAnimation()
6084 => this.TimerRefreshIcon.Enabled = true;
6086 void DisableTasktrayAnimation()
6087 => this.TimerRefreshIcon.Enabled = false;
6089 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6093 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6096 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6097 this.myStatusError = false;
6098 EnableTasktrayAnimation();
6102 var replyIconType = this.settings.Common.ReplyIconState;
6104 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6106 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6107 if (replyTab != null && replyTab.UnreadCount > 0)
6111 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6114 if (this.blinkCnt > 10)
6117 if (this.blinkCnt == 0)
6118 this.blink = !this.blink;
6120 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6121 EnableTasktrayAnimation();
6125 DisableTasktrayAnimation();
6131 // 優先度:リプライ→エラー→オフライン→アイドル
6132 // エラーは更新アイコンでクリアされる
6133 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6134 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6135 else if (this.myStatusError)
6136 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6137 else if (this.myStatusOnline)
6138 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6140 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6143 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6144 => this.RefreshTasktrayIcon(); // 200ms
6146 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6148 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6149 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6150 this.rclickTabName = this.CurrentTabName;
6152 if (this.statuses == null) return;
6153 if (this.statuses.Tabs == null) return;
6155 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6158 this.NotifyDispMenuItem.Checked = tb.Notify;
6159 this.NotifyTbMenuItem.Checked = tb.Notify;
6161 this.soundfileListup = true;
6162 this.SoundFileComboBox.Items.Clear();
6163 this.SoundFileTbComboBox.Items.Clear();
6164 this.SoundFileComboBox.Items.Add("");
6165 this.SoundFileTbComboBox.Items.Add("");
6166 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6167 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6169 oDir = oDir.GetDirectories("Sounds")[0];
6171 foreach (var oFile in oDir.GetFiles("*.wav"))
6173 this.SoundFileComboBox.Items.Add(oFile.Name);
6174 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6176 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6177 if (idx == -1) idx = 0;
6178 this.SoundFileComboBox.SelectedIndex = idx;
6179 this.SoundFileTbComboBox.SelectedIndex = idx;
6180 this.soundfileListup = false;
6181 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6182 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6184 this.TabMenuControl(this.rclickTabName);
6187 private void TabMenuControl(string tabName)
6189 var tabInfo = this.statuses.GetTabByName(tabName)!;
6191 this.FilterEditMenuItem.Enabled = true;
6192 this.EditRuleTbMenuItem.Enabled = true;
6194 if (tabInfo.IsDefaultTabType)
6196 this.ProtectTabMenuItem.Enabled = false;
6197 this.ProtectTbMenuItem.Enabled = false;
6201 this.ProtectTabMenuItem.Enabled = true;
6202 this.ProtectTbMenuItem.Enabled = true;
6205 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6207 this.ProtectTabMenuItem.Checked = true;
6208 this.ProtectTbMenuItem.Checked = true;
6209 this.DeleteTabMenuItem.Enabled = false;
6210 this.DeleteTbMenuItem.Enabled = false;
6214 this.ProtectTabMenuItem.Checked = false;
6215 this.ProtectTbMenuItem.Checked = false;
6216 this.DeleteTabMenuItem.Enabled = true;
6217 this.DeleteTbMenuItem.Enabled = true;
6221 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6223 var checkState = ((ToolStripMenuItem)sender).Checked;
6226 this.ProtectTbMenuItem.Checked = checkState;
6227 this.ProtectTabMenuItem.Checked = checkState;
6230 this.DeleteTabMenuItem.Enabled = !checkState;
6231 this.DeleteTbMenuItem.Enabled = !checkState;
6233 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6234 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6236 this.SaveConfigsTabs();
6239 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6241 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6242 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6244 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6245 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6247 this.SaveConfigsTabs();
6250 public void ChangeTabUnreadManage(string tabName, bool isManage)
6252 var idx = this.GetTabPageIndex(tabName);
6256 var tab = this.statuses.Tabs[tabName];
6257 tab.UnreadManage = isManage;
6259 if (this.settings.Common.TabIconDisp)
6261 var tabPage = this.ListTab.TabPages[idx];
6262 if (tab.UnreadCount > 0)
6263 tabPage.ImageIndex = 0;
6265 tabPage.ImageIndex = -1;
6268 if (this.CurrentTabName == tabName)
6270 this.listCache?.PurgeCache();
6271 this.CurrentListView.Refresh();
6274 this.SetMainWindowTitle();
6275 this.SetStatusLabelUrl();
6276 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6279 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6281 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6282 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6284 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6286 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6288 this.SaveConfigsTabs();
6291 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6293 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6295 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6297 this.SaveConfigsTabs();
6300 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6302 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6303 this.rclickTabName = this.CurrentTabName;
6305 this.RemoveSpecifiedTab(this.rclickTabName, true);
6306 this.SaveConfigsTabs();
6309 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6311 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6313 using (var fltDialog = new FilterDialog())
6315 fltDialog.Owner = this;
6316 fltDialog.SetCurrent(this.rclickTabName);
6317 fltDialog.ShowDialog(this);
6319 this.TopMost = this.settings.Common.AlwaysTop;
6321 this.ApplyPostFilters();
6322 this.SaveConfigsTabs();
6325 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6327 string? tabName = null;
6328 MyCommon.TabUsageType tabUsage;
6329 using (var inputName = new InputTabName())
6331 inputName.TabName = this.statuses.MakeTabName("MyTab");
6332 inputName.IsShowUsage = true;
6333 inputName.ShowDialog();
6334 if (inputName.DialogResult == DialogResult.Cancel) return;
6335 tabName = inputName.TabName;
6336 tabUsage = inputName.Usage;
6338 this.TopMost = this.settings.Common.AlwaysTop;
6339 if (!MyCommon.IsNullOrEmpty(tabName))
6342 ListElement? list = null;
6343 if (tabUsage == MyCommon.TabUsageType.Lists)
6345 using var listAvail = new ListAvailable();
6346 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6348 if (listAvail.SelectedList == null)
6350 list = listAvail.SelectedList;
6356 case MyCommon.TabUsageType.UserDefined:
6357 tab = new FilterTabModel(tabName);
6359 case MyCommon.TabUsageType.PublicSearch:
6360 tab = new PublicSearchTabModel(tabName);
6362 case MyCommon.TabUsageType.Lists:
6363 tab = new ListTimelineTabModel(tabName, list!);
6369 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6371 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6372 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6377 this.SaveConfigsTabs();
6379 var tabIndex = this.statuses.Tabs.Count - 1;
6381 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6383 this.ListTab.SelectedIndex = tabIndex;
6384 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6386 if (tabUsage == MyCommon.TabUsageType.Lists)
6388 this.ListTab.SelectedIndex = tabIndex;
6389 await this.RefreshTabAsync(this.CurrentTab);
6395 private void TabMenuItem_Click(object sender, EventArgs e)
6398 foreach (var post in this.CurrentTab.SelectedPosts)
6401 if (!this.SelectTab(out var tab))
6404 using (var fltDialog = new FilterDialog())
6406 fltDialog.Owner = this;
6407 fltDialog.SetCurrent(tab.TabName);
6409 if (post.RetweetedBy == null)
6411 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6415 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6417 fltDialog.ShowDialog(this);
6420 this.TopMost = this.settings.Common.AlwaysTop;
6423 this.ApplyPostFilters();
6424 this.SaveConfigsTabs();
6427 protected override bool ProcessDialogKey(Keys keyData)
6429 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6430 if ((keyData & Keys.KeyCode) == Keys.Enter)
6432 if (this.StatusText.Focused)
6434 var newLine = false;
6437 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6439 if (this.StatusText.Multiline)
6441 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6443 if ((keyData & Keys.Control) == Keys.Control) post = true;
6447 if ((keyData & Keys.Control) == Keys.Control) post = true;
6450 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6452 if (this.StatusText.Multiline)
6454 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6456 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6460 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6465 if (this.StatusText.Multiline)
6467 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6469 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6470 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6474 if (((keyData & Keys.Shift) == Keys.Shift) ||
6475 (((keyData & Keys.Control) != Keys.Control) &&
6476 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6482 var pos1 = this.StatusText.SelectionStart;
6483 if (this.StatusText.SelectionLength > 0)
6485 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6487 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6488 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6493 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6499 var tab = this.CurrentTab;
6500 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6502 var tabPage = this.CurrentTabPage;
6503 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6504 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6506 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6513 return base.ProcessDialogKey(keyData);
6516 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6517 => this.MakeReplyText(atAll: true);
6519 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6521 var tab = this.CurrentTab;
6522 var selectedPosts = tab.SelectedPosts;
6525 if (selectedPosts.Length == 0)
6528 var screenNameArray = selectedPosts
6529 .Select(x => x.RetweetedBy ?? x.ScreenName)
6532 this.AddFilterRuleByScreenName(screenNameArray);
6534 if (screenNameArray.Length != 0)
6536 var atids = new List<string>();
6537 foreach (var screenName in screenNameArray)
6539 atids.Add("@" + screenName);
6541 var cnt = this.AtIdSupl.ItemCount;
6542 this.AtIdSupl.AddRangeItem(atids.ToArray());
6543 if (this.AtIdSupl.ItemCount != cnt)
6544 this.MarkSettingAtIdModified();
6548 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6550 var tab = this.CurrentTab;
6551 var selectedPosts = tab.SelectedPosts;
6553 if (selectedPosts.Length == 0)
6556 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6558 this.AddFilterRuleBySource(sourceArray);
6561 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6564 if (!this.SelectTab(out var tab)) return;
6568 if (tab.TabType != MyCommon.TabUsageType.Mute)
6570 this.MoveOrCopy(out mv, out mk);
6574 // ミュートタブでは常に MoveMatches を true にする
6579 foreach (var screenName in screenNameArray)
6581 tab.AddFilter(new PostFilterRule
6583 FilterName = screenName,
6584 UseNameField = true,
6588 FilterByUrl = false,
6592 this.ApplyPostFilters();
6593 this.SaveConfigsTabs();
6596 public void AddFilterRuleBySource(params string[] sourceArray)
6598 // タブ選択ダイアログを表示(or追加)
6599 if (!this.SelectTab(out var filterTab))
6604 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6606 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6607 this.MoveOrCopy(out mv, out mk);
6611 // ミュートタブでは常に MoveMatches を true にする
6616 // 振り分けルールに追加するSource
6617 foreach (var source in sourceArray)
6619 filterTab.AddFilter(new PostFilterRule
6621 FilterSource = source,
6625 FilterByUrl = false,
6629 this.ApplyPostFilters();
6630 this.SaveConfigsTabs();
6633 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6640 using (var dialog = new TabsDialog(this.statuses))
6642 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6644 tab = dialog.SelectedTab;
6647 this.CurrentTabPage.Focus();
6652 using (var inputName = new InputTabName())
6654 inputName.TabName = this.statuses.MakeTabName("MyTab");
6655 inputName.ShowDialog();
6656 if (inputName.DialogResult == DialogResult.Cancel) return false;
6657 tabName = inputName.TabName;
6659 this.TopMost = this.settings.Common.AlwaysTop;
6660 if (!MyCommon.IsNullOrEmpty(tabName))
6662 var newTab = new FilterTabModel(tabName);
6663 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6665 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6666 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6685 private void MoveOrCopy(out bool move, out bool mark)
6689 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6690 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6698 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6699 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6710 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6713 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6714 => this.CopyIdUri();
6716 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6718 if (this.StatusText.Focused)
6721 this.StatusText.SelectAll();
6725 // ListView上でのCtrl+A
6726 NativeMethods.SelectAllItems(this.CurrentListView);
6730 private void MoveMiddle()
6736 var listView = this.CurrentListView;
6737 if (listView.SelectedIndices.Count == 0) return;
6739 var idx = listView.SelectedIndices[0];
6741 item = listView.GetItemAt(0, 25);
6747 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6749 idx2 = listView.VirtualListSize - 1;
6753 idx -= Math.Abs(idx1 - idx2) / 2;
6754 if (idx < 0) idx = 0;
6756 listView.EnsureVisible(listView.VirtualListSize - 1);
6757 listView.EnsureVisible(idx);
6760 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6762 var linkElements = this.tweetDetailsView.GetLinkElements();
6764 if (linkElements.Length == 0)
6767 var links = new List<OpenUrlItem>(linkElements.Length);
6769 foreach (var linkElm in linkElements)
6771 var displayUrl = linkElm.GetAttribute("title");
6772 var href = linkElm.GetAttribute("href");
6773 var linkedText = linkElm.InnerText;
6775 if (MyCommon.IsNullOrEmpty(displayUrl))
6778 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6782 bool isReverseSettings;
6784 if (links.Count == 1)
6786 // ツイートに含まれる URL が 1 つのみの場合
6787 // => OpenURL ダイアログを表示せずにリンクを開く
6788 selectedUrl = links[0].Href;
6790 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6791 isReverseSettings = false;
6795 // ツイートに含まれる URL が複数ある場合
6796 // => OpenURL を表示しユーザーが選択したリンクを開く
6797 this.urlDialog.ClearUrl();
6799 foreach (var link in links)
6800 this.urlDialog.AddUrl(link);
6802 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6805 this.TopMost = this.settings.Common.AlwaysTop;
6807 selectedUrl = this.urlDialog.SelectedUrl;
6809 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6810 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6813 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6816 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6818 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6819 this.ClearTab(this.rclickTabName, true);
6822 private void ClearTab(string tabName, bool showWarning)
6826 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6827 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6833 this.statuses.ClearTabIds(tabName);
6834 if (this.CurrentTabName == tabName)
6836 this.CurrentTab.ClearAnchor();
6837 this.listCache?.PurgeCache();
6838 this.listCache?.UpdateListSize();
6841 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6842 var tabPage = this.ListTab.TabPages[tabIndex];
6843 tabPage.ImageIndex = -1;
6845 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6847 this.SetMainWindowTitle();
6848 this.SetStatusLabelUrl();
6851 private static long followers = 0;
6853 private void SetMainWindowTitle()
6855 // メインウインドウタイトルの書き換え
6856 var ttl = new StringBuilder(256);
6859 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6860 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6861 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6862 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6864 foreach (var tab in this.statuses.Tabs)
6866 ur += tab.UnreadCount;
6871 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6872 ttl.Append(ApplicationSettings.ApplicationName);
6874 switch (this.settings.Common.DispLatestPost)
6876 case MyCommon.DispTitleEnum.Ver:
6877 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6879 case MyCommon.DispTitleEnum.Post:
6880 if (this.history.Peek() is { } lastItem)
6881 ttl.Append(lastItem.Status.Replace("\r\n", " "));
6883 case MyCommon.DispTitleEnum.UnreadRepCount:
6884 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6886 case MyCommon.DispTitleEnum.UnreadAllCount:
6887 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6889 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6890 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6892 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6893 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6895 case MyCommon.DispTitleEnum.OwnStatus:
6896 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6897 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6903 this.Text = ttl.ToString();
6905 catch (AccessViolationException)
6907 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6911 private string GetStatusLabelText()
6914 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6915 if (this.statuses == null) return "";
6916 var tbRep = this.statuses.MentionTab;
6917 var tbDm = this.statuses.DirectMessageTab;
6918 if (tbRep == null || tbDm == null) return "";
6919 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6924 var slbl = new StringBuilder(256);
6927 foreach (var tab in this.statuses.Tabs)
6929 ur += tab.UnreadCount;
6931 if (tab.TabName == this.CurrentTabName)
6933 tur = tab.UnreadCount;
6943 this.unreadCounter = ur;
6944 this.unreadAtCounter = urat;
6946 var homeTab = this.statuses.HomeTab;
6948 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
6949 if (this.settings.Common.TimelinePeriod == 0)
6951 slbl.Append(Properties.Resources.SetStatusLabelText2);
6955 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
6957 return slbl.ToString();
6960 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
6964 if (this.InvokeRequired && !this.IsDisposed)
6966 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
6970 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
6971 this.SetApiStatusLabel(endpointName);
6974 catch (ObjectDisposedException)
6978 catch (InvalidOperationException)
6984 private void SetApiStatusLabel(string? endpointName = null)
6986 var tabType = this.CurrentTab.TabType;
6988 if (endpointName == null)
6990 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
6993 endpointName = tabType switch
6995 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
6996 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
6997 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
6998 MyCommon.TabUsageType.Favorites => "/favorites/list",
6999 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7000 MyCommon.TabUsageType.UserTimeline =>
7001 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7002 MyCommon.TabUsageType.Lists =>
7003 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7004 MyCommon.TabUsageType.PublicSearch =>
7005 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7006 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7009 this.toolStripApiGauge.ApiEndpoint = endpointName;
7013 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7014 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7018 private void SetStatusLabelUrl()
7019 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7021 public void SetStatusLabel(string text)
7022 => this.StatusLabel.Text = text;
7024 private void SetNotifyIconText()
7026 var ur = new StringBuilder(64);
7028 // タスクトレイアイコンのツールチップテキスト書き換え
7030 ur.Remove(0, ur.Length);
7031 if (this.settings.Common.DispUsername)
7033 ur.Append(this.tw.Username);
7036 ur.Append(ApplicationSettings.ApplicationName);
7038 ur.Append("(Debug Build)");
7040 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7043 ur.Append(this.unreadCounter);
7045 ur.Append(this.unreadAtCounter);
7048 this.NotifyIcon1.Text = ur.ToString();
7051 internal void CheckReplyTo(string statusText)
7055 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7057 foreach (Match hm in m)
7059 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7061 hstr += "#" + hm.Result("$3") + " ";
7062 this.HashSupl.AddItem("#" + hm.Result("$3"));
7065 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7067 hstr += this.HashMgr.UseHash;
7069 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7071 // 本当にリプライ先指定すべきかどうかの判定
7072 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7074 if (this.settings.Common.UseAtIdSupplement)
7076 var bCnt = this.AtIdSupl.ItemCount;
7077 foreach (Match mid in m)
7079 this.AtIdSupl.AddItem(mid.Result("${id}"));
7081 if (bCnt != this.AtIdSupl.ItemCount)
7082 this.MarkSettingAtIdModified();
7085 // リプライ先ステータスIDの指定がない場合は指定しない
7086 if (this.inReplyTo == null)
7090 // 次の条件を満たす場合に in_reply_to_status_id 指定
7091 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7092 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7093 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7097 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7098 if (statusText.StartsWith("@", StringComparison.Ordinal))
7100 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7104 foreach (Match mid in m)
7106 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7111 this.inReplyTo = null;
7114 private void TweenMain_Resize(object sender, EventArgs e)
7116 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7118 this.Visible = false;
7120 if (this.WindowState != FormWindowState.Minimized)
7122 this.formWindowState = this.WindowState;
7126 private void ApplyLayoutFromSettings()
7128 // 現在の DPI と設定保存時の DPI との比を取得する
7129 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7131 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7134 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7135 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7136 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7138 this.SplitContainer1.SplitterDistance = splitterDistance;
7142 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7143 if (this.StatusText.Multiline)
7145 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7146 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7147 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7149 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7151 this.StatusText.Height = statusTextHeight;
7155 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7157 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7161 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7162 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7164 this.SplitContainer3.SplitterDistance = previewDistance;
7167 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7168 this.SplitContainer3.Panel2Collapsed = true;
7169 this.initialLayout = false;
7172 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7174 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7175 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7176 if (this.PlaySoundMenuItem.Checked)
7178 this.settings.Common.PlaySound = true;
7182 this.settings.Common.PlaySound = false;
7184 this.MarkSettingCommonModified();
7187 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7189 if (this.initialLayout)
7192 int splitterDistance;
7193 switch (this.WindowState)
7195 case FormWindowState.Normal:
7196 splitterDistance = this.SplitContainer1.SplitterDistance;
7198 case FormWindowState.Maximized:
7199 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7200 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7201 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7202 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7208 this.mySpDis = splitterDistance;
7209 this.MarkSettingLocalModified();
7212 private async Task DoRepliedStatusOpen()
7214 var currentPost = this.CurrentPost;
7215 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7217 if (MyCommon.IsKeyDown(Keys.Shift))
7219 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7222 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7224 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7228 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7230 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7231 repPost = tb.Posts[currentPost.InReplyToStatusId];
7232 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7235 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7240 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7241 => await this.DoRepliedStatusOpen();
7243 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7245 if (this.initialLayout)
7246 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7248 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7249 if (multiline != this.StatusText.Multiline)
7251 this.StatusText.Multiline = multiline;
7252 this.settings.Local.StatusMultiline = multiline;
7253 this.MarkSettingLocalModified();
7257 private void StatusText_MultilineChanged(object sender, EventArgs e)
7259 if (this.StatusText.Multiline)
7260 this.StatusText.ScrollBars = ScrollBars.Vertical;
7262 this.StatusText.ScrollBars = ScrollBars.None;
7264 if (!this.initialLayout)
7265 this.MarkSettingLocalModified();
7268 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7271 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7272 this.StatusText.Multiline = menuItemChecked;
7273 this.settings.Local.StatusMultiline = menuItemChecked;
7274 if (menuItemChecked)
7276 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7277 this.SplitContainer2.SplitterDistance = 0;
7279 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7283 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7285 this.MarkSettingLocalModified();
7288 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7290 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7292 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7293 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7294 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7296 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7301 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7302 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7303 // Appendix A. Collected ABNF for URI
7304 // http://www.ietf.org/rfc/rfc3986.txt
7306 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7309 if (this.StatusText.SelectionLength > 0)
7311 var tmp = this.StatusText.SelectedText;
7312 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7313 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7315 // 文字列が選択されている場合はその文字列について処理
7317 // nico.ms使用、nicovideoにマッチしたら変換
7318 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7320 result = Nicoms.Shorten(tmp);
7322 else if (converterType != MyCommon.UrlConverter.Nicoms)
7327 var srcUri = new Uri(tmp);
7328 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7329 result = resultUri.AbsoluteUri;
7331 catch (WebApiException e)
7333 this.StatusLabel.Text = converterType + ":" + e.Message;
7336 catch (UriFormatException e)
7338 this.StatusLabel.Text = converterType + ":" + e.Message;
7347 if (!MyCommon.IsNullOrEmpty(result))
7349 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7350 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7351 if (origUrlIndex == -1)
7354 this.StatusText.Select(origUrlIndex, tmp.Length);
7355 this.StatusText.SelectedText = result;
7358 var undo = new UrlUndo
7364 if (this.urlUndoBuffer == null)
7366 this.urlUndoBuffer = new List<UrlUndo>();
7367 this.UrlUndoToolStripMenuItem.Enabled = true;
7370 this.urlUndoBuffer.Add(undo);
7376 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7377 @"(?<url>(?<protocol>https?://)" +
7378 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7379 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7380 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7381 // 正規表現にマッチしたURL文字列をtinyurl化
7382 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7384 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7386 var tmp = mt.Result("${url}");
7387 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7388 tmp = "http://" + tmp;
7391 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7393 // nico.ms使用、nicovideoにマッチしたら変換
7394 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7396 result = Nicoms.Shorten(tmp);
7398 else if (converterType != MyCommon.UrlConverter.Nicoms)
7403 var srcUri = new Uri(tmp);
7404 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7405 result = resultUri.AbsoluteUri;
7407 catch (HttpRequestException e)
7409 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7410 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7411 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7413 this.StatusLabel.Text = converterType + ":" + message;
7416 catch (WebApiException e)
7418 this.StatusLabel.Text = converterType + ":" + e.Message;
7421 catch (UriFormatException e)
7423 this.StatusLabel.Text = converterType + ":" + e.Message;
7432 if (!MyCommon.IsNullOrEmpty(result))
7434 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7435 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7436 if (origUrlIndex == -1)
7439 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7440 this.StatusText.SelectedText = result;
7442 var undo = new UrlUndo
7444 Before = mt.Result("${url}"),
7448 if (this.urlUndoBuffer == null)
7450 this.urlUndoBuffer = new List<UrlUndo>();
7451 this.UrlUndoToolStripMenuItem.Enabled = true;
7454 this.urlUndoBuffer.Add(undo);
7462 private void DoUrlUndo()
7464 if (this.urlUndoBuffer != null)
7466 var tmp = this.StatusText.Text;
7467 foreach (var data in this.urlUndoBuffer)
7469 tmp = tmp.Replace(data.After, data.Before);
7471 this.StatusText.Text = tmp;
7472 this.urlUndoBuffer = null;
7473 this.UrlUndoToolStripMenuItem.Enabled = false;
7474 this.StatusText.SelectionStart = 0;
7475 this.StatusText.SelectionLength = 0;
7479 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7480 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7482 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7483 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7485 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7486 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7488 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7490 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7492 var rnd = new Random();
7494 MyCommon.UrlConverter svc;
7495 // 前回使用した短縮URLサービス以外を選択する
7498 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7500 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7501 await this.UrlConvertAsync(svc);
7505 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7506 => this.DoUrlUndo();
7508 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7510 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7511 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7512 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7513 this.MarkSettingCommonModified();
7516 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7518 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7519 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7520 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7521 this.MarkSettingCommonModified();
7524 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7526 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7527 this.MenuStrip1.Tag = new object();
7528 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7531 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7533 var currentTabPage = this.CurrentTabPage;
7534 if (this.Tag != null) // 設定された戻り先へ遷移
7536 if (this.Tag == currentTabPage)
7537 ((Control)currentTabPage.Tag).Select();
7539 ((Control)this.Tag).Select();
7541 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7543 this.Tag = currentTabPage.Tag;
7544 ((Control)this.Tag).Select();
7546 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7547 this.MenuStrip1.Tag = null;
7550 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7552 if (this.Use2ColumnsMode)
7558 var lst = (DetailsListView)sender;
7559 var columnsCount = lst.Columns.Count;
7561 var darr = new int[columnsCount];
7562 for (var i = 0; i < columnsCount; i++)
7563 darr[lst.Columns[i].DisplayIndex] = i;
7565 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7567 for (var i = 0; i < columnsCount; i++)
7568 this.settings.Local.ColumnsOrder[darr[i]] = i;
7570 this.MarkSettingLocalModified();
7571 this.isColumnChanged = true;
7574 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7576 var lst = (DetailsListView)sender;
7577 if (this.settings.Local == null) return;
7579 var modified = false;
7580 if (this.Use2ColumnsMode)
7582 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7584 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7587 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7589 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7595 var columnsCount = lst.Columns.Count;
7596 for (var i = 0; i < columnsCount; i++)
7598 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7601 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7607 this.MarkSettingLocalModified();
7608 this.isColumnChanged = true;
7612 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7614 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7615 this.MarkSettingLocalModified();
7618 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7620 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7622 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7624 this.SelectMedia_DragDrop(e);
7627 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7629 var (url, title) = GetUrlFromDataObject(e.Data);
7635 appendText = title + " " + url;
7637 if (this.StatusText.TextLength == 0)
7638 this.StatusText.Text = appendText;
7640 this.StatusText.Text += " " + appendText;
7642 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7644 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7646 this.StatusText.Text += text;
7648 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7650 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7651 if (data != null) this.StatusText.Text += data;
7656 /// IDataObject から URL とタイトルの対を取得します
7659 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7661 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7662 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7663 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7665 if (data.GetDataPresent("text/x-moz-url"))
7667 // Firefox, Google Chrome で利用可能
7668 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7670 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7671 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7672 if (lines.Length < 2)
7673 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7675 return (lines[0], lines[1]);
7677 else if (data.GetDataPresent("IESiteModeToUrl"))
7679 // Internet Exproler 用
7680 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7682 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7683 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7684 if (lines.Length < 2)
7685 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7687 return (lines[0], lines[1]);
7689 else if (data.GetDataPresent("UniformResourceLocatorW"))
7693 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7694 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7698 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7701 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7703 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7705 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7707 this.SelectMedia_DragEnter(e);
7711 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7713 e.Effect = DragDropEffects.Copy;
7716 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7718 e.Effect = DragDropEffects.Copy;
7721 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7723 e.Effect = DragDropEffects.Copy;
7727 e.Effect = DragDropEffects.None;
7730 private void TweenMain_DragOver(object sender, DragEventArgs e)
7734 public bool IsNetworkAvailable()
7736 var nw = MyCommon.IsNetworkAvailable();
7737 this.myStatusOnline = nw;
7741 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7743 var uriStr = uri.AbsoluteUri;
7745 // OpenTween 内部で使用する URL
7746 if (uri.Authority == "opentween")
7748 await this.OpenInternalUriAsync(uri);
7752 // ハッシュタグを含む Twitter 検索
7753 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7756 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7757 var pos = unescapedQuery.IndexOf('#');
7758 if (pos == -1) return;
7760 var hash = unescapedQuery.Substring(pos);
7761 this.HashSupl.AddItem(hash);
7762 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7763 this.AddNewTabForSearch(hash);
7768 // フラグが立っている場合は設定と逆の動作をする
7769 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7770 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7772 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7773 if (userUriMatch.Success)
7775 var screenName = userUriMatch.Groups["ScreenName"].Value;
7776 if (this.IsTwitterId(screenName))
7778 await this.AddNewTabForUserTimeline(screenName);
7785 await MyCommon.OpenInBrowserAsync(this, uriStr);
7789 /// OpenTween 内部の機能を呼び出すための URL を開きます
7791 private async Task OpenInternalUriAsync(Uri uri)
7793 // ツイートを開く (//opentween/status/:status_id)
7794 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7797 var statusId = new TwitterStatusId(match.Groups[1].Value);
7798 await this.OpenRelatedTab(statusId);
7803 private void ListTabSelect(TabPage tabPage)
7805 this.SetListProperty();
7807 var previousTabName = this.CurrentTabName;
7808 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7809 previousListViewState.Save(this.ListLockMenuItem.Checked);
7811 this.listCache?.PurgeCache();
7813 this.statuses.SelectTab(tabPage.Text);
7815 this.InitializeTimelineListView();
7817 var tab = this.CurrentTab;
7820 var listView = this.CurrentListView;
7822 var currentListViewState = this.listViewState[tab.TabName];
7823 currentListViewState.Restore(forceScroll: true);
7825 if (this.Use2ColumnsMode)
7827 listView.Columns[1].Text = this.columnText[2];
7831 for (var i = 0; i < listView.Columns.Count; i++)
7833 listView.Columns[i].Text = this.columnText[i];
7838 private void InitializeTimelineListView()
7840 var listView = this.CurrentListView;
7841 var tab = this.CurrentTab;
7843 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7844 (this.listCache, var oldCache) = (newCache, this.listCache);
7845 oldCache?.Dispose();
7847 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7848 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7849 oldDrawer?.Dispose();
7851 newDrawer.IconSize = this.settings.Common.IconSize;
7852 newDrawer.UpdateItemHeight();
7855 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7856 => this.ListTabSelect(e.TabPage);
7858 private void SelectListItem(DetailsListView lView, int index)
7861 var bnd = new Rectangle();
7863 var item = lView.FocusedItem;
7872 lView.SelectedIndices.Clear();
7874 while (lView.SelectedIndices.Count > 0);
7875 item = lView.Items[index];
7876 item.Selected = true;
7877 item.Focused = true;
7879 if (flg) lView.Invalidate(bnd);
7882 private async void TweenMain_Shown(object sender, EventArgs e)
7884 this.NotifyIcon1.Visible = true;
7887 if (this.settings.IsFirstRun)
7889 // 初回起動時だけ右下のメニューを目立たせる
7890 this.HashStripSplitButton.ShowDropDown();
7893 if (this.IsNetworkAvailable())
7895 var loadTasks = new TaskCollection();
7899 this.RefreshMuteUserIdsAsync,
7900 this.RefreshBlockIdsAsync,
7901 this.RefreshNoRetweetIdsAsync,
7902 this.RefreshTwitterConfigurationAsync,
7903 this.RefreshTabAsync<HomeTabModel>,
7904 this.RefreshTabAsync<MentionsTabModel>,
7905 this.RefreshTabAsync<DirectMessagesTabModel>,
7906 this.RefreshTabAsync<PublicSearchTabModel>,
7907 this.RefreshTabAsync<UserTimelineTabModel>,
7908 this.RefreshTabAsync<ListTimelineTabModel>,
7911 if (this.settings.Common.StartupFollowers)
7912 loadTasks.Add(this.RefreshFollowerIdsAsync);
7914 if (this.settings.Common.GetFav)
7915 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7917 var allTasks = loadTasks.RunAll();
7922 var timeout = Task.Delay(5000);
7923 if (await Task.WhenAny(allTasks, timeout) != timeout)
7927 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7929 if (MyCommon.EndingFlag)
7933 if (MyCommon.EndingFlag) return;
7935 if (ApplicationSettings.VersionInfoUrl != null)
7937 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7938 if (this.settings.Common.StartupVersion)
7939 await this.CheckNewVersion(true);
7943 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
7944 this.VerUpMenuItem.Enabled = false;
7945 this.VerUpMenuItem.Available = false;
7946 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
7949 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
7950 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
7952 MessageBox.Show(Properties.Resources.ReAuthorizeText);
7953 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
7957 var reloadTasks = new TaskCollection();
7959 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
7960 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
7962 if (!this.tw.GetNoRetweetSuccess)
7963 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
7965 if (this.tw.Configuration.PhotoSizeLimit == 0)
7966 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
7968 await reloadTasks.RunAll();
7971 this.initial = false;
7974 private void StartTimers()
7976 if (!this.StopRefreshAllMenuItem.Checked)
7977 this.timelineScheduler.Enabled = true;
7979 this.selectionDebouncer.Enabled = true;
7980 this.saveConfigDebouncer.Enabled = true;
7981 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
7984 private async Task DoGetFollowersMenu()
7986 await this.RefreshFollowerIdsAsync();
7987 this.DispSelectedPost(true);
7990 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
7991 => await this.DoGetFollowersMenu();
7993 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
7994 => this.DoReTweetUnofficial();
7996 private async Task DoReTweetOfficial(bool isConfirm)
7999 if (this.ExistCurrentPost)
8001 var selectedPosts = this.CurrentTab.SelectedPosts;
8003 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8005 if (selectedPosts.Any(x => x.IsProtect))
8006 MessageBox.Show("Protected.");
8008 this.doFavRetweetFlags = false;
8012 if (selectedPosts.Length > 15)
8014 MessageBox.Show(Properties.Resources.RetweetLimitText);
8015 this.doFavRetweetFlags = false;
8018 else if (selectedPosts.Length > 1)
8020 var questionText = Properties.Resources.RetweetQuestion2;
8021 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8022 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8024 case DialogResult.Cancel:
8025 case DialogResult.No:
8026 this.doFavRetweetFlags = false;
8032 if (!this.settings.Common.RetweetNoConfirm)
8034 var questiontext = Properties.Resources.RetweetQuestion1;
8035 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8036 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8038 this.doFavRetweetFlags = false;
8044 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8046 await this.RetweetAsync(statusIds);
8050 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8051 => await this.DoReTweetOfficial(true);
8053 private async Task FavoritesRetweetOfficial()
8055 if (!this.ExistCurrentPost) return;
8056 this.doFavRetweetFlags = true;
8058 var tasks = new TaskCollection();
8059 tasks.Add(() => this.DoReTweetOfficial(true));
8061 if (this.doFavRetweetFlags)
8063 this.doFavRetweetFlags = false;
8064 tasks.Add(() => this.FavoriteChange(true, false));
8067 await tasks.RunAll();
8070 private async Task FavoritesRetweetUnofficial()
8072 var post = this.CurrentPost;
8073 if (this.ExistCurrentPost && post != null && !post.IsDm)
8075 this.doFavRetweetFlags = true;
8076 var favoriteTask = this.FavoriteChange(true);
8077 if (!post.IsProtect && this.doFavRetweetFlags)
8079 this.doFavRetweetFlags = false;
8080 this.DoReTweetUnofficial();
8088 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8090 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8091 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8092 /// <returns>復元されたツイート本文</returns>
8093 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8095 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8098 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8100 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8102 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8104 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8108 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8110 statusHtml = statusHtml.Replace("<br>", " ");
8112 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8113 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8114 statusHtml = statusHtml.Replace(" ", " ");
8116 return WebUtility.HtmlDecode(statusHtml);
8119 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8121 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8123 if (this.CurrentPost != null)
8124 this.DispSelectedPost(true);
8127 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8129 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8130 this.DebugModeToolStripMenuItem.Visible = true;
8132 this.DebugModeToolStripMenuItem.Visible = false;
8135 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8136 => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8138 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8139 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8141 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8142 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8144 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8146 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8147 this.MarkSettingCommonModified();
8150 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8152 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8153 this.MarkSettingCommonModified();
8156 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8158 this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8159 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8160 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8161 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8162 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8163 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8166 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8168 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8169 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8170 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8171 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8172 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8173 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8176 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8178 if (this.TraceOutToolStripMenuItem.Checked)
8179 MyCommon.TraceFlag = true;
8181 MyCommon.TraceFlag = false;
8184 private void TweenMain_Deactivate(object sender, EventArgs e)
8185 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8187 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8189 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8191 _ = this.TabRename(this.rclickTabName, out _);
8194 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8195 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8197 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8198 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8200 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8202 TwitterApiStatus? apiStatus;
8204 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8206 var cancellationToken = dialog.EnableCancellation();
8210 var task = this.tw.GetInfoApi();
8211 apiStatus = await dialog.WaitForAsync(this, task);
8213 catch (WebApiException)
8218 if (cancellationToken.IsCancellationRequested)
8221 if (apiStatus == null)
8223 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8228 using var apiDlg = new ApiInfoDialog();
8229 apiDlg.ShowDialog(this);
8232 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8234 var id = this.CurrentPost?.ScreenName ?? "";
8236 await this.FollowCommand(id);
8239 internal async Task FollowCommand(string id)
8241 using (var inputName = new InputTabName())
8243 inputName.FormTitle = "Follow";
8244 inputName.FormDescription = Properties.Resources.FRMessage1;
8245 inputName.TabName = id;
8247 if (inputName.ShowDialog(this) != DialogResult.OK)
8249 if (string.IsNullOrWhiteSpace(inputName.TabName))
8252 id = inputName.TabName.Trim();
8255 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8259 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8260 await dialog.WaitForAsync(this, task);
8262 catch (WebApiException ex)
8264 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8269 MessageBox.Show(Properties.Resources.FRMessage3);
8272 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8274 var id = this.CurrentPost?.ScreenName ?? "";
8276 await this.RemoveCommand(id, false);
8279 internal async Task RemoveCommand(string id, bool skipInput)
8283 using var inputName = new InputTabName();
8284 inputName.FormTitle = "Unfollow";
8285 inputName.FormDescription = Properties.Resources.FRMessage1;
8286 inputName.TabName = id;
8288 if (inputName.ShowDialog(this) != DialogResult.OK)
8290 if (string.IsNullOrWhiteSpace(inputName.TabName))
8293 id = inputName.TabName.Trim();
8296 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8300 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8301 await dialog.WaitForAsync(this, task);
8303 catch (WebApiException ex)
8305 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8310 MessageBox.Show(Properties.Resources.FRMessage3);
8313 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8315 var id = this.CurrentPost?.ScreenName ?? "";
8317 await this.ShowFriendship(id);
8320 internal async Task ShowFriendship(string id)
8322 using (var inputName = new InputTabName())
8324 inputName.FormTitle = "Show Friendships";
8325 inputName.FormDescription = Properties.Resources.FRMessage1;
8326 inputName.TabName = id;
8328 if (inputName.ShowDialog(this) != DialogResult.OK)
8330 if (string.IsNullOrWhiteSpace(inputName.TabName))
8333 id = inputName.TabName.Trim();
8336 bool isFollowing, isFollowed;
8338 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8340 var cancellationToken = dialog.EnableCancellation();
8344 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8345 var friendship = await dialog.WaitForAsync(this, task);
8347 isFollowing = friendship.Relationship.Source.Following;
8348 isFollowed = friendship.Relationship.Source.FollowedBy;
8350 catch (WebApiException ex)
8352 if (!cancellationToken.IsCancellationRequested)
8353 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8357 if (cancellationToken.IsCancellationRequested)
8364 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8368 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8372 result += Properties.Resources.GetFriendshipInfo3;
8376 result += Properties.Resources.GetFriendshipInfo4;
8378 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8379 MessageBox.Show(result);
8382 internal async Task ShowFriendship(string[] ids)
8384 foreach (var id in ids)
8386 bool isFollowing, isFollowed;
8388 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8390 var cancellationToken = dialog.EnableCancellation();
8394 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8395 var friendship = await dialog.WaitForAsync(this, task);
8397 isFollowing = friendship.Relationship.Source.Following;
8398 isFollowed = friendship.Relationship.Source.FollowedBy;
8400 catch (WebApiException ex)
8402 if (!cancellationToken.IsCancellationRequested)
8403 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8407 if (cancellationToken.IsCancellationRequested)
8417 ff += Properties.Resources.GetFriendshipInfo1;
8421 ff += Properties.Resources.GetFriendshipInfo2;
8424 ff += System.Environment.NewLine + " ";
8427 ff += Properties.Resources.GetFriendshipInfo3;
8431 ff += Properties.Resources.GetFriendshipInfo4;
8433 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8436 if (MessageBox.Show(
8437 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8438 Properties.Resources.GetFriendshipInfo8,
8439 MessageBoxButtons.YesNo,
8440 MessageBoxIcon.Question,
8441 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8443 await this.RemoveCommand(id, true);
8448 MessageBox.Show(result);
8453 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8454 => await this.DoShowUserStatus(this.tw.Username, false);
8456 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8459 public bool IsTwitterId(string name)
8461 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8462 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8464 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8467 private void DoQuoteOfficial()
8469 var post = this.CurrentPost;
8470 if (this.ExistCurrentPost && post != null)
8472 if (post.IsDm || !this.StatusText.Enabled)
8477 MessageBox.Show("Protected.");
8481 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8483 this.inReplyTo = null;
8485 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8487 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8488 this.StatusText.Focus();
8492 private void DoReTweetUnofficial()
8495 var post = this.CurrentPost;
8496 if (this.ExistCurrentPost && post != null)
8498 if (post.IsDm || !this.StatusText.Enabled)
8503 MessageBox.Show("Protected.");
8506 var rtdata = post.Text;
8507 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8509 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8511 // 投稿時に in_reply_to_status_id を付加する
8512 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8513 var inReplyToScreenName = post.ScreenName;
8514 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8516 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8518 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8519 this.StatusText.Focus();
8523 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8524 => this.DoQuoteOfficial();
8526 private async void SearchButton_Click(object sender, EventArgs e)
8529 var pnl = ((Control)sender).Parent;
8530 if (pnl == null) return;
8531 var tbName = pnl.Parent.Text;
8532 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8533 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8534 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8535 cmb.Text = cmb.Text.Trim();
8536 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8538 var buf = new StringBuilder();
8539 var c = cmb.Text.ToCharArray();
8540 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8542 if (cnt > cmb.Text.Length - 4)
8544 buf.Append(cmb.Text.Substring(cnt));
8553 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8562 cmb.Text = buf.ToString();
8564 var listView = (DetailsListView)pnl.Parent.Tag;
8566 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8568 tb.SearchWords = cmb.Text;
8569 tb.SearchLang = cmbLang.Text;
8570 if (MyCommon.IsNullOrEmpty(cmb.Text))
8573 this.SaveConfigsTabs();
8578 var idx = cmb.Items.IndexOf(tb.SearchWords);
8579 if (idx > -1) cmb.Items.RemoveAt(idx);
8580 cmb.Items.Insert(0, tb.SearchWords);
8581 cmb.Text = tb.SearchWords;
8583 this.statuses.ClearTabIds(tbName);
8584 this.listCache?.PurgeCache();
8585 this.listCache?.UpdateListSize();
8586 this.SaveConfigsTabs(); // 検索条件の保存
8590 await this.RefreshTabAsync(tb);
8593 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8594 => await this.DoRefreshMore(); // もっと前を取得
8597 /// 指定されたタブのListTabにおける位置を返します
8600 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8602 public int GetTabPageIndex(string tabName)
8603 => this.statuses.Tabs.IndexOf(tabName);
8605 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8609 var restoredTab = this.statuses.UndoRemovedTab();
8610 this.AddNewTab(restoredTab, startup: false);
8612 var tabIndex = this.statuses.Tabs.Count - 1;
8613 this.ListTab.SelectedIndex = tabIndex;
8615 this.SaveConfigsTabs();
8617 catch (TabException ex)
8619 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8623 private async Task DoMoveToRTHome()
8625 var post = this.CurrentPost;
8626 if (post != null && post.RetweetedId != null)
8627 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8630 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8631 => await this.DoMoveToRTHome();
8633 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8635 var screenName = this.CurrentPost?.ScreenName;
8636 if (screenName != null)
8637 this.ListManageUserContext(screenName);
8640 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8642 var screenName = this.CurrentPost?.RetweetedBy;
8643 if (screenName != null)
8644 this.ListManageUserContext(screenName);
8647 public void ListManageUserContext(string screenName)
8649 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8650 listSelectForm.ShowDialog(this);
8653 private void SearchControls_Enter(object sender, EventArgs e)
8655 var pnl = (Control)sender;
8656 foreach (Control ctl in pnl.Controls)
8662 private void SearchControls_Leave(object sender, EventArgs e)
8664 var pnl = (Control)sender;
8665 foreach (Control ctl in pnl.Controls)
8667 ctl.TabStop = false;
8671 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8673 var tab = this.CurrentTab;
8674 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8675 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8678 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8679 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8681 private void HashManageMenuItem_Click(object sender, EventArgs e)
8686 rslt = this.HashMgr.ShowDialog();
8692 this.TopMost = this.settings.Common.AlwaysTop;
8693 if (rslt == DialogResult.Cancel) return;
8694 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8696 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8697 this.HashTogglePullDownMenuItem.Checked = true;
8698 this.HashToggleMenuItem.Checked = true;
8702 this.HashStripSplitButton.Text = "#[-]";
8703 this.HashTogglePullDownMenuItem.Checked = false;
8704 this.HashToggleMenuItem.Checked = false;
8707 this.MarkSettingCommonModified();
8708 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8711 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8713 this.HashMgr.ToggleHash();
8714 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8716 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8717 this.HashToggleMenuItem.Checked = true;
8718 this.HashTogglePullDownMenuItem.Checked = true;
8722 this.HashStripSplitButton.Text = "#[-]";
8723 this.HashToggleMenuItem.Checked = false;
8724 this.HashTogglePullDownMenuItem.Checked = false;
8726 this.MarkSettingCommonModified();
8727 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8730 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8731 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8733 public void SetPermanentHashtag(string hashtag)
8735 this.HashMgr.SetPermanentHash("#" + hashtag);
8736 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8737 this.HashTogglePullDownMenuItem.Checked = true;
8738 this.HashToggleMenuItem.Checked = true;
8740 this.MarkSettingCommonModified();
8743 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8745 var tab = this.CurrentTab;
8746 var post = this.CurrentPost;
8747 if (!this.ExistCurrentPost)
8749 this.ReplyOpMenuItem.Enabled = false;
8750 this.ReplyAllOpMenuItem.Enabled = false;
8751 this.DmOpMenuItem.Enabled = false;
8752 this.CreateTabRuleOpMenuItem.Enabled = false;
8753 this.CreateIdRuleOpMenuItem.Enabled = false;
8754 this.CreateSourceRuleOpMenuItem.Enabled = false;
8755 this.ReadOpMenuItem.Enabled = false;
8756 this.UnreadOpMenuItem.Enabled = false;
8757 this.AuthorMenuItem.Visible = false;
8758 this.RetweetedByMenuItem.Visible = false;
8762 this.ReplyOpMenuItem.Enabled = true;
8763 this.ReplyAllOpMenuItem.Enabled = true;
8764 this.DmOpMenuItem.Enabled = true;
8765 this.CreateTabRuleOpMenuItem.Enabled = true;
8766 this.CreateIdRuleOpMenuItem.Enabled = true;
8767 this.CreateSourceRuleOpMenuItem.Enabled = true;
8768 this.ReadOpMenuItem.Enabled = true;
8769 this.UnreadOpMenuItem.Enabled = true;
8770 this.AuthorMenuItem.Visible = true;
8771 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8772 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8773 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8776 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8778 this.FavOpMenuItem.Enabled = false;
8779 this.UnFavOpMenuItem.Enabled = false;
8780 this.OpenStatusOpMenuItem.Enabled = false;
8781 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8782 this.RtOpMenuItem.Enabled = false;
8783 this.RtUnOpMenuItem.Enabled = false;
8784 this.QtOpMenuItem.Enabled = false;
8785 this.FavoriteRetweetMenuItem.Enabled = false;
8786 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8790 this.FavOpMenuItem.Enabled = true;
8791 this.UnFavOpMenuItem.Enabled = true;
8792 this.OpenStatusOpMenuItem.Enabled = true;
8793 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8795 if (!post.CanRetweetBy(this.tw.UserId))
8797 this.RtOpMenuItem.Enabled = false;
8798 this.RtUnOpMenuItem.Enabled = false;
8799 this.QtOpMenuItem.Enabled = false;
8800 this.FavoriteRetweetMenuItem.Enabled = false;
8801 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8805 this.RtOpMenuItem.Enabled = true;
8806 this.RtUnOpMenuItem.Enabled = true;
8807 this.QtOpMenuItem.Enabled = true;
8808 this.FavoriteRetweetMenuItem.Enabled = true;
8809 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8813 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8815 this.RefreshPrevOpMenuItem.Enabled = true;
8819 this.RefreshPrevOpMenuItem.Enabled = false;
8821 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8823 this.OpenRepSourceOpMenuItem.Enabled = false;
8827 this.OpenRepSourceOpMenuItem.Enabled = true;
8830 if (this.ExistCurrentPost && post != null)
8832 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8836 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8837 => this.ContextMenuTabProperty_Opening(sender, null!);
8839 public Twitter TwitterInstance
8842 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8844 if (this.initialLayout)
8847 int splitterDistance;
8848 switch (this.WindowState)
8850 case FormWindowState.Normal:
8851 splitterDistance = this.SplitContainer3.SplitterDistance;
8853 case FormWindowState.Maximized:
8854 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8855 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8856 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8857 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8863 this.mySpDis3 = splitterDistance;
8864 this.MarkSettingLocalModified();
8867 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8869 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8871 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8872 this.PublicSearchQueryMenuItem.Enabled = true;
8874 this.PublicSearchQueryMenuItem.Enabled = false;
8876 var post = this.CurrentPost;
8877 if (!this.ExistCurrentPost || post == null)
8879 this.CopySTOTMenuItem.Enabled = false;
8880 this.CopyURLMenuItem.Enabled = false;
8881 this.CopyUserIdStripMenuItem.Enabled = false;
8885 this.CopySTOTMenuItem.Enabled = true;
8886 this.CopyURLMenuItem.Enabled = true;
8887 this.CopyUserIdStripMenuItem.Enabled = true;
8889 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8890 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8894 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8895 => this.SetNotifyIconText();
8897 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8898 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8900 private async Task DoShowUserStatus(string id, bool showInputDialog)
8902 TwitterUser? user = null;
8904 if (showInputDialog)
8906 using var inputName = new InputTabName();
8907 inputName.FormTitle = "Show UserStatus";
8908 inputName.FormDescription = Properties.Resources.FRMessage1;
8909 inputName.TabName = id;
8911 if (inputName.ShowDialog(this) != DialogResult.OK)
8913 if (string.IsNullOrWhiteSpace(inputName.TabName))
8916 id = inputName.TabName.Trim();
8919 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8921 var cancellationToken = dialog.EnableCancellation();
8925 var task = this.tw.GetUserInfo(id);
8926 user = await dialog.WaitForAsync(this, task);
8928 catch (WebApiException ex)
8930 if (!cancellationToken.IsCancellationRequested)
8931 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8935 if (cancellationToken.IsCancellationRequested)
8939 await this.DoShowUserStatus(user);
8942 private async Task DoShowUserStatus(TwitterUser user)
8944 using var userDialog = new UserInfoDialog(this, this.tw.Api, this.detailsHtmlBuilder);
8945 var showUserTask = userDialog.ShowUserAsync(user);
8946 userDialog.ShowDialog(this);
8949 this.BringToFront();
8951 // ユーザー情報の表示が完了するまで userDialog を破棄しない
8955 internal Task ShowUserStatus(string id, bool showInputDialog)
8956 => this.DoShowUserStatus(id, showInputDialog);
8958 internal Task ShowUserStatus(string id)
8959 => this.DoShowUserStatus(id, true);
8961 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
8963 var post = this.CurrentPost;
8966 await this.ShowUserStatus(post.ScreenName, false);
8970 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
8972 var retweetedBy = this.CurrentPost?.RetweetedBy;
8973 if (retweetedBy != null)
8975 await this.ShowUserStatus(retweetedBy, false);
8979 private async void RtCountMenuItem_Click(object sender, EventArgs e)
8981 var post = this.CurrentPost;
8982 if (!this.ExistCurrentPost || post == null)
8985 var statusId = post.RetweetedId ?? post.StatusId;
8986 TwitterStatus status;
8988 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
8990 var cancellationToken = dialog.EnableCancellation();
8994 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
8995 status = await dialog.WaitForAsync(this, task);
8997 catch (WebApiException ex)
8999 if (!cancellationToken.IsCancellationRequested)
9000 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9004 if (cancellationToken.IsCancellationRequested)
9008 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9011 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9013 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9016 this.Visible = false;
9018 else if (Form.ActiveForm == null)
9020 this.Visible = true;
9021 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9023 this.BringToFront();
9024 this.StatusText.Focus();
9028 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9029 => this.MultiLinePullDownMenuItem.PerformClick();
9032 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9034 if (this.ImageSelector.Visible)
9035 this.ImageSelector.EndSelection();
9037 this.ImageSelector.BeginSelection();
9040 private void SelectMedia_DragEnter(DragEventArgs e)
9042 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9044 e.Effect = DragDropEffects.Copy;
9047 e.Effect = DragDropEffects.None;
9050 private void SelectMedia_DragDrop(DragEventArgs e)
9053 this.BringToFront();
9055 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9056 this.ImageSelector.BeginSelection();
9057 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9058 this.StatusText.Focus();
9061 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9063 this.TimelinePanel.Visible = false;
9064 this.TimelinePanel.Enabled = false;
9067 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9069 this.TimelinePanel.Visible = true;
9070 this.TimelinePanel.Enabled = true;
9071 this.CurrentListView.Focus();
9074 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9075 => this.AllowDrop = false;
9077 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9078 => this.AllowDrop = true;
9080 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9082 if (this.ImageSelector.Visible)
9084 this.MarkSettingCommonModified();
9085 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9089 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9090 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9093 /// StatusTextでCtrl+Vが押下された時の処理
9095 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9099 if (Clipboard.ContainsText())
9101 // clipboardにテキストがある場合は貼り付け処理
9102 this.StatusText.Paste(Clipboard.GetText());
9104 else if (Clipboard.ContainsImage())
9107 using var image = Clipboard.GetImage();
9108 this.ImageSelector.BeginSelection();
9109 this.ImageSelector.Model.AddMediaItemFromImage(image);
9111 else if (Clipboard.ContainsFileDropList())
9113 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9114 this.ImageSelector.BeginSelection();
9115 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9118 catch (ExternalException ex)
9120 MessageBox.Show(ex.Message);
9125 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9127 using var form = new ListManage(this.tw);
9128 form.ShowDialog(this);
9131 private bool ModifySettingCommon { get; set; }
9133 private bool ModifySettingLocal { get; set; }
9135 private bool ModifySettingAtId { get; set; }
9137 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9139 var post = this.CurrentPost;
9140 if (this.ExistCurrentPost && post != null && !post.IsDm)
9141 this.RtCountMenuItem.Enabled = true;
9143 this.RtCountMenuItem.Enabled = false;
9146 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9147 => this.CopyUserId();
9149 private void CopyUserId()
9151 var post = this.CurrentPost;
9152 if (post == null) return;
9153 var clstr = post.ScreenName;
9156 Clipboard.SetDataObject(clstr, false, 5, 100);
9158 catch (Exception ex)
9160 MessageBox.Show(ex.Message);
9164 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9166 var post = this.CurrentPost;
9167 if (this.ExistCurrentPost && post != null && !post.IsDm)
9171 await this.OpenRelatedTab(post);
9173 catch (TabException ex)
9175 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9181 /// 指定されたツイートに対する関連発言タブを開きます
9183 /// <param name="statusId">表示するツイートのID</param>
9184 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9185 public async Task OpenRelatedTab(PostId statusId)
9187 var post = this.statuses[statusId];
9192 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9194 catch (WebApiException ex)
9196 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9201 await this.OpenRelatedTab(post);
9205 /// 指定されたツイートに対する関連発言タブを開きます
9207 /// <param name="post">表示する対象となるツイート</param>
9208 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9209 private async Task OpenRelatedTab(PostClass post)
9211 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9212 if (tabRelated != null)
9214 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9217 var tabName = this.statuses.MakeTabName("Related Tweets");
9219 tabRelated = new RelatedPostsTabModel(tabName, post)
9221 UnreadManage = false,
9225 this.statuses.AddTab(tabRelated);
9226 this.AddNewTab(tabRelated, startup: false);
9228 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9230 await this.RefreshTabAsync(tabRelated);
9232 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9236 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9238 var tabPage = this.ListTab.TabPages[tabIndex];
9239 var listView = (DetailsListView)tabPage.Tag;
9240 var targetPost = tabRelated.TargetPost;
9241 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9243 if (index != -1 && index < listView.Items.Count)
9245 listView.SelectedIndices.Add(index);
9246 listView.Items[index].Focused = true;
9251 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9253 var buf = new StringBuilder();
9254 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9255 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9256 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9259 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9261 MyCommon.EndingFlag = true;
9265 Application.Restart();
9269 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9273 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9274 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9276 private bool ExistCurrentPost
9280 var post = this.CurrentPost;
9281 return post != null && !post.IsDeleted;
9285 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9286 => await this.ShowUserTimeline();
9288 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9289 => await this.ShowRetweeterTimeline();
9291 private string GetUserIdFromCurPostOrInput(string caption)
9293 var id = this.CurrentPost?.ScreenName ?? "";
9295 using var inputName = new InputTabName();
9296 inputName.FormTitle = caption;
9297 inputName.FormDescription = Properties.Resources.FRMessage1;
9298 inputName.TabName = id;
9300 if (inputName.ShowDialog() == DialogResult.OK &&
9301 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9303 id = inputName.TabName.Trim();
9312 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9314 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9315 if (!MyCommon.IsNullOrEmpty(id))
9317 await this.AddNewTabForUserTimeline(id);
9321 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9323 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9324 this.timelineScheduler.SystemResumed();
9327 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9329 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9331 TimeZoneInfo.ClearCachedData();
9333 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9335 if (curTimeOffset != prevTimeOffset)
9338 this.listCache?.PurgeCache();
9339 this.CurrentListView.Refresh();
9341 this.DispSelectedPost(forceupdate: true);
9344 this.timelineScheduler.Reset();
9347 private void TimelineRefreshEnableChange(bool isEnable)
9349 this.timelineScheduler.Enabled = isEnable;
9352 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9353 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9355 private async Task OpenUserAppointUrl()
9357 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9359 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9361 var post = this.CurrentPost;
9364 var xUrl = this.settings.Common.UserAppointUrl;
9365 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9367 var statusId = post.RetweetedId ?? post.StatusId;
9368 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9370 await MyCommon.OpenInBrowserAsync(this, xUrl);
9375 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9380 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9381 => await this.OpenUserAppointUrl();
9383 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9385 if (Form.ActiveForm == null)
9387 await this.InvokeAsync(() =>
9389 this.Visible = true;
9390 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9392 this.BringToFront();
9393 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9395 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9399 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9405 private void ReplaceAppName()
9407 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9408 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9411 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9412 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9414 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9416 if (e.KeyCode == Keys.Space)
9418 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9420 e.SuppressKeyPress = true;
9424 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9426 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9427 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9428 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9429 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9430 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9432 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9435 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9436 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9438 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9439 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9441 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9442 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9444 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9445 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9447 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9448 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9450 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9452 if (this.settings.Common.IconSize == iconSize) return;
9454 var oldIconCol = this.Use2ColumnsMode;
9456 this.settings.Common.IconSize = iconSize;
9457 this.ApplyListViewIconSize(iconSize);
9459 if (this.Use2ColumnsMode != oldIconCol)
9461 foreach (TabPage tp in this.ListTab.TabPages)
9463 this.ResetColumns((DetailsListView)tp.Tag);
9467 this.CurrentListView.Refresh();
9468 this.MarkSettingCommonModified();
9471 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9473 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9474 if (this.settings.Common.SortOrderLock == state) return;
9476 this.settings.Common.SortOrderLock = state;
9477 this.MarkSettingCommonModified();
9480 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9482 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9484 this.StatusLabelUrl.Text = e.StatusText;
9488 this.SetStatusLabelUrl();