1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.Thumbnail;
66 public partial class TweenMain : OTBaseForm
70 /// <summary>画面サイズ</summary>
73 /// <summary>画面位置</summary>
76 /// <summary>区切り位置</summary>
79 /// <summary>発言欄区切り位置</summary>
82 /// <summary>プレビュー区切り位置</summary>
86 private bool initial; // true:起動時処理中
87 private bool initialLayout = true;
88 private bool ignoreConfigSave; // true:起動時処理中
90 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
93 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
94 private Point tabMouseDownPoint;
96 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
97 private string? rclickTabName;
99 private readonly object syncObject = new(); // ロック用
101 private readonly DetailsHtmlBuilder detailsHtmlBuilder = new();
103 private bool myStatusError = false;
104 private bool myStatusOnline = false;
105 private bool soundfileListup = false;
106 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
109 private readonly SettingManager settings;
112 private readonly Twitter tw;
115 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
119 /// <summary>検索画面インスタンス</summary>
120 internal SearchWordDialog SearchDialog = new();
122 private readonly OpenURL urlDialog = new();
124 /// <summary>@id補助</summary>
125 public AtIdSupplement AtIdSupl = null!;
127 /// <summary>Hashtag補助</summary>
128 public AtIdSupplement HashSupl = null!;
130 public HashtagManage HashMgr = null!;
133 private ThemeManager themeManager;
135 /// <summary>アイコン画像リスト</summary>
136 private readonly ImageCache iconCache;
138 private readonly IconAssetsManager iconAssets;
140 private readonly ThumbnailGenerator thumbGenerator;
142 /// <summary>発言履歴</summary>
143 private readonly StatusTextHistory history = new();
145 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
147 /// <summary>リプライ先のステータスID・スクリーン名</summary>
148 private (PostId StatusId, string ScreenName)? inReplyTo = null;
151 private readonly List<DateTimeUtc> postTimestamps = new();
152 private readonly List<DateTimeUtc> favTimestamps = new();
155 private readonly StringFormat sfTab = new();
157 //////////////////////////////////////////////////////////////////////////////////////////////////////////
159 /// <summary>発言保持クラス</summary>
160 private readonly TabInformations statuses;
162 private TimelineListViewCache? listCache;
163 private TimelineListViewDrawer? listDrawer;
164 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
166 private bool isColumnChanged = false;
168 private const int MaxWorderThreads = 20;
169 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
170 private readonly CancellationTokenSource workerCts = new();
171 private readonly IProgress<string> workerProgress = null!;
173 private int unreadCounter = -1;
174 private int unreadAtCounter = -1;
176 private readonly string[] columnOrgText = new string[9];
177 private readonly string[] columnText = new string[9];
179 private bool doFavRetweetFlags = false;
181 //////////////////////////////////////////////////////////////////////////////////////////////////////////
183 private readonly TimelineScheduler timelineScheduler = new();
184 private readonly DebounceTimer selectionDebouncer;
185 private readonly DebounceTimer saveConfigDebouncer;
187 private readonly string recommendedStatusFooter;
189 internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
191 private bool preventSmsCommand = true;
194 private readonly record struct UrlUndo(
199 private List<UrlUndo>? urlUndoBuffer = null;
201 private readonly record struct ReplyChain(
207 /// <summary>[, ]でのリプライ移動の履歴</summary>
208 private Stack<ReplyChain>? replyChains;
210 /// <summary>ポスト選択履歴</summary>
211 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
213 public TabModel CurrentTab
214 => this.statuses.SelectedTab;
216 public string CurrentTabName
217 => this.statuses.SelectedTabName;
219 public TabPage CurrentTabPage
220 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
222 public DetailsListView CurrentListView
223 => (DetailsListView)this.CurrentTabPage.Tag;
225 public PostClass? CurrentPost
226 => this.CurrentTab.SelectedPost;
228 public bool Use2ColumnsMode
229 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
231 /// <summary>検索処理タイプ</summary>
232 internal enum SEARCHTYPE
239 private readonly HookGlobalHotkey hookGlobalHotkey;
242 SettingManager settingManager,
243 TabInformations tabInfo,
245 ImageCache imageCache,
246 IconAssetsManager iconAssets,
247 ThumbnailGenerator thumbGenerator
250 this.settings = settingManager;
251 this.statuses = tabInfo;
253 this.iconCache = imageCache;
254 this.iconAssets = iconAssets;
255 this.thumbGenerator = thumbGenerator;
257 this.InitializeComponent();
259 if (!this.DesignMode)
261 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
262 this.StatusText.Dock = DockStyle.Fill;
265 this.hookGlobalHotkey = new HookGlobalHotkey(this);
267 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
268 this.gh.NotifyClicked += this.GrowlHelper_Callback;
270 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
271 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
273 this.ImageSelector.Visible = false;
274 this.ImageSelector.Enabled = false;
275 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
277 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
279 this.ReplaceAppName();
280 this.InitializeShortcuts();
282 this.ignoreConfigSave = true;
284 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
286 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
288 Regex.CacheSize = 100;
291 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
292 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
293 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
295 // <<<<<<<<<設定関連>>>>>>>>>
299 // 現在の DPI と設定保存時の DPI との比を取得する
300 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
305 // プロキシ設定等の通信まわりの初期化が済んでから処理する
306 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
307 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
308 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
310 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
313 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
314 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
316 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
319 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
320 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
321 this.HashMgr = new HashtagManage(this.HashSupl,
322 this.settings.Common.HashTags.ToArray(),
323 this.settings.Common.HashSelected,
324 this.settings.Common.HashIsPermanent,
325 this.settings.Common.HashIsHead,
326 this.settings.Common.HashIsNotAddToAtReply);
327 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
330 this.themeManager = new(this.settings.Local);
331 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager, this.detailsHtmlBuilder);
333 // StringFormatオブジェクトへの事前設定
334 this.sfTab.Alignment = StringAlignment.Center;
335 this.sfTab.LineAlignment = StringAlignment.Center;
337 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
338 this.tweetDetailsView.ClearPostBrowser();
340 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
342 this.inReplyTo = null;
345 this.SearchDialog.Owner = this;
346 this.urlDialog.Owner = this;
349 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
350 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
352 // 新着取得時のリストスクロールをするか。trueならスクロールしない
353 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
354 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
356 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
357 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
360 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
361 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
362 this.myLoc = this.settings.Local.FormLocation;
364 if (this.WindowState != FormWindowState.Minimized)
366 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
367 var outOfScreen = true;
368 if (Screen.AllScreens.Length == 1) // ハングするとの報告
370 foreach (var scr in Screen.AllScreens)
372 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
380 this.myLoc = new Point(0, 0);
382 this.DesktopLocation = this.myLoc;
384 this.TopMost = this.settings.Common.AlwaysTop;
385 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
386 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
387 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
389 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
390 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
392 this.StatusText.Font = this.themeManager.FontInputFont;
393 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
395 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
396 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
397 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
399 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
400 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
402 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
403 if (this.settings.Common.UnreadManage == false)
405 this.ReadedStripMenuItem.Enabled = false;
406 this.UnreadStripMenuItem.Enabled = false;
409 // リンク先URL表示部の初期化(画面左下)
410 this.StatusLabelUrl.Text = "";
412 this.StatusLabel.Text = "";
413 this.StatusLabel.AutoToolTip = false;
414 this.StatusLabel.ToolTipText = "";
416 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
418 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
419 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
420 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
421 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
423 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
424 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
425 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
426 this.SplitContainer2.Panel2.AccessibleName = "";
428 ////////////////////////////////////////////////////////////////////////////////
429 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
430 var mode = this.settings.Common.SortColumn switch
432 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
433 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
434 1 => ComparerMode.Nickname, // ニックネーム
435 2 => ComparerMode.Data, // 本文
436 3 => ComparerMode.Id, // 時刻=発言Id
437 4 => ComparerMode.Name, // 名前
438 7 => ComparerMode.Source, // Source
439 _ => ComparerMode.Id,
441 this.statuses.SetSortMode(mode, sortOrder);
442 ////////////////////////////////////////////////////////////////////////////////
444 this.ApplyListViewIconSize(this.settings.Common.IconSize);
446 // <<<<<<<<タブ関連>>>>>>>
447 foreach (var tab in this.statuses.Tabs)
449 if (!this.AddNewTab(tab, startup: true))
450 throw new TabException(Properties.Resources.TweenMain_LoadText1);
453 this.ListTabSelect(this.ListTab.SelectedTab);
456 this.SetTabAlignment();
458 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
459 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
461 if (this.settings.Common.TabIconDisp)
463 this.ListTab.DrawMode = TabDrawMode.Normal;
467 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
468 this.ListTab.DrawItem += this.ListTab_DrawItem;
469 this.ListTab.ImageList = null;
472 if (this.settings.Common.HotkeyEnabled)
475 var modKey = HookGlobalHotkey.ModKeys.None;
476 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
477 modKey |= HookGlobalHotkey.ModKeys.Alt;
478 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
479 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
480 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
481 modKey |= HookGlobalHotkey.ModKeys.Shift;
482 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
483 modKey |= HookGlobalHotkey.ModKeys.Win;
485 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
488 if (this.settings.Common.IsUseNotifyGrowl)
489 this.gh.RegisterGrowl();
491 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
493 this.SetMainWindowTitle();
494 this.SetNotifyIconText();
496 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
498 this.Visible = false;
503 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
504 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
505 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
506 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
507 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
508 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
509 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
511 this.DoGetFollowersMenu(),
512 this.RefreshBlockIdsAsync(),
513 this.RefreshMuteUserIdsAsync(),
514 this.RefreshNoRetweetIdsAsync(),
515 this.RefreshTwitterConfigurationAsync(),
517 this.RefreshTimelineScheduler();
519 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
520 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
523 this.TimerRefreshIcon.Interval = 200;
524 this.TimerRefreshIcon.Enabled = false;
526 this.ignoreConfigSave = false;
527 this.ApplyLayoutFromSettings();
530 private void TweenMain_Activated(object sender, EventArgs e)
532 // 画面がアクティブになったら、発言欄の背景色戻す
533 if (this.StatusText.Focused)
535 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
539 private bool disposed = false;
542 /// 使用中のリソースをすべてクリーンアップします。
544 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
545 protected override void Dispose(bool disposing)
547 base.Dispose(disposing);
554 this.components?.Dispose();
557 this.SearchDialog.Dispose();
558 this.urlDialog.Dispose();
559 this.themeManager.Dispose();
560 this.sfTab.Dispose();
562 this.timelineScheduler.Dispose();
563 this.workerCts.Cancel();
564 this.thumbnailTokenSource?.Dispose();
566 this.hookGlobalHotkey.Dispose();
569 // 終了時にRemoveHandlerしておかないとメモリリークする
570 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
571 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
572 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
573 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
575 this.disposed = true;
578 private void InitColumns(ListView list, bool startup)
580 this.InitColumnText();
582 ColumnHeader[]? columns = null;
585 if (this.Use2ColumnsMode)
589 new ColumnHeader(), // アイコン
590 new ColumnHeader(), // 本文
593 columns[0].Text = this.columnText[0];
594 columns[1].Text = this.columnText[2];
598 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
600 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
601 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
602 columns[0].DisplayIndex = 0;
603 columns[1].DisplayIndex = 1;
608 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
610 columns[idx].Width = curListColumn.Width;
611 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
620 new ColumnHeader(), // アイコン
621 new ColumnHeader(), // ニックネーム
622 new ColumnHeader(), // 本文
623 new ColumnHeader(), // 日付
624 new ColumnHeader(), // ユーザID
625 new ColumnHeader(), // 未読
626 new ColumnHeader(), // マーク&プロテクト
627 new ColumnHeader(), // ソース
630 foreach (var i in Enumerable.Range(0, columns.Length))
631 columns[i].Text = this.columnText[i];
635 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
637 foreach (var (column, index) in columns.WithIndex())
639 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
640 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
646 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
648 columns[idx].Width = curListColumn.Width;
649 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
655 list.Columns.AddRange(columns);
663 foreach (var column in columns)
669 private void InitColumnText()
671 this.columnText[0] = "";
672 this.columnText[1] = Properties.Resources.AddNewTabText2;
673 this.columnText[2] = Properties.Resources.AddNewTabText3;
674 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
675 this.columnText[4] = Properties.Resources.AddNewTabText5;
676 this.columnText[5] = "";
677 this.columnText[6] = "";
678 this.columnText[7] = "Source";
680 this.columnOrgText[0] = "";
681 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
682 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
683 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
684 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
685 this.columnOrgText[5] = "";
686 this.columnOrgText[6] = "";
687 this.columnOrgText[7] = "Source";
689 var c = this.statuses.SortMode switch
691 ComparerMode.Nickname => 1, // ニックネーム
692 ComparerMode.Data => 2, // 本文
693 ComparerMode.Id => 3, // 時刻=発言Id
694 ComparerMode.Name => 4, // 名前
695 ComparerMode.Source => 7, // Source
699 if (this.Use2ColumnsMode)
701 if (this.statuses.SortOrder == SortOrder.Descending)
703 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
704 this.columnText[2] = this.columnOrgText[2] + "▾";
708 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
709 this.columnText[2] = this.columnOrgText[2] + "▴";
714 if (this.statuses.SortOrder == SortOrder.Descending)
716 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
717 this.columnText[c] = this.columnOrgText[c] + "▾";
721 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
722 this.columnText[c] = this.columnOrgText[c] + "▴";
727 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
732 txt = this.statuses.Tabs[e.Index].TabName;
739 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
740 if (e.State == DrawItemState.Selected)
742 e.DrawFocusRectangle();
747 if (this.statuses.Tabs[txt].UnreadCount > 0)
750 fore = System.Drawing.SystemBrushes.ControlText;
754 fore = System.Drawing.SystemBrushes.ControlText;
756 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
759 private void LoadConfig()
761 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
762 this.statuses.AddDefaultTabs();
765 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
767 this.RefreshTimelineScheduler();
770 private void RefreshTimelineScheduler()
772 static TimeSpan IntervalSecondsOrDisabled(int seconds)
773 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
775 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
776 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
777 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
778 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
779 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
780 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
781 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
782 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
784 this.timelineScheduler.RefreshSchedule();
787 private void MarkSettingCommonModified()
789 if (this.saveConfigDebouncer == null)
792 this.ModifySettingCommon = true;
793 _ = this.saveConfigDebouncer.Call();
796 private void MarkSettingLocalModified()
798 if (this.saveConfigDebouncer == null)
801 this.ModifySettingLocal = true;
802 _ = this.saveConfigDebouncer.Call();
805 internal void MarkSettingAtIdModified()
807 if (this.saveConfigDebouncer == null)
810 this.ModifySettingAtId = true;
811 _ = this.saveConfigDebouncer.Call();
814 internal void RefreshTimeline()
816 var curListView = this.CurrentListView;
818 // 現在表示中のタブのスクロール位置を退避
819 var currentListViewState = this.listViewState[this.CurrentTabName];
820 currentListViewState.Save(this.ListLockMenuItem.Checked);
824 addCount = this.statuses.SubmitUpdate(
827 out var newMentionOrDm,
830 if (MyCommon.EndingFlag) return;
833 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
835 using (ControlTransaction.Update(curListView))
837 this.listCache.PurgeCache();
838 this.listCache.UpdateListSize();
841 currentListViewState.RestoreSelection();
847 if (this.settings.Common.TabIconDisp)
849 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
851 var tabPage = this.ListTab.TabPages[index];
852 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
853 tabPage.ImageIndex = 0; // 未読アイコン
858 this.ListTab.Refresh();
863 currentListViewState.RestoreScroll();
866 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
868 this.SetMainWindowTitle();
869 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
871 this.HashSupl.AddRangeItem(this.tw.GetHashList());
874 private bool BalloonRequired()
879 if (NativeMethods.IsScreenSaverRunning())
883 if (!this.NewPostPopMenuItem.Checked)
886 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
887 if (this.settings.Common.LimitBalloon)
889 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
896 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
898 if (this.settings.Common.ReadOwnPost)
900 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
905 if (this.BalloonRequired())
907 if (notifyPosts != null && notifyPosts.Length > 0)
909 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
910 if (this.settings.Common.IsUseNotifyGrowl)
912 var sb = new StringBuilder();
916 foreach (var post in notifyPosts)
918 if (!(notifyPosts.Length > 3))
924 if (post.IsReply && !post.IsExcludeReply) reply = true;
925 if (post.IsDm) dm = true;
926 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
927 switch (this.settings.Common.NameBalloon)
929 case MyCommon.NameBalloonEnum.UserID:
930 sb.Append(post.ScreenName).Append(" : ");
932 case MyCommon.NameBalloonEnum.NickName:
933 sb.Append(post.Nickname).Append(" : ");
936 sb.Append(post.TextFromApi);
937 if (notifyPosts.Length > 3)
939 if (notifyPosts.Last() != post) continue;
942 var title = new StringBuilder();
943 GrowlHelper.NotifyType nt;
944 if (this.settings.Common.DispUsername)
946 title.Append(this.tw.Username);
952 title.Append(ApplicationSettings.ApplicationName);
953 title.Append(" [DM] ");
954 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
955 nt = GrowlHelper.NotifyType.DirectMessage;
959 title.Append(ApplicationSettings.ApplicationName);
960 title.Append(" [Reply!] ");
961 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
962 nt = GrowlHelper.NotifyType.Reply;
966 title.Append(ApplicationSettings.ApplicationName);
968 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
969 nt = GrowlHelper.NotifyType.Notify;
971 var bText = sb.ToString();
972 if (MyCommon.IsNullOrEmpty(bText)) return;
974 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
975 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
980 var sb = new StringBuilder();
983 foreach (var post in notifyPosts)
985 if (post.IsReply && !post.IsExcludeReply) reply = true;
986 if (post.IsDm) dm = true;
987 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
988 switch (this.settings.Common.NameBalloon)
990 case MyCommon.NameBalloonEnum.UserID:
991 sb.Append(post.ScreenName).Append(" : ");
993 case MyCommon.NameBalloonEnum.NickName:
994 sb.Append(post.Nickname).Append(" : ");
997 sb.Append(post.TextFromApi);
1000 var title = new StringBuilder();
1002 if (this.settings.Common.DispUsername)
1004 title.Append(this.tw.Username);
1005 title.Append(" - ");
1010 ntIcon = ToolTipIcon.Warning;
1011 title.Append(ApplicationSettings.ApplicationName);
1012 title.Append(" [DM] ");
1013 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1017 ntIcon = ToolTipIcon.Warning;
1018 title.Append(ApplicationSettings.ApplicationName);
1019 title.Append(" [Reply!] ");
1020 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1024 ntIcon = ToolTipIcon.Info;
1025 title.Append(ApplicationSettings.ApplicationName);
1027 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1029 var bText = sb.ToString();
1030 if (MyCommon.IsNullOrEmpty(bText)) return;
1032 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1033 this.NotifyIcon1.BalloonTipText = bText;
1034 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1035 this.NotifyIcon1.ShowBalloonTip(500);
1041 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1045 var dir = Application.StartupPath;
1046 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1048 dir = Path.Combine(dir, "Sounds");
1050 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1058 // mentions新着時に画面ブリンク
1059 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1061 NativeMethods.FlashMyWindow(this.Handle, 3);
1065 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1067 var listView = this.CurrentListView;
1068 if (listView != sender)
1071 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1072 this.CurrentTab.SelectPosts(indices);
1074 if (indices.Length != 1)
1077 var index = indices[0];
1078 if (index > listView.VirtualListSize - 1) return;
1080 this.PushSelectPostChain();
1082 var post = this.CurrentPost!;
1083 this.statuses.SetReadAllTab(post.StatusId, read: true);
1085 this.listCache?.RefreshStyle();
1086 await this.selectionDebouncer.Call();
1089 private void StatusTextHistoryBack()
1091 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1092 var historyItem = this.history.Back();
1093 this.inReplyTo = historyItem.InReplyTo;
1094 this.StatusText.Text = historyItem.Status;
1095 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1098 private void StatusTextHistoryForward()
1100 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1101 var historyItem = this.history.Forward();
1102 this.inReplyTo = historyItem.InReplyTo;
1103 this.StatusText.Text = historyItem.Status;
1104 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1107 private async void PostButton_Click(object sender, EventArgs e)
1109 if (this.StatusText.Text.Trim().Length == 0)
1111 if (!this.ImageSelector.Enabled)
1113 await this.DoRefresh();
1118 var currentPost = this.CurrentPost;
1119 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1121 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1123 MessageBoxButtons.YesNoCancel,
1124 MessageBoxIcon.Question);
1127 case DialogResult.Yes:
1128 this.StatusText.Text = "";
1129 await this.DoReTweetOfficial(false);
1131 case DialogResult.Cancel:
1136 if (TextContainsOnlyMentions(this.StatusText.Text))
1138 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1139 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1141 if (ret != DialogResult.OK)
1145 if (this.settings.Common.Nicoms)
1147 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1148 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1151 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1152 this.CheckReplyTo(this.StatusText.Text);
1154 var status = new PostStatusParams();
1156 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1157 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1159 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1160 // 収まる場合はこれらのオプションを使用せずに投稿する
1161 status.Text = statusTextCompat;
1162 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1166 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1167 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1169 status.AttachmentUrl = attachmentUrl;
1171 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1173 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1174 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1176 status.AutoPopulateReplyMetadata = true;
1178 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1179 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1184 if (this.GetRestStatusCount(status.Text) < 0)
1186 // 文字数制限を超えているが強制的に投稿するか
1187 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1188 if (ret != DialogResult.OK)
1192 IMediaUploadService? uploadService = null;
1193 IMediaItem[]? uploadItems = null;
1194 if (this.ImageSelector.Visible)
1197 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1200 this.ImageSelector.EndSelection();
1201 uploadService = this.ImageSelector.Model.GetService(serviceName);
1204 this.history.AddLast(this.StatusText.Text, this.inReplyTo);
1206 this.inReplyTo = null;
1207 this.StatusText.Text = "";
1208 if (!this.settings.Common.FocusLockToStatusText)
1209 this.CurrentListView.Focus();
1210 this.urlUndoBuffer = null;
1211 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1214 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1216 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1217 await MyCommon.OpenInBrowserAsync(this, tmp);
1220 await this.PostMessageAsync(status, uploadService, uploadItems);
1223 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1225 MyCommon.EndingFlag = true;
1229 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1231 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1233 // _endingFlag=false:フォームの×ボタン
1235 this.Visible = false;
1239 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1240 this.ignoreConfigSave = true;
1241 MyCommon.EndingFlag = true;
1242 this.timelineScheduler.Enabled = false;
1243 this.TimerRefreshIcon.Enabled = false;
1247 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1249 this.Visible = true;
1250 if (this.WindowState == FormWindowState.Minimized)
1252 this.WindowState = FormWindowState.Normal;
1255 this.BringToFront();
1258 private static int errorCount = 0;
1260 private static bool CheckAccountValid()
1262 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1268 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1277 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1278 private Task RefreshTabAsync<T>()
1280 => this.RefreshTabAsync<T>(backward: false);
1282 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1283 private Task RefreshTabAsync<T>(bool backward)
1287 from tab in this.statuses.GetTabsByType<T>()
1288 select this.RefreshTabAsync(tab, backward);
1290 return Task.WhenAll(loadTasks);
1293 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1294 private Task RefreshTabAsync(TabModel tab)
1295 => this.RefreshTabAsync(tab, backward: false);
1297 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1298 private async Task RefreshTabAsync(TabModel tab, bool backward)
1300 await this.workerSemaphore.WaitAsync();
1304 this.RefreshTasktrayIcon();
1305 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1307 catch (WebApiException ex)
1309 this.myStatusError = true;
1310 var tabType = tab switch
1312 HomeTabModel => "GetTimeline",
1313 MentionsTabModel => "GetTimeline",
1314 DirectMessagesTabModel => "GetDirectMessage",
1315 FavoritesTabModel => "GetFavorites",
1316 PublicSearchTabModel => "GetSearch",
1317 UserTimelineTabModel => "GetUserTimeline",
1318 ListTimelineTabModel => "GetListStatus",
1319 RelatedPostsTabModel => "GetRelatedTweets",
1320 _ => tab.GetType().Name.Replace("Model", ""),
1322 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1326 this.RefreshTimeline();
1327 this.workerSemaphore.Release();
1331 private async Task FavAddAsync(PostId statusId, TabModel tab)
1333 await this.workerSemaphore.WaitAsync();
1337 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1339 this.RefreshTasktrayIcon();
1340 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1342 catch (WebApiException ex)
1344 this.myStatusError = true;
1345 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1349 this.workerSemaphore.Release();
1353 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1355 if (ct.IsCancellationRequested)
1358 if (!CheckAccountValid())
1359 throw new WebApiException("Auth error. Check your account");
1361 if (!tab.Posts.TryGetValue(statusId, out var post))
1367 await Task.Run(async () =>
1369 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1373 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1376 await this.tw.Api.FavoritesCreate(twitterStatusId)
1378 .ConfigureAwait(false);
1380 catch (TwitterApiException ex)
1381 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1383 // エラーコード 139 のみの場合は成功と見なす
1386 if (this.settings.Common.RestrictFavCheck)
1388 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1389 .ConfigureAwait(false);
1391 if (status.Favorited != true)
1392 throw new WebApiException("NG(Restricted?)");
1395 this.favTimestamps.Add(DateTimeUtc.Now);
1398 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1400 postTl.IsFav = true;
1402 var favTab = this.statuses.FavoriteTab;
1403 favTab.AddPostQueue(postTl);
1406 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1407 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1409 if (tb.Contains(statusId))
1410 tb.Posts[statusId].IsFav = true;
1413 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1415 catch (WebApiException)
1417 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1422 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1423 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1425 if (this.favTimestamps[i] < oneHour)
1426 this.favTimestamps.RemoveAt(i);
1429 this.statuses.DistributePosts();
1432 if (ct.IsCancellationRequested)
1435 this.RefreshTimeline();
1437 if (this.CurrentTabName == tab.TabName)
1439 using (ControlTransaction.Update(this.CurrentListView))
1441 var idx = tab.IndexOf(statusId);
1443 this.listCache?.RefreshStyle(idx);
1446 var currentPost = this.CurrentPost;
1447 if (currentPost != null && statusId == currentPost.StatusId)
1448 this.DispSelectedPost(true); // 選択アイテム再表示
1452 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1454 await this.workerSemaphore.WaitAsync();
1458 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1460 this.RefreshTasktrayIcon();
1461 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1463 catch (WebApiException ex)
1465 this.myStatusError = true;
1466 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1470 this.workerSemaphore.Release();
1474 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1476 if (ct.IsCancellationRequested)
1479 if (!CheckAccountValid())
1480 throw new WebApiException("Auth error. Check your account");
1482 var successIds = new List<PostId>();
1484 await Task.Run(async () =>
1488 var failedCount = 0;
1489 foreach (var statusId in statusIds)
1493 var post = tab.Posts[statusId];
1495 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1500 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1504 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1506 .ConfigureAwait(false);
1508 catch (WebApiException)
1514 successIds.Add(statusId);
1515 post.IsFav = false; // リスト再描画必要
1517 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1518 tabinfoPost.IsFav = false;
1520 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1521 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1523 if (tb.Contains(statusId))
1524 tb.Posts[statusId].IsFav = false;
1529 if (ct.IsCancellationRequested)
1532 var favTab = this.statuses.FavoriteTab;
1533 foreach (var statusId in successIds)
1535 // ツイートが削除された訳ではないので IsDeleted はセットしない
1536 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1539 this.RefreshTimeline();
1541 if (this.CurrentTabName == tab.TabName)
1543 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1549 using (ControlTransaction.Update(this.CurrentListView))
1551 foreach (var statusId in successIds)
1553 var idx = tab.IndexOf(statusId);
1555 this.listCache?.RefreshStyle(idx);
1559 var currentPost = this.CurrentPost;
1560 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1561 this.DispSelectedPost(true); // 選択アイテム再表示
1566 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1568 await this.workerSemaphore.WaitAsync();
1572 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1574 this.RefreshTasktrayIcon();
1575 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1577 catch (WebApiException ex)
1579 this.myStatusError = true;
1580 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1584 this.workerSemaphore.Release();
1588 private async Task PostMessageAsyncInternal(
1589 IProgress<string> p,
1590 CancellationToken ct,
1591 PostStatusParams postParams,
1592 IMediaUploadService? uploadService,
1593 IMediaItem[]? uploadItems)
1595 if (ct.IsCancellationRequested)
1598 if (!CheckAccountValid())
1599 throw new WebApiException("Auth error. Check your account");
1601 p.Report("Posting...");
1603 PostClass? post = null;
1608 await Task.Run(async () =>
1610 var postParamsWithMedia = postParams;
1612 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1614 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1615 .ConfigureAwait(false);
1618 post = await this.tw.PostStatus(postParamsWithMedia)
1619 .ConfigureAwait(false);
1622 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1624 catch (WebApiException ex)
1626 // 処理は中断せずエラーの表示のみ行う
1627 errMsg = $"Err:{ex.Message}(PostMessage)";
1629 this.myStatusError = true;
1631 catch (UnauthorizedAccessException ex)
1633 // アップロード対象のファイルが開けなかった場合など
1634 errMsg = $"Err:{ex.Message}(PostMessage)";
1636 this.myStatusError = true;
1640 // 使い終わった MediaItem は破棄する
1641 if (uploadItems != null)
1643 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1645 disposableItem.Dispose();
1650 if (ct.IsCancellationRequested)
1653 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1654 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1655 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1657 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1659 var ret = MessageBox.Show(
1661 "Failed to update status",
1662 MessageBoxButtons.RetryCancel,
1663 MessageBoxIcon.Question);
1665 if (ret == DialogResult.Retry)
1667 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1671 this.StatusTextHistoryBack();
1672 this.StatusText.Focus();
1674 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1675 if (this.settings.Common.FocusLockToStatusText)
1676 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1681 this.postTimestamps.Add(DateTimeUtc.Now);
1683 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1684 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1686 if (this.postTimestamps[i] < oneHour)
1687 this.postTimestamps.RemoveAt(i);
1690 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1692 this.HashMgr.ClearHashtag();
1693 this.HashStripSplitButton.Text = "#[-]";
1694 this.HashTogglePullDownMenuItem.Checked = false;
1695 this.HashToggleMenuItem.Checked = false;
1698 this.SetMainWindowTitle();
1703 this.statuses.AddPost(post);
1704 this.statuses.DistributePosts();
1705 this.RefreshTimeline();
1708 if (this.settings.Common.PostAndGet)
1709 await this.RefreshTabAsync<HomeTabModel>();
1712 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1714 await this.workerSemaphore.WaitAsync();
1718 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1720 this.RefreshTasktrayIcon();
1721 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1723 catch (WebApiException ex)
1725 this.myStatusError = true;
1726 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1730 this.workerSemaphore.Release();
1734 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1736 if (ct.IsCancellationRequested)
1739 if (!CheckAccountValid())
1740 throw new WebApiException("Auth error. Check your account");
1743 if (!this.settings.Common.UnreadManage)
1746 read = this.initial && this.settings.Common.Read;
1748 p.Report("Posting...");
1750 var posts = new List<PostClass>();
1752 await Task.Run(async () =>
1754 foreach (var statusId in statusIds)
1756 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1757 if (post != null) posts.Add(post);
1761 if (ct.IsCancellationRequested)
1764 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1766 this.postTimestamps.Add(DateTimeUtc.Now);
1768 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1769 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1771 if (this.postTimestamps[i] < oneHour)
1772 this.postTimestamps.RemoveAt(i);
1775 // 自分のRTはTLの更新では取得できない場合があるので、
1776 // 投稿時取得の有無に関わらず追加しておく
1777 posts.ForEach(post => this.statuses.AddPost(post));
1779 if (this.settings.Common.PostAndGet)
1781 await this.RefreshTabAsync<HomeTabModel>();
1785 this.statuses.DistributePosts();
1786 this.RefreshTimeline();
1790 private async Task RefreshFollowerIdsAsync()
1792 await this.workerSemaphore.WaitAsync();
1796 this.RefreshTasktrayIcon();
1797 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1799 await this.tw.RefreshFollowerIds();
1801 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1803 this.RefreshTimeline();
1804 this.listCache?.PurgeCache();
1805 this.CurrentListView.Refresh();
1807 catch (WebApiException ex)
1809 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1813 this.workerSemaphore.Release();
1817 private async Task RefreshNoRetweetIdsAsync()
1819 await this.workerSemaphore.WaitAsync();
1823 this.RefreshTasktrayIcon();
1824 await this.tw.RefreshNoRetweetIds();
1826 this.StatusLabel.Text = "NoRetweetIds refreshed";
1828 catch (WebApiException ex)
1830 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1834 this.workerSemaphore.Release();
1838 private async Task RefreshBlockIdsAsync()
1840 await this.workerSemaphore.WaitAsync();
1844 this.RefreshTasktrayIcon();
1845 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1847 await this.tw.RefreshBlockIds();
1849 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1851 catch (WebApiException ex)
1853 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1857 this.workerSemaphore.Release();
1861 private async Task RefreshTwitterConfigurationAsync()
1863 await this.workerSemaphore.WaitAsync();
1867 this.RefreshTasktrayIcon();
1868 await this.tw.RefreshConfiguration();
1870 if (this.tw.Configuration.PhotoSizeLimit != 0)
1872 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1874 service.UpdateTwitterConfiguration(this.tw.Configuration);
1878 this.listCache?.PurgeCache();
1879 this.CurrentListView.Refresh();
1881 catch (WebApiException ex)
1883 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1887 this.workerSemaphore.Release();
1891 private async Task RefreshMuteUserIdsAsync()
1893 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1897 await this.tw.RefreshMuteUserIdsAsync();
1899 catch (WebApiException ex)
1901 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1905 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1908 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1910 if (e.Button == MouseButtons.Left)
1912 this.Visible = true;
1913 if (this.WindowState == FormWindowState.Minimized)
1915 this.WindowState = this.formWindowState;
1918 this.BringToFront();
1922 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1923 => await this.ListItemDoubleClickAction();
1925 private async Task ListItemDoubleClickAction()
1927 switch (this.settings.Common.ListDoubleClickAction)
1929 case MyCommon.ListItemDoubleClickActionType.Reply:
1930 this.MakeReplyText();
1932 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1933 this.MakeReplyText(atAll: true);
1935 case MyCommon.ListItemDoubleClickActionType.Favorite:
1936 await this.FavoriteChange(true);
1938 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1939 var post = this.CurrentPost;
1941 await this.ShowUserStatus(post.ScreenName, false);
1943 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
1944 await this.ShowUserTimeline();
1946 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
1947 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
1949 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
1950 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
1952 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
1953 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
1955 case MyCommon.ListItemDoubleClickActionType.None:
1962 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
1963 => await this.FavoriteChange(true);
1965 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
1966 => await this.FavoriteChange(false);
1968 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
1969 => await this.FavoritesRetweetOfficial();
1971 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
1972 => await this.FavoritesRetweetUnofficial();
1974 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
1976 var tab = this.CurrentTab;
1977 var posts = tab.SelectedPosts;
1979 // trueでFavAdd,falseでFavRemove
1980 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
1981 || !this.ExistCurrentPost) return;
1983 if (posts.Length > 1)
1988 // https://support.twitter.com/articles/76915#favoriting
1989 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
1990 this.doFavRetweetFlags = false;
1995 if (multiFavoriteChangeDialogEnable)
1997 var confirm = MessageBox.Show(
1998 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
1999 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2000 MessageBoxButtons.OKCancel,
2001 MessageBoxIcon.Question);
2003 if (confirm == DialogResult.Cancel)
2011 var selectedPost = posts.Single();
2012 if (selectedPost.IsFav)
2014 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2018 await this.FavAddAsync(selectedPost.StatusId, tab);
2022 var selectedPosts = posts.Where(x => x.IsFav);
2023 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2024 if (statusIds.Length == 0)
2026 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2030 await this.FavRemoveAsync(statusIds, tab);
2034 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2036 var post = this.CurrentPost;
2038 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2040 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2043 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2045 if ((!this.initialLayout) && this.Visible)
2047 if (this.WindowState == FormWindowState.Normal)
2049 this.mySize = this.ClientSize;
2050 this.mySpDis = this.SplitContainer1.SplitterDistance;
2051 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2052 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2053 this.MarkSettingLocalModified();
2058 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2060 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2061 if (comparerMode == null)
2064 this.SetSortColumn(comparerMode.Value);
2068 /// 列インデックスからソートを行う ComparerMode を求める
2070 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2071 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2072 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2074 if (this.Use2ColumnsMode)
2075 return ComparerMode.Id;
2077 return columnIndex switch
2079 1 => ComparerMode.Nickname, // ニックネーム
2080 2 => ComparerMode.Data, // 本文
2081 3 => ComparerMode.Id, // 時刻=発言Id
2082 4 => ComparerMode.Name, // 名前
2083 7 => ComparerMode.Source, // Source
2084 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2089 /// 発言一覧の指定した位置の列でソートする
2091 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2092 private void SetSortColumnByDisplayIndex(int columnIndex)
2094 // 表示上の列の位置から ColumnHeader を求める
2095 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2096 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2101 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2102 if (comparerMode == null)
2105 this.SetSortColumn(comparerMode.Value);
2109 /// 発言一覧の最後列の項目でソートする
2111 private void SetSortLastColumn()
2113 // 表示上の最後列にある ColumnHeader を求める
2114 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2115 .OrderByDescending(x => x.DisplayIndex)
2118 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2119 if (comparerMode == null)
2122 this.SetSortColumn(comparerMode.Value);
2126 /// 発言一覧を指定された ComparerMode に基づいてソートする
2128 private void SetSortColumn(ComparerMode sortColumn)
2130 if (this.settings.Common.SortOrderLock)
2133 this.statuses.ToggleSortOrder(sortColumn);
2134 this.InitColumnText();
2136 var list = this.CurrentListView;
2137 if (this.Use2ColumnsMode)
2139 list.Columns[0].Text = this.columnText[0];
2140 list.Columns[1].Text = this.columnText[2];
2144 for (var i = 0; i <= 7; i++)
2146 list.Columns[i].Text = this.columnText[i];
2150 this.listCache?.PurgeCache();
2152 var tab = this.CurrentTab;
2153 var post = this.CurrentPost;
2154 if (tab.AllCount > 0 && post != null)
2156 var idx = tab.IndexOf(post.StatusId);
2159 this.SelectListItem(list, idx);
2160 list.EnsureVisible(idx);
2165 this.MarkSettingCommonModified();
2168 private void TweenMain_LocationChanged(object sender, EventArgs e)
2170 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2172 this.myLoc = this.DesktopLocation;
2173 this.MarkSettingLocalModified();
2177 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2179 var post = this.CurrentPost;
2180 if (!this.ExistCurrentPost)
2182 this.ReplyStripMenuItem.Enabled = false;
2183 this.ReplyAllStripMenuItem.Enabled = false;
2184 this.DMStripMenuItem.Enabled = false;
2185 this.TabMenuItem.Enabled = false;
2186 this.IDRuleMenuItem.Enabled = false;
2187 this.SourceRuleMenuItem.Enabled = false;
2188 this.ReadedStripMenuItem.Enabled = false;
2189 this.UnreadStripMenuItem.Enabled = false;
2190 this.AuthorContextMenuItem.Visible = false;
2191 this.RetweetedByContextMenuItem.Visible = false;
2195 this.ReplyStripMenuItem.Enabled = true;
2196 this.ReplyAllStripMenuItem.Enabled = true;
2197 this.DMStripMenuItem.Enabled = true;
2198 this.TabMenuItem.Enabled = true;
2199 this.IDRuleMenuItem.Enabled = true;
2200 this.SourceRuleMenuItem.Enabled = true;
2201 this.ReadedStripMenuItem.Enabled = true;
2202 this.UnreadStripMenuItem.Enabled = true;
2203 this.AuthorContextMenuItem.Visible = true;
2204 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2205 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2206 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2208 var tab = this.CurrentTab;
2209 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2211 this.FavAddToolStripMenuItem.Enabled = false;
2212 this.FavRemoveToolStripMenuItem.Enabled = false;
2213 this.StatusOpenMenuItem.Enabled = false;
2214 this.ShowRelatedStatusesMenuItem.Enabled = false;
2216 this.ReTweetStripMenuItem.Enabled = false;
2217 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2218 this.QuoteStripMenuItem.Enabled = false;
2219 this.FavoriteRetweetContextMenu.Enabled = false;
2220 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2224 this.FavAddToolStripMenuItem.Enabled = true;
2225 this.FavRemoveToolStripMenuItem.Enabled = true;
2226 this.StatusOpenMenuItem.Enabled = true;
2227 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2229 if (!post.CanRetweetBy(this.tw.UserId))
2231 this.ReTweetStripMenuItem.Enabled = false;
2232 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2233 this.QuoteStripMenuItem.Enabled = false;
2234 this.FavoriteRetweetContextMenu.Enabled = false;
2235 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2239 this.ReTweetStripMenuItem.Enabled = true;
2240 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2241 this.QuoteStripMenuItem.Enabled = true;
2242 this.FavoriteRetweetContextMenu.Enabled = true;
2243 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2247 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2249 this.RepliedStatusOpenMenuItem.Enabled = false;
2253 this.RepliedStatusOpenMenuItem.Enabled = true;
2256 if (this.ExistCurrentPost && post != null)
2258 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2259 if (post.RetweetedByUserId == this.tw.UserId)
2260 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2262 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2266 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2267 => this.MakeReplyText();
2269 private void DMStripMenuItem_Click(object sender, EventArgs e)
2270 => this.MakeDirectMessageText();
2272 private async Task DoStatusDelete()
2274 var posts = this.CurrentTab.SelectedPosts;
2275 if (posts.Length == 0)
2278 // 選択されたツイートの中に削除可能なものが一つでもあるか
2279 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2282 var ret = MessageBox.Show(
2284 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2285 Properties.Resources.DeleteStripMenuItem_ClickText2,
2286 MessageBoxButtons.OKCancel,
2287 MessageBoxIcon.Question);
2289 if (ret != DialogResult.OK)
2292 var currentListView = this.CurrentListView;
2293 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2295 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2297 Exception? lastException = null;
2298 foreach (var post in posts)
2300 if (!post.CanDeleteBy(this.tw.UserId))
2305 if (post.StatusId is TwitterDirectMessageId dmId)
2307 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2311 if (post.RetweetedByUserId == this.tw.UserId)
2313 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2315 await this.tw.DeleteRetweet(post);
2319 if (post.UserId == this.tw.UserId)
2321 if (post.RetweetedId != null)
2323 // 他人に RT された自分のツイート
2324 // => RT 元の自分のツイートを削除
2325 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2331 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2337 catch (WebApiException ex)
2343 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2346 if (lastException == null)
2347 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2349 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2351 using (ControlTransaction.Update(currentListView))
2353 this.listCache?.PurgeCache();
2354 this.listCache?.UpdateListSize();
2356 currentListView.SelectedIndices.Clear();
2358 var currentTab = this.CurrentTab;
2359 if (currentTab.AllCount != 0)
2362 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2363 selectedIndex = focusedIndex;
2365 selectedIndex = currentTab.AllCount - 1;
2367 currentListView.SelectedIndices.Add(selectedIndex);
2368 currentListView.EnsureVisible(selectedIndex);
2369 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2373 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2375 var tabPage = this.ListTab.TabPages[index];
2376 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2378 if (tabPage.ImageIndex == 0)
2379 tabPage.ImageIndex = -1; // タブアイコン
2383 if (!this.settings.Common.TabIconDisp)
2384 this.ListTab.Refresh();
2388 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2389 => await this.DoStatusDelete();
2391 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2393 using (ControlTransaction.Update(this.CurrentListView))
2395 var tab = this.CurrentTab;
2396 foreach (var statusId in tab.SelectedStatusIds)
2398 this.statuses.SetReadAllTab(statusId, read: true);
2399 var idx = tab.IndexOf(statusId);
2400 this.listCache?.RefreshStyle(idx);
2403 if (this.settings.Common.TabIconDisp)
2405 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2407 if (tab.UnreadCount == 0)
2409 var tabPage = this.ListTab.TabPages[index];
2410 if (tabPage.ImageIndex == 0)
2411 tabPage.ImageIndex = -1; // タブアイコン
2415 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2418 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2420 using (ControlTransaction.Update(this.CurrentListView))
2422 var tab = this.CurrentTab;
2423 foreach (var statusId in tab.SelectedStatusIds)
2425 this.statuses.SetReadAllTab(statusId, read: false);
2426 var idx = tab.IndexOf(statusId);
2427 this.listCache?.RefreshStyle(idx);
2430 if (this.settings.Common.TabIconDisp)
2432 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2434 if (tab.UnreadCount > 0)
2436 var tabPage = this.ListTab.TabPages[index];
2437 if (tabPage.ImageIndex == -1)
2438 tabPage.ImageIndex = 0; // タブアイコン
2442 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2445 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2446 => await this.DoRefresh();
2448 private async Task DoRefresh()
2449 => await this.RefreshTabAsync(this.CurrentTab);
2451 private async Task DoRefreshMore()
2452 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2454 private DialogResult ShowSettingDialog()
2456 using var settingDialog = new AppendSettingDialog();
2457 settingDialog.Icon = this.iconAssets.IconMain;
2458 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2460 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2462 DialogResult result;
2465 result = settingDialog.ShowDialog(this);
2469 return DialogResult.Abort;
2472 if (result == DialogResult.OK)
2474 lock (this.syncObject)
2476 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2483 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2486 var previousUserId = this.settings.Common.UserId;
2487 var oldIconCol = this.Use2ColumnsMode;
2489 if (this.ShowSettingDialog() == DialogResult.OK)
2491 lock (this.syncObject)
2493 this.settings.ApplySettings();
2495 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2496 this.tw.ClearAuthInfo();
2498 var account = this.settings.Common.SelectedAccount;
2499 if (account != null)
2500 this.tw.Initialize(account.GetTwitterCredential(), account.Username, account.UserId);
2502 this.tw.Initialize(new TwitterCredentialNone(), "", 0L);
2504 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2505 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2507 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2511 if (this.settings.Common.TabIconDisp)
2513 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2514 this.ListTab.DrawMode = TabDrawMode.Normal;
2515 this.ListTab.ImageList = this.TabImage;
2519 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2520 this.ListTab.DrawItem += this.ListTab_DrawItem;
2521 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2522 this.ListTab.ImageList = null;
2525 catch (Exception ex)
2527 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2528 ex.Data["IsTerminatePermission"] = false;
2534 if (!this.settings.Common.UnreadManage)
2536 this.ReadedStripMenuItem.Enabled = false;
2537 this.UnreadStripMenuItem.Enabled = false;
2538 if (this.settings.Common.TabIconDisp)
2540 foreach (TabPage myTab in this.ListTab.TabPages)
2542 myTab.ImageIndex = -1;
2548 this.ReadedStripMenuItem.Enabled = true;
2549 this.UnreadStripMenuItem.Enabled = true;
2552 catch (Exception ex)
2554 ex.Data["Instance"] = "ListTab(UnreadManage)";
2555 ex.Data["IsTerminatePermission"] = false;
2560 this.SetTabAlignment();
2562 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2564 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2565 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2566 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2568 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2569 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2570 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2571 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2573 var newTheme = new ThemeManager(this.settings.Local);
2574 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2575 this.tweetDetailsView.Theme = this.themeManager;
2576 if (this.listDrawer != null)
2577 this.listDrawer.Theme = this.themeManager;
2582 if (this.StatusText.Focused)
2583 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2585 this.StatusText.Font = this.themeManager.FontInputFont;
2586 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2588 catch (Exception ex)
2590 MessageBox.Show(ex.Message);
2595 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
2597 catch (Exception ex)
2599 ex.Data["Instance"] = "Font";
2600 ex.Data["IsTerminatePermission"] = false;
2606 if (this.settings.Common.TabIconDisp)
2608 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2610 var tabPage = this.ListTab.TabPages[index];
2611 if (tab.UnreadCount == 0)
2612 tabPage.ImageIndex = -1;
2614 tabPage.ImageIndex = 0;
2618 catch (Exception ex)
2620 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2621 ex.Data["IsTerminatePermission"] = false;
2627 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2629 foreach (TabPage tp in this.ListTab.TabPages)
2631 var lst = (DetailsListView)tp.Tag;
2633 using (ControlTransaction.Update(lst))
2635 lst.GridLines = this.settings.Common.ShowGrid;
2637 if (this.Use2ColumnsMode != oldIconCol)
2638 this.ResetColumns(lst);
2642 catch (Exception ex)
2644 ex.Data["Instance"] = "ListView(IconSize)";
2645 ex.Data["IsTerminatePermission"] = false;
2649 this.SetMainWindowTitle();
2650 this.SetNotifyIconText();
2652 this.listCache?.PurgeCache();
2653 this.CurrentListView.Refresh();
2654 this.ListTab.Refresh();
2656 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2657 if (this.settings.Common.HotkeyEnabled)
2659 // グローバルホットキーの登録。設定で変更可能にするかも
2660 var modKey = HookGlobalHotkey.ModKeys.None;
2661 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2662 modKey |= HookGlobalHotkey.ModKeys.Alt;
2663 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2664 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2665 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2666 modKey |= HookGlobalHotkey.ModKeys.Shift;
2667 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2668 modKey |= HookGlobalHotkey.ModKeys.Win;
2670 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2673 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2676 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2684 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2686 this.TopMost = this.settings.Common.AlwaysTop;
2687 this.SaveConfigsAll(false);
2689 if (this.tw.UserId != previousUserId)
2690 await this.DoGetFollowersMenu();
2696 private void SetTabAlignment()
2698 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2699 if (this.ListTab.Alignment == newAlignment) return;
2702 var currentListViewState = this.listViewState[this.CurrentTabName];
2703 currentListViewState.Save(this.ListLockMenuItem.Checked);
2705 this.ListTab.Alignment = newAlignment;
2707 currentListViewState.Restore(forceScroll: true);
2710 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2713 if (this.listDrawer != null)
2715 this.listDrawer.IconSize = iconSz;
2716 this.listDrawer.UpdateItemHeight();
2719 this.listCache?.PurgeCache();
2722 private void ResetColumns(DetailsListView list)
2724 using (ControlTransaction.Update(list))
2725 using (ControlTransaction.Layout(list, false))
2728 list.ColumnClick -= this.MyList_ColumnClick;
2729 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2730 list.ColumnReordered -= this.MyList_ColumnReordered;
2731 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2733 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2734 list.Columns.Clear();
2735 cols.ForEach(col => col.Dispose());
2738 this.InitColumns(list, true);
2740 list.ColumnClick += this.MyList_ColumnClick;
2741 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2742 list.ColumnReordered += this.MyList_ColumnReordered;
2743 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2747 public void AddNewTabForSearch(string searchWord)
2749 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2750 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2752 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2754 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2755 this.ListTab.SelectedIndex = tabIndex;
2760 var tabName = searchWord;
2761 for (var i = 0; i <= 100; i++)
2763 if (this.statuses.ContainsTab(tabName))
2769 var tab = new PublicSearchTabModel(tabName);
2770 this.statuses.AddTab(tab);
2771 this.AddNewTab(tab, startup: false);
2773 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2775 var tabPage = this.CurrentTabPage;
2776 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2777 cmb.Items.Add(searchWord);
2778 cmb.Text = searchWord;
2779 this.SaveConfigsTabs();
2781 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2784 private async Task ShowUserTimeline()
2786 var post = this.CurrentPost;
2787 if (post == null || !this.ExistCurrentPost) return;
2788 await this.AddNewTabForUserTimeline(post.ScreenName);
2791 private async Task ShowRetweeterTimeline()
2793 var retweetedBy = this.CurrentPost?.RetweetedBy;
2794 if (retweetedBy == null || !this.ExistCurrentPost) return;
2795 await this.AddNewTabForUserTimeline(retweetedBy);
2798 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2800 if (e.KeyCode == Keys.Escape)
2802 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2803 this.SaveConfigsTabs();
2804 e.SuppressKeyPress = true;
2808 public async Task AddNewTabForUserTimeline(string user)
2810 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2811 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2813 if (tb.ScreenName == user)
2815 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2816 this.ListTab.SelectedIndex = tabIndex;
2821 var tabName = "user:" + user;
2822 while (this.statuses.ContainsTab(tabName))
2827 var tab = new UserTimelineTabModel(tabName, user);
2828 this.statuses.AddTab(tab);
2829 this.AddNewTab(tab, startup: false);
2831 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2832 this.SaveConfigsTabs();
2834 await this.RefreshTabAsync(tab);
2837 public bool AddNewTab(TabModel tab, bool startup)
2840 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2844 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2846 var tabPage = new TabPage();
2847 var listCustom = new DetailsListView();
2849 var cnt = this.statuses.Tabs.Count;
2851 // ToDo:Create and set controls follow tabtypes
2853 using (ControlTransaction.Update(listCustom))
2854 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2855 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2856 using (ControlTransaction.Layout(this.SplitContainer1, false))
2857 using (ControlTransaction.Layout(this.ListTab, false))
2858 using (ControlTransaction.Layout(this))
2859 using (ControlTransaction.Layout(tabPage, false))
2861 tabPage.Controls.Add(listCustom);
2864 var userTab = tab as UserTimelineTabModel;
2865 var listTab = tab as ListTimelineTabModel;
2866 var searchTab = tab as PublicSearchTabModel;
2868 if (userTab != null || listTab != null)
2870 var label = new Label
2872 Dock = DockStyle.Top,
2877 if (listTab != null)
2879 label.Text = listTab.ListInfo.ToString();
2881 else if (userTab != null)
2883 label.Text = userTab.ScreenName + "'s Timeline";
2885 label.TextAlign = ContentAlignment.MiddleLeft;
2886 using (var tmpComboBox = new ComboBox())
2888 label.Height = tmpComboBox.Height;
2890 tabPage.Controls.Add(label);
2893 else if (searchTab != null)
2895 var pnl = new Panel();
2897 var lbl = new Label();
2898 var cmb = new ComboBox();
2899 var btn = new Button();
2900 var cmbLang = new ComboBox();
2902 using (ControlTransaction.Layout(pnl, false))
2904 pnl.Controls.Add(cmb);
2905 pnl.Controls.Add(cmbLang);
2906 pnl.Controls.Add(btn);
2907 pnl.Controls.Add(lbl);
2908 pnl.Name = "panelSearch";
2910 pnl.Dock = DockStyle.Top;
2911 pnl.Height = cmb.Height;
2912 pnl.Enter += this.SearchControls_Enter;
2913 pnl.Leave += this.SearchControls_Leave;
2916 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2917 cmb.Dock = DockStyle.Fill;
2918 cmb.Name = "comboSearch";
2919 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2920 cmb.ImeMode = ImeMode.NoControl;
2921 cmb.TabStop = false;
2923 cmb.AutoCompleteMode = AutoCompleteMode.None;
2924 cmb.KeyDown += this.SearchComboBox_KeyDown;
2927 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2928 cmbLang.Dock = DockStyle.Right;
2930 cmbLang.Name = "comboLang";
2931 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2932 cmbLang.TabStop = false;
2933 cmbLang.TabIndex = 2;
2934 cmbLang.Items.Add("");
2935 cmbLang.Items.Add("ja");
2936 cmbLang.Items.Add("en");
2937 cmbLang.Items.Add("ar");
2938 cmbLang.Items.Add("da");
2939 cmbLang.Items.Add("nl");
2940 cmbLang.Items.Add("fa");
2941 cmbLang.Items.Add("fi");
2942 cmbLang.Items.Add("fr");
2943 cmbLang.Items.Add("de");
2944 cmbLang.Items.Add("hu");
2945 cmbLang.Items.Add("is");
2946 cmbLang.Items.Add("it");
2947 cmbLang.Items.Add("no");
2948 cmbLang.Items.Add("pl");
2949 cmbLang.Items.Add("pt");
2950 cmbLang.Items.Add("ru");
2951 cmbLang.Items.Add("es");
2952 cmbLang.Items.Add("sv");
2953 cmbLang.Items.Add("th");
2955 lbl.Text = "Search(C-S-f)";
2956 lbl.Name = "label1";
2957 lbl.Dock = DockStyle.Left;
2959 lbl.Height = cmb.Height;
2960 lbl.TextAlign = ContentAlignment.MiddleLeft;
2963 btn.Text = "Search";
2964 btn.Name = "buttonSearch";
2965 btn.UseVisualStyleBackColor = true;
2966 btn.Dock = DockStyle.Right;
2967 btn.TabStop = false;
2969 btn.Click += this.SearchButton_Click;
2971 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
2973 cmb.Items.Add(searchTab.SearchWords);
2974 cmb.Text = searchTab.SearchWords;
2977 cmbLang.Text = searchTab.SearchLang;
2979 tabPage.Controls.Add(pnl);
2983 tabPage.Tag = listCustom;
2984 this.ListTab.Controls.Add(tabPage);
2986 tabPage.Location = new Point(4, 4);
2987 tabPage.Name = "CTab" + cnt;
2988 tabPage.Size = new Size(380, 260);
2989 tabPage.TabIndex = 2 + cnt;
2990 tabPage.Text = tab.TabName;
2991 tabPage.UseVisualStyleBackColor = true;
2992 tabPage.AccessibleRole = AccessibleRole.PageTab;
2994 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
2995 listCustom.TabIndex = 1;
2996 listCustom.AllowColumnReorder = true;
2997 listCustom.ContextMenuStrip = this.ContextMenuOperate;
2998 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
2999 listCustom.Dock = DockStyle.Fill;
3000 listCustom.FullRowSelect = true;
3001 listCustom.HideSelection = false;
3002 listCustom.Location = new Point(0, 0);
3003 listCustom.Margin = new Padding(0);
3004 listCustom.Name = "CList" + Environment.TickCount;
3005 listCustom.ShowItemToolTips = true;
3006 listCustom.Size = new Size(380, 260);
3007 listCustom.UseCompatibleStateImageBehavior = false;
3008 listCustom.View = View.Details;
3009 listCustom.OwnerDraw = true;
3010 listCustom.VirtualMode = true;
3012 listCustom.GridLines = this.settings.Common.ShowGrid;
3013 listCustom.AllowDrop = true;
3015 this.InitColumns(listCustom, startup);
3017 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3018 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3019 listCustom.ColumnClick += this.MyList_ColumnClick;
3020 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3021 listCustom.DragDrop += this.TweenMain_DragDrop;
3022 listCustom.DragEnter += this.TweenMain_DragEnter;
3023 listCustom.DragOver += this.TweenMain_DragOver;
3024 listCustom.MouseClick += this.MyList_MouseClick;
3025 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3026 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3027 listCustom.HScrolled += this.MyList_HScrolled;
3030 var state = new TimelineListViewState(listCustom, tab);
3031 this.listViewState[tab.TabName] = state;
3036 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3038 var tabInfo = this.statuses.GetTabByName(tabName);
3039 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3044 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3045 var result = MessageBox.Show(
3047 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3048 MessageBoxButtons.OKCancel,
3049 MessageBoxIcon.Question,
3050 MessageBoxDefaultButton.Button2);
3051 if (result == DialogResult.Cancel)
3057 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3061 var tabPage = this.ListTab.TabPages[tabIndex];
3063 this.SetListProperty(); // 他のタブに列幅等を反映
3065 this.listViewState.Remove(tabName);
3068 var listCustom = (DetailsListView)tabPage.Tag;
3071 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3072 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3073 using (ControlTransaction.Layout(this.SplitContainer1, false))
3074 using (ControlTransaction.Layout(this.ListTab, false))
3075 using (ControlTransaction.Layout(this))
3076 using (ControlTransaction.Layout(tabPage, false))
3078 if (this.CurrentTabName == tabName)
3080 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3081 this.beforeSelectedTab = null;
3083 this.ListTab.Controls.Remove(tabPage);
3086 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3088 using var label = tabPage.Controls["labelUser"];
3089 tabPage.Controls.Remove(label);
3091 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3093 using var pnl = tabPage.Controls["panelSearch"];
3095 pnl.Enter -= this.SearchControls_Enter;
3096 pnl.Leave -= this.SearchControls_Leave;
3097 tabPage.Controls.Remove(pnl);
3099 foreach (Control ctrl in pnl.Controls)
3101 if (ctrl.Name == "buttonSearch")
3103 ctrl.Click -= this.SearchButton_Click;
3105 else if (ctrl.Name == "comboSearch")
3107 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3109 pnl.Controls.Remove(ctrl);
3114 tabPage.Controls.Remove(listCustom);
3116 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3117 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3118 listCustom.ColumnClick -= this.MyList_ColumnClick;
3119 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3120 listCustom.DragDrop -= this.TweenMain_DragDrop;
3121 listCustom.DragEnter -= this.TweenMain_DragEnter;
3122 listCustom.DragOver -= this.TweenMain_DragOver;
3123 listCustom.MouseClick -= this.MyList_MouseClick;
3124 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3125 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3126 listCustom.HScrolled -= this.MyList_HScrolled;
3128 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3129 listCustom.Columns.Clear();
3130 cols.ForEach(col => col.Dispose());
3133 listCustom.ContextMenuStrip = null;
3134 listCustom.ColumnHeaderContextMenuStrip = null;
3135 listCustom.Font = null;
3137 listCustom.SmallImageList = null;
3138 listCustom.ListViewItemSorter = null;
3141 this.listCache?.PurgeCache();
3145 listCustom.Dispose();
3146 this.statuses.RemoveTab(tabName);
3151 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3153 this.listCache?.PurgeCache();
3154 this.beforeSelectedTab = e.TabPage;
3157 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3161 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3164 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3165 if (!dragEnableRectangle.Contains(e.Location))
3167 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3168 tn = this.CurrentTabName;
3171 if (MyCommon.IsNullOrEmpty(tn)) return;
3173 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3176 var tabPage = this.ListTab.TabPages[tabIndex];
3177 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3182 this.tabDrag = false;
3185 var cpos = new Point(e.X, e.Y);
3186 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3188 var rect = this.ListTab.GetTabRect(index);
3189 if (rect.Contains(cpos))
3191 this.rclickTabName = tab.TabName;
3197 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3199 this.SetMainWindowTitle();
3200 this.SetStatusLabelUrl();
3201 this.SetApiStatusLabel();
3202 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3203 this.Tag = this.ListTab.Tag;
3204 this.TabMenuControl(this.CurrentTabName);
3205 this.PushSelectPostChain();
3206 this.DispSelectedPost();
3209 private void SetListProperty()
3211 if (!this.isColumnChanged) return;
3213 var currentListView = this.CurrentListView;
3215 var dispOrder = new int[currentListView.Columns.Count];
3216 for (var i = 0; i < currentListView.Columns.Count; i++)
3218 for (var j = 0; j < currentListView.Columns.Count; j++)
3220 if (currentListView.Columns[j].DisplayIndex == i)
3229 foreach (TabPage tb in this.ListTab.TabPages)
3231 if (tb.Text == this.CurrentTabName)
3234 if (tb.Tag != null && tb.Controls.Count > 0)
3236 var lst = (DetailsListView)tb.Tag;
3237 for (var i = 0; i < lst.Columns.Count; i++)
3239 lst.Columns[dispOrder[i]].DisplayIndex = i;
3240 lst.Columns[i].Width = currentListView.Columns[i].Width;
3245 this.isColumnChanged = false;
3248 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3250 if (e.KeyChar == '@')
3252 if (!this.settings.Common.UseAtIdSupplement) return;
3254 var cnt = this.AtIdSupl.ItemCount;
3255 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3256 if (cnt != this.AtIdSupl.ItemCount)
3257 this.MarkSettingAtIdModified();
3260 else if (e.KeyChar == '#')
3262 if (!this.settings.Common.UseHashSupplement) return;
3263 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3268 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3269 => this.ShowSuplDialog(owner, dialog, 0, "");
3271 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3272 => this.ShowSuplDialog(owner, dialog, offset, "");
3274 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3276 dialog.StartsWith = startswith;
3283 dialog.ShowDialog();
3285 this.TopMost = this.settings.Common.AlwaysTop;
3286 var selStart = owner.SelectionStart;
3289 if (dialog.DialogResult == DialogResult.OK)
3291 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3295 fHalf = owner.Text.Substring(0, selStart - offset);
3297 if (selStart < owner.Text.Length)
3299 eHalf = owner.Text.Substring(selStart);
3301 owner.Text = fHalf + dialog.InputText + eHalf;
3302 owner.SelectionStart = selStart + dialog.InputText.Length;
3309 fHalf = owner.Text.Substring(0, selStart);
3311 if (selStart < owner.Text.Length)
3313 eHalf = owner.Text.Substring(selStart);
3315 owner.Text = fHalf + eHalf;
3318 owner.SelectionStart = selStart;
3324 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3327 if (!e.Alt && !e.Control && !e.Shift)
3329 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3331 var isSpace = false;
3332 foreach (var c in this.StatusText.Text)
3334 if (c == ' ' || c == ' ')
3347 this.StatusText.Text = "";
3348 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3352 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3355 private void StatusText_TextChanged(object sender, EventArgs e)
3358 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3359 this.lblLen.Text = pLen.ToString();
3362 this.StatusText.ForeColor = Color.Red;
3366 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3369 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3371 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3373 this.inReplyTo = null;
3378 /// メンション以外の文字列が含まれていないテキストであるか判定します
3380 internal static bool TextContainsOnlyMentions(string text)
3382 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3385 foreach (var mention in mentions)
3387 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3389 if (!string.IsNullOrWhiteSpace(textPart))
3392 startIndex = mention.Indices[1];
3395 var textPartLast = text.Substring(startIndex);
3397 if (!string.IsNullOrWhiteSpace(textPartLast))
3404 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3406 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3408 var autoPopulatedUserIdList = new List<long>();
3410 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3411 if (replyToPost != null)
3413 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3415 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3416 autoPopulatedUserIdList.Add(replyToPost.UserId);
3418 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3420 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3422 statusText = statusText.Substring(screenName.Length + 2);
3423 autoPopulatedUserIdList.Add(userId);
3429 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3435 /// attachment_url に指定可能な URL が含まれていれば除去
3437 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3439 attachmentUrl = null;
3441 // attachment_url は media_id と同時に使用できない
3442 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3445 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3449 attachmentUrl = match.Value;
3452 statusText = statusText.Substring(0, match.Index);
3454 // テキストと URL の間にスペースが含まれていれば除去
3455 return statusText.TrimEnd(' ');
3458 private string FormatStatusTextExtended(string statusText)
3459 => this.FormatStatusTextExtended(statusText, out _, out _);
3462 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3464 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3466 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3468 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3470 return this.FormatStatusText(statusText);
3473 internal string FormatStatusText(string statusText)
3474 => this.FormatStatusText(statusText, Control.ModifierKeys);
3477 /// ツイート投稿前のフッター付与などの前処理を行います
3479 internal string FormatStatusText(string statusText, Keys modifierKeys)
3481 statusText = statusText.Replace("\r\n", "\n");
3483 if (this.SeparateUrlAndFullwidthCharacter)
3486 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3489 if (this.settings.Common.WideSpaceConvert)
3491 // 文中の全角スペースを半角スペース1個にする
3492 statusText = statusText.Replace(" ", " ");
3495 // DM の場合はこれ以降の処理を行わない
3496 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3500 if (this.settings.Common.PostShiftEnter)
3502 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3506 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3507 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3509 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3512 if (statusText.Contains("RT @"))
3513 disableFooter = true;
3515 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3516 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3518 var mentionSelf = $"@{this.tw.Username} ";
3519 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3521 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3522 statusText = statusText.Substring(mentionSelf.Length);
3529 var hashtag = this.HashMgr.UseHash;
3530 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3532 if (this.HashMgr.IsHead)
3533 header = this.HashMgr.UseHash + " ";
3535 footer = " " + this.HashMgr.UseHash;
3540 if (this.settings.Local.UseRecommendStatus)
3543 footer += this.recommendedStatusFooter;
3545 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3547 // テキストボックスに入力されている文字列を使用する
3548 footer += " " + this.settings.Local.StatusText.Trim();
3552 statusText = header + statusText + footer;
3554 if (this.preventSmsCommand)
3556 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3557 // 参照: https://support.twitter.com/articles/14020
3559 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3560 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3562 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3563 statusText = '\u200b' + statusText;
3571 /// 投稿欄に表示する入力可能な文字数を計算します
3573 private int GetRestStatusCount(string statusText)
3575 var remainCount = this.tw.GetTextLengthRemain(statusText);
3577 var uploadService = this.GetSelectedImageService();
3578 if (uploadService != null)
3580 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3581 remainCount -= uploadService.GetReservedTextLength(1);
3587 private IMediaUploadService? GetSelectedImageService()
3588 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3591 /// 全てのタブの振り分けルールを反映し直します
3593 private void ApplyPostFilters()
3595 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3597 this.statuses.FilterAll();
3599 var listView = this.CurrentListView;
3600 using (ControlTransaction.Update(listView))
3602 this.listCache?.PurgeCache();
3603 this.listCache?.UpdateListSize();
3606 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3608 var tabPage = this.ListTab.TabPages[index];
3610 if (this.settings.Common.TabIconDisp)
3612 if (tab.UnreadCount > 0)
3613 tabPage.ImageIndex = 0;
3615 tabPage.ImageIndex = -1;
3619 if (!this.settings.Common.TabIconDisp)
3620 this.ListTab.Refresh();
3622 this.SetMainWindowTitle();
3623 this.SetStatusLabelUrl();
3627 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3628 => e.DrawDefault = true;
3630 private void MyList_HScrolled(object sender, EventArgs e)
3631 => ((DetailsListView)sender).Refresh();
3633 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3635 base.ScaleControl(factor, specified);
3637 ScaleChildControl(this.TabImage, factor);
3639 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3640 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3642 foreach (var listview in listviews)
3644 ScaleChildControl(listview, factor);
3648 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3650 var tab = this.CurrentTab;
3652 if (tab.AllCount == 0)
3654 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3658 var selectedIndex = tab.SelectedIndex;
3663 case SEARCHTYPE.NextSearch: // 次を検索
3664 if (selectedIndex != -1)
3665 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3669 case SEARCHTYPE.PrevSearch: // 前を検索
3670 if (selectedIndex != -1)
3671 startIndex = Math.Max(selectedIndex - 1, 0);
3673 startIndex = tab.AllCount - 1;
3675 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3677 if (selectedIndex != -1)
3678 startIndex = selectedIndex;
3684 Func<string, bool> stringComparer;
3687 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3689 catch (ArgumentException)
3691 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3695 var reverse = searchType == SEARCHTYPE.PrevSearch;
3696 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3697 .DefaultIfEmpty(-1).First();
3699 if (foundIndex == -1)
3701 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3705 var listView = this.CurrentListView;
3706 this.SelectListItem(listView, foundIndex);
3707 listView.EnsureVisible(foundIndex);
3710 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3711 => this.ShowSearchDialog(); // 検索メニュー
3713 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3715 var previousSearch = this.SearchDialog.ResultOptions;
3716 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3718 this.SearchDialog.Reset();
3719 this.ShowSearchDialog();
3725 previousSearch.Query,
3726 previousSearch.CaseSensitive,
3727 previousSearch.UseRegex,
3728 SEARCHTYPE.NextSearch);
3731 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3733 var previousSearch = this.SearchDialog.ResultOptions;
3734 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3736 this.SearchDialog.Reset();
3737 this.ShowSearchDialog();
3743 previousSearch.Query,
3744 previousSearch.CaseSensitive,
3745 previousSearch.UseRegex,
3746 SEARCHTYPE.PrevSearch);
3750 /// 検索ダイアログを表示し、検索を実行します
3752 private void ShowSearchDialog()
3754 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3756 this.TopMost = this.settings.Common.AlwaysTop;
3759 this.TopMost = this.settings.Common.AlwaysTop;
3761 var searchOptions = this.SearchDialog.ResultOptions!;
3762 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3764 if (searchOptions.NewTab)
3766 var tabName = Properties.Resources.SearchResults_TabName;
3770 tabName = this.statuses.MakeTabName(tabName);
3772 catch (TabException ex)
3774 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3777 var resultTab = new LocalSearchTabModel(tabName);
3778 this.AddNewTab(resultTab, startup: false);
3779 this.statuses.AddTab(resultTab);
3781 var targetTab = this.CurrentTab;
3783 Func<string, bool> stringComparer;
3786 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3788 catch (ArgumentException)
3790 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3794 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3795 if (foundIndices.Length == 0)
3797 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3801 var foundPosts = foundIndices.Select(x => targetTab[x]);
3802 foreach (var post in foundPosts)
3804 resultTab.AddPostQueue(post);
3807 this.statuses.DistributePosts();
3808 this.RefreshTimeline();
3810 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3811 this.ListTab.SelectedIndex = tabIndex;
3816 searchOptions.Query,
3817 searchOptions.CaseSensitive,
3818 searchOptions.UseRegex,
3819 SEARCHTYPE.DialogSearch);
3822 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3824 this.AddNewTabForSearch(searchOptions.Query);
3828 /// <summary>発言検索に使用するメソッドを生成します</summary>
3829 /// <exception cref="ArgumentException">
3830 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3832 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3836 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3837 var regex = new Regex(query, regexOption);
3839 return x => regex.IsMatch(x);
3843 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3845 return x => x.IndexOf(query, comparisonType) != -1;
3849 private void AboutMenuItem_Click(object sender, EventArgs e)
3851 using (var about = new TweenAboutBox())
3853 about.ShowDialog(this);
3855 this.TopMost = this.settings.Common.AlwaysTop;
3858 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3860 var bgnIdx = this.statuses.SelectedTabIndex;
3862 if (this.ImageSelector.Enabled)
3865 TabModel? foundTab = null;
3869 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3871 var unreadIndex = tab.NextUnreadIndex;
3872 if (unreadIndex != -1)
3874 this.ListTab.SelectedIndex = index;
3876 foundIndex = unreadIndex;
3881 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3882 if (foundTab == null && bgnIdx > 0)
3884 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3886 var unreadIndex = tab.NextUnreadIndex;
3887 if (unreadIndex != -1)
3889 this.ListTab.SelectedIndex = index;
3891 foundIndex = unreadIndex;
3897 DetailsListView lst;
3899 if (foundTab == null)
3901 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3902 this.ListTab.SelectedIndex = 0;
3903 var tabPage = this.ListTab.TabPages[0];
3904 var tab = this.statuses.Tabs[0];
3906 if (tab.AllCount == 0)
3909 if (this.statuses.SortOrder == SortOrder.Ascending)
3910 foundIndex = tab.AllCount - 1;
3914 lst = (DetailsListView)tabPage.Tag;
3918 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3919 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3922 this.SelectListItem(lst, foundIndex);
3924 if (this.statuses.SortMode == ComparerMode.Id)
3926 var rowHeight = lst.SmallImageList.ImageSize.Height;
3927 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3928 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3934 lst.EnsureVisible(foundIndex);
3939 lst.EnsureVisible(foundIndex);
3945 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
3947 var tab = this.CurrentTab;
3948 var post = this.CurrentPost;
3949 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
3950 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
3953 private async void VerUpMenuItem_Click(object sender, EventArgs e)
3954 => await this.CheckNewVersion(false);
3956 private void RunTweenUp()
3958 var pinfo = new ProcessStartInfo
3960 UseShellExecute = true,
3961 WorkingDirectory = this.settings.SettingsPath,
3962 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
3963 Arguments = "\"" + Application.StartupPath + "\"",
3968 Process.Start(pinfo);
3972 MessageBox.Show("Failed to execute TweenUp3.exe.");
3976 public readonly record struct VersionInfo(
3983 /// OpenTween の最新バージョンの情報を取得します
3985 public async Task<VersionInfo> GetVersionInfoAsync()
3987 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
3988 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
3990 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
3991 .ConfigureAwait(false);
3993 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
3994 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
3996 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
3997 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
3999 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4001 return new VersionInfo
4003 Version = Version.Parse(msgHeader[0]),
4004 DownloadUri = new Uri(msgHeader[1]),
4005 ReleaseNote = msgBody,
4009 private async Task CheckNewVersion(bool startup = false)
4011 if (ApplicationSettings.VersionInfoUrl == null)
4012 return; // 更新チェック無効化
4016 var versionInfo = await this.GetVersionInfoAsync();
4018 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4023 var msgtext = string.Format(
4024 Properties.Resources.CheckNewVersionText7,
4025 MyCommon.GetReadableVersion(),
4026 MyCommon.GetReadableVersion(versionInfo.Version));
4027 msgtext = MyCommon.ReplaceAppName(msgtext);
4031 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4032 MessageBoxButtons.OK,
4033 MessageBoxIcon.Information);
4038 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4041 using var dialog = new UpdateDialog();
4043 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4044 MyCommon.GetReadableVersion(versionInfo.Version));
4045 dialog.DetailsText = versionInfo.ReleaseNote;
4047 if (dialog.ShowDialog(this) == DialogResult.Yes)
4049 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4051 else if (dialog.SkipButtonPressed)
4053 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4054 this.MarkSettingCommonModified();
4059 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4063 Properties.Resources.CheckNewVersionText10,
4064 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4065 MessageBoxButtons.OK,
4066 MessageBoxIcon.Exclamation,
4067 MessageBoxDefaultButton.Button2);
4072 private void UpdateSelectedPost()
4074 // 件数関連の場合、タイトル即時書き換え
4075 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4076 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4077 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4078 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4080 this.SetMainWindowTitle();
4082 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4083 this.SetStatusLabelUrl();
4085 if (this.settings.Common.TabIconDisp)
4087 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4089 if (tab.UnreadCount == 0)
4091 var tabPage = this.ListTab.TabPages[index];
4092 if (tabPage.ImageIndex == 0)
4093 tabPage.ImageIndex = -1;
4099 this.ListTab.Refresh();
4102 this.DispSelectedPost();
4105 private void DispSelectedPost()
4106 => this.DispSelectedPost(false);
4108 private PostClass displayPost = new();
4111 /// サムネイル表示に使用する CancellationToken の生成元
4113 private CancellationTokenSource? thumbnailTokenSource = null;
4115 private void DispSelectedPost(bool forceupdate)
4117 var currentPost = this.CurrentPost;
4118 if (currentPost == null)
4121 var oldDisplayPost = this.displayPost;
4122 this.displayPost = currentPost;
4124 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4127 var loadTasks = new TaskCollection();
4128 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4130 if (this.settings.Common.PreviewEnable)
4132 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4133 oldTokenSource?.Cancel();
4135 var token = this.thumbnailTokenSource!.Token;
4136 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4140 this.SplitContainer3.Panel2Collapsed = true;
4143 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4145 .IgnoreException(x => x is OperationCanceledException)
4149 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4151 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4153 var timeout = Task.Delay(100);
4154 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4156 token.ThrowIfCancellationRequested();
4158 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4159 this.SplitContainer3.Panel2Collapsed = true;
4163 token.ThrowIfCancellationRequested();
4165 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4168 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4169 => await this.OpenApplicationWebsite();
4171 private async Task OpenApplicationWebsite()
4172 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4174 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4175 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4177 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4179 var tab = this.CurrentTab;
4180 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4182 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4183 if (pnl.Controls["comboSearch"].Focused ||
4184 pnl.Controls["comboLang"].Focused ||
4185 pnl.Controls["buttonSearch"].Focused) return;
4188 if (e.Control || e.Shift || e.Alt)
4191 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4194 e.SuppressKeyPress = true;
4197 if (asyncTask != null)
4201 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4203 private void InitializeShortcuts()
4205 this.shortcutCommands = new[]
4207 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4208 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4209 .FocusedOn(FocusedControl.ListTab)
4210 .Do(() => SendKeys.Send("{DOWN}")),
4212 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4213 .FocusedOn(FocusedControl.ListTab)
4214 .Do(() => SendKeys.Send("{UP}")),
4216 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4217 .FocusedOn(FocusedControl.ListTab)
4218 .Do(() => SendKeys.Send("{PGDN}")),
4220 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4221 .FocusedOn(FocusedControl.ListTab)
4222 .Do(() => SendKeys.Send("{PGUP}")),
4224 ShortcutCommand.Create(Keys.F1)
4225 .Do(() => this.OpenApplicationWebsite()),
4227 ShortcutCommand.Create(Keys.F3)
4228 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4230 ShortcutCommand.Create(Keys.F5)
4231 .Do(() => this.DoRefresh()),
4233 ShortcutCommand.Create(Keys.F6)
4234 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4236 ShortcutCommand.Create(Keys.F7)
4237 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4239 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4240 .NotFocusedOn(FocusedControl.StatusText)
4243 this.CurrentTab.ClearAnchor();
4244 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4247 ShortcutCommand.Create(Keys.G)
4248 .NotFocusedOn(FocusedControl.StatusText)
4251 this.CurrentTab.ClearAnchor();
4252 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4255 ShortcutCommand.Create(Keys.Right, Keys.N)
4256 .FocusedOn(FocusedControl.ListTab)
4257 .Do(() => this.GoRelPost(forward: true)),
4259 ShortcutCommand.Create(Keys.Left, Keys.P)
4260 .FocusedOn(FocusedControl.ListTab)
4261 .Do(() => this.GoRelPost(forward: false)),
4263 ShortcutCommand.Create(Keys.OemPeriod)
4264 .FocusedOn(FocusedControl.ListTab)
4265 .Do(() => this.GoAnchor()),
4267 ShortcutCommand.Create(Keys.I)
4268 .FocusedOn(FocusedControl.ListTab)
4269 .OnlyWhen(() => this.StatusText.Enabled)
4270 .Do(() => this.StatusText.Focus()),
4272 ShortcutCommand.Create(Keys.Enter)
4273 .FocusedOn(FocusedControl.ListTab)
4274 .Do(() => this.ListItemDoubleClickAction()),
4276 ShortcutCommand.Create(Keys.R)
4277 .FocusedOn(FocusedControl.ListTab)
4278 .Do(() => this.DoRefresh()),
4280 ShortcutCommand.Create(Keys.L)
4281 .FocusedOn(FocusedControl.ListTab)
4284 this.CurrentTab.ClearAnchor();
4285 this.GoPost(forward: true);
4288 ShortcutCommand.Create(Keys.H)
4289 .FocusedOn(FocusedControl.ListTab)
4292 this.CurrentTab.ClearAnchor();
4293 this.GoPost(forward: false);
4296 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4297 .FocusedOn(FocusedControl.ListTab)
4300 this.CurrentTab.ClearAnchor();
4304 ShortcutCommand.Create(Keys.S)
4305 .FocusedOn(FocusedControl.ListTab)
4308 this.CurrentTab.ClearAnchor();
4309 this.GoNextTab(forward: true);
4312 ShortcutCommand.Create(Keys.A)
4313 .FocusedOn(FocusedControl.ListTab)
4316 this.CurrentTab.ClearAnchor();
4317 this.GoNextTab(forward: false);
4320 // ] in_reply_to参照元へ戻る
4321 ShortcutCommand.Create(Keys.Oem4)
4322 .FocusedOn(FocusedControl.ListTab)
4325 this.CurrentTab.ClearAnchor();
4326 return this.GoInReplyToPostTree();
4329 // [ in_reply_toへジャンプ
4330 ShortcutCommand.Create(Keys.Oem6)
4331 .FocusedOn(FocusedControl.ListTab)
4334 this.CurrentTab.ClearAnchor();
4335 this.GoBackInReplyToPostTree();
4338 ShortcutCommand.Create(Keys.Escape)
4339 .FocusedOn(FocusedControl.ListTab)
4342 this.CurrentTab.ClearAnchor();
4343 var tab = this.CurrentTab;
4344 var tabtype = tab.TabType;
4345 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4347 this.RemoveSpecifiedTab(tab.TabName, false);
4348 this.SaveConfigsTabs();
4352 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4353 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4354 .FocusedOn(FocusedControl.ListTab)
4355 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4357 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4358 ShortcutCommand.Create(Keys.Up, Keys.Down)
4359 .FocusedOn(FocusedControl.PostBrowser)
4362 ShortcutCommand.Create(Keys.Control | Keys.R)
4363 .Do(() => this.MakeReplyText()),
4365 ShortcutCommand.Create(Keys.Control | Keys.D)
4366 .Do(() => this.DoStatusDelete()),
4368 ShortcutCommand.Create(Keys.Control | Keys.M)
4369 .Do(() => this.MakeDirectMessageText()),
4371 ShortcutCommand.Create(Keys.Control | Keys.S)
4372 .Do(() => this.FavoriteChange(favAdd: true)),
4374 ShortcutCommand.Create(Keys.Control | Keys.I)
4375 .Do(() => this.DoRepliedStatusOpen()),
4377 ShortcutCommand.Create(Keys.Control | Keys.Q)
4378 .Do(() => this.DoQuoteOfficial()),
4380 ShortcutCommand.Create(Keys.Control | Keys.B)
4381 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4383 ShortcutCommand.Create(Keys.Control | Keys.T)
4384 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4386 ShortcutCommand.Create(Keys.Control | Keys.L)
4387 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4389 ShortcutCommand.Create(Keys.Control | Keys.Y)
4390 .NotFocusedOn(FocusedControl.PostBrowser)
4391 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4393 ShortcutCommand.Create(Keys.Control | Keys.F)
4394 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4396 ShortcutCommand.Create(Keys.Control | Keys.U)
4397 .Do(() => this.ShowUserTimeline()),
4399 ShortcutCommand.Create(Keys.Control | Keys.H)
4400 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4402 ShortcutCommand.Create(Keys.Control | Keys.O)
4403 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4405 ShortcutCommand.Create(Keys.Control | Keys.E)
4406 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4408 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4409 .FocusedOn(FocusedControl.ListTab)
4410 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4412 ShortcutCommand.Create(Keys.Control | Keys.N)
4413 .FocusedOn(FocusedControl.ListTab)
4414 .Do(() => this.GoNextTab(forward: true)),
4416 ShortcutCommand.Create(Keys.Control | Keys.P)
4417 .FocusedOn(FocusedControl.ListTab)
4418 .Do(() => this.GoNextTab(forward: false)),
4420 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4421 .FocusedOn(FocusedControl.ListTab)
4422 .Do(() => this.CopyStot()),
4424 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4425 ShortcutCommand.Create(Keys.Control | Keys.D1)
4426 .FocusedOn(FocusedControl.ListTab)
4427 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4428 .Do(() => this.ListTab.SelectedIndex = 0),
4430 ShortcutCommand.Create(Keys.Control | Keys.D2)
4431 .FocusedOn(FocusedControl.ListTab)
4432 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4433 .Do(() => this.ListTab.SelectedIndex = 1),
4435 ShortcutCommand.Create(Keys.Control | Keys.D3)
4436 .FocusedOn(FocusedControl.ListTab)
4437 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4438 .Do(() => this.ListTab.SelectedIndex = 2),
4440 ShortcutCommand.Create(Keys.Control | Keys.D4)
4441 .FocusedOn(FocusedControl.ListTab)
4442 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4443 .Do(() => this.ListTab.SelectedIndex = 3),
4445 ShortcutCommand.Create(Keys.Control | Keys.D5)
4446 .FocusedOn(FocusedControl.ListTab)
4447 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4448 .Do(() => this.ListTab.SelectedIndex = 4),
4450 ShortcutCommand.Create(Keys.Control | Keys.D6)
4451 .FocusedOn(FocusedControl.ListTab)
4452 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4453 .Do(() => this.ListTab.SelectedIndex = 5),
4455 ShortcutCommand.Create(Keys.Control | Keys.D7)
4456 .FocusedOn(FocusedControl.ListTab)
4457 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4458 .Do(() => this.ListTab.SelectedIndex = 6),
4460 ShortcutCommand.Create(Keys.Control | Keys.D8)
4461 .FocusedOn(FocusedControl.ListTab)
4462 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4463 .Do(() => this.ListTab.SelectedIndex = 7),
4465 ShortcutCommand.Create(Keys.Control | Keys.D9)
4466 .FocusedOn(FocusedControl.ListTab)
4467 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4469 ShortcutCommand.Create(Keys.Control | Keys.A)
4470 .FocusedOn(FocusedControl.StatusText)
4471 .Do(() => this.StatusText.SelectAll()),
4473 ShortcutCommand.Create(Keys.Control | Keys.V)
4474 .FocusedOn(FocusedControl.StatusText)
4475 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4477 ShortcutCommand.Create(Keys.Control | Keys.Up)
4478 .FocusedOn(FocusedControl.StatusText)
4479 .Do(() => this.StatusTextHistoryBack()),
4481 ShortcutCommand.Create(Keys.Control | Keys.Down)
4482 .FocusedOn(FocusedControl.StatusText)
4483 .Do(() => this.StatusTextHistoryForward()),
4485 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4486 .FocusedOn(FocusedControl.StatusText)
4489 if (this.ListTab.SelectedIndex == 0)
4491 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4495 this.ListTab.SelectedIndex -= 1;
4497 this.StatusText.Focus();
4500 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4501 .FocusedOn(FocusedControl.StatusText)
4504 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4506 this.ListTab.SelectedIndex = 0;
4510 this.ListTab.SelectedIndex += 1;
4512 this.StatusText.Focus();
4515 ShortcutCommand.Create(Keys.Control | Keys.Y)
4516 .FocusedOn(FocusedControl.PostBrowser)
4519 var multiline = !this.settings.Local.StatusMultiline;
4520 this.settings.Local.StatusMultiline = multiline;
4521 this.MultiLineMenuItem.Checked = multiline;
4522 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4525 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4526 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4528 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4529 .Do(() => this.DoRefreshMore()),
4531 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4532 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4534 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4535 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4537 ShortcutCommand.Create(Keys.Shift | Keys.R)
4538 .NotFocusedOn(FocusedControl.StatusText)
4539 .Do(() => this.DoRefreshMore()),
4541 ShortcutCommand.Create(Keys.Shift | Keys.H)
4542 .FocusedOn(FocusedControl.ListTab)
4543 .Do(() => this.GoTopEnd(goTop: true)),
4545 ShortcutCommand.Create(Keys.Shift | Keys.L)
4546 .FocusedOn(FocusedControl.ListTab)
4547 .Do(() => this.GoTopEnd(goTop: false)),
4549 ShortcutCommand.Create(Keys.Shift | Keys.M)
4550 .FocusedOn(FocusedControl.ListTab)
4551 .Do(() => this.GoMiddle()),
4553 ShortcutCommand.Create(Keys.Shift | Keys.G)
4554 .FocusedOn(FocusedControl.ListTab)
4555 .Do(() => this.GoLast()),
4557 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4558 .FocusedOn(FocusedControl.ListTab)
4559 .Do(() => this.MoveMiddle()),
4561 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4562 .FocusedOn(FocusedControl.ListTab)
4563 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4565 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4566 .FocusedOn(FocusedControl.ListTab)
4567 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4569 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4570 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4571 .FocusedOn(FocusedControl.ListTab)
4572 .Do(() => this.GoFav(forward: true)),
4574 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4575 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4576 .FocusedOn(FocusedControl.ListTab)
4577 .Do(() => this.GoFav(forward: false)),
4579 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4580 .FocusedOn(FocusedControl.ListTab)
4581 .Do(() => this.GoBackSelectPostChain()),
4583 ShortcutCommand.Create(Keys.Alt | Keys.R)
4584 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4586 ShortcutCommand.Create(Keys.Alt | Keys.P)
4587 .OnlyWhen(() => this.CurrentPost != null)
4588 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4590 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4591 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4593 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4594 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4596 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4597 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4599 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4600 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4602 // 別タブの同じ書き込みへ(ALT+←/→)
4603 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4604 .FocusedOn(FocusedControl.ListTab)
4605 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4607 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4608 .FocusedOn(FocusedControl.ListTab)
4609 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4611 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4612 .Do(() => this.MakeReplyText(atAll: true)),
4614 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4615 .Do(() => this.CopyIdUri()),
4617 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4618 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4619 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4621 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4622 .Do(() => this.DoQuoteOfficial()),
4624 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4625 .Do(() => this.FavoriteChange(favAdd: false)),
4627 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4628 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4630 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4631 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4633 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4634 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4636 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4637 .Do(() => this.DoMoveToRTHome()),
4639 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4640 .FocusedOn(FocusedControl.StatusText)
4643 var tab = this.CurrentTab;
4644 var selectedIndex = tab.SelectedIndex;
4645 if (selectedIndex != -1 && selectedIndex > 0)
4647 var listView = this.CurrentListView;
4648 var idx = selectedIndex - 1;
4649 this.SelectListItem(listView, idx);
4650 listView.EnsureVisible(idx);
4654 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4655 .FocusedOn(FocusedControl.StatusText)
4658 var tab = this.CurrentTab;
4659 var selectedIndex = tab.SelectedIndex;
4660 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4662 var listView = this.CurrentListView;
4663 var idx = selectedIndex + 1;
4664 this.SelectListItem(listView, idx);
4665 listView.EnsureVisible(idx);
4669 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4670 .FocusedOn(FocusedControl.StatusText)
4673 if (this.StatusText.SelectionStart > 0)
4675 var endidx = this.StatusText.SelectionStart - 1;
4677 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4679 var c = this.StatusText.Text[i];
4680 if (char.IsLetterOrDigit(c) || c == '_')
4686 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4687 var cnt = this.AtIdSupl.ItemCount;
4688 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4689 if (this.AtIdSupl.ItemCount != cnt)
4690 this.MarkSettingAtIdModified();
4694 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4695 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4705 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4706 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4707 .FocusedOn(FocusedControl.ListTab)
4708 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4710 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4711 .FocusedOn(FocusedControl.ListTab)
4712 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4714 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4715 .FocusedOn(FocusedControl.ListTab)
4716 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4718 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4719 .FocusedOn(FocusedControl.ListTab)
4720 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4722 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4723 .FocusedOn(FocusedControl.ListTab)
4724 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4726 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4727 .FocusedOn(FocusedControl.ListTab)
4728 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4730 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4731 .FocusedOn(FocusedControl.ListTab)
4732 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4734 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4735 .FocusedOn(FocusedControl.ListTab)
4736 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4738 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4739 .FocusedOn(FocusedControl.ListTab)
4740 .Do(() => this.SetSortLastColumn()),
4742 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4743 .FocusedOn(FocusedControl.ListTab)
4744 .Do(() => this.FavoritesRetweetOfficial()),
4746 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4747 .FocusedOn(FocusedControl.ListTab)
4748 .Do(() => this.FavoritesRetweetUnofficial()),
4750 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4751 .FocusedOn(FocusedControl.ListTab)
4752 .Do(() => this.OpenUserAppointUrl()),
4754 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4755 .FocusedOn(FocusedControl.PostBrowser)
4756 .Do(() => this.DoReTweetUnofficial()),
4758 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4759 .OnlyWhen(() => this.ExistCurrentPost)
4760 .Do(() => this.tweetDetailsView.DoTranslation()),
4762 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4763 .Do(() => this.DoReTweetUnofficial()),
4765 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4766 .Do(() => this.CopyUserId()),
4768 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4769 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4771 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4772 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4774 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4775 .FocusedOn(FocusedControl.ListTab)
4776 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4777 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4781 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4783 // Task を返す非同期処理があれば asyncTask に代入する
4786 // ShortcutCommand に対応しているコマンドはここで処理される
4787 foreach (var command in this.shortcutCommands)
4789 if (command.IsMatch(keyData, focusedOn))
4791 asyncTask = command.RunCommand();
4792 return command.PreventDefault;
4799 private void GoNextTab(bool forward)
4801 var idx = this.statuses.SelectedTabIndex;
4802 var tabCount = this.statuses.Tabs.Count;
4806 if (idx > tabCount - 1) idx = 0;
4811 if (idx < 0) idx = tabCount - 1;
4813 this.ListTab.SelectedIndex = idx;
4816 private void CopyStot()
4818 var sb = new StringBuilder();
4819 var tab = this.CurrentTab;
4820 var isProtected = false;
4821 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4822 foreach (var post in tab.SelectedPosts)
4824 if (post.IsDeleted) continue;
4827 if (post.RetweetedId != null)
4828 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4830 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4834 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4839 MessageBox.Show(Properties.Resources.CopyStotText1);
4843 var clstr = sb.ToString();
4846 Clipboard.SetDataObject(clstr, false, 5, 100);
4848 catch (Exception ex)
4850 MessageBox.Show(ex.Message);
4855 private void CopyIdUri()
4857 var tab = this.CurrentTab;
4858 if (tab == null || tab is DirectMessagesTabModel)
4861 var copyUrls = new List<string>();
4862 foreach (var post in tab.SelectedPosts)
4863 copyUrls.Add(MyCommon.GetStatusUrl(post));
4865 if (copyUrls.Count == 0)
4870 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4872 catch (ExternalException ex)
4874 MessageBox.Show(ex.Message);
4878 private void GoFav(bool forward)
4880 var tab = this.CurrentTab;
4881 if (tab.AllCount == 0)
4884 var selectedIndex = tab.SelectedIndex;
4892 if (selectedIndex == -1)
4898 fIdx = selectedIndex + 1;
4899 if (fIdx > tab.AllCount - 1)
4902 toIdx = tab.AllCount;
4907 if (selectedIndex == -1)
4909 fIdx = tab.AllCount - 1;
4913 fIdx = selectedIndex - 1;
4921 for (var idx = fIdx; idx != toIdx; idx += stp)
4925 var listView = this.CurrentListView;
4926 this.SelectListItem(listView, idx);
4927 listView.EnsureVisible(idx);
4933 private void GoSamePostToAnotherTab(bool left)
4935 var tab = this.CurrentTab;
4937 // Directタブは対象外(見つかるはずがない)
4938 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4941 var selectedStatusId = tab.SelectedStatusId;
4942 if (selectedStatusId == null)
4945 int fIdx, toIdx, stp;
4950 if (this.ListTab.SelectedIndex == 0)
4956 fIdx = this.ListTab.SelectedIndex - 1;
4964 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4970 fIdx = this.ListTab.SelectedIndex + 1;
4972 toIdx = this.ListTab.TabCount;
4976 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
4978 var targetTab = this.statuses.Tabs[tabidx];
4981 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
4984 var foundIndex = targetTab.IndexOf(selectedStatusId);
4985 if (foundIndex != -1)
4987 this.ListTab.SelectedIndex = tabidx;
4988 var listView = this.CurrentListView;
4989 this.SelectListItem(listView, foundIndex);
4990 listView.EnsureVisible(foundIndex);
4996 private void GoPost(bool forward)
4998 var tab = this.CurrentTab;
4999 var currentPost = this.CurrentPost;
5001 if (currentPost == null)
5004 var selectedIndex = tab.SelectedIndex;
5006 int fIdx, toIdx, stp;
5010 fIdx = selectedIndex + 1;
5011 if (fIdx > tab.AllCount - 1) return;
5012 toIdx = tab.AllCount;
5017 fIdx = selectedIndex - 1;
5018 if (fIdx < 0) return;
5024 if (currentPost.RetweetedBy == null)
5026 name = currentPost.ScreenName;
5030 name = currentPost.RetweetedBy;
5032 for (var idx = fIdx; idx != toIdx; idx += stp)
5034 var post = tab[idx];
5035 if (post.RetweetedId == null)
5037 if (post.ScreenName == name)
5039 var listView = this.CurrentListView;
5040 this.SelectListItem(listView, idx);
5041 listView.EnsureVisible(idx);
5047 if (post.RetweetedBy == name)
5049 var listView = this.CurrentListView;
5050 this.SelectListItem(listView, idx);
5051 listView.EnsureVisible(idx);
5058 private void GoRelPost(bool forward)
5060 var tab = this.CurrentTab;
5061 var selectedIndex = tab.SelectedIndex;
5063 if (selectedIndex == -1)
5066 int fIdx, toIdx, stp;
5070 fIdx = selectedIndex + 1;
5071 if (fIdx > tab.AllCount - 1) return;
5072 toIdx = tab.AllCount;
5077 fIdx = selectedIndex - 1;
5078 if (fIdx < 0) return;
5083 var anchorPost = tab.AnchorPost;
5084 if (anchorPost == null)
5086 var currentPost = this.CurrentPost;
5087 if (currentPost == null)
5090 anchorPost = currentPost;
5091 tab.AnchorPost = currentPost;
5094 for (var idx = fIdx; idx != toIdx; idx += stp)
5096 var post = tab[idx];
5097 if (post.ScreenName == anchorPost.ScreenName ||
5098 post.RetweetedBy == anchorPost.ScreenName ||
5099 post.ScreenName == anchorPost.RetweetedBy ||
5100 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5101 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5102 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5103 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5104 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5106 var listView = this.CurrentListView;
5107 this.SelectListItem(listView, idx);
5108 listView.EnsureVisible(idx);
5114 private void GoAnchor()
5116 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5117 if (anchorStatusId == null)
5120 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5124 var listView = this.CurrentListView;
5125 this.SelectListItem(listView, idx);
5126 listView.EnsureVisible(idx);
5129 private void GoTopEnd(bool goTop)
5131 var listView = this.CurrentListView;
5132 if (listView.VirtualListSize == 0)
5140 item = listView.GetItemAt(0, 25);
5148 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5150 idx = listView.VirtualListSize - 1;
5154 this.SelectListItem(listView, idx);
5157 private void GoMiddle()
5159 var listView = this.CurrentListView;
5160 if (listView.VirtualListSize == 0)
5168 item = listView.GetItemAt(0, 0);
5178 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5181 idx2 = listView.VirtualListSize - 1;
5187 idx3 = (idx1 + idx2) / 2;
5189 this.SelectListItem(listView, idx3);
5192 private void GoLast()
5194 var listView = this.CurrentListView;
5195 if (listView.VirtualListSize == 0) return;
5197 if (this.statuses.SortOrder == SortOrder.Ascending)
5199 this.SelectListItem(listView, listView.VirtualListSize - 1);
5200 listView.EnsureVisible(listView.VirtualListSize - 1);
5204 this.SelectListItem(listView, 0);
5205 listView.EnsureVisible(0);
5209 private void MoveTop()
5211 var listView = this.CurrentListView;
5212 if (listView.SelectedIndices.Count == 0) return;
5213 var idx = listView.SelectedIndices[0];
5214 if (this.statuses.SortOrder == SortOrder.Ascending)
5216 listView.EnsureVisible(listView.VirtualListSize - 1);
5220 listView.EnsureVisible(0);
5222 listView.EnsureVisible(idx);
5225 private async Task GoInReplyToPostTree()
5227 var curTabClass = this.CurrentTab;
5228 var currentPost = this.CurrentPost;
5230 if (currentPost == null)
5233 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5237 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5239 currentPost = currentPost with
5241 InReplyToStatusId = post.InReplyToStatusId,
5242 InReplyToUser = post.InReplyToUser,
5243 IsReply = post.IsReply,
5245 curTabClass.ReplacePost(currentPost);
5246 this.listCache?.PurgeCache();
5248 var index = curTabClass.SelectedIndex;
5249 this.CurrentListView.RedrawItems(index, index, false);
5251 catch (WebApiException ex)
5253 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5257 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5259 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5261 this.replyChains = new Stack<ReplyChain>();
5263 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5266 string inReplyToTabName;
5267 var inReplyToId = currentPost.InReplyToStatusId;
5268 var inReplyToUser = currentPost.InReplyToUser;
5270 var inReplyToPosts = from tab in this.statuses.Tabs
5271 orderby tab != curTabClass
5272 from post in tab.Posts.Values
5273 where post.StatusId == inReplyToId
5274 let index = tab.IndexOf(post.StatusId)
5276 select new { Tab = tab, Index = index };
5278 var inReplyPost = inReplyToPosts.FirstOrDefault();
5279 if (inReplyPost == null)
5283 await Task.Run(async () =>
5285 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5286 .ConfigureAwait(false);
5289 this.statuses.AddPost(post);
5290 this.statuses.DistributePosts();
5293 catch (WebApiException ex)
5295 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5296 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5300 this.RefreshTimeline();
5302 inReplyPost = inReplyToPosts.FirstOrDefault();
5303 if (inReplyPost == null)
5305 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5309 inReplyToTabName = inReplyPost.Tab.TabName;
5310 inReplyToIndex = inReplyPost.Index;
5312 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5313 var tabPage = this.ListTab.TabPages[tabIndex];
5314 var listView = (DetailsListView)tabPage.Tag;
5316 if (this.CurrentTabName != inReplyToTabName)
5318 this.ListTab.SelectedIndex = tabIndex;
5321 this.SelectListItem(listView, inReplyToIndex);
5322 listView.EnsureVisible(inReplyToIndex);
5325 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5327 var curTabClass = this.CurrentTab;
5328 var currentPost = this.CurrentPost;
5330 if (currentPost == null)
5335 if (currentPost.InReplyToStatusId != null)
5337 var posts = from t in this.statuses.Tabs
5339 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5340 let indexOf = t.IndexOf(p.Value.StatusId)
5342 orderby isForward ? indexOf : indexOf * -1
5343 orderby t != curTabClass
5344 select new { Tab = t, Post = p.Value, Index = indexOf };
5347 var postList = posts.ToList();
5348 for (var i = postList.Count - 1; i >= 0; i--)
5351 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5353 postList.RemoveAt(index);
5356 var currentIndex = this.CurrentTab.SelectedIndex;
5357 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5358 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5359 if (post == null) post = postList.First();
5360 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5361 this.ListTab.SelectedIndex = tabIndex;
5362 var listView = this.CurrentListView;
5363 this.SelectListItem(listView, post.Index);
5364 listView.EnsureVisible(post.Index);
5366 catch (InvalidOperationException)
5374 if (this.replyChains == null || this.replyChains.Count < 1)
5376 var posts = from t in this.statuses.Tabs
5378 where p.Value.InReplyToStatusId == currentPost.StatusId
5379 let indexOf = t.IndexOf(p.Value.StatusId)
5382 orderby t != curTabClass
5383 select new { Tab = t, Index = indexOf };
5386 var post = posts.First();
5387 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5388 this.ListTab.SelectedIndex = tabIndex;
5389 var listView = this.CurrentListView;
5390 this.SelectListItem(listView, post.Index);
5391 listView.EnsureVisible(post.Index);
5393 catch (InvalidOperationException)
5400 var chainHead = this.replyChains.Pop();
5401 if (chainHead.InReplyToId == currentPost.StatusId)
5403 var tab = chainHead.OriginalTab;
5404 if (!this.statuses.Tabs.Contains(tab))
5406 this.replyChains = null;
5410 var idx = tab.IndexOf(chainHead.OriginalId);
5413 this.replyChains = null;
5417 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5420 this.ListTab.SelectedIndex = tabIndex;
5424 this.replyChains = null;
5426 var listView = this.CurrentListView;
5427 this.SelectListItem(listView, idx);
5428 listView.EnsureVisible(idx);
5434 this.replyChains = null;
5435 this.GoBackInReplyToPostTree(parallel);
5441 private void GoBackSelectPostChain()
5443 if (this.selectPostChains.Count > 1)
5446 TabModel? foundTab = null;
5452 this.selectPostChains.Pop();
5453 var (tab, post) = this.selectPostChains.Peek();
5455 if (!this.statuses.Tabs.Contains(tab))
5456 continue; // 該当タブが存在しないので無視
5460 idx = tab.IndexOf(post.StatusId);
5461 if (idx == -1) continue; // 該当ポストが存在しないので無視
5466 this.selectPostChains.Pop();
5468 catch (InvalidOperationException)
5474 while (this.selectPostChains.Count > 1);
5476 if (foundTab == null)
5479 // 履歴が残り1つであればクリアしておく
5480 if (this.selectPostChains.Count == 1)
5481 this.selectPostChains.Clear();
5485 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5486 var tabPage = this.ListTab.TabPages[tabIndex];
5487 var lst = (DetailsListView)tabPage.Tag;
5488 this.ListTab.SelectedIndex = tabIndex;
5492 this.SelectListItem(lst, idx);
5493 lst.EnsureVisible(idx);
5499 private void PushSelectPostChain()
5501 var currentTab = this.CurrentTab;
5502 var currentPost = this.CurrentPost;
5504 var count = this.selectPostChains.Count;
5507 var (tab, post) = this.selectPostChains.Peek();
5508 if (tab == currentTab)
5510 if (post == currentPost) return; // 最新の履歴と同一
5511 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5514 if (count >= 2500) this.TrimPostChain();
5515 this.selectPostChains.Push((currentTab, currentPost));
5518 private void TrimPostChain()
5520 if (this.selectPostChains.Count <= 2000) return;
5521 var p = new Stack<(TabModel, PostClass?)>(2000);
5522 for (var i = 0; i < 2000; i++)
5524 p.Push(this.selectPostChains.Pop());
5526 this.selectPostChains.Clear();
5527 for (var i = 0; i < 2000; i++)
5529 this.selectPostChains.Push(p.Pop());
5533 private bool GoStatus(PostId statusId)
5535 var tab = this.statuses.Tabs
5536 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5537 .Where(x => x.Contains(statusId))
5543 var index = tab.IndexOf(statusId);
5545 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5546 this.ListTab.SelectedIndex = tabIndex;
5548 var listView = this.CurrentListView;
5549 this.SelectListItem(listView, index);
5550 listView.EnsureVisible(index);
5555 private bool GoDirectMessage(PostId statusId)
5557 var tab = this.statuses.DirectMessageTab;
5558 var index = tab.IndexOf(statusId);
5563 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5564 this.ListTab.SelectedIndex = tabIndex;
5566 var listView = this.CurrentListView;
5567 this.SelectListItem(listView, index);
5568 listView.EnsureVisible(index);
5573 private void MyList_MouseClick(object sender, MouseEventArgs e)
5574 => this.CurrentTab.ClearAnchor();
5576 private void StatusText_Enter(object sender, EventArgs e)
5578 // フォーカスの戻り先を StatusText に設定
5579 this.Tag = this.StatusText;
5580 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5583 public Color InputBackColor
5584 => this.themeManager.ColorInputBackcolor;
5586 private void StatusText_Leave(object sender, EventArgs e)
5588 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5589 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5590 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5593 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5595 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5598 e.SuppressKeyPress = true;
5601 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5603 if (asyncTask != null)
5607 private void SaveConfigsAll(bool ifModified)
5611 this.SaveConfigsCommon();
5612 this.SaveConfigsLocal();
5613 this.SaveConfigsTabs();
5614 this.SaveConfigsAtId();
5618 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5619 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5620 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5624 private void SaveConfigsAtId()
5626 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5628 this.ModifySettingAtId = false;
5629 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5630 this.settings.SaveAtIdList();
5633 private void SaveConfigsCommon()
5635 if (this.ignoreConfigSave) return;
5637 this.ModifySettingCommon = false;
5638 lock (this.syncObject)
5640 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5641 this.settings.Common.SortColumn = this.statuses.SortMode switch
5643 ComparerMode.Nickname => 1, // ニックネーム
5644 ComparerMode.Data => 2, // 本文
5645 ComparerMode.Id => 3, // 時刻=発言Id
5646 ComparerMode.Name => 4, // 名前
5647 ComparerMode.Source => 7, // Source
5648 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5650 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5651 if (this.HashMgr.IsPermanent)
5653 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5657 this.settings.Common.HashSelected = "";
5659 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5660 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5661 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5662 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5663 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5665 this.settings.SaveCommon();
5669 private void SaveConfigsLocal()
5671 if (this.ignoreConfigSave) return;
5672 lock (this.syncObject)
5674 this.ModifySettingLocal = false;
5675 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5676 this.settings.Local.FormSize = this.mySize;
5677 this.settings.Local.FormLocation = this.myLoc;
5678 this.settings.Local.SplitterDistance = this.mySpDis;
5679 this.settings.Local.PreviewDistance = this.mySpDis3;
5680 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5681 this.settings.Local.StatusTextHeight = this.mySpDis2;
5683 if (this.ignoreConfigSave) return;
5684 this.settings.SaveLocal();
5688 private void SaveConfigsTabs()
5690 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5692 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5694 foreach (var tab in tabs)
5696 if (!tab.IsPermanentTabType)
5699 var tabSetting = new SettingTabs.SettingTabItem
5701 TabName = tab.TabName,
5702 TabType = tab.TabType,
5703 UnreadManage = tab.UnreadManage,
5704 Protected = tab.Protected,
5705 Notify = tab.Notify,
5706 SoundFile = tab.SoundFile,
5711 case FilterTabModel filterTab:
5712 tabSetting.FilterArray = filterTab.FilterArray;
5714 case UserTimelineTabModel userTab:
5715 tabSetting.User = userTab.ScreenName;
5716 tabSetting.UserId = userTab.UserId;
5718 case PublicSearchTabModel searchTab:
5719 tabSetting.SearchWords = searchTab.SearchWords;
5720 tabSetting.SearchLang = searchTab.SearchLang;
5722 case ListTimelineTabModel listTab:
5723 tabSetting.ListInfo = listTab.ListInfo;
5727 tabSettingList.Add(tabSetting);
5730 this.settings.Tabs.Tabs = tabSettingList;
5731 this.settings.SaveTabs();
5734 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5736 static void ShowFormatErrorDialog(IWin32Window owner)
5740 Properties.Resources.OpenURL_InvalidFormat,
5741 Properties.Resources.OpenURL_Caption,
5742 MessageBoxButtons.OK,
5743 MessageBoxIcon.Error
5747 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5748 if (ret != DialogResult.OK)
5751 var match = Twitter.StatusUrlRegex.Match(inputText);
5754 ShowFormatErrorDialog(this);
5760 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5761 await this.OpenRelatedTab(statusId);
5763 catch (OverflowException)
5765 ShowFormatErrorDialog(this);
5767 catch (TabException ex)
5769 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5773 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5775 var tab = this.CurrentTab;
5777 var rslt = MessageBox.Show(
5778 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5779 Properties.Resources.SaveLogMenuItem_ClickText2,
5780 MessageBoxButtons.YesNoCancel,
5781 MessageBoxIcon.Question);
5782 if (rslt == DialogResult.Cancel) return;
5784 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5785 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5786 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5787 this.SaveFileDialog1.FilterIndex = 0;
5788 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5789 this.SaveFileDialog1.RestoreDirectory = true;
5791 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5793 if (!this.SaveFileDialog1.ValidateNames) return;
5794 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5795 if (rslt == DialogResult.Yes)
5798 for (var idx = 0; idx < tab.AllCount; idx++)
5800 var post = tab[idx];
5803 protect = "Protect";
5804 sw.WriteLine(post.Nickname + "\t" +
5805 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5806 post.CreatedAt.ToLocalTimeString() + "\t" +
5807 post.ScreenName + "\t" +
5808 post.StatusId.Id + "\t" +
5809 post.ImageUrl + "\t" +
5810 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5816 foreach (var post in this.CurrentTab.SelectedPosts)
5820 protect = "Protect";
5821 sw.WriteLine(post.Nickname + "\t" +
5822 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5823 post.CreatedAt.ToLocalTimeString() + "\t" +
5824 post.ScreenName + "\t" +
5825 post.StatusId.Id + "\t" +
5826 post.ImageUrl + "\t" +
5827 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5832 this.TopMost = this.settings.Common.AlwaysTop;
5835 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5839 using (var inputName = new InputTabName())
5841 inputName.TabName = origTabName;
5842 inputName.ShowDialog();
5843 if (inputName.DialogResult == DialogResult.Cancel) return false;
5844 newTabName = inputName.TabName;
5846 this.TopMost = this.settings.Common.AlwaysTop;
5847 if (!MyCommon.IsNullOrEmpty(newTabName))
5850 if (this.statuses.ContainsTab(newTabName))
5852 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5853 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5857 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5858 var tabPage = this.ListTab.TabPages[tabIndex];
5861 if (tabPage != null)
5862 tabPage.Text = newTabName;
5864 this.statuses.RenameTab(origTabName, newTabName);
5866 var state = this.listViewState[origTabName];
5867 this.listViewState.Remove(origTabName);
5868 this.listViewState[newTabName] = state;
5870 this.SaveConfigsCommon();
5871 this.SaveConfigsTabs();
5872 this.rclickTabName = newTabName;
5881 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5883 if (e.Button == MouseButtons.Middle)
5885 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5887 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5889 this.RemoveSpecifiedTab(tab.TabName, true);
5890 this.SaveConfigsTabs();
5897 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5898 => this.TabRename(this.CurrentTabName, out _);
5900 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5902 if (this.settings.Common.TabMouseLock) return;
5903 if (e.Button == MouseButtons.Left)
5905 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5907 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5909 this.tabDrag = true;
5910 this.tabMouseDownPoint = e.Location;
5917 this.tabDrag = false;
5921 private void ListTab_DragEnter(object sender, DragEventArgs e)
5923 if (e.Data.GetDataPresent(typeof(TabPage)))
5924 e.Effect = DragDropEffects.Move;
5926 e.Effect = DragDropEffects.None;
5929 private void ListTab_DragDrop(object sender, DragEventArgs e)
5931 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5933 this.tabDrag = false;
5936 var cpos = new Point(e.X, e.Y);
5937 var spos = this.ListTab.PointToClient(cpos);
5938 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5940 var rect = this.ListTab.GetTabRect(index);
5941 if (rect.Contains(spos))
5944 if (spos.X <= (rect.Left + rect.Right) / 2)
5953 // タブのないところにドロップ->最後尾へ移動
5954 if (MyCommon.IsNullOrEmpty(tn))
5956 var lastTab = this.statuses.Tabs.Last();
5957 tn = lastTab.TabName;
5961 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
5962 if (tp.Text == tn) return;
5964 this.ReOrderTab(tp.Text, tn, bef);
5967 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
5969 var baseIndex = this.GetTabPageIndex(baseTabText);
5970 if (baseIndex == -1)
5973 var targetIndex = this.GetTabPageIndex(targetTabText);
5974 if (targetIndex == -1)
5977 using (ControlTransaction.Layout(this.ListTab))
5979 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
5980 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
5981 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
5982 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
5984 var tab = this.statuses.Tabs[targetIndex];
5985 var tabPage = this.ListTab.TabPages[targetIndex];
5987 this.ListTab.TabPages.Remove(tabPage);
5989 if (targetIndex < baseIndex)
5992 if (!isBeforeBaseTab)
5995 this.statuses.MoveTab(baseIndex, tab);
5997 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6000 this.SaveConfigsTabs();
6003 private void MakeDirectMessageText()
6005 var selectedPosts = this.CurrentTab.SelectedPosts;
6006 if (selectedPosts.Length > 1)
6009 var post = selectedPosts.Single();
6010 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6012 this.inReplyTo = null;
6013 this.StatusText.Text = text;
6014 this.StatusText.SelectionStart = text.Length;
6015 this.StatusText.Focus();
6018 private void MakeReplyText(bool atAll = false)
6020 var selectedPosts = this.CurrentTab.SelectedPosts;
6021 if (selectedPosts.Any(x => x.IsDm))
6023 this.MakeDirectMessageText();
6027 if (selectedPosts.Length == 1)
6029 var post = selectedPosts.Single();
6030 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6031 var inReplyToScreenName = post.ScreenName;
6032 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6036 this.inReplyTo = null;
6039 var selfScreenName = this.tw.Username;
6040 var targetScreenNames = new List<string>();
6041 foreach (var post in selectedPosts)
6043 if (post.ScreenName != selfScreenName)
6044 targetScreenNames.Add(post.ScreenName);
6048 foreach (var (_, screenName) in post.ReplyToList)
6050 if (screenName != selfScreenName)
6051 targetScreenNames.Add(screenName);
6056 if (this.inReplyTo != null)
6058 var (_, screenName) = this.inReplyTo.Value;
6059 if (screenName == selfScreenName)
6060 targetScreenNames.Insert(0, screenName);
6063 var text = this.StatusText.Text;
6064 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6066 var atText = $"@{screenName} ";
6067 if (!text.Contains(atText))
6068 text = atText + text;
6071 this.StatusText.Text = text;
6072 this.StatusText.SelectionStart = text.Length;
6073 this.StatusText.Focus();
6076 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6077 => this.tabDrag = false;
6079 private int iconCnt = 0;
6080 private int blinkCnt = 0;
6081 private bool blink = false;
6083 private void RefreshTasktrayIcon()
6085 void EnableTasktrayAnimation()
6086 => this.TimerRefreshIcon.Enabled = true;
6088 void DisableTasktrayAnimation()
6089 => this.TimerRefreshIcon.Enabled = false;
6091 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6095 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6098 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6099 this.myStatusError = false;
6100 EnableTasktrayAnimation();
6104 var replyIconType = this.settings.Common.ReplyIconState;
6106 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6108 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6109 if (replyTab != null && replyTab.UnreadCount > 0)
6113 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6116 if (this.blinkCnt > 10)
6119 if (this.blinkCnt == 0)
6120 this.blink = !this.blink;
6122 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6123 EnableTasktrayAnimation();
6127 DisableTasktrayAnimation();
6133 // 優先度:リプライ→エラー→オフライン→アイドル
6134 // エラーは更新アイコンでクリアされる
6135 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6136 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6137 else if (this.myStatusError)
6138 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6139 else if (this.myStatusOnline)
6140 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6142 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6145 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6146 => this.RefreshTasktrayIcon(); // 200ms
6148 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6150 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6151 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6152 this.rclickTabName = this.CurrentTabName;
6154 if (this.statuses == null) return;
6155 if (this.statuses.Tabs == null) return;
6157 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6160 this.NotifyDispMenuItem.Checked = tb.Notify;
6161 this.NotifyTbMenuItem.Checked = tb.Notify;
6163 this.soundfileListup = true;
6164 this.SoundFileComboBox.Items.Clear();
6165 this.SoundFileTbComboBox.Items.Clear();
6166 this.SoundFileComboBox.Items.Add("");
6167 this.SoundFileTbComboBox.Items.Add("");
6168 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6169 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6171 oDir = oDir.GetDirectories("Sounds")[0];
6173 foreach (var oFile in oDir.GetFiles("*.wav"))
6175 this.SoundFileComboBox.Items.Add(oFile.Name);
6176 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6178 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6179 if (idx == -1) idx = 0;
6180 this.SoundFileComboBox.SelectedIndex = idx;
6181 this.SoundFileTbComboBox.SelectedIndex = idx;
6182 this.soundfileListup = false;
6183 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6184 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6186 this.TabMenuControl(this.rclickTabName);
6189 private void TabMenuControl(string tabName)
6191 var tabInfo = this.statuses.GetTabByName(tabName)!;
6193 this.FilterEditMenuItem.Enabled = true;
6194 this.EditRuleTbMenuItem.Enabled = true;
6196 if (tabInfo.IsDefaultTabType)
6198 this.ProtectTabMenuItem.Enabled = false;
6199 this.ProtectTbMenuItem.Enabled = false;
6203 this.ProtectTabMenuItem.Enabled = true;
6204 this.ProtectTbMenuItem.Enabled = true;
6207 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6209 this.ProtectTabMenuItem.Checked = true;
6210 this.ProtectTbMenuItem.Checked = true;
6211 this.DeleteTabMenuItem.Enabled = false;
6212 this.DeleteTbMenuItem.Enabled = false;
6216 this.ProtectTabMenuItem.Checked = false;
6217 this.ProtectTbMenuItem.Checked = false;
6218 this.DeleteTabMenuItem.Enabled = true;
6219 this.DeleteTbMenuItem.Enabled = true;
6223 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6225 var checkState = ((ToolStripMenuItem)sender).Checked;
6228 this.ProtectTbMenuItem.Checked = checkState;
6229 this.ProtectTabMenuItem.Checked = checkState;
6232 this.DeleteTabMenuItem.Enabled = !checkState;
6233 this.DeleteTbMenuItem.Enabled = !checkState;
6235 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6236 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6238 this.SaveConfigsTabs();
6241 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6243 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6244 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6246 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6247 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6249 this.SaveConfigsTabs();
6252 public void ChangeTabUnreadManage(string tabName, bool isManage)
6254 var idx = this.GetTabPageIndex(tabName);
6258 var tab = this.statuses.Tabs[tabName];
6259 tab.UnreadManage = isManage;
6261 if (this.settings.Common.TabIconDisp)
6263 var tabPage = this.ListTab.TabPages[idx];
6264 if (tab.UnreadCount > 0)
6265 tabPage.ImageIndex = 0;
6267 tabPage.ImageIndex = -1;
6270 if (this.CurrentTabName == tabName)
6272 this.listCache?.PurgeCache();
6273 this.CurrentListView.Refresh();
6276 this.SetMainWindowTitle();
6277 this.SetStatusLabelUrl();
6278 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6281 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6283 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6284 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6286 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6288 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6290 this.SaveConfigsTabs();
6293 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6295 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6297 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6299 this.SaveConfigsTabs();
6302 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6304 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6305 this.rclickTabName = this.CurrentTabName;
6307 this.RemoveSpecifiedTab(this.rclickTabName, true);
6308 this.SaveConfigsTabs();
6311 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6313 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6315 using (var fltDialog = new FilterDialog())
6317 fltDialog.Owner = this;
6318 fltDialog.SetCurrent(this.rclickTabName);
6319 fltDialog.ShowDialog(this);
6321 this.TopMost = this.settings.Common.AlwaysTop;
6323 this.ApplyPostFilters();
6324 this.SaveConfigsTabs();
6327 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6329 string? tabName = null;
6330 MyCommon.TabUsageType tabUsage;
6331 using (var inputName = new InputTabName())
6333 inputName.TabName = this.statuses.MakeTabName("MyTab");
6334 inputName.IsShowUsage = true;
6335 inputName.ShowDialog();
6336 if (inputName.DialogResult == DialogResult.Cancel) return;
6337 tabName = inputName.TabName;
6338 tabUsage = inputName.Usage;
6340 this.TopMost = this.settings.Common.AlwaysTop;
6341 if (!MyCommon.IsNullOrEmpty(tabName))
6344 ListElement? list = null;
6345 if (tabUsage == MyCommon.TabUsageType.Lists)
6347 using var listAvail = new ListAvailable();
6348 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6350 if (listAvail.SelectedList == null)
6352 list = listAvail.SelectedList;
6358 case MyCommon.TabUsageType.UserDefined:
6359 tab = new FilterTabModel(tabName);
6361 case MyCommon.TabUsageType.PublicSearch:
6362 tab = new PublicSearchTabModel(tabName);
6364 case MyCommon.TabUsageType.Lists:
6365 tab = new ListTimelineTabModel(tabName, list!);
6371 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6373 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6374 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6379 this.SaveConfigsTabs();
6381 var tabIndex = this.statuses.Tabs.Count - 1;
6383 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6385 this.ListTab.SelectedIndex = tabIndex;
6386 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6388 if (tabUsage == MyCommon.TabUsageType.Lists)
6390 this.ListTab.SelectedIndex = tabIndex;
6391 await this.RefreshTabAsync(this.CurrentTab);
6397 private void TabMenuItem_Click(object sender, EventArgs e)
6400 foreach (var post in this.CurrentTab.SelectedPosts)
6403 if (!this.SelectTab(out var tab))
6406 using (var fltDialog = new FilterDialog())
6408 fltDialog.Owner = this;
6409 fltDialog.SetCurrent(tab.TabName);
6411 if (post.RetweetedBy == null)
6413 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6417 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6419 fltDialog.ShowDialog(this);
6422 this.TopMost = this.settings.Common.AlwaysTop;
6425 this.ApplyPostFilters();
6426 this.SaveConfigsTabs();
6429 protected override bool ProcessDialogKey(Keys keyData)
6431 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6432 if ((keyData & Keys.KeyCode) == Keys.Enter)
6434 if (this.StatusText.Focused)
6436 var newLine = false;
6439 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6441 if (this.StatusText.Multiline)
6443 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6445 if ((keyData & Keys.Control) == Keys.Control) post = true;
6449 if ((keyData & Keys.Control) == Keys.Control) post = true;
6452 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6454 if (this.StatusText.Multiline)
6456 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6458 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6462 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6467 if (this.StatusText.Multiline)
6469 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6471 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6472 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6476 if (((keyData & Keys.Shift) == Keys.Shift) ||
6477 (((keyData & Keys.Control) != Keys.Control) &&
6478 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6484 var pos1 = this.StatusText.SelectionStart;
6485 if (this.StatusText.SelectionLength > 0)
6487 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6489 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6490 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6495 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6501 var tab = this.CurrentTab;
6502 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6504 var tabPage = this.CurrentTabPage;
6505 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6506 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6508 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6515 return base.ProcessDialogKey(keyData);
6518 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6519 => this.MakeReplyText(atAll: true);
6521 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6523 var tab = this.CurrentTab;
6524 var selectedPosts = tab.SelectedPosts;
6527 if (selectedPosts.Length == 0)
6530 var screenNameArray = selectedPosts
6531 .Select(x => x.RetweetedBy ?? x.ScreenName)
6534 this.AddFilterRuleByScreenName(screenNameArray);
6536 if (screenNameArray.Length != 0)
6538 var atids = new List<string>();
6539 foreach (var screenName in screenNameArray)
6541 atids.Add("@" + screenName);
6543 var cnt = this.AtIdSupl.ItemCount;
6544 this.AtIdSupl.AddRangeItem(atids.ToArray());
6545 if (this.AtIdSupl.ItemCount != cnt)
6546 this.MarkSettingAtIdModified();
6550 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6552 var tab = this.CurrentTab;
6553 var selectedPosts = tab.SelectedPosts;
6555 if (selectedPosts.Length == 0)
6558 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6560 this.AddFilterRuleBySource(sourceArray);
6563 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6566 if (!this.SelectTab(out var tab)) return;
6570 if (tab.TabType != MyCommon.TabUsageType.Mute)
6572 this.MoveOrCopy(out mv, out mk);
6576 // ミュートタブでは常に MoveMatches を true にする
6581 foreach (var screenName in screenNameArray)
6583 tab.AddFilter(new PostFilterRule
6585 FilterName = screenName,
6586 UseNameField = true,
6590 FilterByUrl = false,
6594 this.ApplyPostFilters();
6595 this.SaveConfigsTabs();
6598 public void AddFilterRuleBySource(params string[] sourceArray)
6600 // タブ選択ダイアログを表示(or追加)
6601 if (!this.SelectTab(out var filterTab))
6606 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6608 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6609 this.MoveOrCopy(out mv, out mk);
6613 // ミュートタブでは常に MoveMatches を true にする
6618 // 振り分けルールに追加するSource
6619 foreach (var source in sourceArray)
6621 filterTab.AddFilter(new PostFilterRule
6623 FilterSource = source,
6627 FilterByUrl = false,
6631 this.ApplyPostFilters();
6632 this.SaveConfigsTabs();
6635 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6642 using (var dialog = new TabsDialog(this.statuses))
6644 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6646 tab = dialog.SelectedTab;
6649 this.CurrentTabPage.Focus();
6654 using (var inputName = new InputTabName())
6656 inputName.TabName = this.statuses.MakeTabName("MyTab");
6657 inputName.ShowDialog();
6658 if (inputName.DialogResult == DialogResult.Cancel) return false;
6659 tabName = inputName.TabName;
6661 this.TopMost = this.settings.Common.AlwaysTop;
6662 if (!MyCommon.IsNullOrEmpty(tabName))
6664 var newTab = new FilterTabModel(tabName);
6665 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6667 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6668 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6687 private void MoveOrCopy(out bool move, out bool mark)
6691 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6692 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6700 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6701 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6712 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6715 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6716 => this.CopyIdUri();
6718 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6720 if (this.StatusText.Focused)
6723 this.StatusText.SelectAll();
6727 // ListView上でのCtrl+A
6728 NativeMethods.SelectAllItems(this.CurrentListView);
6732 private void MoveMiddle()
6738 var listView = this.CurrentListView;
6739 if (listView.SelectedIndices.Count == 0) return;
6741 var idx = listView.SelectedIndices[0];
6743 item = listView.GetItemAt(0, 25);
6749 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6751 idx2 = listView.VirtualListSize - 1;
6755 idx -= Math.Abs(idx1 - idx2) / 2;
6756 if (idx < 0) idx = 0;
6758 listView.EnsureVisible(listView.VirtualListSize - 1);
6759 listView.EnsureVisible(idx);
6762 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6764 var linkElements = this.tweetDetailsView.GetLinkElements();
6766 if (linkElements.Length == 0)
6769 var links = new List<OpenUrlItem>(linkElements.Length);
6771 foreach (var linkElm in linkElements)
6773 var displayUrl = linkElm.GetAttribute("title");
6774 var href = linkElm.GetAttribute("href");
6775 var linkedText = linkElm.InnerText;
6777 if (MyCommon.IsNullOrEmpty(displayUrl))
6780 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6784 bool isReverseSettings;
6786 if (links.Count == 1)
6788 // ツイートに含まれる URL が 1 つのみの場合
6789 // => OpenURL ダイアログを表示せずにリンクを開く
6790 selectedUrl = links[0].Href;
6792 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6793 isReverseSettings = false;
6797 // ツイートに含まれる URL が複数ある場合
6798 // => OpenURL を表示しユーザーが選択したリンクを開く
6799 this.urlDialog.ClearUrl();
6801 foreach (var link in links)
6802 this.urlDialog.AddUrl(link);
6804 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6807 this.TopMost = this.settings.Common.AlwaysTop;
6809 selectedUrl = this.urlDialog.SelectedUrl;
6811 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6812 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6815 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6818 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6820 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6821 this.ClearTab(this.rclickTabName, true);
6824 private void ClearTab(string tabName, bool showWarning)
6828 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6829 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6835 this.statuses.ClearTabIds(tabName);
6836 if (this.CurrentTabName == tabName)
6838 this.CurrentTab.ClearAnchor();
6839 this.listCache?.PurgeCache();
6840 this.listCache?.UpdateListSize();
6843 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6844 var tabPage = this.ListTab.TabPages[tabIndex];
6845 tabPage.ImageIndex = -1;
6847 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6849 this.SetMainWindowTitle();
6850 this.SetStatusLabelUrl();
6853 private static long followers = 0;
6855 private void SetMainWindowTitle()
6857 // メインウインドウタイトルの書き換え
6858 var ttl = new StringBuilder(256);
6861 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6862 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6863 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6864 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6866 foreach (var tab in this.statuses.Tabs)
6868 ur += tab.UnreadCount;
6873 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6874 ttl.Append(ApplicationSettings.ApplicationName);
6876 switch (this.settings.Common.DispLatestPost)
6878 case MyCommon.DispTitleEnum.Ver:
6879 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6881 case MyCommon.DispTitleEnum.Post:
6882 if (this.history.Peek() is { } lastItem)
6883 ttl.Append(lastItem.Status.Replace("\r\n", " "));
6885 case MyCommon.DispTitleEnum.UnreadRepCount:
6886 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6888 case MyCommon.DispTitleEnum.UnreadAllCount:
6889 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6891 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6892 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6894 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6895 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6897 case MyCommon.DispTitleEnum.OwnStatus:
6898 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6899 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6905 this.Text = ttl.ToString();
6907 catch (AccessViolationException)
6909 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6913 private string GetStatusLabelText()
6916 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6917 if (this.statuses == null) return "";
6918 var tbRep = this.statuses.MentionTab;
6919 var tbDm = this.statuses.DirectMessageTab;
6920 if (tbRep == null || tbDm == null) return "";
6921 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6926 var slbl = new StringBuilder(256);
6929 foreach (var tab in this.statuses.Tabs)
6931 ur += tab.UnreadCount;
6933 if (tab.TabName == this.CurrentTabName)
6935 tur = tab.UnreadCount;
6945 this.unreadCounter = ur;
6946 this.unreadAtCounter = urat;
6948 var homeTab = this.statuses.HomeTab;
6950 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
6951 if (this.settings.Common.TimelinePeriod == 0)
6953 slbl.Append(Properties.Resources.SetStatusLabelText2);
6957 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
6959 return slbl.ToString();
6962 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
6966 if (this.InvokeRequired && !this.IsDisposed)
6968 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
6972 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
6973 this.SetApiStatusLabel(endpointName);
6976 catch (ObjectDisposedException)
6980 catch (InvalidOperationException)
6986 private void SetApiStatusLabel(string? endpointName = null)
6988 var tabType = this.CurrentTab.TabType;
6990 if (endpointName == null)
6992 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
6995 endpointName = tabType switch
6997 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
6998 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
6999 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7000 MyCommon.TabUsageType.Favorites => "/favorites/list",
7001 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7002 MyCommon.TabUsageType.UserTimeline =>
7003 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7004 MyCommon.TabUsageType.Lists =>
7005 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7006 MyCommon.TabUsageType.PublicSearch =>
7007 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7008 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7011 this.toolStripApiGauge.ApiEndpoint = endpointName;
7015 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7016 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7020 private void SetStatusLabelUrl()
7021 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7023 public void SetStatusLabel(string text)
7024 => this.StatusLabel.Text = text;
7026 private void SetNotifyIconText()
7028 var ur = new StringBuilder(64);
7030 // タスクトレイアイコンのツールチップテキスト書き換え
7032 ur.Remove(0, ur.Length);
7033 if (this.settings.Common.DispUsername)
7035 ur.Append(this.tw.Username);
7038 ur.Append(ApplicationSettings.ApplicationName);
7040 ur.Append("(Debug Build)");
7042 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7045 ur.Append(this.unreadCounter);
7047 ur.Append(this.unreadAtCounter);
7050 this.NotifyIcon1.Text = ur.ToString();
7053 internal void CheckReplyTo(string statusText)
7057 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7059 foreach (Match hm in m)
7061 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7063 hstr += "#" + hm.Result("$3") + " ";
7064 this.HashSupl.AddItem("#" + hm.Result("$3"));
7067 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7069 hstr += this.HashMgr.UseHash;
7071 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7073 // 本当にリプライ先指定すべきかどうかの判定
7074 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7076 if (this.settings.Common.UseAtIdSupplement)
7078 var bCnt = this.AtIdSupl.ItemCount;
7079 foreach (Match mid in m)
7081 this.AtIdSupl.AddItem(mid.Result("${id}"));
7083 if (bCnt != this.AtIdSupl.ItemCount)
7084 this.MarkSettingAtIdModified();
7087 // リプライ先ステータスIDの指定がない場合は指定しない
7088 if (this.inReplyTo == null)
7092 // 次の条件を満たす場合に in_reply_to_status_id 指定
7093 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7094 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7095 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7099 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7100 if (statusText.StartsWith("@", StringComparison.Ordinal))
7102 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7106 foreach (Match mid in m)
7108 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7113 this.inReplyTo = null;
7116 private void TweenMain_Resize(object sender, EventArgs e)
7118 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7120 this.Visible = false;
7122 if (this.WindowState != FormWindowState.Minimized)
7124 this.formWindowState = this.WindowState;
7128 private void ApplyLayoutFromSettings()
7130 // 現在の DPI と設定保存時の DPI との比を取得する
7131 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7133 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7136 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7137 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7138 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7140 this.SplitContainer1.SplitterDistance = splitterDistance;
7144 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7145 if (this.StatusText.Multiline)
7147 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7148 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7149 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7151 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7153 this.StatusText.Height = statusTextHeight;
7157 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7159 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7163 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7164 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7166 this.SplitContainer3.SplitterDistance = previewDistance;
7169 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7170 this.SplitContainer3.Panel2Collapsed = true;
7171 this.initialLayout = false;
7174 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7176 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7177 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7178 if (this.PlaySoundMenuItem.Checked)
7180 this.settings.Common.PlaySound = true;
7184 this.settings.Common.PlaySound = false;
7186 this.MarkSettingCommonModified();
7189 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7191 if (this.initialLayout)
7194 int splitterDistance;
7195 switch (this.WindowState)
7197 case FormWindowState.Normal:
7198 splitterDistance = this.SplitContainer1.SplitterDistance;
7200 case FormWindowState.Maximized:
7201 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7202 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7203 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7204 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7210 this.mySpDis = splitterDistance;
7211 this.MarkSettingLocalModified();
7214 private async Task DoRepliedStatusOpen()
7216 var currentPost = this.CurrentPost;
7217 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7219 if (MyCommon.IsKeyDown(Keys.Shift))
7221 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7224 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7226 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7230 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7232 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7233 repPost = tb.Posts[currentPost.InReplyToStatusId];
7234 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7237 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7242 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7243 => await this.DoRepliedStatusOpen();
7245 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7247 if (this.initialLayout)
7248 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7250 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7251 if (multiline != this.StatusText.Multiline)
7253 this.StatusText.Multiline = multiline;
7254 this.settings.Local.StatusMultiline = multiline;
7255 this.MarkSettingLocalModified();
7259 private void StatusText_MultilineChanged(object sender, EventArgs e)
7261 if (this.StatusText.Multiline)
7262 this.StatusText.ScrollBars = ScrollBars.Vertical;
7264 this.StatusText.ScrollBars = ScrollBars.None;
7266 if (!this.initialLayout)
7267 this.MarkSettingLocalModified();
7270 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7273 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7274 this.StatusText.Multiline = menuItemChecked;
7275 this.settings.Local.StatusMultiline = menuItemChecked;
7276 if (menuItemChecked)
7278 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7279 this.SplitContainer2.SplitterDistance = 0;
7281 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7285 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7287 this.MarkSettingLocalModified();
7290 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7292 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7294 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7295 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7296 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7298 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7303 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7304 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7305 // Appendix A. Collected ABNF for URI
7306 // http://www.ietf.org/rfc/rfc3986.txt
7308 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7311 if (this.StatusText.SelectionLength > 0)
7313 var tmp = this.StatusText.SelectedText;
7314 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7315 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7317 // 文字列が選択されている場合はその文字列について処理
7319 // nico.ms使用、nicovideoにマッチしたら変換
7320 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7322 result = Nicoms.Shorten(tmp);
7324 else if (converterType != MyCommon.UrlConverter.Nicoms)
7329 var srcUri = new Uri(tmp);
7330 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7331 result = resultUri.AbsoluteUri;
7333 catch (WebApiException e)
7335 this.StatusLabel.Text = converterType + ":" + e.Message;
7338 catch (UriFormatException e)
7340 this.StatusLabel.Text = converterType + ":" + e.Message;
7349 if (!MyCommon.IsNullOrEmpty(result))
7351 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7352 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7353 if (origUrlIndex == -1)
7356 this.StatusText.Select(origUrlIndex, tmp.Length);
7357 this.StatusText.SelectedText = result;
7360 var undo = new UrlUndo
7366 if (this.urlUndoBuffer == null)
7368 this.urlUndoBuffer = new List<UrlUndo>();
7369 this.UrlUndoToolStripMenuItem.Enabled = true;
7372 this.urlUndoBuffer.Add(undo);
7378 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7379 @"(?<url>(?<protocol>https?://)" +
7380 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7381 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7382 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7383 // 正規表現にマッチしたURL文字列をtinyurl化
7384 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7386 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7388 var tmp = mt.Result("${url}");
7389 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7390 tmp = "http://" + tmp;
7393 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7395 // nico.ms使用、nicovideoにマッチしたら変換
7396 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7398 result = Nicoms.Shorten(tmp);
7400 else if (converterType != MyCommon.UrlConverter.Nicoms)
7405 var srcUri = new Uri(tmp);
7406 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7407 result = resultUri.AbsoluteUri;
7409 catch (HttpRequestException e)
7411 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7412 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7413 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7415 this.StatusLabel.Text = converterType + ":" + message;
7418 catch (WebApiException e)
7420 this.StatusLabel.Text = converterType + ":" + e.Message;
7423 catch (UriFormatException e)
7425 this.StatusLabel.Text = converterType + ":" + e.Message;
7434 if (!MyCommon.IsNullOrEmpty(result))
7436 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7437 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7438 if (origUrlIndex == -1)
7441 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7442 this.StatusText.SelectedText = result;
7444 var undo = new UrlUndo
7446 Before = mt.Result("${url}"),
7450 if (this.urlUndoBuffer == null)
7452 this.urlUndoBuffer = new List<UrlUndo>();
7453 this.UrlUndoToolStripMenuItem.Enabled = true;
7456 this.urlUndoBuffer.Add(undo);
7464 private void DoUrlUndo()
7466 if (this.urlUndoBuffer != null)
7468 var tmp = this.StatusText.Text;
7469 foreach (var data in this.urlUndoBuffer)
7471 tmp = tmp.Replace(data.After, data.Before);
7473 this.StatusText.Text = tmp;
7474 this.urlUndoBuffer = null;
7475 this.UrlUndoToolStripMenuItem.Enabled = false;
7476 this.StatusText.SelectionStart = 0;
7477 this.StatusText.SelectionLength = 0;
7481 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7482 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7484 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7485 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7487 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7488 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7490 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7492 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7494 var rnd = new Random();
7496 MyCommon.UrlConverter svc;
7497 // 前回使用した短縮URLサービス以外を選択する
7500 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7502 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7503 await this.UrlConvertAsync(svc);
7507 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7508 => this.DoUrlUndo();
7510 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7512 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7513 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7514 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7515 this.MarkSettingCommonModified();
7518 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7520 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7521 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7522 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7523 this.MarkSettingCommonModified();
7526 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7528 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7529 this.MenuStrip1.Tag = new object();
7530 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7533 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7535 var currentTabPage = this.CurrentTabPage;
7536 if (this.Tag != null) // 設定された戻り先へ遷移
7538 if (this.Tag == currentTabPage)
7539 ((Control)currentTabPage.Tag).Select();
7541 ((Control)this.Tag).Select();
7543 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7545 this.Tag = currentTabPage.Tag;
7546 ((Control)this.Tag).Select();
7548 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7549 this.MenuStrip1.Tag = null;
7552 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7554 if (this.Use2ColumnsMode)
7560 var lst = (DetailsListView)sender;
7561 var columnsCount = lst.Columns.Count;
7563 var darr = new int[columnsCount];
7564 for (var i = 0; i < columnsCount; i++)
7565 darr[lst.Columns[i].DisplayIndex] = i;
7567 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7569 for (var i = 0; i < columnsCount; i++)
7570 this.settings.Local.ColumnsOrder[darr[i]] = i;
7572 this.MarkSettingLocalModified();
7573 this.isColumnChanged = true;
7576 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7578 var lst = (DetailsListView)sender;
7579 if (this.settings.Local == null) return;
7581 var modified = false;
7582 if (this.Use2ColumnsMode)
7584 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7586 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7589 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7591 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7597 var columnsCount = lst.Columns.Count;
7598 for (var i = 0; i < columnsCount; i++)
7600 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7603 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7609 this.MarkSettingLocalModified();
7610 this.isColumnChanged = true;
7614 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7616 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7617 this.MarkSettingLocalModified();
7620 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7622 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7624 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7626 this.SelectMedia_DragDrop(e);
7629 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7631 var (url, title) = GetUrlFromDataObject(e.Data);
7637 appendText = title + " " + url;
7639 if (this.StatusText.TextLength == 0)
7640 this.StatusText.Text = appendText;
7642 this.StatusText.Text += " " + appendText;
7644 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7646 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7648 this.StatusText.Text += text;
7650 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7652 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7653 if (data != null) this.StatusText.Text += data;
7658 /// IDataObject から URL とタイトルの対を取得します
7661 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7663 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7664 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7665 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7667 if (data.GetDataPresent("text/x-moz-url"))
7669 // Firefox, Google Chrome で利用可能
7670 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7672 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7673 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7674 if (lines.Length < 2)
7675 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7677 return (lines[0], lines[1]);
7679 else if (data.GetDataPresent("IESiteModeToUrl"))
7681 // Internet Exproler 用
7682 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7684 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7685 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7686 if (lines.Length < 2)
7687 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7689 return (lines[0], lines[1]);
7691 else if (data.GetDataPresent("UniformResourceLocatorW"))
7695 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7696 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7700 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7703 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7705 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7707 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7709 this.SelectMedia_DragEnter(e);
7713 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7715 e.Effect = DragDropEffects.Copy;
7718 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7720 e.Effect = DragDropEffects.Copy;
7723 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7725 e.Effect = DragDropEffects.Copy;
7729 e.Effect = DragDropEffects.None;
7732 private void TweenMain_DragOver(object sender, DragEventArgs e)
7736 public bool IsNetworkAvailable()
7738 var nw = MyCommon.IsNetworkAvailable();
7739 this.myStatusOnline = nw;
7743 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7745 var uriStr = uri.AbsoluteUri;
7747 // OpenTween 内部で使用する URL
7748 if (uri.Authority == "opentween")
7750 await this.OpenInternalUriAsync(uri);
7754 // ハッシュタグを含む Twitter 検索
7755 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7758 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7759 var pos = unescapedQuery.IndexOf('#');
7760 if (pos == -1) return;
7762 var hash = unescapedQuery.Substring(pos);
7763 this.HashSupl.AddItem(hash);
7764 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7765 this.AddNewTabForSearch(hash);
7770 // フラグが立っている場合は設定と逆の動作をする
7771 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7772 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7774 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7775 if (userUriMatch.Success)
7777 var screenName = userUriMatch.Groups["ScreenName"].Value;
7778 if (this.IsTwitterId(screenName))
7780 await this.AddNewTabForUserTimeline(screenName);
7787 await MyCommon.OpenInBrowserAsync(this, uriStr);
7791 /// OpenTween 内部の機能を呼び出すための URL を開きます
7793 private async Task OpenInternalUriAsync(Uri uri)
7795 // ツイートを開く (//opentween/status/:status_id)
7796 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7799 var statusId = new TwitterStatusId(match.Groups[1].Value);
7800 await this.OpenRelatedTab(statusId);
7805 private void ListTabSelect(TabPage tabPage)
7807 this.SetListProperty();
7809 var previousTabName = this.CurrentTabName;
7810 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7811 previousListViewState.Save(this.ListLockMenuItem.Checked);
7813 this.listCache?.PurgeCache();
7815 this.statuses.SelectTab(tabPage.Text);
7817 this.InitializeTimelineListView();
7819 var tab = this.CurrentTab;
7822 var listView = this.CurrentListView;
7824 var currentListViewState = this.listViewState[tab.TabName];
7825 currentListViewState.Restore(forceScroll: true);
7827 if (this.Use2ColumnsMode)
7829 listView.Columns[1].Text = this.columnText[2];
7833 for (var i = 0; i < listView.Columns.Count; i++)
7835 listView.Columns[i].Text = this.columnText[i];
7840 private void InitializeTimelineListView()
7842 var listView = this.CurrentListView;
7843 var tab = this.CurrentTab;
7845 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7846 (this.listCache, var oldCache) = (newCache, this.listCache);
7847 oldCache?.Dispose();
7849 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7850 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7851 oldDrawer?.Dispose();
7853 newDrawer.IconSize = this.settings.Common.IconSize;
7854 newDrawer.UpdateItemHeight();
7857 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7858 => this.ListTabSelect(e.TabPage);
7860 private void SelectListItem(DetailsListView lView, int index)
7863 var bnd = new Rectangle();
7865 var item = lView.FocusedItem;
7874 lView.SelectedIndices.Clear();
7876 while (lView.SelectedIndices.Count > 0);
7877 item = lView.Items[index];
7878 item.Selected = true;
7879 item.Focused = true;
7881 if (flg) lView.Invalidate(bnd);
7884 private async void TweenMain_Shown(object sender, EventArgs e)
7886 this.NotifyIcon1.Visible = true;
7889 if (this.settings.IsFirstRun)
7891 // 初回起動時だけ右下のメニューを目立たせる
7892 this.HashStripSplitButton.ShowDropDown();
7895 if (this.IsNetworkAvailable())
7897 var loadTasks = new TaskCollection();
7901 this.RefreshMuteUserIdsAsync,
7902 this.RefreshBlockIdsAsync,
7903 this.RefreshNoRetweetIdsAsync,
7904 this.RefreshTwitterConfigurationAsync,
7905 this.RefreshTabAsync<HomeTabModel>,
7906 this.RefreshTabAsync<MentionsTabModel>,
7907 this.RefreshTabAsync<DirectMessagesTabModel>,
7908 this.RefreshTabAsync<PublicSearchTabModel>,
7909 this.RefreshTabAsync<UserTimelineTabModel>,
7910 this.RefreshTabAsync<ListTimelineTabModel>,
7913 if (this.settings.Common.StartupFollowers)
7914 loadTasks.Add(this.RefreshFollowerIdsAsync);
7916 if (this.settings.Common.GetFav)
7917 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7919 var allTasks = loadTasks.RunAll();
7924 var timeout = Task.Delay(5000);
7925 if (await Task.WhenAny(allTasks, timeout) != timeout)
7929 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7931 if (MyCommon.EndingFlag)
7935 if (MyCommon.EndingFlag) return;
7937 if (ApplicationSettings.VersionInfoUrl != null)
7939 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7940 if (this.settings.Common.StartupVersion)
7941 await this.CheckNewVersion(true);
7945 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
7946 this.VerUpMenuItem.Enabled = false;
7947 this.VerUpMenuItem.Available = false;
7948 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
7951 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
7952 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
7954 MessageBox.Show(Properties.Resources.ReAuthorizeText);
7955 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
7959 var reloadTasks = new TaskCollection();
7961 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
7962 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
7964 if (!this.tw.GetNoRetweetSuccess)
7965 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
7967 if (this.tw.Configuration.PhotoSizeLimit == 0)
7968 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
7970 await reloadTasks.RunAll();
7973 this.initial = false;
7976 private void StartTimers()
7978 if (!this.StopRefreshAllMenuItem.Checked)
7979 this.timelineScheduler.Enabled = true;
7981 this.selectionDebouncer.Enabled = true;
7982 this.saveConfigDebouncer.Enabled = true;
7983 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
7986 private async Task DoGetFollowersMenu()
7988 await this.RefreshFollowerIdsAsync();
7989 this.DispSelectedPost(true);
7992 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
7993 => await this.DoGetFollowersMenu();
7995 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
7996 => this.DoReTweetUnofficial();
7998 private async Task DoReTweetOfficial(bool isConfirm)
8001 if (this.ExistCurrentPost)
8003 var selectedPosts = this.CurrentTab.SelectedPosts;
8005 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8007 if (selectedPosts.Any(x => x.IsProtect))
8008 MessageBox.Show("Protected.");
8010 this.doFavRetweetFlags = false;
8014 if (selectedPosts.Length > 15)
8016 MessageBox.Show(Properties.Resources.RetweetLimitText);
8017 this.doFavRetweetFlags = false;
8020 else if (selectedPosts.Length > 1)
8022 var questionText = Properties.Resources.RetweetQuestion2;
8023 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8024 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8026 case DialogResult.Cancel:
8027 case DialogResult.No:
8028 this.doFavRetweetFlags = false;
8034 if (!this.settings.Common.RetweetNoConfirm)
8036 var questiontext = Properties.Resources.RetweetQuestion1;
8037 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8038 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8040 this.doFavRetweetFlags = false;
8046 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8048 await this.RetweetAsync(statusIds);
8052 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8053 => await this.DoReTweetOfficial(true);
8055 private async Task FavoritesRetweetOfficial()
8057 if (!this.ExistCurrentPost) return;
8058 this.doFavRetweetFlags = true;
8060 var tasks = new TaskCollection();
8061 tasks.Add(() => this.DoReTweetOfficial(true));
8063 if (this.doFavRetweetFlags)
8065 this.doFavRetweetFlags = false;
8066 tasks.Add(() => this.FavoriteChange(true, false));
8069 await tasks.RunAll();
8072 private async Task FavoritesRetweetUnofficial()
8074 var post = this.CurrentPost;
8075 if (this.ExistCurrentPost && post != null && !post.IsDm)
8077 this.doFavRetweetFlags = true;
8078 var favoriteTask = this.FavoriteChange(true);
8079 if (!post.IsProtect && this.doFavRetweetFlags)
8081 this.doFavRetweetFlags = false;
8082 this.DoReTweetUnofficial();
8090 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8092 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8093 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8094 /// <returns>復元されたツイート本文</returns>
8095 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8097 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8100 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8102 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8104 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8106 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8110 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8112 statusHtml = statusHtml.Replace("<br>", " ");
8114 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8115 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8116 statusHtml = statusHtml.Replace(" ", " ");
8118 return WebUtility.HtmlDecode(statusHtml);
8121 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8123 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8125 if (this.CurrentPost != null)
8126 this.DispSelectedPost(true);
8129 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8131 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8132 this.DebugModeToolStripMenuItem.Visible = true;
8134 this.DebugModeToolStripMenuItem.Visible = false;
8137 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8138 => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8140 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8141 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8143 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8144 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8146 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8148 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8149 this.MarkSettingCommonModified();
8152 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8154 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8155 this.MarkSettingCommonModified();
8158 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8160 this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8161 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8162 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8163 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8164 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8165 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8168 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8170 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8171 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8172 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8173 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8174 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8175 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8178 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8180 if (this.TraceOutToolStripMenuItem.Checked)
8181 MyCommon.TraceFlag = true;
8183 MyCommon.TraceFlag = false;
8186 private void TweenMain_Deactivate(object sender, EventArgs e)
8187 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8189 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8191 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8193 _ = this.TabRename(this.rclickTabName, out _);
8196 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8197 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8199 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8200 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8202 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8204 TwitterApiStatus? apiStatus;
8206 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8208 var cancellationToken = dialog.EnableCancellation();
8212 var task = this.tw.GetInfoApi();
8213 apiStatus = await dialog.WaitForAsync(this, task);
8215 catch (WebApiException)
8220 if (cancellationToken.IsCancellationRequested)
8223 if (apiStatus == null)
8225 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8230 using var apiDlg = new ApiInfoDialog();
8231 apiDlg.ShowDialog(this);
8234 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8236 var id = this.CurrentPost?.ScreenName ?? "";
8238 await this.FollowCommand(id);
8241 internal async Task FollowCommand(string id)
8243 using (var inputName = new InputTabName())
8245 inputName.FormTitle = "Follow";
8246 inputName.FormDescription = Properties.Resources.FRMessage1;
8247 inputName.TabName = id;
8249 if (inputName.ShowDialog(this) != DialogResult.OK)
8251 if (string.IsNullOrWhiteSpace(inputName.TabName))
8254 id = inputName.TabName.Trim();
8257 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8261 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8262 await dialog.WaitForAsync(this, task);
8264 catch (WebApiException ex)
8266 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8271 MessageBox.Show(Properties.Resources.FRMessage3);
8274 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8276 var id = this.CurrentPost?.ScreenName ?? "";
8278 await this.RemoveCommand(id, false);
8281 internal async Task RemoveCommand(string id, bool skipInput)
8285 using var inputName = new InputTabName();
8286 inputName.FormTitle = "Unfollow";
8287 inputName.FormDescription = Properties.Resources.FRMessage1;
8288 inputName.TabName = id;
8290 if (inputName.ShowDialog(this) != DialogResult.OK)
8292 if (string.IsNullOrWhiteSpace(inputName.TabName))
8295 id = inputName.TabName.Trim();
8298 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8302 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8303 await dialog.WaitForAsync(this, task);
8305 catch (WebApiException ex)
8307 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8312 MessageBox.Show(Properties.Resources.FRMessage3);
8315 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8317 var id = this.CurrentPost?.ScreenName ?? "";
8319 await this.ShowFriendship(id);
8322 internal async Task ShowFriendship(string id)
8324 using (var inputName = new InputTabName())
8326 inputName.FormTitle = "Show Friendships";
8327 inputName.FormDescription = Properties.Resources.FRMessage1;
8328 inputName.TabName = id;
8330 if (inputName.ShowDialog(this) != DialogResult.OK)
8332 if (string.IsNullOrWhiteSpace(inputName.TabName))
8335 id = inputName.TabName.Trim();
8338 bool isFollowing, isFollowed;
8340 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8342 var cancellationToken = dialog.EnableCancellation();
8346 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8347 var friendship = await dialog.WaitForAsync(this, task);
8349 isFollowing = friendship.Relationship.Source.Following;
8350 isFollowed = friendship.Relationship.Source.FollowedBy;
8352 catch (WebApiException ex)
8354 if (!cancellationToken.IsCancellationRequested)
8355 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8359 if (cancellationToken.IsCancellationRequested)
8366 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8370 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8374 result += Properties.Resources.GetFriendshipInfo3;
8378 result += Properties.Resources.GetFriendshipInfo4;
8380 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8381 MessageBox.Show(result);
8384 internal async Task ShowFriendship(string[] ids)
8386 foreach (var id in ids)
8388 bool isFollowing, isFollowed;
8390 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8392 var cancellationToken = dialog.EnableCancellation();
8396 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8397 var friendship = await dialog.WaitForAsync(this, task);
8399 isFollowing = friendship.Relationship.Source.Following;
8400 isFollowed = friendship.Relationship.Source.FollowedBy;
8402 catch (WebApiException ex)
8404 if (!cancellationToken.IsCancellationRequested)
8405 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8409 if (cancellationToken.IsCancellationRequested)
8419 ff += Properties.Resources.GetFriendshipInfo1;
8423 ff += Properties.Resources.GetFriendshipInfo2;
8426 ff += System.Environment.NewLine + " ";
8429 ff += Properties.Resources.GetFriendshipInfo3;
8433 ff += Properties.Resources.GetFriendshipInfo4;
8435 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8438 if (MessageBox.Show(
8439 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8440 Properties.Resources.GetFriendshipInfo8,
8441 MessageBoxButtons.YesNo,
8442 MessageBoxIcon.Question,
8443 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8445 await this.RemoveCommand(id, true);
8450 MessageBox.Show(result);
8455 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8456 => await this.DoShowUserStatus(this.tw.Username, false);
8458 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8461 public bool IsTwitterId(string name)
8463 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8464 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8466 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8469 private void DoQuoteOfficial()
8471 var post = this.CurrentPost;
8472 if (this.ExistCurrentPost && post != null)
8474 if (post.IsDm || !this.StatusText.Enabled)
8479 MessageBox.Show("Protected.");
8483 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8485 this.inReplyTo = null;
8487 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8489 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8490 this.StatusText.Focus();
8494 private void DoReTweetUnofficial()
8497 var post = this.CurrentPost;
8498 if (this.ExistCurrentPost && post != null)
8500 if (post.IsDm || !this.StatusText.Enabled)
8505 MessageBox.Show("Protected.");
8508 var rtdata = post.Text;
8509 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8511 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8513 // 投稿時に in_reply_to_status_id を付加する
8514 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8515 var inReplyToScreenName = post.ScreenName;
8516 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8518 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8520 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8521 this.StatusText.Focus();
8525 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8526 => this.DoQuoteOfficial();
8528 private async void SearchButton_Click(object sender, EventArgs e)
8531 var pnl = ((Control)sender).Parent;
8532 if (pnl == null) return;
8533 var tbName = pnl.Parent.Text;
8534 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8535 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8536 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8537 cmb.Text = cmb.Text.Trim();
8538 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8540 var buf = new StringBuilder();
8541 var c = cmb.Text.ToCharArray();
8542 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8544 if (cnt > cmb.Text.Length - 4)
8546 buf.Append(cmb.Text.Substring(cnt));
8555 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8564 cmb.Text = buf.ToString();
8566 var listView = (DetailsListView)pnl.Parent.Tag;
8568 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8570 tb.SearchWords = cmb.Text;
8571 tb.SearchLang = cmbLang.Text;
8572 if (MyCommon.IsNullOrEmpty(cmb.Text))
8575 this.SaveConfigsTabs();
8580 var idx = cmb.Items.IndexOf(tb.SearchWords);
8581 if (idx > -1) cmb.Items.RemoveAt(idx);
8582 cmb.Items.Insert(0, tb.SearchWords);
8583 cmb.Text = tb.SearchWords;
8585 this.statuses.ClearTabIds(tbName);
8586 this.listCache?.PurgeCache();
8587 this.listCache?.UpdateListSize();
8588 this.SaveConfigsTabs(); // 検索条件の保存
8592 await this.RefreshTabAsync(tb);
8595 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8596 => await this.DoRefreshMore(); // もっと前を取得
8599 /// 指定されたタブのListTabにおける位置を返します
8602 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8604 public int GetTabPageIndex(string tabName)
8605 => this.statuses.Tabs.IndexOf(tabName);
8607 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8611 var restoredTab = this.statuses.UndoRemovedTab();
8612 this.AddNewTab(restoredTab, startup: false);
8614 var tabIndex = this.statuses.Tabs.Count - 1;
8615 this.ListTab.SelectedIndex = tabIndex;
8617 this.SaveConfigsTabs();
8619 catch (TabException ex)
8621 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8625 private async Task DoMoveToRTHome()
8627 var post = this.CurrentPost;
8628 if (post != null && post.RetweetedId != null)
8629 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8632 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8633 => await this.DoMoveToRTHome();
8635 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8637 var screenName = this.CurrentPost?.ScreenName;
8638 if (screenName != null)
8639 this.ListManageUserContext(screenName);
8642 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8644 var screenName = this.CurrentPost?.RetweetedBy;
8645 if (screenName != null)
8646 this.ListManageUserContext(screenName);
8649 public void ListManageUserContext(string screenName)
8651 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8652 listSelectForm.ShowDialog(this);
8655 private void SearchControls_Enter(object sender, EventArgs e)
8657 var pnl = (Control)sender;
8658 foreach (Control ctl in pnl.Controls)
8664 private void SearchControls_Leave(object sender, EventArgs e)
8666 var pnl = (Control)sender;
8667 foreach (Control ctl in pnl.Controls)
8669 ctl.TabStop = false;
8673 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8675 var tab = this.CurrentTab;
8676 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8677 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8680 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8681 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8683 private void HashManageMenuItem_Click(object sender, EventArgs e)
8688 rslt = this.HashMgr.ShowDialog();
8694 this.TopMost = this.settings.Common.AlwaysTop;
8695 if (rslt == DialogResult.Cancel) return;
8696 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8698 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8699 this.HashTogglePullDownMenuItem.Checked = true;
8700 this.HashToggleMenuItem.Checked = true;
8704 this.HashStripSplitButton.Text = "#[-]";
8705 this.HashTogglePullDownMenuItem.Checked = false;
8706 this.HashToggleMenuItem.Checked = false;
8709 this.MarkSettingCommonModified();
8710 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8713 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8715 this.HashMgr.ToggleHash();
8716 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8718 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8719 this.HashToggleMenuItem.Checked = true;
8720 this.HashTogglePullDownMenuItem.Checked = true;
8724 this.HashStripSplitButton.Text = "#[-]";
8725 this.HashToggleMenuItem.Checked = false;
8726 this.HashTogglePullDownMenuItem.Checked = false;
8728 this.MarkSettingCommonModified();
8729 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8732 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8733 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8735 public void SetPermanentHashtag(string hashtag)
8737 this.HashMgr.SetPermanentHash("#" + hashtag);
8738 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8739 this.HashTogglePullDownMenuItem.Checked = true;
8740 this.HashToggleMenuItem.Checked = true;
8742 this.MarkSettingCommonModified();
8745 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8747 var tab = this.CurrentTab;
8748 var post = this.CurrentPost;
8749 if (!this.ExistCurrentPost)
8751 this.ReplyOpMenuItem.Enabled = false;
8752 this.ReplyAllOpMenuItem.Enabled = false;
8753 this.DmOpMenuItem.Enabled = false;
8754 this.CreateTabRuleOpMenuItem.Enabled = false;
8755 this.CreateIdRuleOpMenuItem.Enabled = false;
8756 this.CreateSourceRuleOpMenuItem.Enabled = false;
8757 this.ReadOpMenuItem.Enabled = false;
8758 this.UnreadOpMenuItem.Enabled = false;
8759 this.AuthorMenuItem.Visible = false;
8760 this.RetweetedByMenuItem.Visible = false;
8764 this.ReplyOpMenuItem.Enabled = true;
8765 this.ReplyAllOpMenuItem.Enabled = true;
8766 this.DmOpMenuItem.Enabled = true;
8767 this.CreateTabRuleOpMenuItem.Enabled = true;
8768 this.CreateIdRuleOpMenuItem.Enabled = true;
8769 this.CreateSourceRuleOpMenuItem.Enabled = true;
8770 this.ReadOpMenuItem.Enabled = true;
8771 this.UnreadOpMenuItem.Enabled = true;
8772 this.AuthorMenuItem.Visible = true;
8773 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8774 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8775 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8778 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8780 this.FavOpMenuItem.Enabled = false;
8781 this.UnFavOpMenuItem.Enabled = false;
8782 this.OpenStatusOpMenuItem.Enabled = false;
8783 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8784 this.RtOpMenuItem.Enabled = false;
8785 this.RtUnOpMenuItem.Enabled = false;
8786 this.QtOpMenuItem.Enabled = false;
8787 this.FavoriteRetweetMenuItem.Enabled = false;
8788 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8792 this.FavOpMenuItem.Enabled = true;
8793 this.UnFavOpMenuItem.Enabled = true;
8794 this.OpenStatusOpMenuItem.Enabled = true;
8795 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8797 if (!post.CanRetweetBy(this.tw.UserId))
8799 this.RtOpMenuItem.Enabled = false;
8800 this.RtUnOpMenuItem.Enabled = false;
8801 this.QtOpMenuItem.Enabled = false;
8802 this.FavoriteRetweetMenuItem.Enabled = false;
8803 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8807 this.RtOpMenuItem.Enabled = true;
8808 this.RtUnOpMenuItem.Enabled = true;
8809 this.QtOpMenuItem.Enabled = true;
8810 this.FavoriteRetweetMenuItem.Enabled = true;
8811 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8815 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8817 this.RefreshPrevOpMenuItem.Enabled = true;
8821 this.RefreshPrevOpMenuItem.Enabled = false;
8823 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8825 this.OpenRepSourceOpMenuItem.Enabled = false;
8829 this.OpenRepSourceOpMenuItem.Enabled = true;
8832 if (this.ExistCurrentPost && post != null)
8834 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8838 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8839 => this.ContextMenuTabProperty_Opening(sender, null!);
8841 public Twitter TwitterInstance
8844 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8846 if (this.initialLayout)
8849 int splitterDistance;
8850 switch (this.WindowState)
8852 case FormWindowState.Normal:
8853 splitterDistance = this.SplitContainer3.SplitterDistance;
8855 case FormWindowState.Maximized:
8856 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8857 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8858 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8859 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8865 this.mySpDis3 = splitterDistance;
8866 this.MarkSettingLocalModified();
8869 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8871 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8873 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8874 this.PublicSearchQueryMenuItem.Enabled = true;
8876 this.PublicSearchQueryMenuItem.Enabled = false;
8878 var post = this.CurrentPost;
8879 if (!this.ExistCurrentPost || post == null)
8881 this.CopySTOTMenuItem.Enabled = false;
8882 this.CopyURLMenuItem.Enabled = false;
8883 this.CopyUserIdStripMenuItem.Enabled = false;
8887 this.CopySTOTMenuItem.Enabled = true;
8888 this.CopyURLMenuItem.Enabled = true;
8889 this.CopyUserIdStripMenuItem.Enabled = true;
8891 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8892 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8896 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8897 => this.SetNotifyIconText();
8899 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8900 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8902 private async Task DoShowUserStatus(string id, bool showInputDialog)
8904 TwitterUser? user = null;
8906 if (showInputDialog)
8908 using var inputName = new InputTabName();
8909 inputName.FormTitle = "Show UserStatus";
8910 inputName.FormDescription = Properties.Resources.FRMessage1;
8911 inputName.TabName = id;
8913 if (inputName.ShowDialog(this) != DialogResult.OK)
8915 if (string.IsNullOrWhiteSpace(inputName.TabName))
8918 id = inputName.TabName.Trim();
8921 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8923 var cancellationToken = dialog.EnableCancellation();
8927 var task = this.tw.GetUserInfo(id);
8928 user = await dialog.WaitForAsync(this, task);
8930 catch (WebApiException ex)
8932 if (!cancellationToken.IsCancellationRequested)
8933 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8937 if (cancellationToken.IsCancellationRequested)
8941 await this.DoShowUserStatus(user);
8944 private async Task DoShowUserStatus(TwitterUser user)
8946 using var userDialog = new UserInfoDialog(this, this.tw.Api, this.detailsHtmlBuilder);
8947 var showUserTask = userDialog.ShowUserAsync(user);
8948 userDialog.ShowDialog(this);
8951 this.BringToFront();
8953 // ユーザー情報の表示が完了するまで userDialog を破棄しない
8957 internal Task ShowUserStatus(string id, bool showInputDialog)
8958 => this.DoShowUserStatus(id, showInputDialog);
8960 internal Task ShowUserStatus(string id)
8961 => this.DoShowUserStatus(id, true);
8963 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
8965 var post = this.CurrentPost;
8968 await this.ShowUserStatus(post.ScreenName, false);
8972 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
8974 var retweetedBy = this.CurrentPost?.RetweetedBy;
8975 if (retweetedBy != null)
8977 await this.ShowUserStatus(retweetedBy, false);
8981 private async void RtCountMenuItem_Click(object sender, EventArgs e)
8983 var post = this.CurrentPost;
8984 if (!this.ExistCurrentPost || post == null)
8987 var statusId = post.RetweetedId ?? post.StatusId;
8988 TwitterStatus status;
8990 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
8992 var cancellationToken = dialog.EnableCancellation();
8996 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
8997 status = await dialog.WaitForAsync(this, task);
8999 catch (WebApiException ex)
9001 if (!cancellationToken.IsCancellationRequested)
9002 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9006 if (cancellationToken.IsCancellationRequested)
9010 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9013 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9015 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9018 this.Visible = false;
9020 else if (Form.ActiveForm == null)
9022 this.Visible = true;
9023 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9025 this.BringToFront();
9026 this.StatusText.Focus();
9030 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9031 => this.MultiLinePullDownMenuItem.PerformClick();
9034 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9036 if (this.ImageSelector.Visible)
9037 this.ImageSelector.EndSelection();
9039 this.ImageSelector.BeginSelection();
9042 private void SelectMedia_DragEnter(DragEventArgs e)
9044 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9046 e.Effect = DragDropEffects.Copy;
9049 e.Effect = DragDropEffects.None;
9052 private void SelectMedia_DragDrop(DragEventArgs e)
9055 this.BringToFront();
9057 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9058 this.ImageSelector.BeginSelection();
9059 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9060 this.StatusText.Focus();
9063 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9065 this.TimelinePanel.Visible = false;
9066 this.TimelinePanel.Enabled = false;
9069 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9071 this.TimelinePanel.Visible = true;
9072 this.TimelinePanel.Enabled = true;
9073 this.CurrentListView.Focus();
9076 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9077 => this.AllowDrop = false;
9079 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9080 => this.AllowDrop = true;
9082 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9084 if (this.ImageSelector.Visible)
9086 this.MarkSettingCommonModified();
9087 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9091 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9092 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9095 /// StatusTextでCtrl+Vが押下された時の処理
9097 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9101 if (Clipboard.ContainsText())
9103 // clipboardにテキストがある場合は貼り付け処理
9104 this.StatusText.Paste(Clipboard.GetText());
9106 else if (Clipboard.ContainsImage())
9109 using var image = Clipboard.GetImage();
9110 this.ImageSelector.BeginSelection();
9111 this.ImageSelector.Model.AddMediaItemFromImage(image);
9113 else if (Clipboard.ContainsFileDropList())
9115 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9116 this.ImageSelector.BeginSelection();
9117 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9120 catch (ExternalException ex)
9122 MessageBox.Show(ex.Message);
9127 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9129 using var form = new ListManage(this.tw);
9130 form.ShowDialog(this);
9133 private bool ModifySettingCommon { get; set; }
9135 private bool ModifySettingLocal { get; set; }
9137 private bool ModifySettingAtId { get; set; }
9139 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9141 var post = this.CurrentPost;
9142 if (this.ExistCurrentPost && post != null && !post.IsDm)
9143 this.RtCountMenuItem.Enabled = true;
9145 this.RtCountMenuItem.Enabled = false;
9148 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9149 => this.CopyUserId();
9151 private void CopyUserId()
9153 var post = this.CurrentPost;
9154 if (post == null) return;
9155 var clstr = post.ScreenName;
9158 Clipboard.SetDataObject(clstr, false, 5, 100);
9160 catch (Exception ex)
9162 MessageBox.Show(ex.Message);
9166 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9168 var post = this.CurrentPost;
9169 if (this.ExistCurrentPost && post != null && !post.IsDm)
9173 await this.OpenRelatedTab(post);
9175 catch (TabException ex)
9177 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9183 /// 指定されたツイートに対する関連発言タブを開きます
9185 /// <param name="statusId">表示するツイートのID</param>
9186 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9187 public async Task OpenRelatedTab(PostId statusId)
9189 var post = this.statuses[statusId];
9194 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9196 catch (WebApiException ex)
9198 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9203 await this.OpenRelatedTab(post);
9207 /// 指定されたツイートに対する関連発言タブを開きます
9209 /// <param name="post">表示する対象となるツイート</param>
9210 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9211 private async Task OpenRelatedTab(PostClass post)
9213 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9214 if (tabRelated != null)
9216 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9219 var tabName = this.statuses.MakeTabName("Related Tweets");
9221 tabRelated = new RelatedPostsTabModel(tabName, post)
9223 UnreadManage = false,
9227 this.statuses.AddTab(tabRelated);
9228 this.AddNewTab(tabRelated, startup: false);
9230 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9232 await this.RefreshTabAsync(tabRelated);
9234 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9238 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9240 var tabPage = this.ListTab.TabPages[tabIndex];
9241 var listView = (DetailsListView)tabPage.Tag;
9242 var targetPost = tabRelated.TargetPost;
9243 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9245 if (index != -1 && index < listView.Items.Count)
9247 listView.SelectedIndices.Add(index);
9248 listView.Items[index].Focused = true;
9253 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9255 var buf = new StringBuilder();
9256 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9257 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9258 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9261 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9263 MyCommon.EndingFlag = true;
9267 Application.Restart();
9271 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9275 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9276 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9278 private bool ExistCurrentPost
9282 var post = this.CurrentPost;
9283 return post != null && !post.IsDeleted;
9287 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9288 => await this.ShowUserTimeline();
9290 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9291 => await this.ShowRetweeterTimeline();
9293 private string GetUserIdFromCurPostOrInput(string caption)
9295 var id = this.CurrentPost?.ScreenName ?? "";
9297 using var inputName = new InputTabName();
9298 inputName.FormTitle = caption;
9299 inputName.FormDescription = Properties.Resources.FRMessage1;
9300 inputName.TabName = id;
9302 if (inputName.ShowDialog() == DialogResult.OK &&
9303 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9305 id = inputName.TabName.Trim();
9314 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9316 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9317 if (!MyCommon.IsNullOrEmpty(id))
9319 await this.AddNewTabForUserTimeline(id);
9323 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9325 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9326 this.timelineScheduler.SystemResumed();
9329 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9331 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9333 TimeZoneInfo.ClearCachedData();
9335 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9337 if (curTimeOffset != prevTimeOffset)
9340 this.listCache?.PurgeCache();
9341 this.CurrentListView.Refresh();
9343 this.DispSelectedPost(forceupdate: true);
9346 this.timelineScheduler.Reset();
9349 private void TimelineRefreshEnableChange(bool isEnable)
9351 this.timelineScheduler.Enabled = isEnable;
9354 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9355 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9357 private async Task OpenUserAppointUrl()
9359 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9361 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9363 var post = this.CurrentPost;
9366 var xUrl = this.settings.Common.UserAppointUrl;
9367 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9369 var statusId = post.RetweetedId ?? post.StatusId;
9370 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9372 await MyCommon.OpenInBrowserAsync(this, xUrl);
9377 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9382 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9383 => await this.OpenUserAppointUrl();
9385 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9387 if (Form.ActiveForm == null)
9389 await this.InvokeAsync(() =>
9391 this.Visible = true;
9392 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9394 this.BringToFront();
9395 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9397 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9401 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9407 private void ReplaceAppName()
9409 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9410 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9413 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9414 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9416 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9418 if (e.KeyCode == Keys.Space)
9420 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9422 e.SuppressKeyPress = true;
9426 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9428 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9429 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9430 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9431 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9432 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9434 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9437 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9438 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9440 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9441 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9443 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9444 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9446 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9447 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9449 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9450 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9452 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9454 if (this.settings.Common.IconSize == iconSize) return;
9456 var oldIconCol = this.Use2ColumnsMode;
9458 this.settings.Common.IconSize = iconSize;
9459 this.ApplyListViewIconSize(iconSize);
9461 if (this.Use2ColumnsMode != oldIconCol)
9463 foreach (TabPage tp in this.ListTab.TabPages)
9465 this.ResetColumns((DetailsListView)tp.Tag);
9469 this.CurrentListView.Refresh();
9470 this.MarkSettingCommonModified();
9473 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9475 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9476 if (this.settings.Common.SortOrderLock == state) return;
9478 this.settings.Common.SortOrderLock = state;
9479 this.MarkSettingCommonModified();
9482 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9484 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9486 this.StatusLabelUrl.Text = e.StatusText;
9490 this.SetStatusLabelUrl();