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.SocialProtocol;
63 using OpenTween.Thumbnail;
67 public partial class TweenMain : OTBaseForm
71 /// <summary>画面サイズ</summary>
74 /// <summary>画面位置</summary>
77 /// <summary>区切り位置</summary>
80 /// <summary>発言欄区切り位置</summary>
83 /// <summary>プレビュー区切り位置</summary>
87 private bool initial; // true:起動時処理中
88 private bool initialLayout = true;
89 private bool ignoreConfigSave; // true:起動時処理中
91 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
94 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
95 private Point tabMouseDownPoint;
97 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
98 private string? rclickTabName;
100 private readonly object syncObject = new(); // ロック用
102 private readonly DetailsHtmlBuilder detailsHtmlBuilder = new();
104 private bool myStatusError = false;
105 private bool myStatusOnline = false;
106 private bool soundfileListup = false;
107 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
110 private readonly SettingManager settings;
113 private readonly AccountCollection accounts;
115 #pragma warning disable SA1300
116 private Twitter tw => this.accounts.Primary; // AccountCollection への移行用
117 #pragma warning restore SA1300
120 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
124 /// <summary>検索画面インスタンス</summary>
125 internal SearchWordDialog SearchDialog = new();
127 private readonly OpenURL urlDialog = new();
129 /// <summary>@id補助</summary>
130 public AtIdSupplement AtIdSupl = null!;
132 /// <summary>Hashtag補助</summary>
133 public AtIdSupplement HashSupl = null!;
135 public HashtagManage HashMgr = null!;
138 private ThemeManager themeManager;
140 /// <summary>アイコン画像リスト</summary>
141 private readonly ImageCache iconCache;
143 private readonly IconAssetsManager iconAssets;
145 private readonly ThumbnailGenerator thumbGenerator;
147 /// <summary>発言履歴</summary>
148 private readonly StatusTextHistory history = new();
150 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
152 /// <summary>リプライ先のステータスID・スクリーン名</summary>
153 private (PostId StatusId, string ScreenName)? inReplyTo = null;
156 private readonly List<DateTimeUtc> postTimestamps = new();
157 private readonly List<DateTimeUtc> favTimestamps = new();
160 private readonly StringFormat sfTab = new();
162 //////////////////////////////////////////////////////////////////////////////////////////////////////////
164 /// <summary>発言保持クラス</summary>
165 private readonly TabInformations statuses;
167 private TimelineListViewCache? listCache;
168 private TimelineListViewDrawer? listDrawer;
169 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
171 private bool isColumnChanged = false;
173 private const int MaxWorderThreads = 20;
174 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
175 private readonly CancellationTokenSource workerCts = new();
176 private readonly IProgress<string> workerProgress = null!;
178 private int unreadCounter = -1;
179 private int unreadAtCounter = -1;
181 private readonly string[] columnOrgText = new string[9];
182 private readonly string[] columnText = new string[9];
184 private bool doFavRetweetFlags = false;
186 //////////////////////////////////////////////////////////////////////////////////////////////////////////
188 private readonly TimelineScheduler timelineScheduler = new();
189 private readonly DebounceTimer selectionDebouncer;
190 private readonly DebounceTimer saveConfigDebouncer;
192 private readonly string recommendedStatusFooter;
194 internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
196 private bool preventSmsCommand = true;
199 private readonly record struct UrlUndo(
204 private List<UrlUndo>? urlUndoBuffer = null;
206 private readonly record struct ReplyChain(
212 /// <summary>[, ]でのリプライ移動の履歴</summary>
213 private Stack<ReplyChain>? replyChains;
215 /// <summary>ポスト選択履歴</summary>
216 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
218 public TabModel CurrentTab
219 => this.statuses.SelectedTab;
221 public string CurrentTabName
222 => this.statuses.SelectedTabName;
224 public TabPage CurrentTabPage
225 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
227 public DetailsListView CurrentListView
228 => (DetailsListView)this.CurrentTabPage.Tag;
230 public PostClass? CurrentPost
231 => this.CurrentTab.SelectedPost;
233 public bool Use2ColumnsMode
234 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
236 /// <summary>検索処理タイプ</summary>
237 internal enum SEARCHTYPE
244 private readonly HookGlobalHotkey hookGlobalHotkey;
247 SettingManager settingManager,
248 TabInformations tabInfo,
249 AccountCollection accounts,
250 ImageCache imageCache,
251 IconAssetsManager iconAssets,
252 ThumbnailGenerator thumbGenerator
255 this.settings = settingManager;
256 this.statuses = tabInfo;
257 this.accounts = accounts;
258 this.iconCache = imageCache;
259 this.iconAssets = iconAssets;
260 this.thumbGenerator = thumbGenerator;
262 this.InitializeComponent();
264 if (!this.DesignMode)
266 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
267 this.StatusText.Dock = DockStyle.Fill;
270 this.hookGlobalHotkey = new HookGlobalHotkey(this);
272 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
273 this.gh.NotifyClicked += this.GrowlHelper_Callback;
275 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
276 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
278 this.ImageSelector.Visible = false;
279 this.ImageSelector.Enabled = false;
280 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
282 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
284 this.ReplaceAppName();
285 this.InitializeShortcuts();
287 this.ignoreConfigSave = true;
289 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
291 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
293 Regex.CacheSize = 100;
296 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
297 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
298 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
300 // <<<<<<<<<設定関連>>>>>>>>>
304 // 現在の DPI と設定保存時の DPI との比を取得する
305 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
310 // プロキシ設定等の通信まわりの初期化が済んでから処理する
311 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
312 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
313 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
315 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
318 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
319 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
321 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
324 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
325 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
326 this.HashMgr = new HashtagManage(this.HashSupl,
327 this.settings.Common.HashTags.ToArray(),
328 this.settings.Common.HashSelected,
329 this.settings.Common.HashIsPermanent,
330 this.settings.Common.HashIsHead,
331 this.settings.Common.HashIsNotAddToAtReply);
332 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
335 this.themeManager = new(this.settings.Local);
336 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager, this.detailsHtmlBuilder);
338 // StringFormatオブジェクトへの事前設定
339 this.sfTab.Alignment = StringAlignment.Center;
340 this.sfTab.LineAlignment = StringAlignment.Center;
342 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
343 this.tweetDetailsView.ClearPostBrowser();
345 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
347 this.inReplyTo = null;
350 this.SearchDialog.Owner = this;
351 this.urlDialog.Owner = this;
354 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
355 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
357 // 新着取得時のリストスクロールをするか。trueならスクロールしない
358 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
359 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
361 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
362 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
365 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
366 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
367 this.myLoc = this.settings.Local.FormLocation;
369 if (this.WindowState != FormWindowState.Minimized)
371 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
372 var outOfScreen = true;
373 if (Screen.AllScreens.Length == 1) // ハングするとの報告
375 foreach (var scr in Screen.AllScreens)
377 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
385 this.myLoc = new Point(0, 0);
387 this.DesktopLocation = this.myLoc;
389 this.TopMost = this.settings.Common.AlwaysTop;
390 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
391 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
392 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
394 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
395 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
397 this.StatusText.Font = this.themeManager.FontInputFont;
398 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
400 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
401 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
402 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
404 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
405 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
407 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
408 if (this.settings.Common.UnreadManage == false)
410 this.ReadedStripMenuItem.Enabled = false;
411 this.UnreadStripMenuItem.Enabled = false;
414 // リンク先URL表示部の初期化(画面左下)
415 this.StatusLabelUrl.Text = "";
417 this.StatusLabel.Text = "";
418 this.StatusLabel.AutoToolTip = false;
419 this.StatusLabel.ToolTipText = "";
421 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
423 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
424 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
425 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
426 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
428 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
429 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
430 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
431 this.SplitContainer2.Panel2.AccessibleName = "";
433 ////////////////////////////////////////////////////////////////////////////////
434 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
435 var mode = this.settings.Common.SortColumn switch
437 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
438 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
439 1 => ComparerMode.Nickname, // ニックネーム
440 2 => ComparerMode.Data, // 本文
441 3 => ComparerMode.Id, // 時刻=発言Id
442 4 => ComparerMode.Name, // 名前
443 7 => ComparerMode.Source, // Source
444 _ => ComparerMode.Id,
446 this.statuses.SetSortMode(mode, sortOrder);
447 ////////////////////////////////////////////////////////////////////////////////
449 this.ApplyListViewIconSize(this.settings.Common.IconSize);
451 // <<<<<<<<タブ関連>>>>>>>
452 foreach (var tab in this.statuses.Tabs)
454 if (!this.AddNewTab(tab, startup: true))
455 throw new TabException(Properties.Resources.TweenMain_LoadText1);
458 this.ListTabSelect(this.ListTab.SelectedTab);
461 this.SetTabAlignment();
463 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
464 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
466 if (this.settings.Common.TabIconDisp)
468 this.ListTab.DrawMode = TabDrawMode.Normal;
472 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
473 this.ListTab.DrawItem += this.ListTab_DrawItem;
474 this.ListTab.ImageList = null;
477 if (this.settings.Common.HotkeyEnabled)
480 var modKey = HookGlobalHotkey.ModKeys.None;
481 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
482 modKey |= HookGlobalHotkey.ModKeys.Alt;
483 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
484 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
485 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
486 modKey |= HookGlobalHotkey.ModKeys.Shift;
487 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
488 modKey |= HookGlobalHotkey.ModKeys.Win;
490 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
493 if (this.settings.Common.IsUseNotifyGrowl)
494 this.gh.RegisterGrowl();
496 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
498 this.SetMainWindowTitle();
499 this.SetNotifyIconText();
501 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
503 this.Visible = false;
508 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
509 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
510 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
511 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
512 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
513 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
514 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
516 this.DoGetFollowersMenu(),
517 this.RefreshBlockIdsAsync(),
518 this.RefreshMuteUserIdsAsync(),
519 this.RefreshNoRetweetIdsAsync(),
520 this.RefreshTwitterConfigurationAsync(),
522 this.RefreshTimelineScheduler();
524 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
525 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
528 this.TimerRefreshIcon.Interval = 200;
529 this.TimerRefreshIcon.Enabled = false;
531 this.ignoreConfigSave = false;
532 this.ApplyLayoutFromSettings();
535 private void TweenMain_Activated(object sender, EventArgs e)
537 // 画面がアクティブになったら、発言欄の背景色戻す
538 if (this.StatusText.Focused)
540 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
544 private bool disposed = false;
547 /// 使用中のリソースをすべてクリーンアップします。
549 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
550 protected override void Dispose(bool disposing)
552 base.Dispose(disposing);
559 this.components?.Dispose();
562 this.SearchDialog.Dispose();
563 this.urlDialog.Dispose();
564 this.themeManager.Dispose();
565 this.sfTab.Dispose();
567 this.timelineScheduler.Dispose();
568 this.workerCts.Cancel();
569 this.thumbnailTokenSource?.Dispose();
571 this.hookGlobalHotkey.Dispose();
574 // 終了時にRemoveHandlerしておかないとメモリリークする
575 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
576 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
577 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
578 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
580 this.disposed = true;
583 private void InitColumns(ListView list, bool startup)
585 this.InitColumnText();
587 ColumnHeader[]? columns = null;
590 if (this.Use2ColumnsMode)
594 new ColumnHeader(), // アイコン
595 new ColumnHeader(), // 本文
598 columns[0].Text = this.columnText[0];
599 columns[1].Text = this.columnText[2];
603 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
605 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
606 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
607 columns[0].DisplayIndex = 0;
608 columns[1].DisplayIndex = 1;
613 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
615 columns[idx].Width = curListColumn.Width;
616 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
625 new ColumnHeader(), // アイコン
626 new ColumnHeader(), // ニックネーム
627 new ColumnHeader(), // 本文
628 new ColumnHeader(), // 日付
629 new ColumnHeader(), // ユーザID
630 new ColumnHeader(), // 未読
631 new ColumnHeader(), // マーク&プロテクト
632 new ColumnHeader(), // ソース
635 foreach (var i in Enumerable.Range(0, columns.Length))
636 columns[i].Text = this.columnText[i];
640 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
642 foreach (var (column, index) in columns.WithIndex())
644 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
645 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
651 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
653 columns[idx].Width = curListColumn.Width;
654 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
660 list.Columns.AddRange(columns);
668 foreach (var column in columns)
674 private void InitColumnText()
676 this.columnText[0] = "";
677 this.columnText[1] = Properties.Resources.AddNewTabText2;
678 this.columnText[2] = Properties.Resources.AddNewTabText3;
679 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
680 this.columnText[4] = Properties.Resources.AddNewTabText5;
681 this.columnText[5] = "";
682 this.columnText[6] = "";
683 this.columnText[7] = "Source";
685 this.columnOrgText[0] = "";
686 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
687 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
688 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
689 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
690 this.columnOrgText[5] = "";
691 this.columnOrgText[6] = "";
692 this.columnOrgText[7] = "Source";
694 var c = this.statuses.SortMode switch
696 ComparerMode.Nickname => 1, // ニックネーム
697 ComparerMode.Data => 2, // 本文
698 ComparerMode.Id => 3, // 時刻=発言Id
699 ComparerMode.Name => 4, // 名前
700 ComparerMode.Source => 7, // Source
704 if (this.Use2ColumnsMode)
706 if (this.statuses.SortOrder == SortOrder.Descending)
708 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
709 this.columnText[2] = this.columnOrgText[2] + "▾";
713 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
714 this.columnText[2] = this.columnOrgText[2] + "▴";
719 if (this.statuses.SortOrder == SortOrder.Descending)
721 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
722 this.columnText[c] = this.columnOrgText[c] + "▾";
726 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
727 this.columnText[c] = this.columnOrgText[c] + "▴";
732 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
737 txt = this.statuses.Tabs[e.Index].TabName;
744 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
745 if (e.State == DrawItemState.Selected)
747 e.DrawFocusRectangle();
752 if (this.statuses.Tabs[txt].UnreadCount > 0)
755 fore = System.Drawing.SystemBrushes.ControlText;
759 fore = System.Drawing.SystemBrushes.ControlText;
761 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
764 private void LoadConfig()
766 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
767 this.statuses.AddDefaultTabs();
770 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
772 this.RefreshTimelineScheduler();
775 private void RefreshTimelineScheduler()
777 static TimeSpan IntervalSecondsOrDisabled(int seconds)
778 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
780 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
781 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
782 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
783 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
784 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
785 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
786 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
787 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
789 this.timelineScheduler.RefreshSchedule();
792 private void MarkSettingCommonModified()
794 if (this.saveConfigDebouncer == null)
797 this.ModifySettingCommon = true;
798 _ = this.saveConfigDebouncer.Call();
801 private void MarkSettingLocalModified()
803 if (this.saveConfigDebouncer == null)
806 this.ModifySettingLocal = true;
807 _ = this.saveConfigDebouncer.Call();
810 internal void MarkSettingAtIdModified()
812 if (this.saveConfigDebouncer == null)
815 this.ModifySettingAtId = true;
816 _ = this.saveConfigDebouncer.Call();
819 internal void RefreshTimeline()
821 var curListView = this.CurrentListView;
823 // 現在表示中のタブのスクロール位置を退避
824 var currentListViewState = this.listViewState[this.CurrentTabName];
825 currentListViewState.Save(this.ListLockMenuItem.Checked);
829 addCount = this.statuses.SubmitUpdate(
832 out var newMentionOrDm,
835 if (MyCommon.EndingFlag) return;
838 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
840 using (ControlTransaction.Update(curListView))
842 this.listCache.PurgeCache();
843 this.listCache.UpdateListSize();
846 currentListViewState.RestoreSelection();
852 if (this.settings.Common.TabIconDisp)
854 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
856 var tabPage = this.ListTab.TabPages[index];
857 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
858 tabPage.ImageIndex = 0; // 未読アイコン
863 this.ListTab.Refresh();
868 currentListViewState.RestoreScroll();
871 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
873 this.SetMainWindowTitle();
874 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
876 this.HashSupl.AddRangeItem(this.tw.GetHashList());
879 private bool BalloonRequired()
884 if (NativeMethods.IsScreenSaverRunning())
888 if (!this.NewPostPopMenuItem.Checked)
891 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
892 if (this.settings.Common.LimitBalloon)
894 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
901 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
903 if (this.settings.Common.ReadOwnPost)
905 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
910 if (this.BalloonRequired())
912 if (notifyPosts != null && notifyPosts.Length > 0)
914 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
915 if (this.settings.Common.IsUseNotifyGrowl)
917 var sb = new StringBuilder();
921 foreach (var post in notifyPosts)
923 if (!(notifyPosts.Length > 3))
929 if (post.IsReply && !post.IsExcludeReply) reply = true;
930 if (post.IsDm) dm = true;
931 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
932 switch (this.settings.Common.NameBalloon)
934 case MyCommon.NameBalloonEnum.UserID:
935 sb.Append(post.ScreenName).Append(" : ");
937 case MyCommon.NameBalloonEnum.NickName:
938 sb.Append(post.Nickname).Append(" : ");
941 sb.Append(post.TextFromApi);
942 if (notifyPosts.Length > 3)
944 if (notifyPosts.Last() != post) continue;
947 var title = new StringBuilder();
948 GrowlHelper.NotifyType nt;
949 if (this.settings.Common.DispUsername)
951 title.Append(this.tw.Username);
957 title.Append(ApplicationSettings.ApplicationName);
958 title.Append(" [DM] ");
959 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
960 nt = GrowlHelper.NotifyType.DirectMessage;
964 title.Append(ApplicationSettings.ApplicationName);
965 title.Append(" [Reply!] ");
966 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
967 nt = GrowlHelper.NotifyType.Reply;
971 title.Append(ApplicationSettings.ApplicationName);
973 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
974 nt = GrowlHelper.NotifyType.Notify;
976 var bText = sb.ToString();
977 if (MyCommon.IsNullOrEmpty(bText)) return;
979 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
980 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
985 var sb = new StringBuilder();
988 foreach (var post in notifyPosts)
990 if (post.IsReply && !post.IsExcludeReply) reply = true;
991 if (post.IsDm) dm = true;
992 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
993 switch (this.settings.Common.NameBalloon)
995 case MyCommon.NameBalloonEnum.UserID:
996 sb.Append(post.ScreenName).Append(" : ");
998 case MyCommon.NameBalloonEnum.NickName:
999 sb.Append(post.Nickname).Append(" : ");
1002 sb.Append(post.TextFromApi);
1005 var title = new StringBuilder();
1007 if (this.settings.Common.DispUsername)
1009 title.Append(this.tw.Username);
1010 title.Append(" - ");
1015 ntIcon = ToolTipIcon.Warning;
1016 title.Append(ApplicationSettings.ApplicationName);
1017 title.Append(" [DM] ");
1018 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1022 ntIcon = ToolTipIcon.Warning;
1023 title.Append(ApplicationSettings.ApplicationName);
1024 title.Append(" [Reply!] ");
1025 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1029 ntIcon = ToolTipIcon.Info;
1030 title.Append(ApplicationSettings.ApplicationName);
1032 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1034 var bText = sb.ToString();
1035 if (MyCommon.IsNullOrEmpty(bText)) return;
1037 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1038 this.NotifyIcon1.BalloonTipText = bText;
1039 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1040 this.NotifyIcon1.ShowBalloonTip(500);
1046 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1050 var dir = Application.StartupPath;
1051 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1053 dir = Path.Combine(dir, "Sounds");
1055 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1063 // mentions新着時に画面ブリンク
1064 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1066 NativeMethods.FlashMyWindow(this.Handle, 3);
1070 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1072 var listView = this.CurrentListView;
1073 if (listView != sender)
1076 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1077 this.CurrentTab.SelectPosts(indices);
1079 if (indices.Length != 1)
1082 var index = indices[0];
1083 if (index > listView.VirtualListSize - 1) return;
1085 this.PushSelectPostChain();
1087 var post = this.CurrentPost!;
1088 this.statuses.SetReadAllTab(post.StatusId, read: true);
1090 this.listCache?.RefreshStyle();
1091 await this.selectionDebouncer.Call();
1094 private void StatusTextHistoryBack()
1096 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1097 var historyItem = this.history.Back();
1098 this.inReplyTo = historyItem.InReplyTo;
1099 this.StatusText.Text = historyItem.Status;
1100 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1103 private void StatusTextHistoryForward()
1105 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1106 var historyItem = this.history.Forward();
1107 this.inReplyTo = historyItem.InReplyTo;
1108 this.StatusText.Text = historyItem.Status;
1109 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1112 private async void PostButton_Click(object sender, EventArgs e)
1114 if (this.StatusText.Text.Trim().Length == 0)
1116 if (!this.ImageSelector.Enabled)
1118 await this.DoRefresh();
1123 var currentPost = this.CurrentPost;
1124 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1126 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1128 MessageBoxButtons.YesNoCancel,
1129 MessageBoxIcon.Question);
1132 case DialogResult.Yes:
1133 this.StatusText.Text = "";
1134 await this.DoReTweetOfficial(false);
1136 case DialogResult.Cancel:
1141 if (TextContainsOnlyMentions(this.StatusText.Text))
1143 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1144 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1146 if (ret != DialogResult.OK)
1150 if (this.settings.Common.Nicoms)
1152 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1153 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1156 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1157 this.CheckReplyTo(this.StatusText.Text);
1159 var status = new PostStatusParams();
1161 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1162 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1164 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1165 // 収まる場合はこれらのオプションを使用せずに投稿する
1166 status.Text = statusTextCompat;
1167 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1171 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1172 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1174 status.AttachmentUrl = attachmentUrl;
1176 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1178 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1179 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1181 status.AutoPopulateReplyMetadata = true;
1183 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1184 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1189 if (this.GetRestStatusCount(status.Text) < 0)
1191 // 文字数制限を超えているが強制的に投稿するか
1192 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1193 if (ret != DialogResult.OK)
1197 IMediaUploadService? uploadService = null;
1198 IMediaItem[]? uploadItems = null;
1199 if (this.ImageSelector.Visible)
1202 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1205 this.ImageSelector.EndSelection();
1206 uploadService = this.ImageSelector.Model.GetService(serviceName);
1209 this.history.AddLast(this.StatusText.Text, this.inReplyTo);
1211 this.inReplyTo = null;
1212 this.StatusText.Text = "";
1213 if (!this.settings.Common.FocusLockToStatusText)
1214 this.CurrentListView.Focus();
1215 this.urlUndoBuffer = null;
1216 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1219 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1221 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1222 await MyCommon.OpenInBrowserAsync(this, tmp);
1225 await this.PostMessageAsync(status, uploadService, uploadItems);
1228 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1230 MyCommon.EndingFlag = true;
1234 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1236 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1238 // _endingFlag=false:フォームの×ボタン
1240 this.Visible = false;
1244 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1245 this.ignoreConfigSave = true;
1246 MyCommon.EndingFlag = true;
1247 this.timelineScheduler.Enabled = false;
1248 this.TimerRefreshIcon.Enabled = false;
1252 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1254 this.Visible = true;
1255 if (this.WindowState == FormWindowState.Minimized)
1257 this.WindowState = FormWindowState.Normal;
1260 this.BringToFront();
1263 private static int errorCount = 0;
1265 private static bool CheckAccountValid()
1267 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1273 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1282 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1283 private Task RefreshTabAsync<T>()
1285 => this.RefreshTabAsync<T>(backward: false);
1287 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1288 private Task RefreshTabAsync<T>(bool backward)
1292 from tab in this.statuses.GetTabsByType<T>()
1293 select this.RefreshTabAsync(tab, backward);
1295 return Task.WhenAll(loadTasks);
1298 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1299 private Task RefreshTabAsync(TabModel tab)
1300 => this.RefreshTabAsync(tab, backward: false);
1302 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1303 private async Task RefreshTabAsync(TabModel tab, bool backward)
1305 await this.workerSemaphore.WaitAsync();
1309 this.RefreshTasktrayIcon();
1310 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1312 catch (WebApiException ex)
1314 this.myStatusError = true;
1315 var tabType = tab switch
1317 HomeTabModel => "GetTimeline",
1318 MentionsTabModel => "GetTimeline",
1319 DirectMessagesTabModel => "GetDirectMessage",
1320 FavoritesTabModel => "GetFavorites",
1321 PublicSearchTabModel => "GetSearch",
1322 UserTimelineTabModel => "GetUserTimeline",
1323 ListTimelineTabModel => "GetListStatus",
1324 RelatedPostsTabModel => "GetRelatedTweets",
1325 _ => tab.GetType().Name.Replace("Model", ""),
1327 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1331 this.RefreshTimeline();
1332 this.workerSemaphore.Release();
1336 private async Task FavAddAsync(PostId statusId, TabModel tab)
1338 await this.workerSemaphore.WaitAsync();
1342 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1344 this.RefreshTasktrayIcon();
1345 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1347 catch (WebApiException ex)
1349 this.myStatusError = true;
1350 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1354 this.workerSemaphore.Release();
1358 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1360 if (ct.IsCancellationRequested)
1363 if (!CheckAccountValid())
1364 throw new WebApiException("Auth error. Check your account");
1366 if (!tab.Posts.TryGetValue(statusId, out var post))
1372 await Task.Run(async () =>
1374 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1378 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1381 await this.tw.Api.FavoritesCreate(twitterStatusId)
1383 .ConfigureAwait(false);
1385 catch (TwitterApiException ex)
1386 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1388 // エラーコード 139 のみの場合は成功と見なす
1391 if (this.settings.Common.RestrictFavCheck)
1393 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1394 .ConfigureAwait(false);
1396 if (status.Favorited != true)
1397 throw new WebApiException("NG(Restricted?)");
1400 this.favTimestamps.Add(DateTimeUtc.Now);
1403 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1405 postTl.IsFav = true;
1407 var favTab = this.statuses.FavoriteTab;
1408 favTab.AddPostQueue(postTl);
1411 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1412 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1414 if (tb.Contains(statusId))
1415 tb.Posts[statusId].IsFav = true;
1418 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1420 catch (WebApiException)
1422 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1427 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1428 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1430 if (this.favTimestamps[i] < oneHour)
1431 this.favTimestamps.RemoveAt(i);
1434 this.statuses.DistributePosts();
1437 if (ct.IsCancellationRequested)
1440 this.RefreshTimeline();
1442 if (this.CurrentTabName == tab.TabName)
1444 using (ControlTransaction.Update(this.CurrentListView))
1446 var idx = tab.IndexOf(statusId);
1448 this.listCache?.RefreshStyle(idx);
1451 var currentPost = this.CurrentPost;
1452 if (currentPost != null && statusId == currentPost.StatusId)
1453 this.DispSelectedPost(true); // 選択アイテム再表示
1457 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1459 await this.workerSemaphore.WaitAsync();
1463 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1465 this.RefreshTasktrayIcon();
1466 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1468 catch (WebApiException ex)
1470 this.myStatusError = true;
1471 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1475 this.workerSemaphore.Release();
1479 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1481 if (ct.IsCancellationRequested)
1484 if (!CheckAccountValid())
1485 throw new WebApiException("Auth error. Check your account");
1487 var successIds = new List<PostId>();
1489 await Task.Run(async () =>
1493 var failedCount = 0;
1494 foreach (var statusId in statusIds)
1498 var post = tab.Posts[statusId];
1500 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1505 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1509 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1511 .ConfigureAwait(false);
1513 catch (WebApiException)
1519 successIds.Add(statusId);
1520 post.IsFav = false; // リスト再描画必要
1522 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1523 tabinfoPost.IsFav = false;
1525 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1526 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1528 if (tb.Contains(statusId))
1529 tb.Posts[statusId].IsFav = false;
1534 if (ct.IsCancellationRequested)
1537 var favTab = this.statuses.FavoriteTab;
1538 foreach (var statusId in successIds)
1540 // ツイートが削除された訳ではないので IsDeleted はセットしない
1541 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1544 this.RefreshTimeline();
1546 if (this.CurrentTabName == tab.TabName)
1548 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1554 using (ControlTransaction.Update(this.CurrentListView))
1556 foreach (var statusId in successIds)
1558 var idx = tab.IndexOf(statusId);
1560 this.listCache?.RefreshStyle(idx);
1564 var currentPost = this.CurrentPost;
1565 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1566 this.DispSelectedPost(true); // 選択アイテム再表示
1571 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1573 await this.workerSemaphore.WaitAsync();
1577 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1579 this.RefreshTasktrayIcon();
1580 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1582 catch (WebApiException ex)
1584 this.myStatusError = true;
1585 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1589 this.workerSemaphore.Release();
1593 private async Task PostMessageAsyncInternal(
1594 IProgress<string> p,
1595 CancellationToken ct,
1596 PostStatusParams postParams,
1597 IMediaUploadService? uploadService,
1598 IMediaItem[]? uploadItems)
1600 if (ct.IsCancellationRequested)
1603 if (!CheckAccountValid())
1604 throw new WebApiException("Auth error. Check your account");
1606 p.Report("Posting...");
1608 PostClass? post = null;
1613 await Task.Run(async () =>
1615 var postParamsWithMedia = postParams;
1617 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1619 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1620 .ConfigureAwait(false);
1623 post = await this.tw.PostStatus(postParamsWithMedia)
1624 .ConfigureAwait(false);
1627 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1629 catch (WebApiException ex)
1631 // 処理は中断せずエラーの表示のみ行う
1632 errMsg = $"Err:{ex.Message}(PostMessage)";
1634 this.myStatusError = true;
1636 catch (UnauthorizedAccessException ex)
1638 // アップロード対象のファイルが開けなかった場合など
1639 errMsg = $"Err:{ex.Message}(PostMessage)";
1641 this.myStatusError = true;
1645 // 使い終わった MediaItem は破棄する
1646 if (uploadItems != null)
1648 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1650 disposableItem.Dispose();
1655 if (ct.IsCancellationRequested)
1658 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1659 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1660 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1662 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1664 var ret = MessageBox.Show(
1666 "Failed to update status",
1667 MessageBoxButtons.RetryCancel,
1668 MessageBoxIcon.Question);
1670 if (ret == DialogResult.Retry)
1672 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1676 this.StatusTextHistoryBack();
1677 this.StatusText.Focus();
1679 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1680 if (this.settings.Common.FocusLockToStatusText)
1681 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1686 this.postTimestamps.Add(DateTimeUtc.Now);
1688 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1689 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1691 if (this.postTimestamps[i] < oneHour)
1692 this.postTimestamps.RemoveAt(i);
1695 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1697 this.HashMgr.ClearHashtag();
1698 this.HashStripSplitButton.Text = "#[-]";
1699 this.HashTogglePullDownMenuItem.Checked = false;
1700 this.HashToggleMenuItem.Checked = false;
1703 this.SetMainWindowTitle();
1708 this.statuses.AddPost(post);
1709 this.statuses.DistributePosts();
1710 this.RefreshTimeline();
1713 if (this.settings.Common.PostAndGet)
1714 await this.RefreshTabAsync<HomeTabModel>();
1717 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1719 await this.workerSemaphore.WaitAsync();
1723 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1725 this.RefreshTasktrayIcon();
1726 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1728 catch (WebApiException ex)
1730 this.myStatusError = true;
1731 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1735 this.workerSemaphore.Release();
1739 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1741 if (ct.IsCancellationRequested)
1744 if (!CheckAccountValid())
1745 throw new WebApiException("Auth error. Check your account");
1748 if (!this.settings.Common.UnreadManage)
1751 read = this.initial && this.settings.Common.Read;
1753 p.Report("Posting...");
1755 var posts = new List<PostClass>();
1757 await Task.Run(async () =>
1759 foreach (var statusId in statusIds)
1761 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1762 if (post != null) posts.Add(post);
1766 if (ct.IsCancellationRequested)
1769 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1771 this.postTimestamps.Add(DateTimeUtc.Now);
1773 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1774 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1776 if (this.postTimestamps[i] < oneHour)
1777 this.postTimestamps.RemoveAt(i);
1780 // 自分のRTはTLの更新では取得できない場合があるので、
1781 // 投稿時取得の有無に関わらず追加しておく
1782 posts.ForEach(post => this.statuses.AddPost(post));
1784 if (this.settings.Common.PostAndGet)
1786 await this.RefreshTabAsync<HomeTabModel>();
1790 this.statuses.DistributePosts();
1791 this.RefreshTimeline();
1795 private async Task RefreshFollowerIdsAsync()
1797 await this.workerSemaphore.WaitAsync();
1801 this.RefreshTasktrayIcon();
1802 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1804 await this.tw.RefreshFollowerIds();
1806 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1808 this.RefreshTimeline();
1809 this.listCache?.PurgeCache();
1810 this.CurrentListView.Refresh();
1812 catch (WebApiException ex)
1814 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1818 this.workerSemaphore.Release();
1822 private async Task RefreshNoRetweetIdsAsync()
1824 await this.workerSemaphore.WaitAsync();
1828 this.RefreshTasktrayIcon();
1829 await this.tw.RefreshNoRetweetIds();
1831 this.StatusLabel.Text = "NoRetweetIds refreshed";
1833 catch (WebApiException ex)
1835 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1839 this.workerSemaphore.Release();
1843 private async Task RefreshBlockIdsAsync()
1845 await this.workerSemaphore.WaitAsync();
1849 this.RefreshTasktrayIcon();
1850 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1852 await this.tw.RefreshBlockIds();
1854 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1856 catch (WebApiException ex)
1858 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1862 this.workerSemaphore.Release();
1866 private async Task RefreshTwitterConfigurationAsync()
1868 await this.workerSemaphore.WaitAsync();
1872 this.RefreshTasktrayIcon();
1873 await this.tw.RefreshConfiguration();
1875 if (this.tw.Configuration.PhotoSizeLimit != 0)
1877 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1879 service.UpdateTwitterConfiguration(this.tw.Configuration);
1883 this.listCache?.PurgeCache();
1884 this.CurrentListView.Refresh();
1886 catch (WebApiException ex)
1888 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1892 this.workerSemaphore.Release();
1896 private async Task RefreshMuteUserIdsAsync()
1898 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1902 await this.tw.RefreshMuteUserIdsAsync();
1904 catch (WebApiException ex)
1906 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1910 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1913 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1915 if (e.Button == MouseButtons.Left)
1917 this.Visible = true;
1918 if (this.WindowState == FormWindowState.Minimized)
1920 this.WindowState = this.formWindowState;
1923 this.BringToFront();
1927 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1928 => await this.ListItemDoubleClickAction();
1930 private async Task ListItemDoubleClickAction()
1932 switch (this.settings.Common.ListDoubleClickAction)
1934 case MyCommon.ListItemDoubleClickActionType.Reply:
1935 this.MakeReplyText();
1937 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1938 this.MakeReplyText(atAll: true);
1940 case MyCommon.ListItemDoubleClickActionType.Favorite:
1941 await this.FavoriteChange(true);
1943 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1944 var post = this.CurrentPost;
1946 await this.ShowUserStatus(post.ScreenName, false);
1948 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
1949 await this.ShowUserTimeline();
1951 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
1952 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
1954 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
1955 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
1957 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
1958 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
1960 case MyCommon.ListItemDoubleClickActionType.None:
1967 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
1968 => await this.FavoriteChange(true);
1970 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
1971 => await this.FavoriteChange(false);
1973 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
1974 => await this.FavoritesRetweetOfficial();
1976 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
1977 => await this.FavoritesRetweetUnofficial();
1979 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
1981 var tab = this.CurrentTab;
1982 var posts = tab.SelectedPosts;
1984 // trueでFavAdd,falseでFavRemove
1985 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
1986 || !this.ExistCurrentPost) return;
1988 if (posts.Length > 1)
1993 // https://support.twitter.com/articles/76915#favoriting
1994 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
1995 this.doFavRetweetFlags = false;
2000 if (multiFavoriteChangeDialogEnable)
2002 var confirm = MessageBox.Show(
2003 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2004 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2005 MessageBoxButtons.OKCancel,
2006 MessageBoxIcon.Question);
2008 if (confirm == DialogResult.Cancel)
2016 var selectedPost = posts.Single();
2017 if (selectedPost.IsFav)
2019 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2023 await this.FavAddAsync(selectedPost.StatusId, tab);
2027 var selectedPosts = posts.Where(x => x.IsFav);
2028 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2029 if (statusIds.Length == 0)
2031 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2035 await this.FavRemoveAsync(statusIds, tab);
2039 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2041 var post = this.CurrentPost;
2043 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2045 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2048 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2050 if ((!this.initialLayout) && this.Visible)
2052 if (this.WindowState == FormWindowState.Normal)
2054 this.mySize = this.ClientSize;
2055 this.mySpDis = this.SplitContainer1.SplitterDistance;
2056 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2057 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2058 this.MarkSettingLocalModified();
2063 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2065 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2066 if (comparerMode == null)
2069 this.SetSortColumn(comparerMode.Value);
2073 /// 列インデックスからソートを行う ComparerMode を求める
2075 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2076 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2077 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2079 if (this.Use2ColumnsMode)
2080 return ComparerMode.Id;
2082 return columnIndex switch
2084 1 => ComparerMode.Nickname, // ニックネーム
2085 2 => ComparerMode.Data, // 本文
2086 3 => ComparerMode.Id, // 時刻=発言Id
2087 4 => ComparerMode.Name, // 名前
2088 7 => ComparerMode.Source, // Source
2089 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2094 /// 発言一覧の指定した位置の列でソートする
2096 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2097 private void SetSortColumnByDisplayIndex(int columnIndex)
2099 // 表示上の列の位置から ColumnHeader を求める
2100 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2101 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2106 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2107 if (comparerMode == null)
2110 this.SetSortColumn(comparerMode.Value);
2114 /// 発言一覧の最後列の項目でソートする
2116 private void SetSortLastColumn()
2118 // 表示上の最後列にある ColumnHeader を求める
2119 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2120 .OrderByDescending(x => x.DisplayIndex)
2123 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2124 if (comparerMode == null)
2127 this.SetSortColumn(comparerMode.Value);
2131 /// 発言一覧を指定された ComparerMode に基づいてソートする
2133 private void SetSortColumn(ComparerMode sortColumn)
2135 if (this.settings.Common.SortOrderLock)
2138 this.statuses.ToggleSortOrder(sortColumn);
2139 this.InitColumnText();
2141 var list = this.CurrentListView;
2142 if (this.Use2ColumnsMode)
2144 list.Columns[0].Text = this.columnText[0];
2145 list.Columns[1].Text = this.columnText[2];
2149 for (var i = 0; i <= 7; i++)
2151 list.Columns[i].Text = this.columnText[i];
2155 this.listCache?.PurgeCache();
2157 var tab = this.CurrentTab;
2158 var post = this.CurrentPost;
2159 if (tab.AllCount > 0 && post != null)
2161 var idx = tab.IndexOf(post.StatusId);
2164 this.SelectListItem(list, idx);
2165 list.EnsureVisible(idx);
2170 this.MarkSettingCommonModified();
2173 private void TweenMain_LocationChanged(object sender, EventArgs e)
2175 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2177 this.myLoc = this.DesktopLocation;
2178 this.MarkSettingLocalModified();
2182 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2184 var post = this.CurrentPost;
2185 if (!this.ExistCurrentPost)
2187 this.ReplyStripMenuItem.Enabled = false;
2188 this.ReplyAllStripMenuItem.Enabled = false;
2189 this.DMStripMenuItem.Enabled = false;
2190 this.TabMenuItem.Enabled = false;
2191 this.IDRuleMenuItem.Enabled = false;
2192 this.SourceRuleMenuItem.Enabled = false;
2193 this.ReadedStripMenuItem.Enabled = false;
2194 this.UnreadStripMenuItem.Enabled = false;
2195 this.AuthorContextMenuItem.Visible = false;
2196 this.RetweetedByContextMenuItem.Visible = false;
2200 this.ReplyStripMenuItem.Enabled = true;
2201 this.ReplyAllStripMenuItem.Enabled = true;
2202 this.DMStripMenuItem.Enabled = true;
2203 this.TabMenuItem.Enabled = true;
2204 this.IDRuleMenuItem.Enabled = true;
2205 this.SourceRuleMenuItem.Enabled = true;
2206 this.ReadedStripMenuItem.Enabled = true;
2207 this.UnreadStripMenuItem.Enabled = true;
2208 this.AuthorContextMenuItem.Visible = true;
2209 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2210 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2211 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2213 var tab = this.CurrentTab;
2214 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2216 this.FavAddToolStripMenuItem.Enabled = false;
2217 this.FavRemoveToolStripMenuItem.Enabled = false;
2218 this.StatusOpenMenuItem.Enabled = false;
2219 this.ShowRelatedStatusesMenuItem.Enabled = false;
2221 this.ReTweetStripMenuItem.Enabled = false;
2222 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2223 this.QuoteStripMenuItem.Enabled = false;
2224 this.FavoriteRetweetContextMenu.Enabled = false;
2225 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2229 this.FavAddToolStripMenuItem.Enabled = true;
2230 this.FavRemoveToolStripMenuItem.Enabled = true;
2231 this.StatusOpenMenuItem.Enabled = true;
2232 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2234 if (!post.CanRetweetBy(this.tw.UserId))
2236 this.ReTweetStripMenuItem.Enabled = false;
2237 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2238 this.QuoteStripMenuItem.Enabled = false;
2239 this.FavoriteRetweetContextMenu.Enabled = false;
2240 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2244 this.ReTweetStripMenuItem.Enabled = true;
2245 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2246 this.QuoteStripMenuItem.Enabled = true;
2247 this.FavoriteRetweetContextMenu.Enabled = true;
2248 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2252 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2254 this.RepliedStatusOpenMenuItem.Enabled = false;
2258 this.RepliedStatusOpenMenuItem.Enabled = true;
2261 if (this.ExistCurrentPost && post != null)
2263 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2264 if (post.RetweetedByUserId == this.tw.UserId)
2265 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2267 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2271 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2272 => this.MakeReplyText();
2274 private void DMStripMenuItem_Click(object sender, EventArgs e)
2275 => this.MakeDirectMessageText();
2277 private async Task DoStatusDelete()
2279 var posts = this.CurrentTab.SelectedPosts;
2280 if (posts.Length == 0)
2283 // 選択されたツイートの中に削除可能なものが一つでもあるか
2284 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2287 var ret = MessageBox.Show(
2289 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2290 Properties.Resources.DeleteStripMenuItem_ClickText2,
2291 MessageBoxButtons.OKCancel,
2292 MessageBoxIcon.Question);
2294 if (ret != DialogResult.OK)
2297 var currentListView = this.CurrentListView;
2298 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2300 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2302 Exception? lastException = null;
2303 foreach (var post in posts)
2305 if (!post.CanDeleteBy(this.tw.UserId))
2310 if (post.StatusId is TwitterDirectMessageId dmId)
2312 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2316 if (post.RetweetedByUserId == this.tw.UserId)
2318 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2320 await this.tw.DeleteRetweet(post);
2324 if (post.UserId == this.tw.UserId)
2326 if (post.RetweetedId != null)
2328 // 他人に RT された自分のツイート
2329 // => RT 元の自分のツイートを削除
2330 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2336 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2342 catch (WebApiException ex)
2348 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2351 if (lastException == null)
2352 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2354 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2356 using (ControlTransaction.Update(currentListView))
2358 this.listCache?.PurgeCache();
2359 this.listCache?.UpdateListSize();
2361 currentListView.SelectedIndices.Clear();
2363 var currentTab = this.CurrentTab;
2364 if (currentTab.AllCount != 0)
2367 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2368 selectedIndex = focusedIndex;
2370 selectedIndex = currentTab.AllCount - 1;
2372 currentListView.SelectedIndices.Add(selectedIndex);
2373 currentListView.EnsureVisible(selectedIndex);
2374 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2378 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2380 var tabPage = this.ListTab.TabPages[index];
2381 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2383 if (tabPage.ImageIndex == 0)
2384 tabPage.ImageIndex = -1; // タブアイコン
2388 if (!this.settings.Common.TabIconDisp)
2389 this.ListTab.Refresh();
2393 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2394 => await this.DoStatusDelete();
2396 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2398 using (ControlTransaction.Update(this.CurrentListView))
2400 var tab = this.CurrentTab;
2401 foreach (var statusId in tab.SelectedStatusIds)
2403 this.statuses.SetReadAllTab(statusId, read: true);
2404 var idx = tab.IndexOf(statusId);
2405 this.listCache?.RefreshStyle(idx);
2408 if (this.settings.Common.TabIconDisp)
2410 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2412 if (tab.UnreadCount == 0)
2414 var tabPage = this.ListTab.TabPages[index];
2415 if (tabPage.ImageIndex == 0)
2416 tabPage.ImageIndex = -1; // タブアイコン
2420 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2423 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2425 using (ControlTransaction.Update(this.CurrentListView))
2427 var tab = this.CurrentTab;
2428 foreach (var statusId in tab.SelectedStatusIds)
2430 this.statuses.SetReadAllTab(statusId, read: false);
2431 var idx = tab.IndexOf(statusId);
2432 this.listCache?.RefreshStyle(idx);
2435 if (this.settings.Common.TabIconDisp)
2437 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2439 if (tab.UnreadCount > 0)
2441 var tabPage = this.ListTab.TabPages[index];
2442 if (tabPage.ImageIndex == -1)
2443 tabPage.ImageIndex = 0; // タブアイコン
2447 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2450 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2451 => await this.DoRefresh();
2453 private async Task DoRefresh()
2454 => await this.RefreshTabAsync(this.CurrentTab);
2456 private async Task DoRefreshMore()
2457 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2459 private DialogResult ShowSettingDialog()
2461 using var settingDialog = new AppendSettingDialog();
2462 settingDialog.Icon = this.iconAssets.IconMain;
2463 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2465 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2467 DialogResult result;
2470 result = settingDialog.ShowDialog(this);
2474 return DialogResult.Abort;
2477 if (result == DialogResult.OK)
2479 lock (this.syncObject)
2481 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2488 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2491 var previousUserId = this.settings.Common.UserId;
2492 var oldIconCol = this.Use2ColumnsMode;
2494 if (this.ShowSettingDialog() == DialogResult.OK)
2496 lock (this.syncObject)
2498 this.settings.ApplySettings();
2500 this.accounts.LoadFromSettings(this.settings.Common);
2501 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2505 if (this.settings.Common.TabIconDisp)
2507 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2508 this.ListTab.DrawMode = TabDrawMode.Normal;
2509 this.ListTab.ImageList = this.TabImage;
2513 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2514 this.ListTab.DrawItem += this.ListTab_DrawItem;
2515 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2516 this.ListTab.ImageList = null;
2519 catch (Exception ex)
2521 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2522 ex.Data["IsTerminatePermission"] = false;
2528 if (!this.settings.Common.UnreadManage)
2530 this.ReadedStripMenuItem.Enabled = false;
2531 this.UnreadStripMenuItem.Enabled = false;
2532 if (this.settings.Common.TabIconDisp)
2534 foreach (TabPage myTab in this.ListTab.TabPages)
2536 myTab.ImageIndex = -1;
2542 this.ReadedStripMenuItem.Enabled = true;
2543 this.UnreadStripMenuItem.Enabled = true;
2546 catch (Exception ex)
2548 ex.Data["Instance"] = "ListTab(UnreadManage)";
2549 ex.Data["IsTerminatePermission"] = false;
2554 this.SetTabAlignment();
2556 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2558 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2559 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2560 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2562 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2563 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2564 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2565 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2567 var newTheme = new ThemeManager(this.settings.Local);
2568 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2569 this.tweetDetailsView.Theme = this.themeManager;
2570 if (this.listDrawer != null)
2571 this.listDrawer.Theme = this.themeManager;
2576 if (this.StatusText.Focused)
2577 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2579 this.StatusText.Font = this.themeManager.FontInputFont;
2580 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2582 catch (Exception ex)
2584 MessageBox.Show(ex.Message);
2589 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
2591 catch (Exception ex)
2593 ex.Data["Instance"] = "Font";
2594 ex.Data["IsTerminatePermission"] = false;
2600 if (this.settings.Common.TabIconDisp)
2602 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2604 var tabPage = this.ListTab.TabPages[index];
2605 if (tab.UnreadCount == 0)
2606 tabPage.ImageIndex = -1;
2608 tabPage.ImageIndex = 0;
2612 catch (Exception ex)
2614 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2615 ex.Data["IsTerminatePermission"] = false;
2621 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2623 foreach (TabPage tp in this.ListTab.TabPages)
2625 var lst = (DetailsListView)tp.Tag;
2627 using (ControlTransaction.Update(lst))
2629 lst.GridLines = this.settings.Common.ShowGrid;
2631 if (this.Use2ColumnsMode != oldIconCol)
2632 this.ResetColumns(lst);
2636 catch (Exception ex)
2638 ex.Data["Instance"] = "ListView(IconSize)";
2639 ex.Data["IsTerminatePermission"] = false;
2643 this.SetMainWindowTitle();
2644 this.SetNotifyIconText();
2646 this.listCache?.PurgeCache();
2647 this.CurrentListView.Refresh();
2648 this.ListTab.Refresh();
2650 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2651 if (this.settings.Common.HotkeyEnabled)
2653 // グローバルホットキーの登録。設定で変更可能にするかも
2654 var modKey = HookGlobalHotkey.ModKeys.None;
2655 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2656 modKey |= HookGlobalHotkey.ModKeys.Alt;
2657 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2658 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2659 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2660 modKey |= HookGlobalHotkey.ModKeys.Shift;
2661 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2662 modKey |= HookGlobalHotkey.ModKeys.Win;
2664 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2667 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2670 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2678 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2680 this.TopMost = this.settings.Common.AlwaysTop;
2681 this.SaveConfigsAll(false);
2683 if (this.tw.UserId != previousUserId)
2684 await this.DoGetFollowersMenu();
2690 private void SetTabAlignment()
2692 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2693 if (this.ListTab.Alignment == newAlignment) return;
2696 var currentListViewState = this.listViewState[this.CurrentTabName];
2697 currentListViewState.Save(this.ListLockMenuItem.Checked);
2699 this.ListTab.Alignment = newAlignment;
2701 currentListViewState.Restore(forceScroll: true);
2704 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2707 if (this.listDrawer != null)
2709 this.listDrawer.IconSize = iconSz;
2710 this.listDrawer.UpdateItemHeight();
2713 this.listCache?.PurgeCache();
2716 private void ResetColumns(DetailsListView list)
2718 using (ControlTransaction.Update(list))
2719 using (ControlTransaction.Layout(list, false))
2722 list.ColumnClick -= this.MyList_ColumnClick;
2723 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2724 list.ColumnReordered -= this.MyList_ColumnReordered;
2725 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2727 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2728 list.Columns.Clear();
2729 cols.ForEach(col => col.Dispose());
2732 this.InitColumns(list, true);
2734 list.ColumnClick += this.MyList_ColumnClick;
2735 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2736 list.ColumnReordered += this.MyList_ColumnReordered;
2737 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2741 public void AddNewTabForSearch(string searchWord)
2743 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2744 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2746 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2748 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2749 this.ListTab.SelectedIndex = tabIndex;
2754 var tabName = searchWord;
2755 for (var i = 0; i <= 100; i++)
2757 if (this.statuses.ContainsTab(tabName))
2763 var tab = new PublicSearchTabModel(tabName);
2764 this.statuses.AddTab(tab);
2765 this.AddNewTab(tab, startup: false);
2767 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2769 var tabPage = this.CurrentTabPage;
2770 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2771 cmb.Items.Add(searchWord);
2772 cmb.Text = searchWord;
2773 this.SaveConfigsTabs();
2775 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2778 private async Task ShowUserTimeline()
2780 var post = this.CurrentPost;
2781 if (post == null || !this.ExistCurrentPost) return;
2782 await this.AddNewTabForUserTimeline(post.ScreenName);
2785 private async Task ShowRetweeterTimeline()
2787 var retweetedBy = this.CurrentPost?.RetweetedBy;
2788 if (retweetedBy == null || !this.ExistCurrentPost) return;
2789 await this.AddNewTabForUserTimeline(retweetedBy);
2792 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2794 if (e.KeyCode == Keys.Escape)
2796 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2797 this.SaveConfigsTabs();
2798 e.SuppressKeyPress = true;
2802 public async Task AddNewTabForUserTimeline(string user)
2804 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2805 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2807 if (tb.ScreenName == user)
2809 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2810 this.ListTab.SelectedIndex = tabIndex;
2815 var tabName = "user:" + user;
2816 while (this.statuses.ContainsTab(tabName))
2821 var tab = new UserTimelineTabModel(tabName, user);
2822 this.statuses.AddTab(tab);
2823 this.AddNewTab(tab, startup: false);
2825 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2826 this.SaveConfigsTabs();
2828 await this.RefreshTabAsync(tab);
2831 public bool AddNewTab(TabModel tab, bool startup)
2834 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2838 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2840 var tabPage = new TabPage();
2841 var listCustom = new DetailsListView();
2843 var cnt = this.statuses.Tabs.Count;
2845 // ToDo:Create and set controls follow tabtypes
2847 using (ControlTransaction.Update(listCustom))
2848 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2849 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2850 using (ControlTransaction.Layout(this.SplitContainer1, false))
2851 using (ControlTransaction.Layout(this.ListTab, false))
2852 using (ControlTransaction.Layout(this))
2853 using (ControlTransaction.Layout(tabPage, false))
2855 tabPage.Controls.Add(listCustom);
2858 var userTab = tab as UserTimelineTabModel;
2859 var listTab = tab as ListTimelineTabModel;
2860 var searchTab = tab as PublicSearchTabModel;
2862 if (userTab != null || listTab != null)
2864 var label = new Label
2866 Dock = DockStyle.Top,
2871 if (listTab != null)
2873 label.Text = listTab.ListInfo.ToString();
2875 else if (userTab != null)
2877 label.Text = userTab.ScreenName + "'s Timeline";
2879 label.TextAlign = ContentAlignment.MiddleLeft;
2880 using (var tmpComboBox = new ComboBox())
2882 label.Height = tmpComboBox.Height;
2884 tabPage.Controls.Add(label);
2887 else if (searchTab != null)
2889 var pnl = new Panel();
2891 var lbl = new Label();
2892 var cmb = new ComboBox();
2893 var btn = new Button();
2894 var cmbLang = new ComboBox();
2896 using (ControlTransaction.Layout(pnl, false))
2898 pnl.Controls.Add(cmb);
2899 pnl.Controls.Add(cmbLang);
2900 pnl.Controls.Add(btn);
2901 pnl.Controls.Add(lbl);
2902 pnl.Name = "panelSearch";
2904 pnl.Dock = DockStyle.Top;
2905 pnl.Height = cmb.Height;
2906 pnl.Enter += this.SearchControls_Enter;
2907 pnl.Leave += this.SearchControls_Leave;
2910 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2911 cmb.Dock = DockStyle.Fill;
2912 cmb.Name = "comboSearch";
2913 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2914 cmb.ImeMode = ImeMode.NoControl;
2915 cmb.TabStop = false;
2917 cmb.AutoCompleteMode = AutoCompleteMode.None;
2918 cmb.KeyDown += this.SearchComboBox_KeyDown;
2921 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2922 cmbLang.Dock = DockStyle.Right;
2924 cmbLang.Name = "comboLang";
2925 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2926 cmbLang.TabStop = false;
2927 cmbLang.TabIndex = 2;
2928 cmbLang.Items.Add("");
2929 cmbLang.Items.Add("ja");
2930 cmbLang.Items.Add("en");
2931 cmbLang.Items.Add("ar");
2932 cmbLang.Items.Add("da");
2933 cmbLang.Items.Add("nl");
2934 cmbLang.Items.Add("fa");
2935 cmbLang.Items.Add("fi");
2936 cmbLang.Items.Add("fr");
2937 cmbLang.Items.Add("de");
2938 cmbLang.Items.Add("hu");
2939 cmbLang.Items.Add("is");
2940 cmbLang.Items.Add("it");
2941 cmbLang.Items.Add("no");
2942 cmbLang.Items.Add("pl");
2943 cmbLang.Items.Add("pt");
2944 cmbLang.Items.Add("ru");
2945 cmbLang.Items.Add("es");
2946 cmbLang.Items.Add("sv");
2947 cmbLang.Items.Add("th");
2949 lbl.Text = "Search(C-S-f)";
2950 lbl.Name = "label1";
2951 lbl.Dock = DockStyle.Left;
2953 lbl.Height = cmb.Height;
2954 lbl.TextAlign = ContentAlignment.MiddleLeft;
2957 btn.Text = "Search";
2958 btn.Name = "buttonSearch";
2959 btn.UseVisualStyleBackColor = true;
2960 btn.Dock = DockStyle.Right;
2961 btn.TabStop = false;
2963 btn.Click += this.SearchButton_Click;
2965 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
2967 cmb.Items.Add(searchTab.SearchWords);
2968 cmb.Text = searchTab.SearchWords;
2971 cmbLang.Text = searchTab.SearchLang;
2973 tabPage.Controls.Add(pnl);
2977 tabPage.Tag = listCustom;
2978 this.ListTab.Controls.Add(tabPage);
2980 tabPage.Location = new Point(4, 4);
2981 tabPage.Name = "CTab" + cnt;
2982 tabPage.Size = new Size(380, 260);
2983 tabPage.TabIndex = 2 + cnt;
2984 tabPage.Text = tab.TabName;
2985 tabPage.UseVisualStyleBackColor = true;
2986 tabPage.AccessibleRole = AccessibleRole.PageTab;
2988 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
2989 listCustom.TabIndex = 1;
2990 listCustom.AllowColumnReorder = true;
2991 listCustom.ContextMenuStrip = this.ContextMenuOperate;
2992 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
2993 listCustom.Dock = DockStyle.Fill;
2994 listCustom.FullRowSelect = true;
2995 listCustom.HideSelection = false;
2996 listCustom.Location = new Point(0, 0);
2997 listCustom.Margin = new Padding(0);
2998 listCustom.Name = "CList" + Environment.TickCount;
2999 listCustom.ShowItemToolTips = true;
3000 listCustom.Size = new Size(380, 260);
3001 listCustom.UseCompatibleStateImageBehavior = false;
3002 listCustom.View = View.Details;
3003 listCustom.OwnerDraw = true;
3004 listCustom.VirtualMode = true;
3006 listCustom.GridLines = this.settings.Common.ShowGrid;
3007 listCustom.AllowDrop = true;
3009 this.InitColumns(listCustom, startup);
3011 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3012 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3013 listCustom.ColumnClick += this.MyList_ColumnClick;
3014 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3015 listCustom.DragDrop += this.TweenMain_DragDrop;
3016 listCustom.DragEnter += this.TweenMain_DragEnter;
3017 listCustom.DragOver += this.TweenMain_DragOver;
3018 listCustom.MouseClick += this.MyList_MouseClick;
3019 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3020 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3021 listCustom.HScrolled += this.MyList_HScrolled;
3024 var state = new TimelineListViewState(listCustom, tab);
3025 this.listViewState[tab.TabName] = state;
3030 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3032 var tabInfo = this.statuses.GetTabByName(tabName);
3033 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3038 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3039 var result = MessageBox.Show(
3041 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3042 MessageBoxButtons.OKCancel,
3043 MessageBoxIcon.Question,
3044 MessageBoxDefaultButton.Button2);
3045 if (result == DialogResult.Cancel)
3051 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3055 var tabPage = this.ListTab.TabPages[tabIndex];
3057 this.SetListProperty(); // 他のタブに列幅等を反映
3059 this.listViewState.Remove(tabName);
3062 var listCustom = (DetailsListView)tabPage.Tag;
3065 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3066 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3067 using (ControlTransaction.Layout(this.SplitContainer1, false))
3068 using (ControlTransaction.Layout(this.ListTab, false))
3069 using (ControlTransaction.Layout(this))
3070 using (ControlTransaction.Layout(tabPage, false))
3072 if (this.CurrentTabName == tabName)
3074 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3075 this.beforeSelectedTab = null;
3077 this.ListTab.Controls.Remove(tabPage);
3080 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3082 using var label = tabPage.Controls["labelUser"];
3083 tabPage.Controls.Remove(label);
3085 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3087 using var pnl = tabPage.Controls["panelSearch"];
3089 pnl.Enter -= this.SearchControls_Enter;
3090 pnl.Leave -= this.SearchControls_Leave;
3091 tabPage.Controls.Remove(pnl);
3093 foreach (Control ctrl in pnl.Controls)
3095 if (ctrl.Name == "buttonSearch")
3097 ctrl.Click -= this.SearchButton_Click;
3099 else if (ctrl.Name == "comboSearch")
3101 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3103 pnl.Controls.Remove(ctrl);
3108 tabPage.Controls.Remove(listCustom);
3110 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3111 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3112 listCustom.ColumnClick -= this.MyList_ColumnClick;
3113 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3114 listCustom.DragDrop -= this.TweenMain_DragDrop;
3115 listCustom.DragEnter -= this.TweenMain_DragEnter;
3116 listCustom.DragOver -= this.TweenMain_DragOver;
3117 listCustom.MouseClick -= this.MyList_MouseClick;
3118 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3119 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3120 listCustom.HScrolled -= this.MyList_HScrolled;
3122 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3123 listCustom.Columns.Clear();
3124 cols.ForEach(col => col.Dispose());
3127 listCustom.ContextMenuStrip = null;
3128 listCustom.ColumnHeaderContextMenuStrip = null;
3129 listCustom.Font = null;
3131 listCustom.SmallImageList = null;
3132 listCustom.ListViewItemSorter = null;
3135 this.listCache?.PurgeCache();
3139 listCustom.Dispose();
3140 this.statuses.RemoveTab(tabName);
3145 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3147 this.listCache?.PurgeCache();
3148 this.beforeSelectedTab = e.TabPage;
3151 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3155 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3158 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3159 if (!dragEnableRectangle.Contains(e.Location))
3161 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3162 tn = this.CurrentTabName;
3165 if (MyCommon.IsNullOrEmpty(tn)) return;
3167 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3170 var tabPage = this.ListTab.TabPages[tabIndex];
3171 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3176 this.tabDrag = false;
3179 var cpos = new Point(e.X, e.Y);
3180 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3182 var rect = this.ListTab.GetTabRect(index);
3183 if (rect.Contains(cpos))
3185 this.rclickTabName = tab.TabName;
3191 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3193 this.SetMainWindowTitle();
3194 this.SetStatusLabelUrl();
3195 this.SetApiStatusLabel();
3196 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3197 this.Tag = this.ListTab.Tag;
3198 this.TabMenuControl(this.CurrentTabName);
3199 this.PushSelectPostChain();
3200 this.DispSelectedPost();
3203 private void SetListProperty()
3205 if (!this.isColumnChanged) return;
3207 var currentListView = this.CurrentListView;
3209 var dispOrder = new int[currentListView.Columns.Count];
3210 for (var i = 0; i < currentListView.Columns.Count; i++)
3212 for (var j = 0; j < currentListView.Columns.Count; j++)
3214 if (currentListView.Columns[j].DisplayIndex == i)
3223 foreach (TabPage tb in this.ListTab.TabPages)
3225 if (tb.Text == this.CurrentTabName)
3228 if (tb.Tag != null && tb.Controls.Count > 0)
3230 var lst = (DetailsListView)tb.Tag;
3231 for (var i = 0; i < lst.Columns.Count; i++)
3233 lst.Columns[dispOrder[i]].DisplayIndex = i;
3234 lst.Columns[i].Width = currentListView.Columns[i].Width;
3239 this.isColumnChanged = false;
3242 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3244 if (e.KeyChar == '@')
3246 if (!this.settings.Common.UseAtIdSupplement) return;
3248 var cnt = this.AtIdSupl.ItemCount;
3249 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3250 if (cnt != this.AtIdSupl.ItemCount)
3251 this.MarkSettingAtIdModified();
3254 else if (e.KeyChar == '#')
3256 if (!this.settings.Common.UseHashSupplement) return;
3257 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3262 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3263 => this.ShowSuplDialog(owner, dialog, 0, "");
3265 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3266 => this.ShowSuplDialog(owner, dialog, offset, "");
3268 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3270 dialog.StartsWith = startswith;
3277 dialog.ShowDialog();
3279 this.TopMost = this.settings.Common.AlwaysTop;
3280 var selStart = owner.SelectionStart;
3283 if (dialog.DialogResult == DialogResult.OK)
3285 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3289 fHalf = owner.Text.Substring(0, selStart - offset);
3291 if (selStart < owner.Text.Length)
3293 eHalf = owner.Text.Substring(selStart);
3295 owner.Text = fHalf + dialog.InputText + eHalf;
3296 owner.SelectionStart = selStart + dialog.InputText.Length;
3303 fHalf = owner.Text.Substring(0, selStart);
3305 if (selStart < owner.Text.Length)
3307 eHalf = owner.Text.Substring(selStart);
3309 owner.Text = fHalf + eHalf;
3312 owner.SelectionStart = selStart;
3318 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3321 if (!e.Alt && !e.Control && !e.Shift)
3323 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3325 var isSpace = false;
3326 foreach (var c in this.StatusText.Text)
3328 if (c == ' ' || c == ' ')
3341 this.StatusText.Text = "";
3342 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3346 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3349 private void StatusText_TextChanged(object sender, EventArgs e)
3352 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3353 this.lblLen.Text = pLen.ToString();
3356 this.StatusText.ForeColor = Color.Red;
3360 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3363 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3365 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3367 this.inReplyTo = null;
3372 /// メンション以外の文字列が含まれていないテキストであるか判定します
3374 internal static bool TextContainsOnlyMentions(string text)
3376 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3379 foreach (var mention in mentions)
3381 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3383 if (!string.IsNullOrWhiteSpace(textPart))
3386 startIndex = mention.Indices[1];
3389 var textPartLast = text.Substring(startIndex);
3391 if (!string.IsNullOrWhiteSpace(textPartLast))
3398 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3400 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3402 var autoPopulatedUserIdList = new List<long>();
3404 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3405 if (replyToPost != null)
3407 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3409 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3410 autoPopulatedUserIdList.Add(replyToPost.UserId);
3412 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3414 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3416 statusText = statusText.Substring(screenName.Length + 2);
3417 autoPopulatedUserIdList.Add(userId);
3423 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3429 /// attachment_url に指定可能な URL が含まれていれば除去
3431 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3433 attachmentUrl = null;
3435 // attachment_url は media_id と同時に使用できない
3436 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3439 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3443 attachmentUrl = match.Value;
3446 statusText = statusText.Substring(0, match.Index);
3448 // テキストと URL の間にスペースが含まれていれば除去
3449 return statusText.TrimEnd(' ');
3452 private string FormatStatusTextExtended(string statusText)
3453 => this.FormatStatusTextExtended(statusText, out _, out _);
3456 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3458 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3460 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3462 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3464 return this.FormatStatusText(statusText);
3467 internal string FormatStatusText(string statusText)
3468 => this.FormatStatusText(statusText, Control.ModifierKeys);
3471 /// ツイート投稿前のフッター付与などの前処理を行います
3473 internal string FormatStatusText(string statusText, Keys modifierKeys)
3475 statusText = statusText.Replace("\r\n", "\n");
3477 if (this.SeparateUrlAndFullwidthCharacter)
3480 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3483 if (this.settings.Common.WideSpaceConvert)
3485 // 文中の全角スペースを半角スペース1個にする
3486 statusText = statusText.Replace(" ", " ");
3489 // DM の場合はこれ以降の処理を行わない
3490 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3494 if (this.settings.Common.PostShiftEnter)
3496 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3500 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3501 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3503 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3506 if (statusText.Contains("RT @"))
3507 disableFooter = true;
3509 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3510 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3512 var mentionSelf = $"@{this.tw.Username} ";
3513 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3515 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3516 statusText = statusText.Substring(mentionSelf.Length);
3523 var hashtag = this.HashMgr.UseHash;
3524 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3526 if (this.HashMgr.IsHead)
3527 header = this.HashMgr.UseHash + " ";
3529 footer = " " + this.HashMgr.UseHash;
3534 if (this.settings.Local.UseRecommendStatus)
3537 footer += this.recommendedStatusFooter;
3539 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3541 // テキストボックスに入力されている文字列を使用する
3542 footer += " " + this.settings.Local.StatusText.Trim();
3546 statusText = header + statusText + footer;
3548 if (this.preventSmsCommand)
3550 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3551 // 参照: https://support.twitter.com/articles/14020
3553 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3554 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3556 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3557 statusText = '\u200b' + statusText;
3565 /// 投稿欄に表示する入力可能な文字数を計算します
3567 private int GetRestStatusCount(string statusText)
3569 var remainCount = this.tw.GetTextLengthRemain(statusText);
3571 var uploadService = this.GetSelectedImageService();
3572 if (uploadService != null)
3574 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3575 remainCount -= uploadService.GetReservedTextLength(1);
3581 private IMediaUploadService? GetSelectedImageService()
3582 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3585 /// 全てのタブの振り分けルールを反映し直します
3587 private void ApplyPostFilters()
3589 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3591 this.statuses.FilterAll();
3593 var listView = this.CurrentListView;
3594 using (ControlTransaction.Update(listView))
3596 this.listCache?.PurgeCache();
3597 this.listCache?.UpdateListSize();
3600 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3602 var tabPage = this.ListTab.TabPages[index];
3604 if (this.settings.Common.TabIconDisp)
3606 if (tab.UnreadCount > 0)
3607 tabPage.ImageIndex = 0;
3609 tabPage.ImageIndex = -1;
3613 if (!this.settings.Common.TabIconDisp)
3614 this.ListTab.Refresh();
3616 this.SetMainWindowTitle();
3617 this.SetStatusLabelUrl();
3621 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3622 => e.DrawDefault = true;
3624 private void MyList_HScrolled(object sender, EventArgs e)
3625 => ((DetailsListView)sender).Refresh();
3627 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3629 base.ScaleControl(factor, specified);
3631 ScaleChildControl(this.TabImage, factor);
3633 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3634 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3636 foreach (var listview in listviews)
3638 ScaleChildControl(listview, factor);
3642 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3644 var tab = this.CurrentTab;
3646 if (tab.AllCount == 0)
3648 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3652 var selectedIndex = tab.SelectedIndex;
3657 case SEARCHTYPE.NextSearch: // 次を検索
3658 if (selectedIndex != -1)
3659 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3663 case SEARCHTYPE.PrevSearch: // 前を検索
3664 if (selectedIndex != -1)
3665 startIndex = Math.Max(selectedIndex - 1, 0);
3667 startIndex = tab.AllCount - 1;
3669 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3671 if (selectedIndex != -1)
3672 startIndex = selectedIndex;
3678 Func<string, bool> stringComparer;
3681 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3683 catch (ArgumentException)
3685 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3689 var reverse = searchType == SEARCHTYPE.PrevSearch;
3690 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3691 .DefaultIfEmpty(-1).First();
3693 if (foundIndex == -1)
3695 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3699 var listView = this.CurrentListView;
3700 this.SelectListItem(listView, foundIndex);
3701 listView.EnsureVisible(foundIndex);
3704 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3705 => this.ShowSearchDialog(); // 検索メニュー
3707 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3709 var previousSearch = this.SearchDialog.ResultOptions;
3710 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3712 this.SearchDialog.Reset();
3713 this.ShowSearchDialog();
3719 previousSearch.Query,
3720 previousSearch.CaseSensitive,
3721 previousSearch.UseRegex,
3722 SEARCHTYPE.NextSearch);
3725 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3727 var previousSearch = this.SearchDialog.ResultOptions;
3728 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3730 this.SearchDialog.Reset();
3731 this.ShowSearchDialog();
3737 previousSearch.Query,
3738 previousSearch.CaseSensitive,
3739 previousSearch.UseRegex,
3740 SEARCHTYPE.PrevSearch);
3744 /// 検索ダイアログを表示し、検索を実行します
3746 private void ShowSearchDialog()
3748 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3750 this.TopMost = this.settings.Common.AlwaysTop;
3753 this.TopMost = this.settings.Common.AlwaysTop;
3755 var searchOptions = this.SearchDialog.ResultOptions!;
3756 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3758 if (searchOptions.NewTab)
3760 var tabName = Properties.Resources.SearchResults_TabName;
3764 tabName = this.statuses.MakeTabName(tabName);
3766 catch (TabException ex)
3768 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3771 var resultTab = new LocalSearchTabModel(tabName);
3772 this.AddNewTab(resultTab, startup: false);
3773 this.statuses.AddTab(resultTab);
3775 var targetTab = this.CurrentTab;
3777 Func<string, bool> stringComparer;
3780 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3782 catch (ArgumentException)
3784 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3788 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3789 if (foundIndices.Length == 0)
3791 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3795 var foundPosts = foundIndices.Select(x => targetTab[x]);
3796 foreach (var post in foundPosts)
3798 resultTab.AddPostQueue(post);
3801 this.statuses.DistributePosts();
3802 this.RefreshTimeline();
3804 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3805 this.ListTab.SelectedIndex = tabIndex;
3810 searchOptions.Query,
3811 searchOptions.CaseSensitive,
3812 searchOptions.UseRegex,
3813 SEARCHTYPE.DialogSearch);
3816 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3818 this.AddNewTabForSearch(searchOptions.Query);
3822 /// <summary>発言検索に使用するメソッドを生成します</summary>
3823 /// <exception cref="ArgumentException">
3824 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3826 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3830 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3831 var regex = new Regex(query, regexOption);
3833 return x => regex.IsMatch(x);
3837 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3839 return x => x.IndexOf(query, comparisonType) != -1;
3843 private void AboutMenuItem_Click(object sender, EventArgs e)
3845 using (var about = new TweenAboutBox())
3847 about.ShowDialog(this);
3849 this.TopMost = this.settings.Common.AlwaysTop;
3852 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3854 var bgnIdx = this.statuses.SelectedTabIndex;
3856 if (this.ImageSelector.Enabled)
3859 TabModel? foundTab = null;
3863 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3865 var unreadIndex = tab.NextUnreadIndex;
3866 if (unreadIndex != -1)
3868 this.ListTab.SelectedIndex = index;
3870 foundIndex = unreadIndex;
3875 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3876 if (foundTab == null && bgnIdx > 0)
3878 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3880 var unreadIndex = tab.NextUnreadIndex;
3881 if (unreadIndex != -1)
3883 this.ListTab.SelectedIndex = index;
3885 foundIndex = unreadIndex;
3891 DetailsListView lst;
3893 if (foundTab == null)
3895 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3896 this.ListTab.SelectedIndex = 0;
3897 var tabPage = this.ListTab.TabPages[0];
3898 var tab = this.statuses.Tabs[0];
3900 if (tab.AllCount == 0)
3903 if (this.statuses.SortOrder == SortOrder.Ascending)
3904 foundIndex = tab.AllCount - 1;
3908 lst = (DetailsListView)tabPage.Tag;
3912 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3913 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3916 this.SelectListItem(lst, foundIndex);
3918 if (this.statuses.SortMode == ComparerMode.Id)
3920 var rowHeight = lst.SmallImageList.ImageSize.Height;
3921 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3922 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3928 lst.EnsureVisible(foundIndex);
3933 lst.EnsureVisible(foundIndex);
3939 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
3941 var tab = this.CurrentTab;
3942 var post = this.CurrentPost;
3943 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
3944 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
3947 private async void VerUpMenuItem_Click(object sender, EventArgs e)
3948 => await this.CheckNewVersion(false);
3950 private void RunTweenUp()
3952 var pinfo = new ProcessStartInfo
3954 UseShellExecute = true,
3955 WorkingDirectory = this.settings.SettingsPath,
3956 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
3957 Arguments = "\"" + Application.StartupPath + "\"",
3962 Process.Start(pinfo);
3966 MessageBox.Show("Failed to execute TweenUp3.exe.");
3970 public readonly record struct VersionInfo(
3977 /// OpenTween の最新バージョンの情報を取得します
3979 public async Task<VersionInfo> GetVersionInfoAsync()
3981 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
3982 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
3984 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
3985 .ConfigureAwait(false);
3987 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
3988 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
3990 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
3991 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
3993 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
3995 return new VersionInfo
3997 Version = Version.Parse(msgHeader[0]),
3998 DownloadUri = new Uri(msgHeader[1]),
3999 ReleaseNote = msgBody,
4003 private async Task CheckNewVersion(bool startup = false)
4005 if (ApplicationSettings.VersionInfoUrl == null)
4006 return; // 更新チェック無効化
4010 var versionInfo = await this.GetVersionInfoAsync();
4012 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4017 var msgtext = string.Format(
4018 Properties.Resources.CheckNewVersionText7,
4019 MyCommon.GetReadableVersion(),
4020 MyCommon.GetReadableVersion(versionInfo.Version));
4021 msgtext = MyCommon.ReplaceAppName(msgtext);
4025 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4026 MessageBoxButtons.OK,
4027 MessageBoxIcon.Information);
4032 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4035 using var dialog = new UpdateDialog();
4037 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4038 MyCommon.GetReadableVersion(versionInfo.Version));
4039 dialog.DetailsText = versionInfo.ReleaseNote;
4041 if (dialog.ShowDialog(this) == DialogResult.Yes)
4043 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4045 else if (dialog.SkipButtonPressed)
4047 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4048 this.MarkSettingCommonModified();
4053 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4057 Properties.Resources.CheckNewVersionText10,
4058 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4059 MessageBoxButtons.OK,
4060 MessageBoxIcon.Exclamation,
4061 MessageBoxDefaultButton.Button2);
4066 private void UpdateSelectedPost()
4068 // 件数関連の場合、タイトル即時書き換え
4069 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4070 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4071 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4072 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4074 this.SetMainWindowTitle();
4076 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4077 this.SetStatusLabelUrl();
4079 if (this.settings.Common.TabIconDisp)
4081 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4083 if (tab.UnreadCount == 0)
4085 var tabPage = this.ListTab.TabPages[index];
4086 if (tabPage.ImageIndex == 0)
4087 tabPage.ImageIndex = -1;
4093 this.ListTab.Refresh();
4096 this.DispSelectedPost();
4099 private void DispSelectedPost()
4100 => this.DispSelectedPost(false);
4102 private PostClass displayPost = new();
4105 /// サムネイル表示に使用する CancellationToken の生成元
4107 private CancellationTokenSource? thumbnailTokenSource = null;
4109 private void DispSelectedPost(bool forceupdate)
4111 var currentPost = this.CurrentPost;
4112 if (currentPost == null)
4115 var oldDisplayPost = this.displayPost;
4116 this.displayPost = currentPost;
4118 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4121 var loadTasks = new TaskCollection();
4122 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4124 if (this.settings.Common.PreviewEnable)
4126 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4127 oldTokenSource?.Cancel();
4129 var token = this.thumbnailTokenSource!.Token;
4130 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4134 this.SplitContainer3.Panel2Collapsed = true;
4137 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4139 .IgnoreException(x => x is OperationCanceledException)
4143 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4145 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4147 var timeout = Task.Delay(100);
4148 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4150 token.ThrowIfCancellationRequested();
4152 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4153 this.SplitContainer3.Panel2Collapsed = true;
4157 token.ThrowIfCancellationRequested();
4159 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4162 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4163 => await this.OpenApplicationWebsite();
4165 private async Task OpenApplicationWebsite()
4166 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4168 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4169 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4171 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4173 var tab = this.CurrentTab;
4174 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4176 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4177 if (pnl.Controls["comboSearch"].Focused ||
4178 pnl.Controls["comboLang"].Focused ||
4179 pnl.Controls["buttonSearch"].Focused) return;
4182 if (e.Control || e.Shift || e.Alt)
4185 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4188 e.SuppressKeyPress = true;
4191 if (asyncTask != null)
4195 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4197 private void InitializeShortcuts()
4199 this.shortcutCommands = new[]
4201 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4202 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4203 .FocusedOn(FocusedControl.ListTab)
4204 .Do(() => SendKeys.Send("{DOWN}")),
4206 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4207 .FocusedOn(FocusedControl.ListTab)
4208 .Do(() => SendKeys.Send("{UP}")),
4210 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4211 .FocusedOn(FocusedControl.ListTab)
4212 .Do(() => SendKeys.Send("{PGDN}")),
4214 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4215 .FocusedOn(FocusedControl.ListTab)
4216 .Do(() => SendKeys.Send("{PGUP}")),
4218 ShortcutCommand.Create(Keys.F1)
4219 .Do(() => this.OpenApplicationWebsite()),
4221 ShortcutCommand.Create(Keys.F3)
4222 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4224 ShortcutCommand.Create(Keys.F5)
4225 .Do(() => this.DoRefresh()),
4227 ShortcutCommand.Create(Keys.F6)
4228 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4230 ShortcutCommand.Create(Keys.F7)
4231 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4233 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4234 .NotFocusedOn(FocusedControl.StatusText)
4237 this.CurrentTab.ClearAnchor();
4238 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4241 ShortcutCommand.Create(Keys.G)
4242 .NotFocusedOn(FocusedControl.StatusText)
4245 this.CurrentTab.ClearAnchor();
4246 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4249 ShortcutCommand.Create(Keys.Right, Keys.N)
4250 .FocusedOn(FocusedControl.ListTab)
4251 .Do(() => this.GoRelPost(forward: true)),
4253 ShortcutCommand.Create(Keys.Left, Keys.P)
4254 .FocusedOn(FocusedControl.ListTab)
4255 .Do(() => this.GoRelPost(forward: false)),
4257 ShortcutCommand.Create(Keys.OemPeriod)
4258 .FocusedOn(FocusedControl.ListTab)
4259 .Do(() => this.GoAnchor()),
4261 ShortcutCommand.Create(Keys.I)
4262 .FocusedOn(FocusedControl.ListTab)
4263 .OnlyWhen(() => this.StatusText.Enabled)
4264 .Do(() => this.StatusText.Focus()),
4266 ShortcutCommand.Create(Keys.Enter)
4267 .FocusedOn(FocusedControl.ListTab)
4268 .Do(() => this.ListItemDoubleClickAction()),
4270 ShortcutCommand.Create(Keys.R)
4271 .FocusedOn(FocusedControl.ListTab)
4272 .Do(() => this.DoRefresh()),
4274 ShortcutCommand.Create(Keys.L)
4275 .FocusedOn(FocusedControl.ListTab)
4278 this.CurrentTab.ClearAnchor();
4279 this.GoPost(forward: true);
4282 ShortcutCommand.Create(Keys.H)
4283 .FocusedOn(FocusedControl.ListTab)
4286 this.CurrentTab.ClearAnchor();
4287 this.GoPost(forward: false);
4290 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4291 .FocusedOn(FocusedControl.ListTab)
4294 this.CurrentTab.ClearAnchor();
4298 ShortcutCommand.Create(Keys.S)
4299 .FocusedOn(FocusedControl.ListTab)
4302 this.CurrentTab.ClearAnchor();
4303 this.GoNextTab(forward: true);
4306 ShortcutCommand.Create(Keys.A)
4307 .FocusedOn(FocusedControl.ListTab)
4310 this.CurrentTab.ClearAnchor();
4311 this.GoNextTab(forward: false);
4314 // ] in_reply_to参照元へ戻る
4315 ShortcutCommand.Create(Keys.Oem4)
4316 .FocusedOn(FocusedControl.ListTab)
4319 this.CurrentTab.ClearAnchor();
4320 return this.GoInReplyToPostTree();
4323 // [ in_reply_toへジャンプ
4324 ShortcutCommand.Create(Keys.Oem6)
4325 .FocusedOn(FocusedControl.ListTab)
4328 this.CurrentTab.ClearAnchor();
4329 this.GoBackInReplyToPostTree();
4332 ShortcutCommand.Create(Keys.Escape)
4333 .FocusedOn(FocusedControl.ListTab)
4336 this.CurrentTab.ClearAnchor();
4337 var tab = this.CurrentTab;
4338 var tabtype = tab.TabType;
4339 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4341 this.RemoveSpecifiedTab(tab.TabName, false);
4342 this.SaveConfigsTabs();
4346 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4347 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4348 .FocusedOn(FocusedControl.ListTab)
4349 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4351 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4352 ShortcutCommand.Create(Keys.Up, Keys.Down)
4353 .FocusedOn(FocusedControl.PostBrowser)
4356 ShortcutCommand.Create(Keys.Control | Keys.R)
4357 .Do(() => this.MakeReplyText()),
4359 ShortcutCommand.Create(Keys.Control | Keys.D)
4360 .Do(() => this.DoStatusDelete()),
4362 ShortcutCommand.Create(Keys.Control | Keys.M)
4363 .Do(() => this.MakeDirectMessageText()),
4365 ShortcutCommand.Create(Keys.Control | Keys.S)
4366 .Do(() => this.FavoriteChange(favAdd: true)),
4368 ShortcutCommand.Create(Keys.Control | Keys.I)
4369 .Do(() => this.DoRepliedStatusOpen()),
4371 ShortcutCommand.Create(Keys.Control | Keys.Q)
4372 .Do(() => this.DoQuoteOfficial()),
4374 ShortcutCommand.Create(Keys.Control | Keys.B)
4375 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4377 ShortcutCommand.Create(Keys.Control | Keys.T)
4378 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4380 ShortcutCommand.Create(Keys.Control | Keys.L)
4381 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4383 ShortcutCommand.Create(Keys.Control | Keys.Y)
4384 .NotFocusedOn(FocusedControl.PostBrowser)
4385 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4387 ShortcutCommand.Create(Keys.Control | Keys.F)
4388 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4390 ShortcutCommand.Create(Keys.Control | Keys.U)
4391 .Do(() => this.ShowUserTimeline()),
4393 ShortcutCommand.Create(Keys.Control | Keys.H)
4394 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4396 ShortcutCommand.Create(Keys.Control | Keys.O)
4397 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4399 ShortcutCommand.Create(Keys.Control | Keys.E)
4400 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4402 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4403 .FocusedOn(FocusedControl.ListTab)
4404 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4406 ShortcutCommand.Create(Keys.Control | Keys.N)
4407 .FocusedOn(FocusedControl.ListTab)
4408 .Do(() => this.GoNextTab(forward: true)),
4410 ShortcutCommand.Create(Keys.Control | Keys.P)
4411 .FocusedOn(FocusedControl.ListTab)
4412 .Do(() => this.GoNextTab(forward: false)),
4414 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4415 .FocusedOn(FocusedControl.ListTab)
4416 .Do(() => this.CopyStot()),
4418 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4419 ShortcutCommand.Create(Keys.Control | Keys.D1)
4420 .FocusedOn(FocusedControl.ListTab)
4421 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4422 .Do(() => this.ListTab.SelectedIndex = 0),
4424 ShortcutCommand.Create(Keys.Control | Keys.D2)
4425 .FocusedOn(FocusedControl.ListTab)
4426 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4427 .Do(() => this.ListTab.SelectedIndex = 1),
4429 ShortcutCommand.Create(Keys.Control | Keys.D3)
4430 .FocusedOn(FocusedControl.ListTab)
4431 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4432 .Do(() => this.ListTab.SelectedIndex = 2),
4434 ShortcutCommand.Create(Keys.Control | Keys.D4)
4435 .FocusedOn(FocusedControl.ListTab)
4436 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4437 .Do(() => this.ListTab.SelectedIndex = 3),
4439 ShortcutCommand.Create(Keys.Control | Keys.D5)
4440 .FocusedOn(FocusedControl.ListTab)
4441 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4442 .Do(() => this.ListTab.SelectedIndex = 4),
4444 ShortcutCommand.Create(Keys.Control | Keys.D6)
4445 .FocusedOn(FocusedControl.ListTab)
4446 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4447 .Do(() => this.ListTab.SelectedIndex = 5),
4449 ShortcutCommand.Create(Keys.Control | Keys.D7)
4450 .FocusedOn(FocusedControl.ListTab)
4451 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4452 .Do(() => this.ListTab.SelectedIndex = 6),
4454 ShortcutCommand.Create(Keys.Control | Keys.D8)
4455 .FocusedOn(FocusedControl.ListTab)
4456 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4457 .Do(() => this.ListTab.SelectedIndex = 7),
4459 ShortcutCommand.Create(Keys.Control | Keys.D9)
4460 .FocusedOn(FocusedControl.ListTab)
4461 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4463 ShortcutCommand.Create(Keys.Control | Keys.A)
4464 .FocusedOn(FocusedControl.StatusText)
4465 .Do(() => this.StatusText.SelectAll()),
4467 ShortcutCommand.Create(Keys.Control | Keys.V)
4468 .FocusedOn(FocusedControl.StatusText)
4469 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4471 ShortcutCommand.Create(Keys.Control | Keys.Up)
4472 .FocusedOn(FocusedControl.StatusText)
4473 .Do(() => this.StatusTextHistoryBack()),
4475 ShortcutCommand.Create(Keys.Control | Keys.Down)
4476 .FocusedOn(FocusedControl.StatusText)
4477 .Do(() => this.StatusTextHistoryForward()),
4479 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4480 .FocusedOn(FocusedControl.StatusText)
4483 if (this.ListTab.SelectedIndex == 0)
4485 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4489 this.ListTab.SelectedIndex -= 1;
4491 this.StatusText.Focus();
4494 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4495 .FocusedOn(FocusedControl.StatusText)
4498 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4500 this.ListTab.SelectedIndex = 0;
4504 this.ListTab.SelectedIndex += 1;
4506 this.StatusText.Focus();
4509 ShortcutCommand.Create(Keys.Control | Keys.Y)
4510 .FocusedOn(FocusedControl.PostBrowser)
4513 var multiline = !this.settings.Local.StatusMultiline;
4514 this.settings.Local.StatusMultiline = multiline;
4515 this.MultiLineMenuItem.Checked = multiline;
4516 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4519 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4520 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4522 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4523 .Do(() => this.DoRefreshMore()),
4525 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4526 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4528 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4529 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4531 ShortcutCommand.Create(Keys.Shift | Keys.R)
4532 .NotFocusedOn(FocusedControl.StatusText)
4533 .Do(() => this.DoRefreshMore()),
4535 ShortcutCommand.Create(Keys.Shift | Keys.H)
4536 .FocusedOn(FocusedControl.ListTab)
4537 .Do(() => this.GoTopEnd(goTop: true)),
4539 ShortcutCommand.Create(Keys.Shift | Keys.L)
4540 .FocusedOn(FocusedControl.ListTab)
4541 .Do(() => this.GoTopEnd(goTop: false)),
4543 ShortcutCommand.Create(Keys.Shift | Keys.M)
4544 .FocusedOn(FocusedControl.ListTab)
4545 .Do(() => this.GoMiddle()),
4547 ShortcutCommand.Create(Keys.Shift | Keys.G)
4548 .FocusedOn(FocusedControl.ListTab)
4549 .Do(() => this.GoLast()),
4551 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4552 .FocusedOn(FocusedControl.ListTab)
4553 .Do(() => this.MoveMiddle()),
4555 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4556 .FocusedOn(FocusedControl.ListTab)
4557 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4559 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4560 .FocusedOn(FocusedControl.ListTab)
4561 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4563 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4564 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4565 .FocusedOn(FocusedControl.ListTab)
4566 .Do(() => this.GoFav(forward: true)),
4568 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4569 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4570 .FocusedOn(FocusedControl.ListTab)
4571 .Do(() => this.GoFav(forward: false)),
4573 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4574 .FocusedOn(FocusedControl.ListTab)
4575 .Do(() => this.GoBackSelectPostChain()),
4577 ShortcutCommand.Create(Keys.Alt | Keys.R)
4578 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4580 ShortcutCommand.Create(Keys.Alt | Keys.P)
4581 .OnlyWhen(() => this.CurrentPost != null)
4582 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4584 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4585 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4587 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4588 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4590 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4591 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4593 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4594 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4596 // 別タブの同じ書き込みへ(ALT+←/→)
4597 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4598 .FocusedOn(FocusedControl.ListTab)
4599 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4601 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4602 .FocusedOn(FocusedControl.ListTab)
4603 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4605 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4606 .Do(() => this.MakeReplyText(atAll: true)),
4608 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4609 .Do(() => this.CopyIdUri()),
4611 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4612 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4613 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4615 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4616 .Do(() => this.DoQuoteOfficial()),
4618 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4619 .Do(() => this.FavoriteChange(favAdd: false)),
4621 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4622 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4624 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4625 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4627 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4628 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4630 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4631 .Do(() => this.DoMoveToRTHome()),
4633 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4634 .FocusedOn(FocusedControl.StatusText)
4637 var tab = this.CurrentTab;
4638 var selectedIndex = tab.SelectedIndex;
4639 if (selectedIndex != -1 && selectedIndex > 0)
4641 var listView = this.CurrentListView;
4642 var idx = selectedIndex - 1;
4643 this.SelectListItem(listView, idx);
4644 listView.EnsureVisible(idx);
4648 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4649 .FocusedOn(FocusedControl.StatusText)
4652 var tab = this.CurrentTab;
4653 var selectedIndex = tab.SelectedIndex;
4654 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4656 var listView = this.CurrentListView;
4657 var idx = selectedIndex + 1;
4658 this.SelectListItem(listView, idx);
4659 listView.EnsureVisible(idx);
4663 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4664 .FocusedOn(FocusedControl.StatusText)
4667 if (this.StatusText.SelectionStart > 0)
4669 var endidx = this.StatusText.SelectionStart - 1;
4671 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4673 var c = this.StatusText.Text[i];
4674 if (char.IsLetterOrDigit(c) || c == '_')
4680 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4681 var cnt = this.AtIdSupl.ItemCount;
4682 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4683 if (this.AtIdSupl.ItemCount != cnt)
4684 this.MarkSettingAtIdModified();
4688 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4689 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4699 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4700 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4701 .FocusedOn(FocusedControl.ListTab)
4702 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4704 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4705 .FocusedOn(FocusedControl.ListTab)
4706 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4708 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4709 .FocusedOn(FocusedControl.ListTab)
4710 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4712 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4713 .FocusedOn(FocusedControl.ListTab)
4714 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4716 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4717 .FocusedOn(FocusedControl.ListTab)
4718 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4720 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4721 .FocusedOn(FocusedControl.ListTab)
4722 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4724 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4725 .FocusedOn(FocusedControl.ListTab)
4726 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4728 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4729 .FocusedOn(FocusedControl.ListTab)
4730 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4732 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4733 .FocusedOn(FocusedControl.ListTab)
4734 .Do(() => this.SetSortLastColumn()),
4736 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4737 .FocusedOn(FocusedControl.ListTab)
4738 .Do(() => this.FavoritesRetweetOfficial()),
4740 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4741 .FocusedOn(FocusedControl.ListTab)
4742 .Do(() => this.FavoritesRetweetUnofficial()),
4744 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4745 .FocusedOn(FocusedControl.ListTab)
4746 .Do(() => this.OpenUserAppointUrl()),
4748 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4749 .FocusedOn(FocusedControl.PostBrowser)
4750 .Do(() => this.DoReTweetUnofficial()),
4752 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4753 .OnlyWhen(() => this.ExistCurrentPost)
4754 .Do(() => this.tweetDetailsView.DoTranslation()),
4756 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4757 .Do(() => this.DoReTweetUnofficial()),
4759 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4760 .Do(() => this.CopyUserId()),
4762 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4763 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4765 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4766 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4768 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4769 .FocusedOn(FocusedControl.ListTab)
4770 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4771 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4775 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4777 // Task を返す非同期処理があれば asyncTask に代入する
4780 // ShortcutCommand に対応しているコマンドはここで処理される
4781 foreach (var command in this.shortcutCommands)
4783 if (command.IsMatch(keyData, focusedOn))
4785 asyncTask = command.RunCommand();
4786 return command.PreventDefault;
4793 private void GoNextTab(bool forward)
4795 var idx = this.statuses.SelectedTabIndex;
4796 var tabCount = this.statuses.Tabs.Count;
4800 if (idx > tabCount - 1) idx = 0;
4805 if (idx < 0) idx = tabCount - 1;
4807 this.ListTab.SelectedIndex = idx;
4810 private void CopyStot()
4812 var sb = new StringBuilder();
4813 var tab = this.CurrentTab;
4814 var isProtected = false;
4815 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4816 foreach (var post in tab.SelectedPosts)
4818 if (post.IsDeleted) continue;
4821 if (post.RetweetedId != null)
4822 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4824 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4828 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4833 MessageBox.Show(Properties.Resources.CopyStotText1);
4837 var clstr = sb.ToString();
4840 Clipboard.SetDataObject(clstr, false, 5, 100);
4842 catch (Exception ex)
4844 MessageBox.Show(ex.Message);
4849 private void CopyIdUri()
4851 var tab = this.CurrentTab;
4852 if (tab == null || tab is DirectMessagesTabModel)
4855 var copyUrls = new List<string>();
4856 foreach (var post in tab.SelectedPosts)
4857 copyUrls.Add(MyCommon.GetStatusUrl(post));
4859 if (copyUrls.Count == 0)
4864 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4866 catch (ExternalException ex)
4868 MessageBox.Show(ex.Message);
4872 private void GoFav(bool forward)
4874 var tab = this.CurrentTab;
4875 if (tab.AllCount == 0)
4878 var selectedIndex = tab.SelectedIndex;
4886 if (selectedIndex == -1)
4892 fIdx = selectedIndex + 1;
4893 if (fIdx > tab.AllCount - 1)
4896 toIdx = tab.AllCount;
4901 if (selectedIndex == -1)
4903 fIdx = tab.AllCount - 1;
4907 fIdx = selectedIndex - 1;
4915 for (var idx = fIdx; idx != toIdx; idx += stp)
4919 var listView = this.CurrentListView;
4920 this.SelectListItem(listView, idx);
4921 listView.EnsureVisible(idx);
4927 private void GoSamePostToAnotherTab(bool left)
4929 var tab = this.CurrentTab;
4931 // Directタブは対象外(見つかるはずがない)
4932 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4935 var selectedStatusId = tab.SelectedStatusId;
4936 if (selectedStatusId == null)
4939 int fIdx, toIdx, stp;
4944 if (this.ListTab.SelectedIndex == 0)
4950 fIdx = this.ListTab.SelectedIndex - 1;
4958 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4964 fIdx = this.ListTab.SelectedIndex + 1;
4966 toIdx = this.ListTab.TabCount;
4970 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
4972 var targetTab = this.statuses.Tabs[tabidx];
4975 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
4978 var foundIndex = targetTab.IndexOf(selectedStatusId);
4979 if (foundIndex != -1)
4981 this.ListTab.SelectedIndex = tabidx;
4982 var listView = this.CurrentListView;
4983 this.SelectListItem(listView, foundIndex);
4984 listView.EnsureVisible(foundIndex);
4990 private void GoPost(bool forward)
4992 var tab = this.CurrentTab;
4993 var currentPost = this.CurrentPost;
4995 if (currentPost == null)
4998 var selectedIndex = tab.SelectedIndex;
5000 int fIdx, toIdx, stp;
5004 fIdx = selectedIndex + 1;
5005 if (fIdx > tab.AllCount - 1) return;
5006 toIdx = tab.AllCount;
5011 fIdx = selectedIndex - 1;
5012 if (fIdx < 0) return;
5018 if (currentPost.RetweetedBy == null)
5020 name = currentPost.ScreenName;
5024 name = currentPost.RetweetedBy;
5026 for (var idx = fIdx; idx != toIdx; idx += stp)
5028 var post = tab[idx];
5029 if (post.RetweetedId == null)
5031 if (post.ScreenName == name)
5033 var listView = this.CurrentListView;
5034 this.SelectListItem(listView, idx);
5035 listView.EnsureVisible(idx);
5041 if (post.RetweetedBy == name)
5043 var listView = this.CurrentListView;
5044 this.SelectListItem(listView, idx);
5045 listView.EnsureVisible(idx);
5052 private void GoRelPost(bool forward)
5054 var tab = this.CurrentTab;
5055 var selectedIndex = tab.SelectedIndex;
5057 if (selectedIndex == -1)
5060 int fIdx, toIdx, stp;
5064 fIdx = selectedIndex + 1;
5065 if (fIdx > tab.AllCount - 1) return;
5066 toIdx = tab.AllCount;
5071 fIdx = selectedIndex - 1;
5072 if (fIdx < 0) return;
5077 var anchorPost = tab.AnchorPost;
5078 if (anchorPost == null)
5080 var currentPost = this.CurrentPost;
5081 if (currentPost == null)
5084 anchorPost = currentPost;
5085 tab.AnchorPost = currentPost;
5088 for (var idx = fIdx; idx != toIdx; idx += stp)
5090 var post = tab[idx];
5091 if (post.ScreenName == anchorPost.ScreenName ||
5092 post.RetweetedBy == anchorPost.ScreenName ||
5093 post.ScreenName == anchorPost.RetweetedBy ||
5094 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5095 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5096 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5097 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5098 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5100 var listView = this.CurrentListView;
5101 this.SelectListItem(listView, idx);
5102 listView.EnsureVisible(idx);
5108 private void GoAnchor()
5110 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5111 if (anchorStatusId == null)
5114 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5118 var listView = this.CurrentListView;
5119 this.SelectListItem(listView, idx);
5120 listView.EnsureVisible(idx);
5123 private void GoTopEnd(bool goTop)
5125 var listView = this.CurrentListView;
5126 if (listView.VirtualListSize == 0)
5134 item = listView.GetItemAt(0, 25);
5142 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5144 idx = listView.VirtualListSize - 1;
5148 this.SelectListItem(listView, idx);
5151 private void GoMiddle()
5153 var listView = this.CurrentListView;
5154 if (listView.VirtualListSize == 0)
5162 item = listView.GetItemAt(0, 0);
5172 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5175 idx2 = listView.VirtualListSize - 1;
5181 idx3 = (idx1 + idx2) / 2;
5183 this.SelectListItem(listView, idx3);
5186 private void GoLast()
5188 var listView = this.CurrentListView;
5189 if (listView.VirtualListSize == 0) return;
5191 if (this.statuses.SortOrder == SortOrder.Ascending)
5193 this.SelectListItem(listView, listView.VirtualListSize - 1);
5194 listView.EnsureVisible(listView.VirtualListSize - 1);
5198 this.SelectListItem(listView, 0);
5199 listView.EnsureVisible(0);
5203 private void MoveTop()
5205 var listView = this.CurrentListView;
5206 if (listView.SelectedIndices.Count == 0) return;
5207 var idx = listView.SelectedIndices[0];
5208 if (this.statuses.SortOrder == SortOrder.Ascending)
5210 listView.EnsureVisible(listView.VirtualListSize - 1);
5214 listView.EnsureVisible(0);
5216 listView.EnsureVisible(idx);
5219 private async Task GoInReplyToPostTree()
5221 var curTabClass = this.CurrentTab;
5222 var currentPost = this.CurrentPost;
5224 if (currentPost == null)
5227 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5231 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5233 currentPost = currentPost with
5235 InReplyToStatusId = post.InReplyToStatusId,
5236 InReplyToUser = post.InReplyToUser,
5237 IsReply = post.IsReply,
5239 curTabClass.ReplacePost(currentPost);
5240 this.listCache?.PurgeCache();
5242 var index = curTabClass.SelectedIndex;
5243 this.CurrentListView.RedrawItems(index, index, false);
5245 catch (WebApiException ex)
5247 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5251 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5253 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5255 this.replyChains = new Stack<ReplyChain>();
5257 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5260 string inReplyToTabName;
5261 var inReplyToId = currentPost.InReplyToStatusId;
5262 var inReplyToUser = currentPost.InReplyToUser;
5264 var inReplyToPosts = from tab in this.statuses.Tabs
5265 orderby tab != curTabClass
5266 from post in tab.Posts.Values
5267 where post.StatusId == inReplyToId
5268 let index = tab.IndexOf(post.StatusId)
5270 select new { Tab = tab, Index = index };
5272 var inReplyPost = inReplyToPosts.FirstOrDefault();
5273 if (inReplyPost == null)
5277 await Task.Run(async () =>
5279 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5280 .ConfigureAwait(false);
5283 this.statuses.AddPost(post);
5284 this.statuses.DistributePosts();
5287 catch (WebApiException ex)
5289 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5290 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5294 this.RefreshTimeline();
5296 inReplyPost = inReplyToPosts.FirstOrDefault();
5297 if (inReplyPost == null)
5299 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5303 inReplyToTabName = inReplyPost.Tab.TabName;
5304 inReplyToIndex = inReplyPost.Index;
5306 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5307 var tabPage = this.ListTab.TabPages[tabIndex];
5308 var listView = (DetailsListView)tabPage.Tag;
5310 if (this.CurrentTabName != inReplyToTabName)
5312 this.ListTab.SelectedIndex = tabIndex;
5315 this.SelectListItem(listView, inReplyToIndex);
5316 listView.EnsureVisible(inReplyToIndex);
5319 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5321 var curTabClass = this.CurrentTab;
5322 var currentPost = this.CurrentPost;
5324 if (currentPost == null)
5329 if (currentPost.InReplyToStatusId != null)
5331 var posts = from t in this.statuses.Tabs
5333 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5334 let indexOf = t.IndexOf(p.Value.StatusId)
5336 orderby isForward ? indexOf : indexOf * -1
5337 orderby t != curTabClass
5338 select new { Tab = t, Post = p.Value, Index = indexOf };
5341 var postList = posts.ToList();
5342 for (var i = postList.Count - 1; i >= 0; i--)
5345 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5347 postList.RemoveAt(index);
5350 var currentIndex = this.CurrentTab.SelectedIndex;
5351 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5352 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5353 if (post == null) post = postList.First();
5354 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5355 this.ListTab.SelectedIndex = tabIndex;
5356 var listView = this.CurrentListView;
5357 this.SelectListItem(listView, post.Index);
5358 listView.EnsureVisible(post.Index);
5360 catch (InvalidOperationException)
5368 if (this.replyChains == null || this.replyChains.Count < 1)
5370 var posts = from t in this.statuses.Tabs
5372 where p.Value.InReplyToStatusId == currentPost.StatusId
5373 let indexOf = t.IndexOf(p.Value.StatusId)
5376 orderby t != curTabClass
5377 select new { Tab = t, Index = indexOf };
5380 var post = posts.First();
5381 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5382 this.ListTab.SelectedIndex = tabIndex;
5383 var listView = this.CurrentListView;
5384 this.SelectListItem(listView, post.Index);
5385 listView.EnsureVisible(post.Index);
5387 catch (InvalidOperationException)
5394 var chainHead = this.replyChains.Pop();
5395 if (chainHead.InReplyToId == currentPost.StatusId)
5397 var tab = chainHead.OriginalTab;
5398 if (!this.statuses.Tabs.Contains(tab))
5400 this.replyChains = null;
5404 var idx = tab.IndexOf(chainHead.OriginalId);
5407 this.replyChains = null;
5411 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5414 this.ListTab.SelectedIndex = tabIndex;
5418 this.replyChains = null;
5420 var listView = this.CurrentListView;
5421 this.SelectListItem(listView, idx);
5422 listView.EnsureVisible(idx);
5428 this.replyChains = null;
5429 this.GoBackInReplyToPostTree(parallel);
5435 private void GoBackSelectPostChain()
5437 if (this.selectPostChains.Count > 1)
5440 TabModel? foundTab = null;
5446 this.selectPostChains.Pop();
5447 var (tab, post) = this.selectPostChains.Peek();
5449 if (!this.statuses.Tabs.Contains(tab))
5450 continue; // 該当タブが存在しないので無視
5454 idx = tab.IndexOf(post.StatusId);
5455 if (idx == -1) continue; // 該当ポストが存在しないので無視
5460 this.selectPostChains.Pop();
5462 catch (InvalidOperationException)
5468 while (this.selectPostChains.Count > 1);
5470 if (foundTab == null)
5473 // 履歴が残り1つであればクリアしておく
5474 if (this.selectPostChains.Count == 1)
5475 this.selectPostChains.Clear();
5479 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5480 var tabPage = this.ListTab.TabPages[tabIndex];
5481 var lst = (DetailsListView)tabPage.Tag;
5482 this.ListTab.SelectedIndex = tabIndex;
5486 this.SelectListItem(lst, idx);
5487 lst.EnsureVisible(idx);
5493 private void PushSelectPostChain()
5495 var currentTab = this.CurrentTab;
5496 var currentPost = this.CurrentPost;
5498 var count = this.selectPostChains.Count;
5501 var (tab, post) = this.selectPostChains.Peek();
5502 if (tab == currentTab)
5504 if (post == currentPost) return; // 最新の履歴と同一
5505 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5508 if (count >= 2500) this.TrimPostChain();
5509 this.selectPostChains.Push((currentTab, currentPost));
5512 private void TrimPostChain()
5514 if (this.selectPostChains.Count <= 2000) return;
5515 var p = new Stack<(TabModel, PostClass?)>(2000);
5516 for (var i = 0; i < 2000; i++)
5518 p.Push(this.selectPostChains.Pop());
5520 this.selectPostChains.Clear();
5521 for (var i = 0; i < 2000; i++)
5523 this.selectPostChains.Push(p.Pop());
5527 private bool GoStatus(PostId statusId)
5529 var tab = this.statuses.Tabs
5530 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5531 .Where(x => x.Contains(statusId))
5537 var index = tab.IndexOf(statusId);
5539 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5540 this.ListTab.SelectedIndex = tabIndex;
5542 var listView = this.CurrentListView;
5543 this.SelectListItem(listView, index);
5544 listView.EnsureVisible(index);
5549 private bool GoDirectMessage(PostId statusId)
5551 var tab = this.statuses.DirectMessageTab;
5552 var index = tab.IndexOf(statusId);
5557 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5558 this.ListTab.SelectedIndex = tabIndex;
5560 var listView = this.CurrentListView;
5561 this.SelectListItem(listView, index);
5562 listView.EnsureVisible(index);
5567 private void MyList_MouseClick(object sender, MouseEventArgs e)
5568 => this.CurrentTab.ClearAnchor();
5570 private void StatusText_Enter(object sender, EventArgs e)
5572 // フォーカスの戻り先を StatusText に設定
5573 this.Tag = this.StatusText;
5574 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5577 public Color InputBackColor
5578 => this.themeManager.ColorInputBackcolor;
5580 private void StatusText_Leave(object sender, EventArgs e)
5582 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5583 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5584 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5587 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5589 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5592 e.SuppressKeyPress = true;
5595 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5597 if (asyncTask != null)
5601 private void SaveConfigsAll(bool ifModified)
5605 this.SaveConfigsCommon();
5606 this.SaveConfigsLocal();
5607 this.SaveConfigsTabs();
5608 this.SaveConfigsAtId();
5612 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5613 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5614 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5618 private void SaveConfigsAtId()
5620 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5622 this.ModifySettingAtId = false;
5623 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5624 this.settings.SaveAtIdList();
5627 private void SaveConfigsCommon()
5629 if (this.ignoreConfigSave) return;
5631 this.ModifySettingCommon = false;
5632 lock (this.syncObject)
5634 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5635 this.settings.Common.SortColumn = this.statuses.SortMode switch
5637 ComparerMode.Nickname => 1, // ニックネーム
5638 ComparerMode.Data => 2, // 本文
5639 ComparerMode.Id => 3, // 時刻=発言Id
5640 ComparerMode.Name => 4, // 名前
5641 ComparerMode.Source => 7, // Source
5642 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5644 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5645 if (this.HashMgr.IsPermanent)
5647 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5651 this.settings.Common.HashSelected = "";
5653 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5654 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5655 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5656 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5657 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5659 this.settings.SaveCommon();
5663 private void SaveConfigsLocal()
5665 if (this.ignoreConfigSave) return;
5666 lock (this.syncObject)
5668 this.ModifySettingLocal = false;
5669 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5670 this.settings.Local.FormSize = this.mySize;
5671 this.settings.Local.FormLocation = this.myLoc;
5672 this.settings.Local.SplitterDistance = this.mySpDis;
5673 this.settings.Local.PreviewDistance = this.mySpDis3;
5674 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5675 this.settings.Local.StatusTextHeight = this.mySpDis2;
5677 if (this.ignoreConfigSave) return;
5678 this.settings.SaveLocal();
5682 private void SaveConfigsTabs()
5684 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5686 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5688 foreach (var tab in tabs)
5690 if (!tab.IsPermanentTabType)
5693 var tabSetting = new SettingTabs.SettingTabItem
5695 TabName = tab.TabName,
5696 TabType = tab.TabType,
5697 UnreadManage = tab.UnreadManage,
5698 Protected = tab.Protected,
5699 Notify = tab.Notify,
5700 SoundFile = tab.SoundFile,
5705 case FilterTabModel filterTab:
5706 tabSetting.FilterArray = filterTab.FilterArray;
5708 case UserTimelineTabModel userTab:
5709 tabSetting.User = userTab.ScreenName;
5710 tabSetting.UserId = userTab.UserId;
5712 case PublicSearchTabModel searchTab:
5713 tabSetting.SearchWords = searchTab.SearchWords;
5714 tabSetting.SearchLang = searchTab.SearchLang;
5716 case ListTimelineTabModel listTab:
5717 tabSetting.ListInfo = listTab.ListInfo;
5721 tabSettingList.Add(tabSetting);
5724 this.settings.Tabs.Tabs = tabSettingList;
5725 this.settings.SaveTabs();
5728 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5730 static void ShowFormatErrorDialog(IWin32Window owner)
5734 Properties.Resources.OpenURL_InvalidFormat,
5735 Properties.Resources.OpenURL_Caption,
5736 MessageBoxButtons.OK,
5737 MessageBoxIcon.Error
5741 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5742 if (ret != DialogResult.OK)
5745 var match = Twitter.StatusUrlRegex.Match(inputText);
5748 ShowFormatErrorDialog(this);
5754 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5755 await this.OpenRelatedTab(statusId);
5757 catch (OverflowException)
5759 ShowFormatErrorDialog(this);
5761 catch (TabException ex)
5763 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5767 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5769 var tab = this.CurrentTab;
5771 var rslt = MessageBox.Show(
5772 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5773 Properties.Resources.SaveLogMenuItem_ClickText2,
5774 MessageBoxButtons.YesNoCancel,
5775 MessageBoxIcon.Question);
5776 if (rslt == DialogResult.Cancel) return;
5778 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5779 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5780 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5781 this.SaveFileDialog1.FilterIndex = 0;
5782 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5783 this.SaveFileDialog1.RestoreDirectory = true;
5785 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5787 if (!this.SaveFileDialog1.ValidateNames) return;
5788 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5789 if (rslt == DialogResult.Yes)
5792 for (var idx = 0; idx < tab.AllCount; idx++)
5794 var post = tab[idx];
5797 protect = "Protect";
5798 sw.WriteLine(post.Nickname + "\t" +
5799 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5800 post.CreatedAt.ToLocalTimeString() + "\t" +
5801 post.ScreenName + "\t" +
5802 post.StatusId.Id + "\t" +
5803 post.ImageUrl + "\t" +
5804 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5810 foreach (var post in this.CurrentTab.SelectedPosts)
5814 protect = "Protect";
5815 sw.WriteLine(post.Nickname + "\t" +
5816 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5817 post.CreatedAt.ToLocalTimeString() + "\t" +
5818 post.ScreenName + "\t" +
5819 post.StatusId.Id + "\t" +
5820 post.ImageUrl + "\t" +
5821 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5826 this.TopMost = this.settings.Common.AlwaysTop;
5829 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5833 using (var inputName = new InputTabName())
5835 inputName.TabName = origTabName;
5836 inputName.ShowDialog();
5837 if (inputName.DialogResult == DialogResult.Cancel) return false;
5838 newTabName = inputName.TabName;
5840 this.TopMost = this.settings.Common.AlwaysTop;
5841 if (!MyCommon.IsNullOrEmpty(newTabName))
5844 if (this.statuses.ContainsTab(newTabName))
5846 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5847 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5851 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5852 var tabPage = this.ListTab.TabPages[tabIndex];
5855 if (tabPage != null)
5856 tabPage.Text = newTabName;
5858 this.statuses.RenameTab(origTabName, newTabName);
5860 var state = this.listViewState[origTabName];
5861 this.listViewState.Remove(origTabName);
5862 this.listViewState[newTabName] = state;
5864 this.SaveConfigsCommon();
5865 this.SaveConfigsTabs();
5866 this.rclickTabName = newTabName;
5875 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5877 if (e.Button == MouseButtons.Middle)
5879 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5881 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5883 this.RemoveSpecifiedTab(tab.TabName, true);
5884 this.SaveConfigsTabs();
5891 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5892 => this.TabRename(this.CurrentTabName, out _);
5894 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5896 if (this.settings.Common.TabMouseLock) return;
5897 if (e.Button == MouseButtons.Left)
5899 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5901 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5903 this.tabDrag = true;
5904 this.tabMouseDownPoint = e.Location;
5911 this.tabDrag = false;
5915 private void ListTab_DragEnter(object sender, DragEventArgs e)
5917 if (e.Data.GetDataPresent(typeof(TabPage)))
5918 e.Effect = DragDropEffects.Move;
5920 e.Effect = DragDropEffects.None;
5923 private void ListTab_DragDrop(object sender, DragEventArgs e)
5925 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5927 this.tabDrag = false;
5930 var cpos = new Point(e.X, e.Y);
5931 var spos = this.ListTab.PointToClient(cpos);
5932 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5934 var rect = this.ListTab.GetTabRect(index);
5935 if (rect.Contains(spos))
5938 if (spos.X <= (rect.Left + rect.Right) / 2)
5947 // タブのないところにドロップ->最後尾へ移動
5948 if (MyCommon.IsNullOrEmpty(tn))
5950 var lastTab = this.statuses.Tabs.Last();
5951 tn = lastTab.TabName;
5955 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
5956 if (tp.Text == tn) return;
5958 this.ReOrderTab(tp.Text, tn, bef);
5961 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
5963 var baseIndex = this.GetTabPageIndex(baseTabText);
5964 if (baseIndex == -1)
5967 var targetIndex = this.GetTabPageIndex(targetTabText);
5968 if (targetIndex == -1)
5971 using (ControlTransaction.Layout(this.ListTab))
5973 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
5974 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
5975 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
5976 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
5978 var tab = this.statuses.Tabs[targetIndex];
5979 var tabPage = this.ListTab.TabPages[targetIndex];
5981 this.ListTab.TabPages.Remove(tabPage);
5983 if (targetIndex < baseIndex)
5986 if (!isBeforeBaseTab)
5989 this.statuses.MoveTab(baseIndex, tab);
5991 this.ListTab.TabPages.Insert(baseIndex, tabPage);
5994 this.SaveConfigsTabs();
5997 private void MakeDirectMessageText()
5999 var selectedPosts = this.CurrentTab.SelectedPosts;
6000 if (selectedPosts.Length > 1)
6003 var post = selectedPosts.Single();
6004 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6006 this.inReplyTo = null;
6007 this.StatusText.Text = text;
6008 this.StatusText.SelectionStart = text.Length;
6009 this.StatusText.Focus();
6012 private void MakeReplyText(bool atAll = false)
6014 var selectedPosts = this.CurrentTab.SelectedPosts;
6015 if (selectedPosts.Any(x => x.IsDm))
6017 this.MakeDirectMessageText();
6021 if (selectedPosts.Length == 1)
6023 var post = selectedPosts.Single();
6024 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6025 var inReplyToScreenName = post.ScreenName;
6026 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6030 this.inReplyTo = null;
6033 var selfScreenName = this.tw.Username;
6034 var targetScreenNames = new List<string>();
6035 foreach (var post in selectedPosts)
6037 if (post.ScreenName != selfScreenName)
6038 targetScreenNames.Add(post.ScreenName);
6042 foreach (var (_, screenName) in post.ReplyToList)
6044 if (screenName != selfScreenName)
6045 targetScreenNames.Add(screenName);
6050 if (this.inReplyTo != null)
6052 var (_, screenName) = this.inReplyTo.Value;
6053 if (screenName == selfScreenName)
6054 targetScreenNames.Insert(0, screenName);
6057 var text = this.StatusText.Text;
6058 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6060 var atText = $"@{screenName} ";
6061 if (!text.Contains(atText))
6062 text = atText + text;
6065 this.StatusText.Text = text;
6066 this.StatusText.SelectionStart = text.Length;
6067 this.StatusText.Focus();
6070 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6071 => this.tabDrag = false;
6073 private int iconCnt = 0;
6074 private int blinkCnt = 0;
6075 private bool blink = false;
6077 private void RefreshTasktrayIcon()
6079 void EnableTasktrayAnimation()
6080 => this.TimerRefreshIcon.Enabled = true;
6082 void DisableTasktrayAnimation()
6083 => this.TimerRefreshIcon.Enabled = false;
6085 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6089 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6092 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6093 this.myStatusError = false;
6094 EnableTasktrayAnimation();
6098 var replyIconType = this.settings.Common.ReplyIconState;
6100 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6102 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6103 if (replyTab != null && replyTab.UnreadCount > 0)
6107 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6110 if (this.blinkCnt > 10)
6113 if (this.blinkCnt == 0)
6114 this.blink = !this.blink;
6116 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6117 EnableTasktrayAnimation();
6121 DisableTasktrayAnimation();
6127 // 優先度:リプライ→エラー→オフライン→アイドル
6128 // エラーは更新アイコンでクリアされる
6129 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6130 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6131 else if (this.myStatusError)
6132 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6133 else if (this.myStatusOnline)
6134 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6136 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6139 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6140 => this.RefreshTasktrayIcon(); // 200ms
6142 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6144 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6145 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6146 this.rclickTabName = this.CurrentTabName;
6148 if (this.statuses == null) return;
6149 if (this.statuses.Tabs == null) return;
6151 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6154 this.NotifyDispMenuItem.Checked = tb.Notify;
6155 this.NotifyTbMenuItem.Checked = tb.Notify;
6157 this.soundfileListup = true;
6158 this.SoundFileComboBox.Items.Clear();
6159 this.SoundFileTbComboBox.Items.Clear();
6160 this.SoundFileComboBox.Items.Add("");
6161 this.SoundFileTbComboBox.Items.Add("");
6162 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6163 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6165 oDir = oDir.GetDirectories("Sounds")[0];
6167 foreach (var oFile in oDir.GetFiles("*.wav"))
6169 this.SoundFileComboBox.Items.Add(oFile.Name);
6170 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6172 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6173 if (idx == -1) idx = 0;
6174 this.SoundFileComboBox.SelectedIndex = idx;
6175 this.SoundFileTbComboBox.SelectedIndex = idx;
6176 this.soundfileListup = false;
6177 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6178 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6180 this.TabMenuControl(this.rclickTabName);
6183 private void TabMenuControl(string tabName)
6185 var tabInfo = this.statuses.GetTabByName(tabName)!;
6187 this.FilterEditMenuItem.Enabled = true;
6188 this.EditRuleTbMenuItem.Enabled = true;
6190 if (tabInfo.IsDefaultTabType)
6192 this.ProtectTabMenuItem.Enabled = false;
6193 this.ProtectTbMenuItem.Enabled = false;
6197 this.ProtectTabMenuItem.Enabled = true;
6198 this.ProtectTbMenuItem.Enabled = true;
6201 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6203 this.ProtectTabMenuItem.Checked = true;
6204 this.ProtectTbMenuItem.Checked = true;
6205 this.DeleteTabMenuItem.Enabled = false;
6206 this.DeleteTbMenuItem.Enabled = false;
6210 this.ProtectTabMenuItem.Checked = false;
6211 this.ProtectTbMenuItem.Checked = false;
6212 this.DeleteTabMenuItem.Enabled = true;
6213 this.DeleteTbMenuItem.Enabled = true;
6217 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6219 var checkState = ((ToolStripMenuItem)sender).Checked;
6222 this.ProtectTbMenuItem.Checked = checkState;
6223 this.ProtectTabMenuItem.Checked = checkState;
6226 this.DeleteTabMenuItem.Enabled = !checkState;
6227 this.DeleteTbMenuItem.Enabled = !checkState;
6229 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6230 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6232 this.SaveConfigsTabs();
6235 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6237 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6238 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6240 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6241 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6243 this.SaveConfigsTabs();
6246 public void ChangeTabUnreadManage(string tabName, bool isManage)
6248 var idx = this.GetTabPageIndex(tabName);
6252 var tab = this.statuses.Tabs[tabName];
6253 tab.UnreadManage = isManage;
6255 if (this.settings.Common.TabIconDisp)
6257 var tabPage = this.ListTab.TabPages[idx];
6258 if (tab.UnreadCount > 0)
6259 tabPage.ImageIndex = 0;
6261 tabPage.ImageIndex = -1;
6264 if (this.CurrentTabName == tabName)
6266 this.listCache?.PurgeCache();
6267 this.CurrentListView.Refresh();
6270 this.SetMainWindowTitle();
6271 this.SetStatusLabelUrl();
6272 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6275 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6277 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6278 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6280 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6282 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6284 this.SaveConfigsTabs();
6287 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6289 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6291 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6293 this.SaveConfigsTabs();
6296 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6298 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6299 this.rclickTabName = this.CurrentTabName;
6301 this.RemoveSpecifiedTab(this.rclickTabName, true);
6302 this.SaveConfigsTabs();
6305 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6307 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6309 using (var fltDialog = new FilterDialog())
6311 fltDialog.Owner = this;
6312 fltDialog.SetCurrent(this.rclickTabName);
6313 fltDialog.ShowDialog(this);
6315 this.TopMost = this.settings.Common.AlwaysTop;
6317 this.ApplyPostFilters();
6318 this.SaveConfigsTabs();
6321 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6323 string? tabName = null;
6324 MyCommon.TabUsageType tabUsage;
6325 using (var inputName = new InputTabName())
6327 inputName.TabName = this.statuses.MakeTabName("MyTab");
6328 inputName.IsShowUsage = true;
6329 inputName.ShowDialog();
6330 if (inputName.DialogResult == DialogResult.Cancel) return;
6331 tabName = inputName.TabName;
6332 tabUsage = inputName.Usage;
6334 this.TopMost = this.settings.Common.AlwaysTop;
6335 if (!MyCommon.IsNullOrEmpty(tabName))
6338 ListElement? list = null;
6339 if (tabUsage == MyCommon.TabUsageType.Lists)
6341 using var listAvail = new ListAvailable();
6342 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6344 if (listAvail.SelectedList == null)
6346 list = listAvail.SelectedList;
6352 case MyCommon.TabUsageType.UserDefined:
6353 tab = new FilterTabModel(tabName);
6355 case MyCommon.TabUsageType.PublicSearch:
6356 tab = new PublicSearchTabModel(tabName);
6358 case MyCommon.TabUsageType.Lists:
6359 tab = new ListTimelineTabModel(tabName, list!);
6365 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6367 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6368 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6373 this.SaveConfigsTabs();
6375 var tabIndex = this.statuses.Tabs.Count - 1;
6377 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6379 this.ListTab.SelectedIndex = tabIndex;
6380 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6382 if (tabUsage == MyCommon.TabUsageType.Lists)
6384 this.ListTab.SelectedIndex = tabIndex;
6385 await this.RefreshTabAsync(this.CurrentTab);
6391 private void TabMenuItem_Click(object sender, EventArgs e)
6394 foreach (var post in this.CurrentTab.SelectedPosts)
6397 if (!this.SelectTab(out var tab))
6400 using (var fltDialog = new FilterDialog())
6402 fltDialog.Owner = this;
6403 fltDialog.SetCurrent(tab.TabName);
6405 if (post.RetweetedBy == null)
6407 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6411 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6413 fltDialog.ShowDialog(this);
6416 this.TopMost = this.settings.Common.AlwaysTop;
6419 this.ApplyPostFilters();
6420 this.SaveConfigsTabs();
6423 protected override bool ProcessDialogKey(Keys keyData)
6425 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6426 if ((keyData & Keys.KeyCode) == Keys.Enter)
6428 if (this.StatusText.Focused)
6430 var newLine = false;
6433 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6435 if (this.StatusText.Multiline)
6437 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6439 if ((keyData & Keys.Control) == Keys.Control) post = true;
6443 if ((keyData & Keys.Control) == Keys.Control) post = true;
6446 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6448 if (this.StatusText.Multiline)
6450 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6452 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6456 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6461 if (this.StatusText.Multiline)
6463 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6465 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6466 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6470 if (((keyData & Keys.Shift) == Keys.Shift) ||
6471 (((keyData & Keys.Control) != Keys.Control) &&
6472 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6478 var pos1 = this.StatusText.SelectionStart;
6479 if (this.StatusText.SelectionLength > 0)
6481 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6483 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6484 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6489 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6495 var tab = this.CurrentTab;
6496 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6498 var tabPage = this.CurrentTabPage;
6499 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6500 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6502 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6509 return base.ProcessDialogKey(keyData);
6512 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6513 => this.MakeReplyText(atAll: true);
6515 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6517 var tab = this.CurrentTab;
6518 var selectedPosts = tab.SelectedPosts;
6521 if (selectedPosts.Length == 0)
6524 var screenNameArray = selectedPosts
6525 .Select(x => x.RetweetedBy ?? x.ScreenName)
6528 this.AddFilterRuleByScreenName(screenNameArray);
6530 if (screenNameArray.Length != 0)
6532 var atids = new List<string>();
6533 foreach (var screenName in screenNameArray)
6535 atids.Add("@" + screenName);
6537 var cnt = this.AtIdSupl.ItemCount;
6538 this.AtIdSupl.AddRangeItem(atids.ToArray());
6539 if (this.AtIdSupl.ItemCount != cnt)
6540 this.MarkSettingAtIdModified();
6544 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6546 var tab = this.CurrentTab;
6547 var selectedPosts = tab.SelectedPosts;
6549 if (selectedPosts.Length == 0)
6552 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6554 this.AddFilterRuleBySource(sourceArray);
6557 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6560 if (!this.SelectTab(out var tab)) return;
6564 if (tab.TabType != MyCommon.TabUsageType.Mute)
6566 this.MoveOrCopy(out mv, out mk);
6570 // ミュートタブでは常に MoveMatches を true にする
6575 foreach (var screenName in screenNameArray)
6577 tab.AddFilter(new PostFilterRule
6579 FilterName = screenName,
6580 UseNameField = true,
6584 FilterByUrl = false,
6588 this.ApplyPostFilters();
6589 this.SaveConfigsTabs();
6592 public void AddFilterRuleBySource(params string[] sourceArray)
6594 // タブ選択ダイアログを表示(or追加)
6595 if (!this.SelectTab(out var filterTab))
6600 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6602 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6603 this.MoveOrCopy(out mv, out mk);
6607 // ミュートタブでは常に MoveMatches を true にする
6612 // 振り分けルールに追加するSource
6613 foreach (var source in sourceArray)
6615 filterTab.AddFilter(new PostFilterRule
6617 FilterSource = source,
6621 FilterByUrl = false,
6625 this.ApplyPostFilters();
6626 this.SaveConfigsTabs();
6629 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6636 using (var dialog = new TabsDialog(this.statuses))
6638 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6640 tab = dialog.SelectedTab;
6643 this.CurrentTabPage.Focus();
6648 using (var inputName = new InputTabName())
6650 inputName.TabName = this.statuses.MakeTabName("MyTab");
6651 inputName.ShowDialog();
6652 if (inputName.DialogResult == DialogResult.Cancel) return false;
6653 tabName = inputName.TabName;
6655 this.TopMost = this.settings.Common.AlwaysTop;
6656 if (!MyCommon.IsNullOrEmpty(tabName))
6658 var newTab = new FilterTabModel(tabName);
6659 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6661 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6662 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6681 private void MoveOrCopy(out bool move, out bool mark)
6685 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6686 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6694 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6695 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6706 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6709 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6710 => this.CopyIdUri();
6712 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6714 if (this.StatusText.Focused)
6717 this.StatusText.SelectAll();
6721 // ListView上でのCtrl+A
6722 NativeMethods.SelectAllItems(this.CurrentListView);
6726 private void MoveMiddle()
6732 var listView = this.CurrentListView;
6733 if (listView.SelectedIndices.Count == 0) return;
6735 var idx = listView.SelectedIndices[0];
6737 item = listView.GetItemAt(0, 25);
6743 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6745 idx2 = listView.VirtualListSize - 1;
6749 idx -= Math.Abs(idx1 - idx2) / 2;
6750 if (idx < 0) idx = 0;
6752 listView.EnsureVisible(listView.VirtualListSize - 1);
6753 listView.EnsureVisible(idx);
6756 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6758 var linkElements = this.tweetDetailsView.GetLinkElements();
6760 if (linkElements.Length == 0)
6763 var links = new List<OpenUrlItem>(linkElements.Length);
6765 foreach (var linkElm in linkElements)
6767 var displayUrl = linkElm.GetAttribute("title");
6768 var href = linkElm.GetAttribute("href");
6769 var linkedText = linkElm.InnerText;
6771 if (MyCommon.IsNullOrEmpty(displayUrl))
6774 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6778 bool isReverseSettings;
6780 if (links.Count == 1)
6782 // ツイートに含まれる URL が 1 つのみの場合
6783 // => OpenURL ダイアログを表示せずにリンクを開く
6784 selectedUrl = links[0].Href;
6786 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6787 isReverseSettings = false;
6791 // ツイートに含まれる URL が複数ある場合
6792 // => OpenURL を表示しユーザーが選択したリンクを開く
6793 this.urlDialog.ClearUrl();
6795 foreach (var link in links)
6796 this.urlDialog.AddUrl(link);
6798 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6801 this.TopMost = this.settings.Common.AlwaysTop;
6803 selectedUrl = this.urlDialog.SelectedUrl;
6805 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6806 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6809 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6812 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6814 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6815 this.ClearTab(this.rclickTabName, true);
6818 private void ClearTab(string tabName, bool showWarning)
6822 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6823 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6829 this.statuses.ClearTabIds(tabName);
6830 if (this.CurrentTabName == tabName)
6832 this.CurrentTab.ClearAnchor();
6833 this.listCache?.PurgeCache();
6834 this.listCache?.UpdateListSize();
6837 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6838 var tabPage = this.ListTab.TabPages[tabIndex];
6839 tabPage.ImageIndex = -1;
6841 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6843 this.SetMainWindowTitle();
6844 this.SetStatusLabelUrl();
6847 private static long followers = 0;
6849 private void SetMainWindowTitle()
6851 // メインウインドウタイトルの書き換え
6852 var ttl = new StringBuilder(256);
6855 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6856 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6857 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6858 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6860 foreach (var tab in this.statuses.Tabs)
6862 ur += tab.UnreadCount;
6867 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6868 ttl.Append(ApplicationSettings.ApplicationName);
6870 switch (this.settings.Common.DispLatestPost)
6872 case MyCommon.DispTitleEnum.Ver:
6873 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6875 case MyCommon.DispTitleEnum.Post:
6876 if (this.history.Peek() is { } lastItem)
6877 ttl.Append(lastItem.Status.Replace("\r\n", " "));
6879 case MyCommon.DispTitleEnum.UnreadRepCount:
6880 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6882 case MyCommon.DispTitleEnum.UnreadAllCount:
6883 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6885 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6886 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6888 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6889 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6891 case MyCommon.DispTitleEnum.OwnStatus:
6892 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6893 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6899 this.Text = ttl.ToString();
6901 catch (AccessViolationException)
6903 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6907 private string GetStatusLabelText()
6910 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6911 if (this.statuses == null) return "";
6912 var tbRep = this.statuses.MentionTab;
6913 var tbDm = this.statuses.DirectMessageTab;
6914 if (tbRep == null || tbDm == null) return "";
6915 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6920 var slbl = new StringBuilder(256);
6923 foreach (var tab in this.statuses.Tabs)
6925 ur += tab.UnreadCount;
6927 if (tab.TabName == this.CurrentTabName)
6929 tur = tab.UnreadCount;
6939 this.unreadCounter = ur;
6940 this.unreadAtCounter = urat;
6942 var homeTab = this.statuses.HomeTab;
6944 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
6945 if (this.settings.Common.TimelinePeriod == 0)
6947 slbl.Append(Properties.Resources.SetStatusLabelText2);
6951 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
6953 return slbl.ToString();
6956 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
6960 if (this.InvokeRequired && !this.IsDisposed)
6962 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
6966 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
6967 this.SetApiStatusLabel(endpointName);
6970 catch (ObjectDisposedException)
6974 catch (InvalidOperationException)
6980 private void SetApiStatusLabel(string? endpointName = null)
6982 var tabType = this.CurrentTab.TabType;
6984 if (endpointName == null)
6986 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
6989 endpointName = tabType switch
6991 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
6992 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
6993 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
6994 MyCommon.TabUsageType.Favorites => "/favorites/list",
6995 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
6996 MyCommon.TabUsageType.UserTimeline =>
6997 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
6998 MyCommon.TabUsageType.Lists =>
6999 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7000 MyCommon.TabUsageType.PublicSearch =>
7001 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7002 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7005 this.toolStripApiGauge.ApiEndpoint = endpointName;
7009 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7010 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7014 private void SetStatusLabelUrl()
7015 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7017 public void SetStatusLabel(string text)
7018 => this.StatusLabel.Text = text;
7020 private void SetNotifyIconText()
7022 var ur = new StringBuilder(64);
7024 // タスクトレイアイコンのツールチップテキスト書き換え
7026 ur.Remove(0, ur.Length);
7027 if (this.settings.Common.DispUsername)
7029 ur.Append(this.tw.Username);
7032 ur.Append(ApplicationSettings.ApplicationName);
7034 ur.Append("(Debug Build)");
7036 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7039 ur.Append(this.unreadCounter);
7041 ur.Append(this.unreadAtCounter);
7044 this.NotifyIcon1.Text = ur.ToString();
7047 internal void CheckReplyTo(string statusText)
7051 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7053 foreach (Match hm in m)
7055 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7057 hstr += "#" + hm.Result("$3") + " ";
7058 this.HashSupl.AddItem("#" + hm.Result("$3"));
7061 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7063 hstr += this.HashMgr.UseHash;
7065 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7067 // 本当にリプライ先指定すべきかどうかの判定
7068 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7070 if (this.settings.Common.UseAtIdSupplement)
7072 var bCnt = this.AtIdSupl.ItemCount;
7073 foreach (Match mid in m)
7075 this.AtIdSupl.AddItem(mid.Result("${id}"));
7077 if (bCnt != this.AtIdSupl.ItemCount)
7078 this.MarkSettingAtIdModified();
7081 // リプライ先ステータスIDの指定がない場合は指定しない
7082 if (this.inReplyTo == null)
7086 // 次の条件を満たす場合に in_reply_to_status_id 指定
7087 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7088 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7089 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7093 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7094 if (statusText.StartsWith("@", StringComparison.Ordinal))
7096 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7100 foreach (Match mid in m)
7102 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7107 this.inReplyTo = null;
7110 private void TweenMain_Resize(object sender, EventArgs e)
7112 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7114 this.Visible = false;
7116 if (this.WindowState != FormWindowState.Minimized)
7118 this.formWindowState = this.WindowState;
7122 private void ApplyLayoutFromSettings()
7124 // 現在の DPI と設定保存時の DPI との比を取得する
7125 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7127 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7130 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7131 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7132 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7134 this.SplitContainer1.SplitterDistance = splitterDistance;
7138 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7139 if (this.StatusText.Multiline)
7141 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7142 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7143 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7145 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7147 this.StatusText.Height = statusTextHeight;
7151 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7153 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7157 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7158 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7160 this.SplitContainer3.SplitterDistance = previewDistance;
7163 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7164 this.SplitContainer3.Panel2Collapsed = true;
7165 this.initialLayout = false;
7168 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7170 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7171 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7172 if (this.PlaySoundMenuItem.Checked)
7174 this.settings.Common.PlaySound = true;
7178 this.settings.Common.PlaySound = false;
7180 this.MarkSettingCommonModified();
7183 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7185 if (this.initialLayout)
7188 int splitterDistance;
7189 switch (this.WindowState)
7191 case FormWindowState.Normal:
7192 splitterDistance = this.SplitContainer1.SplitterDistance;
7194 case FormWindowState.Maximized:
7195 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7196 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7197 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7198 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7204 this.mySpDis = splitterDistance;
7205 this.MarkSettingLocalModified();
7208 private async Task DoRepliedStatusOpen()
7210 var currentPost = this.CurrentPost;
7211 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7213 if (MyCommon.IsKeyDown(Keys.Shift))
7215 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7218 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7220 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7224 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7226 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7227 repPost = tb.Posts[currentPost.InReplyToStatusId];
7228 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7231 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7236 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7237 => await this.DoRepliedStatusOpen();
7239 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7241 if (this.initialLayout)
7242 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7244 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7245 if (multiline != this.StatusText.Multiline)
7247 this.StatusText.Multiline = multiline;
7248 this.settings.Local.StatusMultiline = multiline;
7249 this.MarkSettingLocalModified();
7253 private void StatusText_MultilineChanged(object sender, EventArgs e)
7255 if (this.StatusText.Multiline)
7256 this.StatusText.ScrollBars = ScrollBars.Vertical;
7258 this.StatusText.ScrollBars = ScrollBars.None;
7260 if (!this.initialLayout)
7261 this.MarkSettingLocalModified();
7264 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7267 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7268 this.StatusText.Multiline = menuItemChecked;
7269 this.settings.Local.StatusMultiline = menuItemChecked;
7270 if (menuItemChecked)
7272 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7273 this.SplitContainer2.SplitterDistance = 0;
7275 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7279 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7281 this.MarkSettingLocalModified();
7284 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7286 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7288 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7289 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7290 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7292 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7297 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7298 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7299 // Appendix A. Collected ABNF for URI
7300 // http://www.ietf.org/rfc/rfc3986.txt
7302 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7305 if (this.StatusText.SelectionLength > 0)
7307 var tmp = this.StatusText.SelectedText;
7308 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7309 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7311 // 文字列が選択されている場合はその文字列について処理
7313 // nico.ms使用、nicovideoにマッチしたら変換
7314 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7316 result = Nicoms.Shorten(tmp);
7318 else if (converterType != MyCommon.UrlConverter.Nicoms)
7323 var srcUri = new Uri(tmp);
7324 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7325 result = resultUri.AbsoluteUri;
7327 catch (WebApiException e)
7329 this.StatusLabel.Text = converterType + ":" + e.Message;
7332 catch (UriFormatException e)
7334 this.StatusLabel.Text = converterType + ":" + e.Message;
7343 if (!MyCommon.IsNullOrEmpty(result))
7345 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7346 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7347 if (origUrlIndex == -1)
7350 this.StatusText.Select(origUrlIndex, tmp.Length);
7351 this.StatusText.SelectedText = result;
7354 var undo = new UrlUndo
7360 if (this.urlUndoBuffer == null)
7362 this.urlUndoBuffer = new List<UrlUndo>();
7363 this.UrlUndoToolStripMenuItem.Enabled = true;
7366 this.urlUndoBuffer.Add(undo);
7372 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7373 @"(?<url>(?<protocol>https?://)" +
7374 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7375 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7376 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7377 // 正規表現にマッチしたURL文字列をtinyurl化
7378 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7380 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7382 var tmp = mt.Result("${url}");
7383 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7384 tmp = "http://" + tmp;
7387 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7389 // nico.ms使用、nicovideoにマッチしたら変換
7390 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7392 result = Nicoms.Shorten(tmp);
7394 else if (converterType != MyCommon.UrlConverter.Nicoms)
7399 var srcUri = new Uri(tmp);
7400 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7401 result = resultUri.AbsoluteUri;
7403 catch (HttpRequestException e)
7405 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7406 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7407 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7409 this.StatusLabel.Text = converterType + ":" + message;
7412 catch (WebApiException e)
7414 this.StatusLabel.Text = converterType + ":" + e.Message;
7417 catch (UriFormatException e)
7419 this.StatusLabel.Text = converterType + ":" + e.Message;
7428 if (!MyCommon.IsNullOrEmpty(result))
7430 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7431 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7432 if (origUrlIndex == -1)
7435 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7436 this.StatusText.SelectedText = result;
7438 var undo = new UrlUndo
7440 Before = mt.Result("${url}"),
7444 if (this.urlUndoBuffer == null)
7446 this.urlUndoBuffer = new List<UrlUndo>();
7447 this.UrlUndoToolStripMenuItem.Enabled = true;
7450 this.urlUndoBuffer.Add(undo);
7458 private void DoUrlUndo()
7460 if (this.urlUndoBuffer != null)
7462 var tmp = this.StatusText.Text;
7463 foreach (var data in this.urlUndoBuffer)
7465 tmp = tmp.Replace(data.After, data.Before);
7467 this.StatusText.Text = tmp;
7468 this.urlUndoBuffer = null;
7469 this.UrlUndoToolStripMenuItem.Enabled = false;
7470 this.StatusText.SelectionStart = 0;
7471 this.StatusText.SelectionLength = 0;
7475 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7476 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7478 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7479 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7481 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7482 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7484 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7486 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7488 var rnd = new Random();
7490 MyCommon.UrlConverter svc;
7491 // 前回使用した短縮URLサービス以外を選択する
7494 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7496 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7497 await this.UrlConvertAsync(svc);
7501 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7502 => this.DoUrlUndo();
7504 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7506 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7507 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7508 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7509 this.MarkSettingCommonModified();
7512 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7514 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7515 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7516 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7517 this.MarkSettingCommonModified();
7520 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7522 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7523 this.MenuStrip1.Tag = new object();
7524 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7527 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7529 var currentTabPage = this.CurrentTabPage;
7530 if (this.Tag != null) // 設定された戻り先へ遷移
7532 if (this.Tag == currentTabPage)
7533 ((Control)currentTabPage.Tag).Select();
7535 ((Control)this.Tag).Select();
7537 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7539 this.Tag = currentTabPage.Tag;
7540 ((Control)this.Tag).Select();
7542 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7543 this.MenuStrip1.Tag = null;
7546 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7548 if (this.Use2ColumnsMode)
7554 var lst = (DetailsListView)sender;
7555 var columnsCount = lst.Columns.Count;
7557 var darr = new int[columnsCount];
7558 for (var i = 0; i < columnsCount; i++)
7559 darr[lst.Columns[i].DisplayIndex] = i;
7561 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7563 for (var i = 0; i < columnsCount; i++)
7564 this.settings.Local.ColumnsOrder[darr[i]] = i;
7566 this.MarkSettingLocalModified();
7567 this.isColumnChanged = true;
7570 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7572 var lst = (DetailsListView)sender;
7573 if (this.settings.Local == null) return;
7575 var modified = false;
7576 if (this.Use2ColumnsMode)
7578 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7580 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7583 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7585 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7591 var columnsCount = lst.Columns.Count;
7592 for (var i = 0; i < columnsCount; i++)
7594 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7597 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7603 this.MarkSettingLocalModified();
7604 this.isColumnChanged = true;
7608 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7610 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7611 this.MarkSettingLocalModified();
7614 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7616 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7618 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7620 this.SelectMedia_DragDrop(e);
7623 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7625 var (url, title) = GetUrlFromDataObject(e.Data);
7631 appendText = title + " " + url;
7633 if (this.StatusText.TextLength == 0)
7634 this.StatusText.Text = appendText;
7636 this.StatusText.Text += " " + appendText;
7638 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7640 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7642 this.StatusText.Text += text;
7644 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7646 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7647 if (data != null) this.StatusText.Text += data;
7652 /// IDataObject から URL とタイトルの対を取得します
7655 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7657 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7658 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7659 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7661 if (data.GetDataPresent("text/x-moz-url"))
7663 // Firefox, Google Chrome で利用可能
7664 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7666 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7667 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7668 if (lines.Length < 2)
7669 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7671 return (lines[0], lines[1]);
7673 else if (data.GetDataPresent("IESiteModeToUrl"))
7675 // Internet Exproler 用
7676 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7678 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7679 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7680 if (lines.Length < 2)
7681 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7683 return (lines[0], lines[1]);
7685 else if (data.GetDataPresent("UniformResourceLocatorW"))
7689 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7690 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7694 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7697 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7699 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7701 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7703 this.SelectMedia_DragEnter(e);
7707 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7709 e.Effect = DragDropEffects.Copy;
7712 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7714 e.Effect = DragDropEffects.Copy;
7717 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7719 e.Effect = DragDropEffects.Copy;
7723 e.Effect = DragDropEffects.None;
7726 private void TweenMain_DragOver(object sender, DragEventArgs e)
7730 public bool IsNetworkAvailable()
7732 var nw = MyCommon.IsNetworkAvailable();
7733 this.myStatusOnline = nw;
7737 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7739 var uriStr = uri.AbsoluteUri;
7741 // OpenTween 内部で使用する URL
7742 if (uri.Authority == "opentween")
7744 await this.OpenInternalUriAsync(uri);
7748 // ハッシュタグを含む Twitter 検索
7749 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7752 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7753 var pos = unescapedQuery.IndexOf('#');
7754 if (pos == -1) return;
7756 var hash = unescapedQuery.Substring(pos);
7757 this.HashSupl.AddItem(hash);
7758 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7759 this.AddNewTabForSearch(hash);
7764 // フラグが立っている場合は設定と逆の動作をする
7765 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7766 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7768 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7769 if (userUriMatch.Success)
7771 var screenName = userUriMatch.Groups["ScreenName"].Value;
7772 if (this.IsTwitterId(screenName))
7774 await this.AddNewTabForUserTimeline(screenName);
7781 await MyCommon.OpenInBrowserAsync(this, uriStr);
7785 /// OpenTween 内部の機能を呼び出すための URL を開きます
7787 private async Task OpenInternalUriAsync(Uri uri)
7789 // ツイートを開く (//opentween/status/:status_id)
7790 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7793 var statusId = new TwitterStatusId(match.Groups[1].Value);
7794 await this.OpenRelatedTab(statusId);
7799 private void ListTabSelect(TabPage tabPage)
7801 this.SetListProperty();
7803 var previousTabName = this.CurrentTabName;
7804 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7805 previousListViewState.Save(this.ListLockMenuItem.Checked);
7807 this.listCache?.PurgeCache();
7809 this.statuses.SelectTab(tabPage.Text);
7811 this.InitializeTimelineListView();
7813 var tab = this.CurrentTab;
7816 var listView = this.CurrentListView;
7818 var currentListViewState = this.listViewState[tab.TabName];
7819 currentListViewState.Restore(forceScroll: true);
7821 if (this.Use2ColumnsMode)
7823 listView.Columns[1].Text = this.columnText[2];
7827 for (var i = 0; i < listView.Columns.Count; i++)
7829 listView.Columns[i].Text = this.columnText[i];
7834 private void InitializeTimelineListView()
7836 var listView = this.CurrentListView;
7837 var tab = this.CurrentTab;
7839 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7840 (this.listCache, var oldCache) = (newCache, this.listCache);
7841 oldCache?.Dispose();
7843 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7844 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7845 oldDrawer?.Dispose();
7847 newDrawer.IconSize = this.settings.Common.IconSize;
7848 newDrawer.UpdateItemHeight();
7851 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7852 => this.ListTabSelect(e.TabPage);
7854 private void SelectListItem(DetailsListView lView, int index)
7857 var bnd = new Rectangle();
7859 var item = lView.FocusedItem;
7868 lView.SelectedIndices.Clear();
7870 while (lView.SelectedIndices.Count > 0);
7871 item = lView.Items[index];
7872 item.Selected = true;
7873 item.Focused = true;
7875 if (flg) lView.Invalidate(bnd);
7878 private async void TweenMain_Shown(object sender, EventArgs e)
7880 this.NotifyIcon1.Visible = true;
7883 if (this.settings.IsFirstRun)
7885 // 初回起動時だけ右下のメニューを目立たせる
7886 this.HashStripSplitButton.ShowDropDown();
7889 if (this.IsNetworkAvailable())
7891 var loadTasks = new TaskCollection();
7895 this.RefreshMuteUserIdsAsync,
7896 this.RefreshBlockIdsAsync,
7897 this.RefreshNoRetweetIdsAsync,
7898 this.RefreshTwitterConfigurationAsync,
7899 this.RefreshTabAsync<HomeTabModel>,
7900 this.RefreshTabAsync<MentionsTabModel>,
7901 this.RefreshTabAsync<DirectMessagesTabModel>,
7902 this.RefreshTabAsync<PublicSearchTabModel>,
7903 this.RefreshTabAsync<UserTimelineTabModel>,
7904 this.RefreshTabAsync<ListTimelineTabModel>,
7907 if (this.settings.Common.StartupFollowers)
7908 loadTasks.Add(this.RefreshFollowerIdsAsync);
7910 if (this.settings.Common.GetFav)
7911 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7913 var allTasks = loadTasks.RunAll();
7918 var timeout = Task.Delay(5000);
7919 if (await Task.WhenAny(allTasks, timeout) != timeout)
7923 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7925 if (MyCommon.EndingFlag)
7929 if (MyCommon.EndingFlag) return;
7931 if (ApplicationSettings.VersionInfoUrl != null)
7933 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7934 if (this.settings.Common.StartupVersion)
7935 await this.CheckNewVersion(true);
7939 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
7940 this.VerUpMenuItem.Enabled = false;
7941 this.VerUpMenuItem.Available = false;
7942 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
7945 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
7946 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
7948 MessageBox.Show(Properties.Resources.ReAuthorizeText);
7949 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
7953 var reloadTasks = new TaskCollection();
7955 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
7956 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
7958 if (!this.tw.GetNoRetweetSuccess)
7959 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
7961 if (this.tw.Configuration.PhotoSizeLimit == 0)
7962 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
7964 await reloadTasks.RunAll();
7967 this.initial = false;
7970 private void StartTimers()
7972 if (!this.StopRefreshAllMenuItem.Checked)
7973 this.timelineScheduler.Enabled = true;
7975 this.selectionDebouncer.Enabled = true;
7976 this.saveConfigDebouncer.Enabled = true;
7977 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
7980 private async Task DoGetFollowersMenu()
7982 await this.RefreshFollowerIdsAsync();
7983 this.DispSelectedPost(true);
7986 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
7987 => await this.DoGetFollowersMenu();
7989 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
7990 => this.DoReTweetUnofficial();
7992 private async Task DoReTweetOfficial(bool isConfirm)
7995 if (this.ExistCurrentPost)
7997 var selectedPosts = this.CurrentTab.SelectedPosts;
7999 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8001 if (selectedPosts.Any(x => x.IsProtect))
8002 MessageBox.Show("Protected.");
8004 this.doFavRetweetFlags = false;
8008 if (selectedPosts.Length > 15)
8010 MessageBox.Show(Properties.Resources.RetweetLimitText);
8011 this.doFavRetweetFlags = false;
8014 else if (selectedPosts.Length > 1)
8016 var questionText = Properties.Resources.RetweetQuestion2;
8017 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8018 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8020 case DialogResult.Cancel:
8021 case DialogResult.No:
8022 this.doFavRetweetFlags = false;
8028 if (!this.settings.Common.RetweetNoConfirm)
8030 var questiontext = Properties.Resources.RetweetQuestion1;
8031 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8032 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8034 this.doFavRetweetFlags = false;
8040 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8042 await this.RetweetAsync(statusIds);
8046 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8047 => await this.DoReTweetOfficial(true);
8049 private async Task FavoritesRetweetOfficial()
8051 if (!this.ExistCurrentPost) return;
8052 this.doFavRetweetFlags = true;
8054 var tasks = new TaskCollection();
8055 tasks.Add(() => this.DoReTweetOfficial(true));
8057 if (this.doFavRetweetFlags)
8059 this.doFavRetweetFlags = false;
8060 tasks.Add(() => this.FavoriteChange(true, false));
8063 await tasks.RunAll();
8066 private async Task FavoritesRetweetUnofficial()
8068 var post = this.CurrentPost;
8069 if (this.ExistCurrentPost && post != null && !post.IsDm)
8071 this.doFavRetweetFlags = true;
8072 var favoriteTask = this.FavoriteChange(true);
8073 if (!post.IsProtect && this.doFavRetweetFlags)
8075 this.doFavRetweetFlags = false;
8076 this.DoReTweetUnofficial();
8084 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8086 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8087 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8088 /// <returns>復元されたツイート本文</returns>
8089 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8091 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8094 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8096 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8098 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8100 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8104 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8106 statusHtml = statusHtml.Replace("<br>", " ");
8108 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8109 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8110 statusHtml = statusHtml.Replace(" ", " ");
8112 return WebUtility.HtmlDecode(statusHtml);
8115 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8117 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8119 if (this.CurrentPost != null)
8120 this.DispSelectedPost(true);
8123 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8125 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8126 this.DebugModeToolStripMenuItem.Visible = true;
8128 this.DebugModeToolStripMenuItem.Visible = false;
8131 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8132 => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8134 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8135 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8137 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8138 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8140 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8142 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8143 this.MarkSettingCommonModified();
8146 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8148 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8149 this.MarkSettingCommonModified();
8152 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8154 this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8155 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8156 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8157 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8158 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8159 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8162 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8164 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8165 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8166 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8167 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8168 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8169 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8172 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8174 if (this.TraceOutToolStripMenuItem.Checked)
8175 MyCommon.TraceFlag = true;
8177 MyCommon.TraceFlag = false;
8180 private void TweenMain_Deactivate(object sender, EventArgs e)
8181 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8183 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8185 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8187 _ = this.TabRename(this.rclickTabName, out _);
8190 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8191 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8193 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8194 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8196 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8198 TwitterApiStatus? apiStatus;
8200 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8202 var cancellationToken = dialog.EnableCancellation();
8206 var task = this.tw.GetInfoApi();
8207 apiStatus = await dialog.WaitForAsync(this, task);
8209 catch (WebApiException)
8214 if (cancellationToken.IsCancellationRequested)
8217 if (apiStatus == null)
8219 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8224 using var apiDlg = new ApiInfoDialog();
8225 apiDlg.ShowDialog(this);
8228 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8230 var id = this.CurrentPost?.ScreenName ?? "";
8232 await this.FollowCommand(id);
8235 internal async Task FollowCommand(string id)
8237 using (var inputName = new InputTabName())
8239 inputName.FormTitle = "Follow";
8240 inputName.FormDescription = Properties.Resources.FRMessage1;
8241 inputName.TabName = id;
8243 if (inputName.ShowDialog(this) != DialogResult.OK)
8245 if (string.IsNullOrWhiteSpace(inputName.TabName))
8248 id = inputName.TabName.Trim();
8251 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8255 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8256 await dialog.WaitForAsync(this, task);
8258 catch (WebApiException ex)
8260 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8265 MessageBox.Show(Properties.Resources.FRMessage3);
8268 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8270 var id = this.CurrentPost?.ScreenName ?? "";
8272 await this.RemoveCommand(id, false);
8275 internal async Task RemoveCommand(string id, bool skipInput)
8279 using var inputName = new InputTabName();
8280 inputName.FormTitle = "Unfollow";
8281 inputName.FormDescription = Properties.Resources.FRMessage1;
8282 inputName.TabName = id;
8284 if (inputName.ShowDialog(this) != DialogResult.OK)
8286 if (string.IsNullOrWhiteSpace(inputName.TabName))
8289 id = inputName.TabName.Trim();
8292 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8296 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8297 await dialog.WaitForAsync(this, task);
8299 catch (WebApiException ex)
8301 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8306 MessageBox.Show(Properties.Resources.FRMessage3);
8309 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8311 var id = this.CurrentPost?.ScreenName ?? "";
8313 await this.ShowFriendship(id);
8316 internal async Task ShowFriendship(string id)
8318 using (var inputName = new InputTabName())
8320 inputName.FormTitle = "Show Friendships";
8321 inputName.FormDescription = Properties.Resources.FRMessage1;
8322 inputName.TabName = id;
8324 if (inputName.ShowDialog(this) != DialogResult.OK)
8326 if (string.IsNullOrWhiteSpace(inputName.TabName))
8329 id = inputName.TabName.Trim();
8332 bool isFollowing, isFollowed;
8334 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8336 var cancellationToken = dialog.EnableCancellation();
8340 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8341 var friendship = await dialog.WaitForAsync(this, task);
8343 isFollowing = friendship.Relationship.Source.Following;
8344 isFollowed = friendship.Relationship.Source.FollowedBy;
8346 catch (WebApiException ex)
8348 if (!cancellationToken.IsCancellationRequested)
8349 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8353 if (cancellationToken.IsCancellationRequested)
8360 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8364 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8368 result += Properties.Resources.GetFriendshipInfo3;
8372 result += Properties.Resources.GetFriendshipInfo4;
8374 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8375 MessageBox.Show(result);
8378 internal async Task ShowFriendship(string[] ids)
8380 foreach (var id in ids)
8382 bool isFollowing, isFollowed;
8384 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8386 var cancellationToken = dialog.EnableCancellation();
8390 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8391 var friendship = await dialog.WaitForAsync(this, task);
8393 isFollowing = friendship.Relationship.Source.Following;
8394 isFollowed = friendship.Relationship.Source.FollowedBy;
8396 catch (WebApiException ex)
8398 if (!cancellationToken.IsCancellationRequested)
8399 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8403 if (cancellationToken.IsCancellationRequested)
8413 ff += Properties.Resources.GetFriendshipInfo1;
8417 ff += Properties.Resources.GetFriendshipInfo2;
8420 ff += System.Environment.NewLine + " ";
8423 ff += Properties.Resources.GetFriendshipInfo3;
8427 ff += Properties.Resources.GetFriendshipInfo4;
8429 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8432 if (MessageBox.Show(
8433 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8434 Properties.Resources.GetFriendshipInfo8,
8435 MessageBoxButtons.YesNo,
8436 MessageBoxIcon.Question,
8437 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8439 await this.RemoveCommand(id, true);
8444 MessageBox.Show(result);
8449 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8450 => await this.DoShowUserStatus(this.tw.Username, false);
8452 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8455 public bool IsTwitterId(string name)
8457 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8458 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8460 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8463 private void DoQuoteOfficial()
8465 var post = this.CurrentPost;
8466 if (this.ExistCurrentPost && post != null)
8468 if (post.IsDm || !this.StatusText.Enabled)
8473 MessageBox.Show("Protected.");
8477 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8479 this.inReplyTo = null;
8481 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8483 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8484 this.StatusText.Focus();
8488 private void DoReTweetUnofficial()
8491 var post = this.CurrentPost;
8492 if (this.ExistCurrentPost && post != null)
8494 if (post.IsDm || !this.StatusText.Enabled)
8499 MessageBox.Show("Protected.");
8502 var rtdata = post.Text;
8503 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8505 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8507 // 投稿時に in_reply_to_status_id を付加する
8508 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8509 var inReplyToScreenName = post.ScreenName;
8510 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8512 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8514 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8515 this.StatusText.Focus();
8519 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8520 => this.DoQuoteOfficial();
8522 private async void SearchButton_Click(object sender, EventArgs e)
8525 var pnl = ((Control)sender).Parent;
8526 if (pnl == null) return;
8527 var tbName = pnl.Parent.Text;
8528 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8529 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8530 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8531 cmb.Text = cmb.Text.Trim();
8532 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8534 var buf = new StringBuilder();
8535 var c = cmb.Text.ToCharArray();
8536 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8538 if (cnt > cmb.Text.Length - 4)
8540 buf.Append(cmb.Text.Substring(cnt));
8549 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8558 cmb.Text = buf.ToString();
8560 var listView = (DetailsListView)pnl.Parent.Tag;
8562 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8564 tb.SearchWords = cmb.Text;
8565 tb.SearchLang = cmbLang.Text;
8566 if (MyCommon.IsNullOrEmpty(cmb.Text))
8569 this.SaveConfigsTabs();
8574 var idx = cmb.Items.IndexOf(tb.SearchWords);
8575 if (idx > -1) cmb.Items.RemoveAt(idx);
8576 cmb.Items.Insert(0, tb.SearchWords);
8577 cmb.Text = tb.SearchWords;
8579 this.statuses.ClearTabIds(tbName);
8580 this.listCache?.PurgeCache();
8581 this.listCache?.UpdateListSize();
8582 this.SaveConfigsTabs(); // 検索条件の保存
8586 await this.RefreshTabAsync(tb);
8589 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8590 => await this.DoRefreshMore(); // もっと前を取得
8593 /// 指定されたタブのListTabにおける位置を返します
8596 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8598 public int GetTabPageIndex(string tabName)
8599 => this.statuses.Tabs.IndexOf(tabName);
8601 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8605 var restoredTab = this.statuses.UndoRemovedTab();
8606 this.AddNewTab(restoredTab, startup: false);
8608 var tabIndex = this.statuses.Tabs.Count - 1;
8609 this.ListTab.SelectedIndex = tabIndex;
8611 this.SaveConfigsTabs();
8613 catch (TabException ex)
8615 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8619 private async Task DoMoveToRTHome()
8621 var post = this.CurrentPost;
8622 if (post != null && post.RetweetedId != null)
8623 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8626 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8627 => await this.DoMoveToRTHome();
8629 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8631 var screenName = this.CurrentPost?.ScreenName;
8632 if (screenName != null)
8633 this.ListManageUserContext(screenName);
8636 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8638 var screenName = this.CurrentPost?.RetweetedBy;
8639 if (screenName != null)
8640 this.ListManageUserContext(screenName);
8643 public void ListManageUserContext(string screenName)
8645 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8646 listSelectForm.ShowDialog(this);
8649 private void SearchControls_Enter(object sender, EventArgs e)
8651 var pnl = (Control)sender;
8652 foreach (Control ctl in pnl.Controls)
8658 private void SearchControls_Leave(object sender, EventArgs e)
8660 var pnl = (Control)sender;
8661 foreach (Control ctl in pnl.Controls)
8663 ctl.TabStop = false;
8667 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8669 var tab = this.CurrentTab;
8670 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8671 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8674 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8675 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8677 private void HashManageMenuItem_Click(object sender, EventArgs e)
8682 rslt = this.HashMgr.ShowDialog();
8688 this.TopMost = this.settings.Common.AlwaysTop;
8689 if (rslt == DialogResult.Cancel) return;
8690 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8692 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8693 this.HashTogglePullDownMenuItem.Checked = true;
8694 this.HashToggleMenuItem.Checked = true;
8698 this.HashStripSplitButton.Text = "#[-]";
8699 this.HashTogglePullDownMenuItem.Checked = false;
8700 this.HashToggleMenuItem.Checked = false;
8703 this.MarkSettingCommonModified();
8704 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8707 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8709 this.HashMgr.ToggleHash();
8710 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8712 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8713 this.HashToggleMenuItem.Checked = true;
8714 this.HashTogglePullDownMenuItem.Checked = true;
8718 this.HashStripSplitButton.Text = "#[-]";
8719 this.HashToggleMenuItem.Checked = false;
8720 this.HashTogglePullDownMenuItem.Checked = false;
8722 this.MarkSettingCommonModified();
8723 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8726 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8727 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8729 public void SetPermanentHashtag(string hashtag)
8731 this.HashMgr.SetPermanentHash("#" + hashtag);
8732 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8733 this.HashTogglePullDownMenuItem.Checked = true;
8734 this.HashToggleMenuItem.Checked = true;
8736 this.MarkSettingCommonModified();
8739 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8741 var tab = this.CurrentTab;
8742 var post = this.CurrentPost;
8743 if (!this.ExistCurrentPost)
8745 this.ReplyOpMenuItem.Enabled = false;
8746 this.ReplyAllOpMenuItem.Enabled = false;
8747 this.DmOpMenuItem.Enabled = false;
8748 this.CreateTabRuleOpMenuItem.Enabled = false;
8749 this.CreateIdRuleOpMenuItem.Enabled = false;
8750 this.CreateSourceRuleOpMenuItem.Enabled = false;
8751 this.ReadOpMenuItem.Enabled = false;
8752 this.UnreadOpMenuItem.Enabled = false;
8753 this.AuthorMenuItem.Visible = false;
8754 this.RetweetedByMenuItem.Visible = false;
8758 this.ReplyOpMenuItem.Enabled = true;
8759 this.ReplyAllOpMenuItem.Enabled = true;
8760 this.DmOpMenuItem.Enabled = true;
8761 this.CreateTabRuleOpMenuItem.Enabled = true;
8762 this.CreateIdRuleOpMenuItem.Enabled = true;
8763 this.CreateSourceRuleOpMenuItem.Enabled = true;
8764 this.ReadOpMenuItem.Enabled = true;
8765 this.UnreadOpMenuItem.Enabled = true;
8766 this.AuthorMenuItem.Visible = true;
8767 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8768 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8769 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8772 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8774 this.FavOpMenuItem.Enabled = false;
8775 this.UnFavOpMenuItem.Enabled = false;
8776 this.OpenStatusOpMenuItem.Enabled = false;
8777 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8778 this.RtOpMenuItem.Enabled = false;
8779 this.RtUnOpMenuItem.Enabled = false;
8780 this.QtOpMenuItem.Enabled = false;
8781 this.FavoriteRetweetMenuItem.Enabled = false;
8782 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8786 this.FavOpMenuItem.Enabled = true;
8787 this.UnFavOpMenuItem.Enabled = true;
8788 this.OpenStatusOpMenuItem.Enabled = true;
8789 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8791 if (!post.CanRetweetBy(this.tw.UserId))
8793 this.RtOpMenuItem.Enabled = false;
8794 this.RtUnOpMenuItem.Enabled = false;
8795 this.QtOpMenuItem.Enabled = false;
8796 this.FavoriteRetweetMenuItem.Enabled = false;
8797 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8801 this.RtOpMenuItem.Enabled = true;
8802 this.RtUnOpMenuItem.Enabled = true;
8803 this.QtOpMenuItem.Enabled = true;
8804 this.FavoriteRetweetMenuItem.Enabled = true;
8805 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8809 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8811 this.RefreshPrevOpMenuItem.Enabled = true;
8815 this.RefreshPrevOpMenuItem.Enabled = false;
8817 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8819 this.OpenRepSourceOpMenuItem.Enabled = false;
8823 this.OpenRepSourceOpMenuItem.Enabled = true;
8826 if (this.ExistCurrentPost && post != null)
8828 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8832 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8833 => this.ContextMenuTabProperty_Opening(sender, null!);
8835 public Twitter TwitterInstance
8838 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8840 if (this.initialLayout)
8843 int splitterDistance;
8844 switch (this.WindowState)
8846 case FormWindowState.Normal:
8847 splitterDistance = this.SplitContainer3.SplitterDistance;
8849 case FormWindowState.Maximized:
8850 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8851 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8852 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8853 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8859 this.mySpDis3 = splitterDistance;
8860 this.MarkSettingLocalModified();
8863 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8865 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8867 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8868 this.PublicSearchQueryMenuItem.Enabled = true;
8870 this.PublicSearchQueryMenuItem.Enabled = false;
8872 var post = this.CurrentPost;
8873 if (!this.ExistCurrentPost || post == null)
8875 this.CopySTOTMenuItem.Enabled = false;
8876 this.CopyURLMenuItem.Enabled = false;
8877 this.CopyUserIdStripMenuItem.Enabled = false;
8881 this.CopySTOTMenuItem.Enabled = true;
8882 this.CopyURLMenuItem.Enabled = true;
8883 this.CopyUserIdStripMenuItem.Enabled = true;
8885 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8886 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8890 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8891 => this.SetNotifyIconText();
8893 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8894 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8896 private async Task DoShowUserStatus(string id, bool showInputDialog)
8898 TwitterUser? user = null;
8900 if (showInputDialog)
8902 using var inputName = new InputTabName();
8903 inputName.FormTitle = "Show UserStatus";
8904 inputName.FormDescription = Properties.Resources.FRMessage1;
8905 inputName.TabName = id;
8907 if (inputName.ShowDialog(this) != DialogResult.OK)
8909 if (string.IsNullOrWhiteSpace(inputName.TabName))
8912 id = inputName.TabName.Trim();
8915 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8917 var cancellationToken = dialog.EnableCancellation();
8921 var task = this.tw.GetUserInfo(id);
8922 user = await dialog.WaitForAsync(this, task);
8924 catch (WebApiException ex)
8926 if (!cancellationToken.IsCancellationRequested)
8927 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8931 if (cancellationToken.IsCancellationRequested)
8935 await this.DoShowUserStatus(user);
8938 private async Task DoShowUserStatus(TwitterUser user)
8940 using var userDialog = new UserInfoDialog(this, this.tw.Api, this.detailsHtmlBuilder);
8941 var showUserTask = userDialog.ShowUserAsync(user);
8942 userDialog.ShowDialog(this);
8945 this.BringToFront();
8947 // ユーザー情報の表示が完了するまで userDialog を破棄しない
8951 internal Task ShowUserStatus(string id, bool showInputDialog)
8952 => this.DoShowUserStatus(id, showInputDialog);
8954 internal Task ShowUserStatus(string id)
8955 => this.DoShowUserStatus(id, true);
8957 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
8959 var post = this.CurrentPost;
8962 await this.ShowUserStatus(post.ScreenName, false);
8966 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
8968 var retweetedBy = this.CurrentPost?.RetweetedBy;
8969 if (retweetedBy != null)
8971 await this.ShowUserStatus(retweetedBy, false);
8975 private async void RtCountMenuItem_Click(object sender, EventArgs e)
8977 var post = this.CurrentPost;
8978 if (!this.ExistCurrentPost || post == null)
8981 var statusId = post.RetweetedId ?? post.StatusId;
8982 TwitterStatus status;
8984 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
8986 var cancellationToken = dialog.EnableCancellation();
8990 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
8991 status = await dialog.WaitForAsync(this, task);
8993 catch (WebApiException ex)
8995 if (!cancellationToken.IsCancellationRequested)
8996 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9000 if (cancellationToken.IsCancellationRequested)
9004 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9007 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9009 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9012 this.Visible = false;
9014 else if (Form.ActiveForm == null)
9016 this.Visible = true;
9017 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9019 this.BringToFront();
9020 this.StatusText.Focus();
9024 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9025 => this.MultiLinePullDownMenuItem.PerformClick();
9028 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9030 if (this.ImageSelector.Visible)
9031 this.ImageSelector.EndSelection();
9033 this.ImageSelector.BeginSelection();
9036 private void SelectMedia_DragEnter(DragEventArgs e)
9038 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9040 e.Effect = DragDropEffects.Copy;
9043 e.Effect = DragDropEffects.None;
9046 private void SelectMedia_DragDrop(DragEventArgs e)
9049 this.BringToFront();
9051 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9052 this.ImageSelector.BeginSelection();
9053 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9054 this.StatusText.Focus();
9057 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9059 this.TimelinePanel.Visible = false;
9060 this.TimelinePanel.Enabled = false;
9063 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9065 this.TimelinePanel.Visible = true;
9066 this.TimelinePanel.Enabled = true;
9067 this.CurrentListView.Focus();
9070 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9071 => this.AllowDrop = false;
9073 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9074 => this.AllowDrop = true;
9076 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9078 if (this.ImageSelector.Visible)
9080 this.MarkSettingCommonModified();
9081 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9085 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9086 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9089 /// StatusTextでCtrl+Vが押下された時の処理
9091 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9095 if (Clipboard.ContainsText())
9097 // clipboardにテキストがある場合は貼り付け処理
9098 this.StatusText.Paste(Clipboard.GetText());
9100 else if (Clipboard.ContainsImage())
9103 using var image = Clipboard.GetImage();
9104 this.ImageSelector.BeginSelection();
9105 this.ImageSelector.Model.AddMediaItemFromImage(image);
9107 else if (Clipboard.ContainsFileDropList())
9109 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9110 this.ImageSelector.BeginSelection();
9111 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9114 catch (ExternalException ex)
9116 MessageBox.Show(ex.Message);
9121 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9123 using var form = new ListManage(this.tw);
9124 form.ShowDialog(this);
9127 private bool ModifySettingCommon { get; set; }
9129 private bool ModifySettingLocal { get; set; }
9131 private bool ModifySettingAtId { get; set; }
9133 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9135 var post = this.CurrentPost;
9136 if (this.ExistCurrentPost && post != null && !post.IsDm)
9137 this.RtCountMenuItem.Enabled = true;
9139 this.RtCountMenuItem.Enabled = false;
9142 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9143 => this.CopyUserId();
9145 private void CopyUserId()
9147 var post = this.CurrentPost;
9148 if (post == null) return;
9149 var clstr = post.ScreenName;
9152 Clipboard.SetDataObject(clstr, false, 5, 100);
9154 catch (Exception ex)
9156 MessageBox.Show(ex.Message);
9160 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9162 var post = this.CurrentPost;
9163 if (this.ExistCurrentPost && post != null && !post.IsDm)
9167 await this.OpenRelatedTab(post);
9169 catch (TabException ex)
9171 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9177 /// 指定されたツイートに対する関連発言タブを開きます
9179 /// <param name="statusId">表示するツイートのID</param>
9180 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9181 public async Task OpenRelatedTab(PostId statusId)
9183 var post = this.statuses[statusId];
9188 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9190 catch (WebApiException ex)
9192 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9197 await this.OpenRelatedTab(post);
9201 /// 指定されたツイートに対する関連発言タブを開きます
9203 /// <param name="post">表示する対象となるツイート</param>
9204 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9205 private async Task OpenRelatedTab(PostClass post)
9207 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9208 if (tabRelated != null)
9210 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9213 var tabName = this.statuses.MakeTabName("Related Tweets");
9215 tabRelated = new RelatedPostsTabModel(tabName, post)
9217 UnreadManage = false,
9221 this.statuses.AddTab(tabRelated);
9222 this.AddNewTab(tabRelated, startup: false);
9224 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9226 await this.RefreshTabAsync(tabRelated);
9228 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9232 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9234 var tabPage = this.ListTab.TabPages[tabIndex];
9235 var listView = (DetailsListView)tabPage.Tag;
9236 var targetPost = tabRelated.TargetPost;
9237 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9239 if (index != -1 && index < listView.Items.Count)
9241 listView.SelectedIndices.Add(index);
9242 listView.Items[index].Focused = true;
9247 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9249 var buf = new StringBuilder();
9250 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9251 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9252 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9255 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9257 MyCommon.EndingFlag = true;
9261 Application.Restart();
9265 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9269 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9270 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9272 private bool ExistCurrentPost
9276 var post = this.CurrentPost;
9277 return post != null && !post.IsDeleted;
9281 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9282 => await this.ShowUserTimeline();
9284 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9285 => await this.ShowRetweeterTimeline();
9287 private string GetUserIdFromCurPostOrInput(string caption)
9289 var id = this.CurrentPost?.ScreenName ?? "";
9291 using var inputName = new InputTabName();
9292 inputName.FormTitle = caption;
9293 inputName.FormDescription = Properties.Resources.FRMessage1;
9294 inputName.TabName = id;
9296 if (inputName.ShowDialog() == DialogResult.OK &&
9297 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9299 id = inputName.TabName.Trim();
9308 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9310 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9311 if (!MyCommon.IsNullOrEmpty(id))
9313 await this.AddNewTabForUserTimeline(id);
9317 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9319 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9320 this.timelineScheduler.SystemResumed();
9323 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9325 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9327 TimeZoneInfo.ClearCachedData();
9329 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9331 if (curTimeOffset != prevTimeOffset)
9334 this.listCache?.PurgeCache();
9335 this.CurrentListView.Refresh();
9337 this.DispSelectedPost(forceupdate: true);
9340 this.timelineScheduler.Reset();
9343 private void TimelineRefreshEnableChange(bool isEnable)
9345 this.timelineScheduler.Enabled = isEnable;
9348 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9349 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9351 private async Task OpenUserAppointUrl()
9353 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9355 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9357 var post = this.CurrentPost;
9360 var xUrl = this.settings.Common.UserAppointUrl;
9361 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9363 var statusId = post.RetweetedId ?? post.StatusId;
9364 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9366 await MyCommon.OpenInBrowserAsync(this, xUrl);
9371 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9376 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9377 => await this.OpenUserAppointUrl();
9379 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9381 if (Form.ActiveForm == null)
9383 await this.InvokeAsync(() =>
9385 this.Visible = true;
9386 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9388 this.BringToFront();
9389 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9391 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9395 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9401 private void ReplaceAppName()
9403 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9404 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9407 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9408 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9410 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9412 if (e.KeyCode == Keys.Space)
9414 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9416 e.SuppressKeyPress = true;
9420 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9422 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9423 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9424 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9425 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9426 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9428 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9431 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9432 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9434 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9435 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9437 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9438 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9440 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9441 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9443 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9444 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9446 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9448 if (this.settings.Common.IconSize == iconSize) return;
9450 var oldIconCol = this.Use2ColumnsMode;
9452 this.settings.Common.IconSize = iconSize;
9453 this.ApplyListViewIconSize(iconSize);
9455 if (this.Use2ColumnsMode != oldIconCol)
9457 foreach (TabPage tp in this.ListTab.TabPages)
9459 this.ResetColumns((DetailsListView)tp.Tag);
9463 this.CurrentListView.Refresh();
9464 this.MarkSettingCommonModified();
9467 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9469 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9470 if (this.settings.Common.SortOrderLock == state) return;
9472 this.settings.Common.SortOrderLock = state;
9473 this.MarkSettingCommonModified();
9476 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9478 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9480 this.StatusLabelUrl.Text = e.StatusText;
9484 this.SetStatusLabelUrl();