1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.SocialProtocol;
63 using OpenTween.SocialProtocol.Twitter;
64 using OpenTween.Thumbnail;
68 public partial class TweenMain : OTBaseForm
72 /// <summary>画面サイズ</summary>
75 /// <summary>画面位置</summary>
78 /// <summary>区切り位置</summary>
81 /// <summary>発言欄区切り位置</summary>
84 /// <summary>プレビュー区切り位置</summary>
88 private bool initial; // true:起動時処理中
89 private bool initialLayout = true;
90 private bool ignoreConfigSave; // true:起動時処理中
92 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
95 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
96 private Point tabMouseDownPoint;
98 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
99 private string? rclickTabName;
101 private readonly object syncObject = new(); // ロック用
103 private readonly DetailsHtmlBuilder detailsHtmlBuilder = new();
105 private bool myStatusError = false;
106 private bool myStatusOnline = false;
107 private bool soundfileListup = false;
108 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
111 private readonly SettingManager settings;
114 private readonly AccountCollection accounts;
116 #pragma warning disable SA1300
117 private Twitter tw => ((TwitterAccount)this.accounts.Primary).Legacy; // AccountCollection への移行用
118 #pragma warning restore SA1300
121 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
125 /// <summary>検索画面インスタンス</summary>
126 internal SearchWordDialog SearchDialog = new();
128 private readonly OpenURL urlDialog = new();
130 /// <summary>@id補助</summary>
131 public AtIdSupplement AtIdSupl = null!;
133 /// <summary>Hashtag補助</summary>
134 public AtIdSupplement HashSupl = null!;
136 public HashtagManage HashMgr = null!;
139 private ThemeManager themeManager;
141 /// <summary>アイコン画像リスト</summary>
142 private readonly ImageCache iconCache;
144 private readonly IconAssetsManager iconAssets;
146 private readonly ThumbnailGenerator thumbGenerator;
148 /// <summary>発言履歴</summary>
149 private readonly StatusTextHistory history = new();
151 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
153 /// <summary>リプライ先のステータスID・スクリーン名</summary>
154 private (PostId StatusId, string ScreenName)? inReplyTo = null;
157 private readonly List<DateTimeUtc> postTimestamps = new();
158 private readonly List<DateTimeUtc> favTimestamps = new();
161 private readonly StringFormat sfTab = new();
163 //////////////////////////////////////////////////////////////////////////////////////////////////////////
165 /// <summary>発言保持クラス</summary>
166 private readonly TabInformations statuses;
168 private TimelineListViewCache? listCache;
169 private TimelineListViewDrawer? listDrawer;
170 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
172 private bool isColumnChanged = false;
174 private const int MaxWorderThreads = 20;
175 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
176 private readonly CancellationTokenSource workerCts = new();
177 private readonly IProgress<string> workerProgress = null!;
179 private int unreadCounter = -1;
180 private int unreadAtCounter = -1;
182 private readonly string[] columnOrgText = new string[9];
183 private readonly string[] columnText = new string[9];
185 private bool doFavRetweetFlags = false;
187 //////////////////////////////////////////////////////////////////////////////////////////////////////////
189 private readonly TimelineScheduler timelineScheduler = new();
190 private readonly DebounceTimer selectionDebouncer;
191 private readonly DebounceTimer saveConfigDebouncer;
193 private readonly string recommendedStatusFooter;
195 internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
197 private bool preventSmsCommand = true;
200 private readonly record struct UrlUndo(
205 private List<UrlUndo>? urlUndoBuffer = null;
207 private readonly record struct ReplyChain(
213 /// <summary>[, ]でのリプライ移動の履歴</summary>
214 private Stack<ReplyChain>? replyChains;
216 /// <summary>ポスト選択履歴</summary>
217 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
219 public TabModel CurrentTab
220 => this.statuses.SelectedTab;
222 public string CurrentTabName
223 => this.statuses.SelectedTabName;
225 public TabPage CurrentTabPage
226 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
228 public DetailsListView CurrentListView
229 => (DetailsListView)this.CurrentTabPage.Tag;
231 public PostClass? CurrentPost
232 => this.CurrentTab.SelectedPost;
234 public bool Use2ColumnsMode
235 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
237 /// <summary>検索処理タイプ</summary>
238 internal enum SEARCHTYPE
245 private readonly HookGlobalHotkey hookGlobalHotkey;
248 SettingManager settingManager,
249 TabInformations tabInfo,
250 AccountCollection accounts,
251 ImageCache imageCache,
252 IconAssetsManager iconAssets,
253 ThumbnailGenerator thumbGenerator
256 this.settings = settingManager;
257 this.statuses = tabInfo;
258 this.accounts = accounts;
259 this.iconCache = imageCache;
260 this.iconAssets = iconAssets;
261 this.thumbGenerator = thumbGenerator;
263 this.InitializeComponent();
265 if (!this.DesignMode)
267 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
268 this.StatusText.Dock = DockStyle.Fill;
271 this.hookGlobalHotkey = new HookGlobalHotkey(this);
273 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
274 this.gh.NotifyClicked += this.GrowlHelper_Callback;
276 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
277 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
279 this.ImageSelector.Visible = false;
280 this.ImageSelector.Enabled = false;
281 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
283 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
285 this.ReplaceAppName();
286 this.InitializeShortcuts();
288 this.ignoreConfigSave = true;
290 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
292 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
294 Regex.CacheSize = 100;
297 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
298 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
299 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
301 // <<<<<<<<<設定関連>>>>>>>>>
305 // 現在の DPI と設定保存時の DPI との比を取得する
306 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
311 // プロキシ設定等の通信まわりの初期化が済んでから処理する
312 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
313 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
314 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
316 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
319 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
320 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
322 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
325 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
326 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
327 this.HashMgr = new HashtagManage(this.HashSupl,
328 this.settings.Common.HashTags.ToArray(),
329 this.settings.Common.HashSelected,
330 this.settings.Common.HashIsPermanent,
331 this.settings.Common.HashIsHead,
332 this.settings.Common.HashIsNotAddToAtReply);
333 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
336 this.themeManager = new(this.settings.Local);
337 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager, this.detailsHtmlBuilder);
339 // StringFormatオブジェクトへの事前設定
340 this.sfTab.Alignment = StringAlignment.Center;
341 this.sfTab.LineAlignment = StringAlignment.Center;
343 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
344 this.tweetDetailsView.ClearPostBrowser();
346 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
348 this.inReplyTo = null;
351 this.SearchDialog.Owner = this;
352 this.urlDialog.Owner = this;
355 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
356 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
358 // 新着取得時のリストスクロールをするか。trueならスクロールしない
359 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
360 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
362 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
363 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
366 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
367 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
368 this.myLoc = this.settings.Local.FormLocation;
370 if (this.WindowState != FormWindowState.Minimized)
372 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
373 var outOfScreen = true;
374 if (Screen.AllScreens.Length == 1) // ハングするとの報告
376 foreach (var scr in Screen.AllScreens)
378 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
386 this.myLoc = new Point(0, 0);
388 this.DesktopLocation = this.myLoc;
390 this.TopMost = this.settings.Common.AlwaysTop;
391 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
392 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
393 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
395 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
396 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
398 this.StatusText.Font = this.themeManager.FontInputFont;
399 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
401 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
402 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
403 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
405 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
406 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
408 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
409 if (this.settings.Common.UnreadManage == false)
411 this.ReadedStripMenuItem.Enabled = false;
412 this.UnreadStripMenuItem.Enabled = false;
415 // リンク先URL表示部の初期化(画面左下)
416 this.StatusLabelUrl.Text = "";
418 this.StatusLabel.Text = "";
419 this.StatusLabel.AutoToolTip = false;
420 this.StatusLabel.ToolTipText = "";
422 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
424 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
425 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
426 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
427 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
429 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
430 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
431 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
432 this.SplitContainer2.Panel2.AccessibleName = "";
434 ////////////////////////////////////////////////////////////////////////////////
435 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
436 var mode = this.settings.Common.SortColumn switch
438 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
439 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
440 1 => ComparerMode.Nickname, // ニックネーム
441 2 => ComparerMode.Data, // 本文
442 3 => ComparerMode.Id, // 時刻=発言Id
443 4 => ComparerMode.Name, // 名前
444 7 => ComparerMode.Source, // Source
445 _ => ComparerMode.Id,
447 this.statuses.SetSortMode(mode, sortOrder);
448 ////////////////////////////////////////////////////////////////////////////////
450 this.ApplyListViewIconSize(this.settings.Common.IconSize);
452 // <<<<<<<<タブ関連>>>>>>>
453 foreach (var tab in this.statuses.Tabs)
455 if (!this.AddNewTab(tab, startup: true))
456 throw new TabException(Properties.Resources.TweenMain_LoadText1);
459 this.ListTabSelect(this.ListTab.SelectedTab);
462 this.SetTabAlignment();
464 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
465 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
467 if (this.settings.Common.TabIconDisp)
469 this.ListTab.DrawMode = TabDrawMode.Normal;
473 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
474 this.ListTab.DrawItem += this.ListTab_DrawItem;
475 this.ListTab.ImageList = null;
478 if (this.settings.Common.HotkeyEnabled)
481 var modKey = HookGlobalHotkey.ModKeys.None;
482 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
483 modKey |= HookGlobalHotkey.ModKeys.Alt;
484 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
485 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
486 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
487 modKey |= HookGlobalHotkey.ModKeys.Shift;
488 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
489 modKey |= HookGlobalHotkey.ModKeys.Win;
491 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
494 if (this.settings.Common.IsUseNotifyGrowl)
495 this.gh.RegisterGrowl();
497 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
499 this.SetMainWindowTitle();
500 this.SetNotifyIconText();
502 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
504 this.Visible = false;
509 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
510 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
511 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
512 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
513 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
514 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
515 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
517 this.DoGetFollowersMenu(),
518 this.RefreshBlockIdsAsync(),
519 this.RefreshMuteUserIdsAsync(),
520 this.RefreshNoRetweetIdsAsync(),
521 this.RefreshTwitterConfigurationAsync(),
523 this.RefreshTimelineScheduler();
525 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
526 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
529 this.TimerRefreshIcon.Interval = 200;
530 this.TimerRefreshIcon.Enabled = false;
532 this.ignoreConfigSave = false;
533 this.ApplyLayoutFromSettings();
536 private void TweenMain_Activated(object sender, EventArgs e)
538 // 画面がアクティブになったら、発言欄の背景色戻す
539 if (this.StatusText.Focused)
541 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
545 private bool disposed = false;
548 /// 使用中のリソースをすべてクリーンアップします。
550 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
551 protected override void Dispose(bool disposing)
553 base.Dispose(disposing);
560 this.components?.Dispose();
563 this.SearchDialog.Dispose();
564 this.urlDialog.Dispose();
565 this.themeManager.Dispose();
566 this.sfTab.Dispose();
568 this.timelineScheduler.Dispose();
569 this.workerCts.Cancel();
570 this.thumbnailTokenSource?.Dispose();
572 this.hookGlobalHotkey.Dispose();
575 // 終了時にRemoveHandlerしておかないとメモリリークする
576 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
577 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
578 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
579 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
581 this.disposed = true;
584 private void InitColumns(ListView list, bool startup)
586 this.InitColumnText();
588 ColumnHeader[]? columns = null;
591 if (this.Use2ColumnsMode)
595 new ColumnHeader(), // アイコン
596 new ColumnHeader(), // 本文
599 columns[0].Text = this.columnText[0];
600 columns[1].Text = this.columnText[2];
604 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
606 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
607 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
608 columns[0].DisplayIndex = 0;
609 columns[1].DisplayIndex = 1;
614 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
616 columns[idx].Width = curListColumn.Width;
617 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
626 new ColumnHeader(), // アイコン
627 new ColumnHeader(), // ニックネーム
628 new ColumnHeader(), // 本文
629 new ColumnHeader(), // 日付
630 new ColumnHeader(), // ユーザID
631 new ColumnHeader(), // 未読
632 new ColumnHeader(), // マーク&プロテクト
633 new ColumnHeader(), // ソース
636 foreach (var i in Enumerable.Range(0, columns.Length))
637 columns[i].Text = this.columnText[i];
641 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
643 foreach (var (column, index) in columns.WithIndex())
645 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
646 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
652 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
654 columns[idx].Width = curListColumn.Width;
655 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
661 list.Columns.AddRange(columns);
669 foreach (var column in columns)
675 private void InitColumnText()
677 this.columnText[0] = "";
678 this.columnText[1] = Properties.Resources.AddNewTabText2;
679 this.columnText[2] = Properties.Resources.AddNewTabText3;
680 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
681 this.columnText[4] = Properties.Resources.AddNewTabText5;
682 this.columnText[5] = "";
683 this.columnText[6] = "";
684 this.columnText[7] = "Source";
686 this.columnOrgText[0] = "";
687 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
688 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
689 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
690 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
691 this.columnOrgText[5] = "";
692 this.columnOrgText[6] = "";
693 this.columnOrgText[7] = "Source";
695 var c = this.statuses.SortMode switch
697 ComparerMode.Nickname => 1, // ニックネーム
698 ComparerMode.Data => 2, // 本文
699 ComparerMode.Id => 3, // 時刻=発言Id
700 ComparerMode.Name => 4, // 名前
701 ComparerMode.Source => 7, // Source
705 if (this.Use2ColumnsMode)
707 if (this.statuses.SortOrder == SortOrder.Descending)
709 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
710 this.columnText[2] = this.columnOrgText[2] + "▾";
714 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
715 this.columnText[2] = this.columnOrgText[2] + "▴";
720 if (this.statuses.SortOrder == SortOrder.Descending)
722 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
723 this.columnText[c] = this.columnOrgText[c] + "▾";
727 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
728 this.columnText[c] = this.columnOrgText[c] + "▴";
733 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
738 txt = this.statuses.Tabs[e.Index].TabName;
745 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
746 if (e.State == DrawItemState.Selected)
748 e.DrawFocusRectangle();
753 if (this.statuses.Tabs[txt].UnreadCount > 0)
756 fore = System.Drawing.SystemBrushes.ControlText;
760 fore = System.Drawing.SystemBrushes.ControlText;
762 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
765 private void LoadConfig()
767 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
768 this.statuses.AddDefaultTabs();
771 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
773 this.RefreshTimelineScheduler();
776 private void RefreshTimelineScheduler()
778 static TimeSpan IntervalSecondsOrDisabled(int seconds)
779 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
781 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
782 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
783 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
784 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
785 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
786 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
787 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
788 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
790 this.timelineScheduler.RefreshSchedule();
793 private void MarkSettingCommonModified()
795 if (this.saveConfigDebouncer == null)
798 this.ModifySettingCommon = true;
799 _ = this.saveConfigDebouncer.Call();
802 private void MarkSettingLocalModified()
804 if (this.saveConfigDebouncer == null)
807 this.ModifySettingLocal = true;
808 _ = this.saveConfigDebouncer.Call();
811 internal void MarkSettingAtIdModified()
813 if (this.saveConfigDebouncer == null)
816 this.ModifySettingAtId = true;
817 _ = this.saveConfigDebouncer.Call();
820 internal void RefreshTimeline()
822 var curListView = this.CurrentListView;
824 // 現在表示中のタブのスクロール位置を退避
825 var currentListViewState = this.listViewState[this.CurrentTabName];
826 currentListViewState.Save(this.ListLockMenuItem.Checked);
830 addCount = this.statuses.SubmitUpdate(
833 out var newMentionOrDm,
836 if (MyCommon.EndingFlag) return;
839 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
841 using (ControlTransaction.Update(curListView))
843 this.listCache.PurgeCache();
844 this.listCache.UpdateListSize();
847 currentListViewState.RestoreSelection();
853 if (this.settings.Common.TabIconDisp)
855 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
857 var tabPage = this.ListTab.TabPages[index];
858 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
859 tabPage.ImageIndex = 0; // 未読アイコン
864 this.ListTab.Refresh();
869 currentListViewState.RestoreScroll();
872 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
874 this.SetMainWindowTitle();
875 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
877 this.HashSupl.AddRangeItem(this.tw.GetHashList());
880 private bool BalloonRequired()
885 if (NativeMethods.IsScreenSaverRunning())
889 if (!this.NewPostPopMenuItem.Checked)
892 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
893 if (this.settings.Common.LimitBalloon)
895 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
902 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
904 if (this.settings.Common.ReadOwnPost)
906 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
911 if (this.BalloonRequired())
913 if (notifyPosts != null && notifyPosts.Length > 0)
915 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
916 if (this.settings.Common.IsUseNotifyGrowl)
918 var sb = new StringBuilder();
922 foreach (var post in notifyPosts)
924 if (!(notifyPosts.Length > 3))
930 if (post.IsReply && !post.IsExcludeReply) reply = true;
931 if (post.IsDm) dm = true;
932 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
933 switch (this.settings.Common.NameBalloon)
935 case MyCommon.NameBalloonEnum.UserID:
936 sb.Append(post.ScreenName).Append(" : ");
938 case MyCommon.NameBalloonEnum.NickName:
939 sb.Append(post.Nickname).Append(" : ");
942 sb.Append(post.TextFromApi);
943 if (notifyPosts.Length > 3)
945 if (notifyPosts.Last() != post) continue;
948 var title = new StringBuilder();
949 GrowlHelper.NotifyType nt;
950 if (this.settings.Common.DispUsername)
952 title.Append(this.tw.Username);
958 title.Append(ApplicationSettings.ApplicationName);
959 title.Append(" [DM] ");
960 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
961 nt = GrowlHelper.NotifyType.DirectMessage;
965 title.Append(ApplicationSettings.ApplicationName);
966 title.Append(" [Reply!] ");
967 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
968 nt = GrowlHelper.NotifyType.Reply;
972 title.Append(ApplicationSettings.ApplicationName);
974 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
975 nt = GrowlHelper.NotifyType.Notify;
977 var bText = sb.ToString();
978 if (MyCommon.IsNullOrEmpty(bText)) return;
980 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
981 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
986 var sb = new StringBuilder();
989 foreach (var post in notifyPosts)
991 if (post.IsReply && !post.IsExcludeReply) reply = true;
992 if (post.IsDm) dm = true;
993 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
994 switch (this.settings.Common.NameBalloon)
996 case MyCommon.NameBalloonEnum.UserID:
997 sb.Append(post.ScreenName).Append(" : ");
999 case MyCommon.NameBalloonEnum.NickName:
1000 sb.Append(post.Nickname).Append(" : ");
1003 sb.Append(post.TextFromApi);
1006 var title = new StringBuilder();
1008 if (this.settings.Common.DispUsername)
1010 title.Append(this.tw.Username);
1011 title.Append(" - ");
1016 ntIcon = ToolTipIcon.Warning;
1017 title.Append(ApplicationSettings.ApplicationName);
1018 title.Append(" [DM] ");
1019 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1023 ntIcon = ToolTipIcon.Warning;
1024 title.Append(ApplicationSettings.ApplicationName);
1025 title.Append(" [Reply!] ");
1026 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1030 ntIcon = ToolTipIcon.Info;
1031 title.Append(ApplicationSettings.ApplicationName);
1033 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1035 var bText = sb.ToString();
1036 if (MyCommon.IsNullOrEmpty(bText)) return;
1038 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1039 this.NotifyIcon1.BalloonTipText = bText;
1040 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1041 this.NotifyIcon1.ShowBalloonTip(500);
1047 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1051 var dir = Application.StartupPath;
1052 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1054 dir = Path.Combine(dir, "Sounds");
1056 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1064 // mentions新着時に画面ブリンク
1065 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1067 NativeMethods.FlashMyWindow(this.Handle, 3);
1071 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1073 var listView = this.CurrentListView;
1074 if (listView != sender)
1077 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1078 this.CurrentTab.SelectPosts(indices);
1080 if (indices.Length != 1)
1083 var index = indices[0];
1084 if (index > listView.VirtualListSize - 1) return;
1086 this.PushSelectPostChain();
1088 var post = this.CurrentPost!;
1089 this.statuses.SetReadAllTab(post.StatusId, read: true);
1091 this.listCache?.RefreshStyle();
1092 await this.selectionDebouncer.Call();
1095 private void StatusTextHistoryBack()
1097 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1098 var historyItem = this.history.Back();
1099 this.inReplyTo = historyItem.InReplyTo;
1100 this.StatusText.Text = historyItem.Status;
1101 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1104 private void StatusTextHistoryForward()
1106 this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1107 var historyItem = this.history.Forward();
1108 this.inReplyTo = historyItem.InReplyTo;
1109 this.StatusText.Text = historyItem.Status;
1110 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1113 private async void PostButton_Click(object sender, EventArgs e)
1115 if (this.StatusText.Text.Trim().Length == 0)
1117 if (!this.ImageSelector.Enabled)
1119 await this.DoRefresh();
1124 var currentPost = this.CurrentPost;
1125 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1127 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1129 MessageBoxButtons.YesNoCancel,
1130 MessageBoxIcon.Question);
1133 case DialogResult.Yes:
1134 this.StatusText.Text = "";
1135 await this.DoReTweetOfficial(false);
1137 case DialogResult.Cancel:
1142 if (TextContainsOnlyMentions(this.StatusText.Text))
1144 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1145 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1147 if (ret != DialogResult.OK)
1151 if (this.settings.Common.Nicoms)
1153 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1154 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1157 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1158 this.CheckReplyTo(this.StatusText.Text);
1160 var status = new PostStatusParams();
1162 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1163 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1165 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1166 // 収まる場合はこれらのオプションを使用せずに投稿する
1167 status.Text = statusTextCompat;
1168 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1172 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1173 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1175 status.AttachmentUrl = attachmentUrl;
1177 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1179 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1180 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1182 status.AutoPopulateReplyMetadata = true;
1184 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1185 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1190 if (this.GetRestStatusCount(status.Text) < 0)
1192 // 文字数制限を超えているが強制的に投稿するか
1193 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1194 if (ret != DialogResult.OK)
1198 IMediaUploadService? uploadService = null;
1199 IMediaItem[]? uploadItems = null;
1200 if (this.ImageSelector.Visible)
1203 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1206 this.ImageSelector.EndSelection();
1207 uploadService = this.ImageSelector.Model.GetService(serviceName);
1210 this.history.AddLast(this.StatusText.Text, this.inReplyTo);
1212 this.inReplyTo = null;
1213 this.StatusText.Text = "";
1214 if (!this.settings.Common.FocusLockToStatusText)
1215 this.CurrentListView.Focus();
1216 this.urlUndoBuffer = null;
1217 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1220 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1222 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1223 await MyCommon.OpenInBrowserAsync(this, tmp);
1226 await this.PostMessageAsync(status, uploadService, uploadItems);
1229 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1231 MyCommon.EndingFlag = true;
1235 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1237 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1239 // _endingFlag=false:フォームの×ボタン
1241 this.Visible = false;
1245 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1246 this.ignoreConfigSave = true;
1247 MyCommon.EndingFlag = true;
1248 this.timelineScheduler.Enabled = false;
1249 this.TimerRefreshIcon.Enabled = false;
1253 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1255 this.Visible = true;
1256 if (this.WindowState == FormWindowState.Minimized)
1258 this.WindowState = FormWindowState.Normal;
1261 this.BringToFront();
1264 private static int errorCount = 0;
1266 private static bool CheckAccountValid()
1268 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1274 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1283 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1284 private Task RefreshTabAsync<T>()
1286 => this.RefreshTabAsync<T>(backward: false);
1288 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1289 private Task RefreshTabAsync<T>(bool backward)
1293 from tab in this.statuses.GetTabsByType<T>()
1294 select this.RefreshTabAsync(tab, backward);
1296 return Task.WhenAll(loadTasks);
1299 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1300 private Task RefreshTabAsync(TabModel tab)
1301 => this.RefreshTabAsync(tab, backward: false);
1303 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1304 private async Task RefreshTabAsync(TabModel tab, bool backward)
1306 await this.workerSemaphore.WaitAsync();
1310 this.RefreshTasktrayIcon();
1311 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1313 catch (WebApiException ex)
1315 this.myStatusError = true;
1316 var tabType = tab switch
1318 HomeTabModel => "GetTimeline",
1319 MentionsTabModel => "GetTimeline",
1320 DirectMessagesTabModel => "GetDirectMessage",
1321 FavoritesTabModel => "GetFavorites",
1322 PublicSearchTabModel => "GetSearch",
1323 UserTimelineTabModel => "GetUserTimeline",
1324 ListTimelineTabModel => "GetListStatus",
1325 RelatedPostsTabModel => "GetRelatedTweets",
1326 _ => tab.GetType().Name.Replace("Model", ""),
1328 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1332 this.RefreshTimeline();
1333 this.workerSemaphore.Release();
1337 private async Task FavAddAsync(PostId statusId, TabModel tab)
1339 await this.workerSemaphore.WaitAsync();
1343 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1345 this.RefreshTasktrayIcon();
1346 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1348 catch (WebApiException ex)
1350 this.myStatusError = true;
1351 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1355 this.workerSemaphore.Release();
1359 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1361 if (ct.IsCancellationRequested)
1364 if (!CheckAccountValid())
1365 throw new WebApiException("Auth error. Check your account");
1367 if (!tab.Posts.TryGetValue(statusId, out var post))
1373 await Task.Run(async () =>
1375 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1379 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1382 await this.tw.Api.FavoritesCreate(twitterStatusId)
1384 .ConfigureAwait(false);
1386 catch (TwitterApiException ex)
1387 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1389 // エラーコード 139 のみの場合は成功と見なす
1392 if (this.settings.Common.RestrictFavCheck)
1394 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1395 .ConfigureAwait(false);
1397 if (status.Favorited != true)
1398 throw new WebApiException("NG(Restricted?)");
1401 this.favTimestamps.Add(DateTimeUtc.Now);
1404 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1406 postTl.IsFav = true;
1408 var favTab = this.statuses.FavoriteTab;
1409 favTab.AddPostQueue(postTl);
1412 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1413 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1415 if (tb.Contains(statusId))
1416 tb.Posts[statusId].IsFav = true;
1419 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1421 catch (WebApiException)
1423 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1428 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1429 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1431 if (this.favTimestamps[i] < oneHour)
1432 this.favTimestamps.RemoveAt(i);
1435 this.statuses.DistributePosts();
1438 if (ct.IsCancellationRequested)
1441 this.RefreshTimeline();
1443 if (this.CurrentTabName == tab.TabName)
1445 using (ControlTransaction.Update(this.CurrentListView))
1447 var idx = tab.IndexOf(statusId);
1449 this.listCache?.RefreshStyle(idx);
1452 var currentPost = this.CurrentPost;
1453 if (currentPost != null && statusId == currentPost.StatusId)
1454 this.DispSelectedPost(true); // 選択アイテム再表示
1458 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1460 await this.workerSemaphore.WaitAsync();
1464 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1466 this.RefreshTasktrayIcon();
1467 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1469 catch (WebApiException ex)
1471 this.myStatusError = true;
1472 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1476 this.workerSemaphore.Release();
1480 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1482 if (ct.IsCancellationRequested)
1485 if (!CheckAccountValid())
1486 throw new WebApiException("Auth error. Check your account");
1488 var successIds = new List<PostId>();
1490 await Task.Run(async () =>
1494 var failedCount = 0;
1495 foreach (var statusId in statusIds)
1499 var post = tab.Posts[statusId];
1501 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1506 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1510 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1512 .ConfigureAwait(false);
1514 catch (WebApiException)
1520 successIds.Add(statusId);
1521 post.IsFav = false; // リスト再描画必要
1523 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1524 tabinfoPost.IsFav = false;
1526 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1527 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1529 if (tb.Contains(statusId))
1530 tb.Posts[statusId].IsFav = false;
1535 if (ct.IsCancellationRequested)
1538 var favTab = this.statuses.FavoriteTab;
1539 foreach (var statusId in successIds)
1541 // ツイートが削除された訳ではないので IsDeleted はセットしない
1542 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1545 this.RefreshTimeline();
1547 if (this.CurrentTabName == tab.TabName)
1549 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1555 using (ControlTransaction.Update(this.CurrentListView))
1557 foreach (var statusId in successIds)
1559 var idx = tab.IndexOf(statusId);
1561 this.listCache?.RefreshStyle(idx);
1565 var currentPost = this.CurrentPost;
1566 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1567 this.DispSelectedPost(true); // 選択アイテム再表示
1572 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1574 await this.workerSemaphore.WaitAsync();
1578 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1580 this.RefreshTasktrayIcon();
1581 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1583 catch (WebApiException ex)
1585 this.myStatusError = true;
1586 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1590 this.workerSemaphore.Release();
1594 private async Task PostMessageAsyncInternal(
1595 IProgress<string> p,
1596 CancellationToken ct,
1597 PostStatusParams postParams,
1598 IMediaUploadService? uploadService,
1599 IMediaItem[]? uploadItems)
1601 if (ct.IsCancellationRequested)
1604 if (!CheckAccountValid())
1605 throw new WebApiException("Auth error. Check your account");
1607 p.Report("Posting...");
1609 PostClass? post = null;
1614 await Task.Run(async () =>
1616 var postParamsWithMedia = postParams;
1618 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1620 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1621 .ConfigureAwait(false);
1624 post = await this.tw.PostStatus(postParamsWithMedia)
1625 .ConfigureAwait(false);
1628 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1630 catch (WebApiException ex)
1632 // 処理は中断せずエラーの表示のみ行う
1633 errMsg = $"Err:{ex.Message}(PostMessage)";
1635 this.myStatusError = true;
1637 catch (UnauthorizedAccessException ex)
1639 // アップロード対象のファイルが開けなかった場合など
1640 errMsg = $"Err:{ex.Message}(PostMessage)";
1642 this.myStatusError = true;
1646 // 使い終わった MediaItem は破棄する
1647 if (uploadItems != null)
1649 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1651 disposableItem.Dispose();
1656 if (ct.IsCancellationRequested)
1659 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1660 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1661 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1663 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1665 var ret = MessageBox.Show(
1667 "Failed to update status",
1668 MessageBoxButtons.RetryCancel,
1669 MessageBoxIcon.Question);
1671 if (ret == DialogResult.Retry)
1673 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1677 this.StatusTextHistoryBack();
1678 this.StatusText.Focus();
1680 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1681 if (this.settings.Common.FocusLockToStatusText)
1682 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1687 this.postTimestamps.Add(DateTimeUtc.Now);
1689 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1690 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1692 if (this.postTimestamps[i] < oneHour)
1693 this.postTimestamps.RemoveAt(i);
1696 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1698 this.HashMgr.ClearHashtag();
1699 this.HashStripSplitButton.Text = "#[-]";
1700 this.HashTogglePullDownMenuItem.Checked = false;
1701 this.HashToggleMenuItem.Checked = false;
1704 this.SetMainWindowTitle();
1709 this.statuses.AddPost(post);
1710 this.statuses.DistributePosts();
1711 this.RefreshTimeline();
1714 if (this.settings.Common.PostAndGet)
1715 await this.RefreshTabAsync<HomeTabModel>();
1718 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1720 await this.workerSemaphore.WaitAsync();
1724 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1726 this.RefreshTasktrayIcon();
1727 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1729 catch (WebApiException ex)
1731 this.myStatusError = true;
1732 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1736 this.workerSemaphore.Release();
1740 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1742 if (ct.IsCancellationRequested)
1745 if (!CheckAccountValid())
1746 throw new WebApiException("Auth error. Check your account");
1749 if (!this.settings.Common.UnreadManage)
1752 read = this.initial && this.settings.Common.Read;
1754 p.Report("Posting...");
1756 var posts = new List<PostClass>();
1758 await Task.Run(async () =>
1760 foreach (var statusId in statusIds)
1762 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1763 if (post != null) posts.Add(post);
1767 if (ct.IsCancellationRequested)
1770 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1772 this.postTimestamps.Add(DateTimeUtc.Now);
1774 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1775 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1777 if (this.postTimestamps[i] < oneHour)
1778 this.postTimestamps.RemoveAt(i);
1781 // 自分のRTはTLの更新では取得できない場合があるので、
1782 // 投稿時取得の有無に関わらず追加しておく
1783 posts.ForEach(post => this.statuses.AddPost(post));
1785 if (this.settings.Common.PostAndGet)
1787 await this.RefreshTabAsync<HomeTabModel>();
1791 this.statuses.DistributePosts();
1792 this.RefreshTimeline();
1796 private async Task RefreshFollowerIdsAsync()
1798 await this.workerSemaphore.WaitAsync();
1802 this.RefreshTasktrayIcon();
1803 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1805 await this.tw.RefreshFollowerIds();
1807 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1809 this.RefreshTimeline();
1810 this.listCache?.PurgeCache();
1811 this.CurrentListView.Refresh();
1813 catch (WebApiException ex)
1815 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1819 this.workerSemaphore.Release();
1823 private async Task RefreshNoRetweetIdsAsync()
1825 await this.workerSemaphore.WaitAsync();
1829 this.RefreshTasktrayIcon();
1830 await this.tw.RefreshNoRetweetIds();
1832 this.StatusLabel.Text = "NoRetweetIds refreshed";
1834 catch (WebApiException ex)
1836 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1840 this.workerSemaphore.Release();
1844 private async Task RefreshBlockIdsAsync()
1846 await this.workerSemaphore.WaitAsync();
1850 this.RefreshTasktrayIcon();
1851 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1853 await this.tw.RefreshBlockIds();
1855 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1857 catch (WebApiException ex)
1859 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1863 this.workerSemaphore.Release();
1867 private async Task RefreshTwitterConfigurationAsync()
1869 await this.workerSemaphore.WaitAsync();
1873 this.RefreshTasktrayIcon();
1874 await this.tw.RefreshConfiguration();
1876 if (this.tw.Configuration.PhotoSizeLimit != 0)
1878 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1880 service.UpdateTwitterConfiguration(this.tw.Configuration);
1884 this.listCache?.PurgeCache();
1885 this.CurrentListView.Refresh();
1887 catch (WebApiException ex)
1889 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1893 this.workerSemaphore.Release();
1897 private async Task RefreshMuteUserIdsAsync()
1899 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1903 await this.tw.RefreshMuteUserIdsAsync();
1905 catch (WebApiException ex)
1907 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1911 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1914 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1916 if (e.Button == MouseButtons.Left)
1918 this.Visible = true;
1919 if (this.WindowState == FormWindowState.Minimized)
1921 this.WindowState = this.formWindowState;
1924 this.BringToFront();
1928 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1929 => await this.ListItemDoubleClickAction();
1931 private async Task ListItemDoubleClickAction()
1933 switch (this.settings.Common.ListDoubleClickAction)
1935 case MyCommon.ListItemDoubleClickActionType.Reply:
1936 this.MakeReplyText();
1938 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1939 this.MakeReplyText(atAll: true);
1941 case MyCommon.ListItemDoubleClickActionType.Favorite:
1942 await this.FavoriteChange(true);
1944 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1945 var post = this.CurrentPost;
1947 await this.ShowUserStatus(post.ScreenName, false);
1949 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
1950 await this.ShowUserTimeline();
1952 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
1953 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
1955 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
1956 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
1958 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
1959 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
1961 case MyCommon.ListItemDoubleClickActionType.None:
1968 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
1969 => await this.FavoriteChange(true);
1971 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
1972 => await this.FavoriteChange(false);
1974 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
1975 => await this.FavoritesRetweetOfficial();
1977 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
1978 => await this.FavoritesRetweetUnofficial();
1980 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
1982 var tab = this.CurrentTab;
1983 var posts = tab.SelectedPosts;
1985 // trueでFavAdd,falseでFavRemove
1986 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
1987 || !this.ExistCurrentPost) return;
1989 if (posts.Length > 1)
1994 // https://support.twitter.com/articles/76915#favoriting
1995 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
1996 this.doFavRetweetFlags = false;
2001 if (multiFavoriteChangeDialogEnable)
2003 var confirm = MessageBox.Show(
2004 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2005 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2006 MessageBoxButtons.OKCancel,
2007 MessageBoxIcon.Question);
2009 if (confirm == DialogResult.Cancel)
2017 var selectedPost = posts.Single();
2018 if (selectedPost.IsFav)
2020 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2024 await this.FavAddAsync(selectedPost.StatusId, tab);
2028 var selectedPosts = posts.Where(x => x.IsFav);
2029 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2030 if (statusIds.Length == 0)
2032 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2036 await this.FavRemoveAsync(statusIds, tab);
2040 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2042 var post = this.CurrentPost;
2044 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2046 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2049 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2051 if ((!this.initialLayout) && this.Visible)
2053 if (this.WindowState == FormWindowState.Normal)
2055 this.mySize = this.ClientSize;
2056 this.mySpDis = this.SplitContainer1.SplitterDistance;
2057 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2058 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2059 this.MarkSettingLocalModified();
2064 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2066 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2067 if (comparerMode == null)
2070 this.SetSortColumn(comparerMode.Value);
2074 /// 列インデックスからソートを行う ComparerMode を求める
2076 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2077 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2078 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2080 if (this.Use2ColumnsMode)
2081 return ComparerMode.Id;
2083 return columnIndex switch
2085 1 => ComparerMode.Nickname, // ニックネーム
2086 2 => ComparerMode.Data, // 本文
2087 3 => ComparerMode.Id, // 時刻=発言Id
2088 4 => ComparerMode.Name, // 名前
2089 7 => ComparerMode.Source, // Source
2090 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2095 /// 発言一覧の指定した位置の列でソートする
2097 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2098 private void SetSortColumnByDisplayIndex(int columnIndex)
2100 // 表示上の列の位置から ColumnHeader を求める
2101 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2102 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2107 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2108 if (comparerMode == null)
2111 this.SetSortColumn(comparerMode.Value);
2115 /// 発言一覧の最後列の項目でソートする
2117 private void SetSortLastColumn()
2119 // 表示上の最後列にある ColumnHeader を求める
2120 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2121 .OrderByDescending(x => x.DisplayIndex)
2124 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2125 if (comparerMode == null)
2128 this.SetSortColumn(comparerMode.Value);
2132 /// 発言一覧を指定された ComparerMode に基づいてソートする
2134 private void SetSortColumn(ComparerMode sortColumn)
2136 if (this.settings.Common.SortOrderLock)
2139 this.statuses.ToggleSortOrder(sortColumn);
2140 this.InitColumnText();
2142 var list = this.CurrentListView;
2143 if (this.Use2ColumnsMode)
2145 list.Columns[0].Text = this.columnText[0];
2146 list.Columns[1].Text = this.columnText[2];
2150 for (var i = 0; i <= 7; i++)
2152 list.Columns[i].Text = this.columnText[i];
2156 this.listCache?.PurgeCache();
2158 var tab = this.CurrentTab;
2159 var post = this.CurrentPost;
2160 if (tab.AllCount > 0 && post != null)
2162 var idx = tab.IndexOf(post.StatusId);
2165 this.SelectListItem(list, idx);
2166 list.EnsureVisible(idx);
2171 this.MarkSettingCommonModified();
2174 private void TweenMain_LocationChanged(object sender, EventArgs e)
2176 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2178 this.myLoc = this.DesktopLocation;
2179 this.MarkSettingLocalModified();
2183 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2185 var post = this.CurrentPost;
2186 if (!this.ExistCurrentPost)
2188 this.ReplyStripMenuItem.Enabled = false;
2189 this.ReplyAllStripMenuItem.Enabled = false;
2190 this.DMStripMenuItem.Enabled = false;
2191 this.TabMenuItem.Enabled = false;
2192 this.IDRuleMenuItem.Enabled = false;
2193 this.SourceRuleMenuItem.Enabled = false;
2194 this.ReadedStripMenuItem.Enabled = false;
2195 this.UnreadStripMenuItem.Enabled = false;
2196 this.AuthorContextMenuItem.Visible = false;
2197 this.RetweetedByContextMenuItem.Visible = false;
2201 this.ReplyStripMenuItem.Enabled = true;
2202 this.ReplyAllStripMenuItem.Enabled = true;
2203 this.DMStripMenuItem.Enabled = true;
2204 this.TabMenuItem.Enabled = true;
2205 this.IDRuleMenuItem.Enabled = true;
2206 this.SourceRuleMenuItem.Enabled = true;
2207 this.ReadedStripMenuItem.Enabled = true;
2208 this.UnreadStripMenuItem.Enabled = true;
2209 this.AuthorContextMenuItem.Visible = true;
2210 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2211 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2212 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2214 var tab = this.CurrentTab;
2215 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2217 this.FavAddToolStripMenuItem.Enabled = false;
2218 this.FavRemoveToolStripMenuItem.Enabled = false;
2219 this.StatusOpenMenuItem.Enabled = false;
2220 this.ShowRelatedStatusesMenuItem.Enabled = false;
2222 this.ReTweetStripMenuItem.Enabled = false;
2223 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2224 this.QuoteStripMenuItem.Enabled = false;
2225 this.FavoriteRetweetContextMenu.Enabled = false;
2226 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2230 this.FavAddToolStripMenuItem.Enabled = true;
2231 this.FavRemoveToolStripMenuItem.Enabled = true;
2232 this.StatusOpenMenuItem.Enabled = true;
2233 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2235 if (!post.CanRetweetBy(this.tw.UserId))
2237 this.ReTweetStripMenuItem.Enabled = false;
2238 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2239 this.QuoteStripMenuItem.Enabled = false;
2240 this.FavoriteRetweetContextMenu.Enabled = false;
2241 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2245 this.ReTweetStripMenuItem.Enabled = true;
2246 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2247 this.QuoteStripMenuItem.Enabled = true;
2248 this.FavoriteRetweetContextMenu.Enabled = true;
2249 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2253 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2255 this.RepliedStatusOpenMenuItem.Enabled = false;
2259 this.RepliedStatusOpenMenuItem.Enabled = true;
2262 if (this.ExistCurrentPost && post != null)
2264 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2265 if (post.RetweetedByUserId == this.tw.UserId)
2266 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2268 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2272 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2273 => this.MakeReplyText();
2275 private void DMStripMenuItem_Click(object sender, EventArgs e)
2276 => this.MakeDirectMessageText();
2278 private async Task DoStatusDelete()
2280 var posts = this.CurrentTab.SelectedPosts;
2281 if (posts.Length == 0)
2284 // 選択されたツイートの中に削除可能なものが一つでもあるか
2285 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2288 var ret = MessageBox.Show(
2290 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2291 Properties.Resources.DeleteStripMenuItem_ClickText2,
2292 MessageBoxButtons.OKCancel,
2293 MessageBoxIcon.Question);
2295 if (ret != DialogResult.OK)
2298 var currentListView = this.CurrentListView;
2299 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2301 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2303 Exception? lastException = null;
2304 foreach (var post in posts)
2306 if (!post.CanDeleteBy(this.tw.UserId))
2311 if (post.StatusId is TwitterDirectMessageId dmId)
2313 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2317 if (post.RetweetedByUserId == this.tw.UserId)
2319 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2321 await this.tw.DeleteRetweet(post);
2325 if (post.UserId == this.tw.UserId)
2327 if (post.RetweetedId != null)
2329 // 他人に RT された自分のツイート
2330 // => RT 元の自分のツイートを削除
2331 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2337 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2343 catch (WebApiException ex)
2349 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2352 if (lastException == null)
2353 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2355 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2357 using (ControlTransaction.Update(currentListView))
2359 this.listCache?.PurgeCache();
2360 this.listCache?.UpdateListSize();
2362 currentListView.SelectedIndices.Clear();
2364 var currentTab = this.CurrentTab;
2365 if (currentTab.AllCount != 0)
2368 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2369 selectedIndex = focusedIndex;
2371 selectedIndex = currentTab.AllCount - 1;
2373 currentListView.SelectedIndices.Add(selectedIndex);
2374 currentListView.EnsureVisible(selectedIndex);
2375 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2379 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2381 var tabPage = this.ListTab.TabPages[index];
2382 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2384 if (tabPage.ImageIndex == 0)
2385 tabPage.ImageIndex = -1; // タブアイコン
2389 if (!this.settings.Common.TabIconDisp)
2390 this.ListTab.Refresh();
2394 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2395 => await this.DoStatusDelete();
2397 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2399 using (ControlTransaction.Update(this.CurrentListView))
2401 var tab = this.CurrentTab;
2402 foreach (var statusId in tab.SelectedStatusIds)
2404 this.statuses.SetReadAllTab(statusId, read: true);
2405 var idx = tab.IndexOf(statusId);
2406 this.listCache?.RefreshStyle(idx);
2409 if (this.settings.Common.TabIconDisp)
2411 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2413 if (tab.UnreadCount == 0)
2415 var tabPage = this.ListTab.TabPages[index];
2416 if (tabPage.ImageIndex == 0)
2417 tabPage.ImageIndex = -1; // タブアイコン
2421 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2424 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2426 using (ControlTransaction.Update(this.CurrentListView))
2428 var tab = this.CurrentTab;
2429 foreach (var statusId in tab.SelectedStatusIds)
2431 this.statuses.SetReadAllTab(statusId, read: false);
2432 var idx = tab.IndexOf(statusId);
2433 this.listCache?.RefreshStyle(idx);
2436 if (this.settings.Common.TabIconDisp)
2438 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2440 if (tab.UnreadCount > 0)
2442 var tabPage = this.ListTab.TabPages[index];
2443 if (tabPage.ImageIndex == -1)
2444 tabPage.ImageIndex = 0; // タブアイコン
2448 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2451 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2452 => await this.DoRefresh();
2454 private async Task DoRefresh()
2455 => await this.RefreshTabAsync(this.CurrentTab);
2457 private async Task DoRefreshMore()
2458 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2460 private DialogResult ShowSettingDialog()
2462 using var settingDialog = new AppendSettingDialog();
2463 settingDialog.Icon = this.iconAssets.IconMain;
2464 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2466 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2468 DialogResult result;
2471 result = settingDialog.ShowDialog(this);
2475 return DialogResult.Abort;
2478 if (result == DialogResult.OK)
2480 lock (this.syncObject)
2482 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2489 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2492 var previousUserId = this.settings.Common.UserId;
2493 var oldIconCol = this.Use2ColumnsMode;
2495 if (this.ShowSettingDialog() == DialogResult.OK)
2497 lock (this.syncObject)
2499 this.settings.ApplySettings();
2501 this.accounts.LoadFromSettings(this.settings.Common);
2502 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2506 if (this.settings.Common.TabIconDisp)
2508 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2509 this.ListTab.DrawMode = TabDrawMode.Normal;
2510 this.ListTab.ImageList = this.TabImage;
2514 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2515 this.ListTab.DrawItem += this.ListTab_DrawItem;
2516 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2517 this.ListTab.ImageList = null;
2520 catch (Exception ex)
2522 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2523 ex.Data["IsTerminatePermission"] = false;
2529 if (!this.settings.Common.UnreadManage)
2531 this.ReadedStripMenuItem.Enabled = false;
2532 this.UnreadStripMenuItem.Enabled = false;
2533 if (this.settings.Common.TabIconDisp)
2535 foreach (TabPage myTab in this.ListTab.TabPages)
2537 myTab.ImageIndex = -1;
2543 this.ReadedStripMenuItem.Enabled = true;
2544 this.UnreadStripMenuItem.Enabled = true;
2547 catch (Exception ex)
2549 ex.Data["Instance"] = "ListTab(UnreadManage)";
2550 ex.Data["IsTerminatePermission"] = false;
2555 this.SetTabAlignment();
2557 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2559 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2560 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2561 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2563 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2564 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2565 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2566 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2568 var newTheme = new ThemeManager(this.settings.Local);
2569 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2570 this.tweetDetailsView.Theme = this.themeManager;
2571 if (this.listDrawer != null)
2572 this.listDrawer.Theme = this.themeManager;
2577 if (this.StatusText.Focused)
2578 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2580 this.StatusText.Font = this.themeManager.FontInputFont;
2581 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2583 catch (Exception ex)
2585 MessageBox.Show(ex.Message);
2590 this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
2592 catch (Exception ex)
2594 ex.Data["Instance"] = "Font";
2595 ex.Data["IsTerminatePermission"] = false;
2601 if (this.settings.Common.TabIconDisp)
2603 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2605 var tabPage = this.ListTab.TabPages[index];
2606 if (tab.UnreadCount == 0)
2607 tabPage.ImageIndex = -1;
2609 tabPage.ImageIndex = 0;
2613 catch (Exception ex)
2615 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2616 ex.Data["IsTerminatePermission"] = false;
2622 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2624 foreach (TabPage tp in this.ListTab.TabPages)
2626 var lst = (DetailsListView)tp.Tag;
2628 using (ControlTransaction.Update(lst))
2630 lst.GridLines = this.settings.Common.ShowGrid;
2632 if (this.Use2ColumnsMode != oldIconCol)
2633 this.ResetColumns(lst);
2637 catch (Exception ex)
2639 ex.Data["Instance"] = "ListView(IconSize)";
2640 ex.Data["IsTerminatePermission"] = false;
2644 this.SetMainWindowTitle();
2645 this.SetNotifyIconText();
2647 this.listCache?.PurgeCache();
2648 this.CurrentListView.Refresh();
2649 this.ListTab.Refresh();
2651 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2652 if (this.settings.Common.HotkeyEnabled)
2654 // グローバルホットキーの登録。設定で変更可能にするかも
2655 var modKey = HookGlobalHotkey.ModKeys.None;
2656 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2657 modKey |= HookGlobalHotkey.ModKeys.Alt;
2658 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2659 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2660 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2661 modKey |= HookGlobalHotkey.ModKeys.Shift;
2662 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2663 modKey |= HookGlobalHotkey.ModKeys.Win;
2665 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2668 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2671 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2679 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2681 this.TopMost = this.settings.Common.AlwaysTop;
2682 this.SaveConfigsAll(false);
2684 if (this.tw.UserId != previousUserId)
2685 await this.DoGetFollowersMenu();
2691 private void SetTabAlignment()
2693 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2694 if (this.ListTab.Alignment == newAlignment) return;
2697 var currentListViewState = this.listViewState[this.CurrentTabName];
2698 currentListViewState.Save(this.ListLockMenuItem.Checked);
2700 this.ListTab.Alignment = newAlignment;
2702 currentListViewState.Restore(forceScroll: true);
2705 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2708 if (this.listDrawer != null)
2710 this.listDrawer.IconSize = iconSz;
2711 this.listDrawer.UpdateItemHeight();
2714 this.listCache?.PurgeCache();
2717 private void ResetColumns(DetailsListView list)
2719 using (ControlTransaction.Update(list))
2720 using (ControlTransaction.Layout(list, false))
2723 list.ColumnClick -= this.MyList_ColumnClick;
2724 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2725 list.ColumnReordered -= this.MyList_ColumnReordered;
2726 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2728 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2729 list.Columns.Clear();
2730 cols.ForEach(col => col.Dispose());
2733 this.InitColumns(list, true);
2735 list.ColumnClick += this.MyList_ColumnClick;
2736 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2737 list.ColumnReordered += this.MyList_ColumnReordered;
2738 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2742 public void AddNewTabForSearch(string searchWord)
2744 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2745 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2747 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2749 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2750 this.ListTab.SelectedIndex = tabIndex;
2755 var tabName = searchWord;
2756 for (var i = 0; i <= 100; i++)
2758 if (this.statuses.ContainsTab(tabName))
2764 var tab = new PublicSearchTabModel(tabName);
2765 this.statuses.AddTab(tab);
2766 this.AddNewTab(tab, startup: false);
2768 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2770 var tabPage = this.CurrentTabPage;
2771 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2772 cmb.Items.Add(searchWord);
2773 cmb.Text = searchWord;
2774 this.SaveConfigsTabs();
2776 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2779 private async Task ShowUserTimeline()
2781 var post = this.CurrentPost;
2782 if (post == null || !this.ExistCurrentPost) return;
2783 await this.AddNewTabForUserTimeline(post.ScreenName);
2786 private async Task ShowRetweeterTimeline()
2788 var retweetedBy = this.CurrentPost?.RetweetedBy;
2789 if (retweetedBy == null || !this.ExistCurrentPost) return;
2790 await this.AddNewTabForUserTimeline(retweetedBy);
2793 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2795 if (e.KeyCode == Keys.Escape)
2797 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2798 this.SaveConfigsTabs();
2799 e.SuppressKeyPress = true;
2803 public async Task AddNewTabForUserTimeline(string user)
2805 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2806 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2808 if (tb.ScreenName == user)
2810 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2811 this.ListTab.SelectedIndex = tabIndex;
2816 var tabName = "user:" + user;
2817 while (this.statuses.ContainsTab(tabName))
2822 var tab = new UserTimelineTabModel(tabName, user);
2823 this.statuses.AddTab(tab);
2824 this.AddNewTab(tab, startup: false);
2826 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2827 this.SaveConfigsTabs();
2829 await this.RefreshTabAsync(tab);
2832 public bool AddNewTab(TabModel tab, bool startup)
2835 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2839 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2841 var tabPage = new TabPage();
2842 var listCustom = new DetailsListView();
2844 var cnt = this.statuses.Tabs.Count;
2846 // ToDo:Create and set controls follow tabtypes
2848 using (ControlTransaction.Update(listCustom))
2849 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2850 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2851 using (ControlTransaction.Layout(this.SplitContainer1, false))
2852 using (ControlTransaction.Layout(this.ListTab, false))
2853 using (ControlTransaction.Layout(this))
2854 using (ControlTransaction.Layout(tabPage, false))
2856 tabPage.Controls.Add(listCustom);
2859 var userTab = tab as UserTimelineTabModel;
2860 var listTab = tab as ListTimelineTabModel;
2861 var searchTab = tab as PublicSearchTabModel;
2863 if (userTab != null || listTab != null)
2865 var label = new Label
2867 Dock = DockStyle.Top,
2872 if (listTab != null)
2874 label.Text = listTab.ListInfo.ToString();
2876 else if (userTab != null)
2878 label.Text = userTab.ScreenName + "'s Timeline";
2880 label.TextAlign = ContentAlignment.MiddleLeft;
2881 using (var tmpComboBox = new ComboBox())
2883 label.Height = tmpComboBox.Height;
2885 tabPage.Controls.Add(label);
2888 else if (searchTab != null)
2890 var pnl = new Panel();
2892 var lbl = new Label();
2893 var cmb = new ComboBox();
2894 var btn = new Button();
2895 var cmbLang = new ComboBox();
2897 using (ControlTransaction.Layout(pnl, false))
2899 pnl.Controls.Add(cmb);
2900 pnl.Controls.Add(cmbLang);
2901 pnl.Controls.Add(btn);
2902 pnl.Controls.Add(lbl);
2903 pnl.Name = "panelSearch";
2905 pnl.Dock = DockStyle.Top;
2906 pnl.Height = cmb.Height;
2907 pnl.Enter += this.SearchControls_Enter;
2908 pnl.Leave += this.SearchControls_Leave;
2911 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2912 cmb.Dock = DockStyle.Fill;
2913 cmb.Name = "comboSearch";
2914 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2915 cmb.ImeMode = ImeMode.NoControl;
2916 cmb.TabStop = false;
2918 cmb.AutoCompleteMode = AutoCompleteMode.None;
2919 cmb.KeyDown += this.SearchComboBox_KeyDown;
2922 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2923 cmbLang.Dock = DockStyle.Right;
2925 cmbLang.Name = "comboLang";
2926 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2927 cmbLang.TabStop = false;
2928 cmbLang.TabIndex = 2;
2929 cmbLang.Items.Add("");
2930 cmbLang.Items.Add("ja");
2931 cmbLang.Items.Add("en");
2932 cmbLang.Items.Add("ar");
2933 cmbLang.Items.Add("da");
2934 cmbLang.Items.Add("nl");
2935 cmbLang.Items.Add("fa");
2936 cmbLang.Items.Add("fi");
2937 cmbLang.Items.Add("fr");
2938 cmbLang.Items.Add("de");
2939 cmbLang.Items.Add("hu");
2940 cmbLang.Items.Add("is");
2941 cmbLang.Items.Add("it");
2942 cmbLang.Items.Add("no");
2943 cmbLang.Items.Add("pl");
2944 cmbLang.Items.Add("pt");
2945 cmbLang.Items.Add("ru");
2946 cmbLang.Items.Add("es");
2947 cmbLang.Items.Add("sv");
2948 cmbLang.Items.Add("th");
2950 lbl.Text = "Search(C-S-f)";
2951 lbl.Name = "label1";
2952 lbl.Dock = DockStyle.Left;
2954 lbl.Height = cmb.Height;
2955 lbl.TextAlign = ContentAlignment.MiddleLeft;
2958 btn.Text = "Search";
2959 btn.Name = "buttonSearch";
2960 btn.UseVisualStyleBackColor = true;
2961 btn.Dock = DockStyle.Right;
2962 btn.TabStop = false;
2964 btn.Click += this.SearchButton_Click;
2966 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
2968 cmb.Items.Add(searchTab.SearchWords);
2969 cmb.Text = searchTab.SearchWords;
2972 cmbLang.Text = searchTab.SearchLang;
2974 tabPage.Controls.Add(pnl);
2978 tabPage.Tag = listCustom;
2979 this.ListTab.Controls.Add(tabPage);
2981 tabPage.Location = new Point(4, 4);
2982 tabPage.Name = "CTab" + cnt;
2983 tabPage.Size = new Size(380, 260);
2984 tabPage.TabIndex = 2 + cnt;
2985 tabPage.Text = tab.TabName;
2986 tabPage.UseVisualStyleBackColor = true;
2987 tabPage.AccessibleRole = AccessibleRole.PageTab;
2989 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
2990 listCustom.TabIndex = 1;
2991 listCustom.AllowColumnReorder = true;
2992 listCustom.ContextMenuStrip = this.ContextMenuOperate;
2993 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
2994 listCustom.Dock = DockStyle.Fill;
2995 listCustom.FullRowSelect = true;
2996 listCustom.HideSelection = false;
2997 listCustom.Location = new Point(0, 0);
2998 listCustom.Margin = new Padding(0);
2999 listCustom.Name = "CList" + Environment.TickCount;
3000 listCustom.ShowItemToolTips = true;
3001 listCustom.Size = new Size(380, 260);
3002 listCustom.UseCompatibleStateImageBehavior = false;
3003 listCustom.View = View.Details;
3004 listCustom.OwnerDraw = true;
3005 listCustom.VirtualMode = true;
3007 listCustom.GridLines = this.settings.Common.ShowGrid;
3008 listCustom.AllowDrop = true;
3010 this.InitColumns(listCustom, startup);
3012 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3013 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3014 listCustom.ColumnClick += this.MyList_ColumnClick;
3015 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3016 listCustom.DragDrop += this.TweenMain_DragDrop;
3017 listCustom.DragEnter += this.TweenMain_DragEnter;
3018 listCustom.DragOver += this.TweenMain_DragOver;
3019 listCustom.MouseClick += this.MyList_MouseClick;
3020 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3021 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3022 listCustom.HScrolled += this.MyList_HScrolled;
3025 var state = new TimelineListViewState(listCustom, tab);
3026 this.listViewState[tab.TabName] = state;
3031 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3033 var tabInfo = this.statuses.GetTabByName(tabName);
3034 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3039 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3040 var result = MessageBox.Show(
3042 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3043 MessageBoxButtons.OKCancel,
3044 MessageBoxIcon.Question,
3045 MessageBoxDefaultButton.Button2);
3046 if (result == DialogResult.Cancel)
3052 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3056 var tabPage = this.ListTab.TabPages[tabIndex];
3058 this.SetListProperty(); // 他のタブに列幅等を反映
3060 this.listViewState.Remove(tabName);
3063 var listCustom = (DetailsListView)tabPage.Tag;
3066 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3067 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3068 using (ControlTransaction.Layout(this.SplitContainer1, false))
3069 using (ControlTransaction.Layout(this.ListTab, false))
3070 using (ControlTransaction.Layout(this))
3071 using (ControlTransaction.Layout(tabPage, false))
3073 if (this.CurrentTabName == tabName)
3075 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3076 this.beforeSelectedTab = null;
3078 this.ListTab.Controls.Remove(tabPage);
3081 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3083 using var label = tabPage.Controls["labelUser"];
3084 tabPage.Controls.Remove(label);
3086 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3088 using var pnl = tabPage.Controls["panelSearch"];
3090 pnl.Enter -= this.SearchControls_Enter;
3091 pnl.Leave -= this.SearchControls_Leave;
3092 tabPage.Controls.Remove(pnl);
3094 foreach (Control ctrl in pnl.Controls)
3096 if (ctrl.Name == "buttonSearch")
3098 ctrl.Click -= this.SearchButton_Click;
3100 else if (ctrl.Name == "comboSearch")
3102 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3104 pnl.Controls.Remove(ctrl);
3109 tabPage.Controls.Remove(listCustom);
3111 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3112 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3113 listCustom.ColumnClick -= this.MyList_ColumnClick;
3114 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3115 listCustom.DragDrop -= this.TweenMain_DragDrop;
3116 listCustom.DragEnter -= this.TweenMain_DragEnter;
3117 listCustom.DragOver -= this.TweenMain_DragOver;
3118 listCustom.MouseClick -= this.MyList_MouseClick;
3119 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3120 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3121 listCustom.HScrolled -= this.MyList_HScrolled;
3123 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3124 listCustom.Columns.Clear();
3125 cols.ForEach(col => col.Dispose());
3128 listCustom.ContextMenuStrip = null;
3129 listCustom.ColumnHeaderContextMenuStrip = null;
3130 listCustom.Font = null;
3132 listCustom.SmallImageList = null;
3133 listCustom.ListViewItemSorter = null;
3136 this.listCache?.PurgeCache();
3140 listCustom.Dispose();
3141 this.statuses.RemoveTab(tabName);
3146 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3148 this.listCache?.PurgeCache();
3149 this.beforeSelectedTab = e.TabPage;
3152 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3156 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3159 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3160 if (!dragEnableRectangle.Contains(e.Location))
3162 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3163 tn = this.CurrentTabName;
3166 if (MyCommon.IsNullOrEmpty(tn)) return;
3168 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3171 var tabPage = this.ListTab.TabPages[tabIndex];
3172 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3177 this.tabDrag = false;
3180 var cpos = new Point(e.X, e.Y);
3181 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3183 var rect = this.ListTab.GetTabRect(index);
3184 if (rect.Contains(cpos))
3186 this.rclickTabName = tab.TabName;
3192 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3194 this.SetMainWindowTitle();
3195 this.SetStatusLabelUrl();
3196 this.SetApiStatusLabel();
3197 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3198 this.Tag = this.ListTab.Tag;
3199 this.TabMenuControl(this.CurrentTabName);
3200 this.PushSelectPostChain();
3201 this.DispSelectedPost();
3204 private void SetListProperty()
3206 if (!this.isColumnChanged) return;
3208 var currentListView = this.CurrentListView;
3210 var dispOrder = new int[currentListView.Columns.Count];
3211 for (var i = 0; i < currentListView.Columns.Count; i++)
3213 for (var j = 0; j < currentListView.Columns.Count; j++)
3215 if (currentListView.Columns[j].DisplayIndex == i)
3224 foreach (TabPage tb in this.ListTab.TabPages)
3226 if (tb.Text == this.CurrentTabName)
3229 if (tb.Tag != null && tb.Controls.Count > 0)
3231 var lst = (DetailsListView)tb.Tag;
3232 for (var i = 0; i < lst.Columns.Count; i++)
3234 lst.Columns[dispOrder[i]].DisplayIndex = i;
3235 lst.Columns[i].Width = currentListView.Columns[i].Width;
3240 this.isColumnChanged = false;
3243 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3245 if (e.KeyChar == '@')
3247 if (!this.settings.Common.UseAtIdSupplement) return;
3249 var cnt = this.AtIdSupl.ItemCount;
3250 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3251 if (cnt != this.AtIdSupl.ItemCount)
3252 this.MarkSettingAtIdModified();
3255 else if (e.KeyChar == '#')
3257 if (!this.settings.Common.UseHashSupplement) return;
3258 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3263 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3264 => this.ShowSuplDialog(owner, dialog, 0, "");
3266 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3267 => this.ShowSuplDialog(owner, dialog, offset, "");
3269 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3271 dialog.StartsWith = startswith;
3278 dialog.ShowDialog();
3280 this.TopMost = this.settings.Common.AlwaysTop;
3281 var selStart = owner.SelectionStart;
3284 if (dialog.DialogResult == DialogResult.OK)
3286 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3290 fHalf = owner.Text.Substring(0, selStart - offset);
3292 if (selStart < owner.Text.Length)
3294 eHalf = owner.Text.Substring(selStart);
3296 owner.Text = fHalf + dialog.InputText + eHalf;
3297 owner.SelectionStart = selStart + dialog.InputText.Length;
3304 fHalf = owner.Text.Substring(0, selStart);
3306 if (selStart < owner.Text.Length)
3308 eHalf = owner.Text.Substring(selStart);
3310 owner.Text = fHalf + eHalf;
3313 owner.SelectionStart = selStart;
3319 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3322 if (!e.Alt && !e.Control && !e.Shift)
3324 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3326 var isSpace = false;
3327 foreach (var c in this.StatusText.Text)
3329 if (c == ' ' || c == ' ')
3342 this.StatusText.Text = "";
3343 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3347 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3350 private void StatusText_TextChanged(object sender, EventArgs e)
3353 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3354 this.lblLen.Text = pLen.ToString();
3357 this.StatusText.ForeColor = Color.Red;
3361 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3364 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3366 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3368 this.inReplyTo = null;
3373 /// メンション以外の文字列が含まれていないテキストであるか判定します
3375 internal static bool TextContainsOnlyMentions(string text)
3377 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3380 foreach (var mention in mentions)
3382 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3384 if (!string.IsNullOrWhiteSpace(textPart))
3387 startIndex = mention.Indices[1];
3390 var textPartLast = text.Substring(startIndex);
3392 if (!string.IsNullOrWhiteSpace(textPartLast))
3399 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3401 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3403 var autoPopulatedUserIdList = new List<long>();
3405 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3406 if (replyToPost != null)
3408 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3410 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3411 autoPopulatedUserIdList.Add(replyToPost.UserId);
3413 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3415 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3417 statusText = statusText.Substring(screenName.Length + 2);
3418 autoPopulatedUserIdList.Add(userId);
3424 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3430 /// attachment_url に指定可能な URL が含まれていれば除去
3432 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3434 attachmentUrl = null;
3436 // attachment_url は media_id と同時に使用できない
3437 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3440 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3444 attachmentUrl = match.Value;
3447 statusText = statusText.Substring(0, match.Index);
3449 // テキストと URL の間にスペースが含まれていれば除去
3450 return statusText.TrimEnd(' ');
3453 private string FormatStatusTextExtended(string statusText)
3454 => this.FormatStatusTextExtended(statusText, out _, out _);
3457 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3459 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3461 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3463 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3465 return this.FormatStatusText(statusText);
3468 internal string FormatStatusText(string statusText)
3469 => this.FormatStatusText(statusText, Control.ModifierKeys);
3472 /// ツイート投稿前のフッター付与などの前処理を行います
3474 internal string FormatStatusText(string statusText, Keys modifierKeys)
3476 statusText = statusText.Replace("\r\n", "\n");
3478 if (this.SeparateUrlAndFullwidthCharacter)
3481 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3484 if (this.settings.Common.WideSpaceConvert)
3486 // 文中の全角スペースを半角スペース1個にする
3487 statusText = statusText.Replace(" ", " ");
3490 // DM の場合はこれ以降の処理を行わない
3491 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3495 if (this.settings.Common.PostShiftEnter)
3497 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3501 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3502 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3504 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3507 if (statusText.Contains("RT @"))
3508 disableFooter = true;
3510 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3511 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3513 var mentionSelf = $"@{this.tw.Username} ";
3514 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3516 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3517 statusText = statusText.Substring(mentionSelf.Length);
3524 var hashtag = this.HashMgr.UseHash;
3525 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3527 if (this.HashMgr.IsHead)
3528 header = this.HashMgr.UseHash + " ";
3530 footer = " " + this.HashMgr.UseHash;
3535 if (this.settings.Local.UseRecommendStatus)
3538 footer += this.recommendedStatusFooter;
3540 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3542 // テキストボックスに入力されている文字列を使用する
3543 footer += " " + this.settings.Local.StatusText.Trim();
3547 statusText = header + statusText + footer;
3549 if (this.preventSmsCommand)
3551 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3552 // 参照: https://support.twitter.com/articles/14020
3554 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3555 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3557 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3558 statusText = '\u200b' + statusText;
3566 /// 投稿欄に表示する入力可能な文字数を計算します
3568 private int GetRestStatusCount(string statusText)
3570 var remainCount = this.tw.GetTextLengthRemain(statusText);
3572 var uploadService = this.GetSelectedImageService();
3573 if (uploadService != null)
3575 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3576 remainCount -= uploadService.GetReservedTextLength(1);
3582 private IMediaUploadService? GetSelectedImageService()
3583 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3586 /// 全てのタブの振り分けルールを反映し直します
3588 private void ApplyPostFilters()
3590 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3592 this.statuses.FilterAll();
3594 var listView = this.CurrentListView;
3595 using (ControlTransaction.Update(listView))
3597 this.listCache?.PurgeCache();
3598 this.listCache?.UpdateListSize();
3601 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3603 var tabPage = this.ListTab.TabPages[index];
3605 if (this.settings.Common.TabIconDisp)
3607 if (tab.UnreadCount > 0)
3608 tabPage.ImageIndex = 0;
3610 tabPage.ImageIndex = -1;
3614 if (!this.settings.Common.TabIconDisp)
3615 this.ListTab.Refresh();
3617 this.SetMainWindowTitle();
3618 this.SetStatusLabelUrl();
3622 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3623 => e.DrawDefault = true;
3625 private void MyList_HScrolled(object sender, EventArgs e)
3626 => ((DetailsListView)sender).Refresh();
3628 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3630 base.ScaleControl(factor, specified);
3632 ScaleChildControl(this.TabImage, factor);
3634 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3635 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3637 foreach (var listview in listviews)
3639 ScaleChildControl(listview, factor);
3643 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3645 var tab = this.CurrentTab;
3647 if (tab.AllCount == 0)
3649 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3653 var selectedIndex = tab.SelectedIndex;
3658 case SEARCHTYPE.NextSearch: // 次を検索
3659 if (selectedIndex != -1)
3660 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3664 case SEARCHTYPE.PrevSearch: // 前を検索
3665 if (selectedIndex != -1)
3666 startIndex = Math.Max(selectedIndex - 1, 0);
3668 startIndex = tab.AllCount - 1;
3670 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3672 if (selectedIndex != -1)
3673 startIndex = selectedIndex;
3679 Func<string, bool> stringComparer;
3682 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3684 catch (ArgumentException)
3686 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3690 var reverse = searchType == SEARCHTYPE.PrevSearch;
3691 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3692 .DefaultIfEmpty(-1).First();
3694 if (foundIndex == -1)
3696 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3700 var listView = this.CurrentListView;
3701 this.SelectListItem(listView, foundIndex);
3702 listView.EnsureVisible(foundIndex);
3705 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3706 => this.ShowSearchDialog(); // 検索メニュー
3708 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3710 var previousSearch = this.SearchDialog.ResultOptions;
3711 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3713 this.SearchDialog.Reset();
3714 this.ShowSearchDialog();
3720 previousSearch.Query,
3721 previousSearch.CaseSensitive,
3722 previousSearch.UseRegex,
3723 SEARCHTYPE.NextSearch);
3726 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3728 var previousSearch = this.SearchDialog.ResultOptions;
3729 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3731 this.SearchDialog.Reset();
3732 this.ShowSearchDialog();
3738 previousSearch.Query,
3739 previousSearch.CaseSensitive,
3740 previousSearch.UseRegex,
3741 SEARCHTYPE.PrevSearch);
3745 /// 検索ダイアログを表示し、検索を実行します
3747 private void ShowSearchDialog()
3749 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3751 this.TopMost = this.settings.Common.AlwaysTop;
3754 this.TopMost = this.settings.Common.AlwaysTop;
3756 var searchOptions = this.SearchDialog.ResultOptions!;
3757 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3759 if (searchOptions.NewTab)
3761 var tabName = Properties.Resources.SearchResults_TabName;
3765 tabName = this.statuses.MakeTabName(tabName);
3767 catch (TabException ex)
3769 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3772 var resultTab = new LocalSearchTabModel(tabName);
3773 this.AddNewTab(resultTab, startup: false);
3774 this.statuses.AddTab(resultTab);
3776 var targetTab = this.CurrentTab;
3778 Func<string, bool> stringComparer;
3781 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3783 catch (ArgumentException)
3785 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3789 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3790 if (foundIndices.Length == 0)
3792 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3796 var foundPosts = foundIndices.Select(x => targetTab[x]);
3797 foreach (var post in foundPosts)
3799 resultTab.AddPostQueue(post);
3802 this.statuses.DistributePosts();
3803 this.RefreshTimeline();
3805 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3806 this.ListTab.SelectedIndex = tabIndex;
3811 searchOptions.Query,
3812 searchOptions.CaseSensitive,
3813 searchOptions.UseRegex,
3814 SEARCHTYPE.DialogSearch);
3817 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3819 this.AddNewTabForSearch(searchOptions.Query);
3823 /// <summary>発言検索に使用するメソッドを生成します</summary>
3824 /// <exception cref="ArgumentException">
3825 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3827 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3831 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3832 var regex = new Regex(query, regexOption);
3834 return x => regex.IsMatch(x);
3838 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3840 return x => x.IndexOf(query, comparisonType) != -1;
3844 private void AboutMenuItem_Click(object sender, EventArgs e)
3846 using (var about = new TweenAboutBox())
3848 about.ShowDialog(this);
3850 this.TopMost = this.settings.Common.AlwaysTop;
3853 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3855 var bgnIdx = this.statuses.SelectedTabIndex;
3857 if (this.ImageSelector.Enabled)
3860 TabModel? foundTab = null;
3864 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3866 var unreadIndex = tab.NextUnreadIndex;
3867 if (unreadIndex != -1)
3869 this.ListTab.SelectedIndex = index;
3871 foundIndex = unreadIndex;
3876 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3877 if (foundTab == null && bgnIdx > 0)
3879 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3881 var unreadIndex = tab.NextUnreadIndex;
3882 if (unreadIndex != -1)
3884 this.ListTab.SelectedIndex = index;
3886 foundIndex = unreadIndex;
3892 DetailsListView lst;
3894 if (foundTab == null)
3896 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3897 this.ListTab.SelectedIndex = 0;
3898 var tabPage = this.ListTab.TabPages[0];
3899 var tab = this.statuses.Tabs[0];
3901 if (tab.AllCount == 0)
3904 if (this.statuses.SortOrder == SortOrder.Ascending)
3905 foundIndex = tab.AllCount - 1;
3909 lst = (DetailsListView)tabPage.Tag;
3913 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3914 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3917 this.SelectListItem(lst, foundIndex);
3919 if (this.statuses.SortMode == ComparerMode.Id)
3921 var rowHeight = lst.SmallImageList.ImageSize.Height;
3922 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3923 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3929 lst.EnsureVisible(foundIndex);
3934 lst.EnsureVisible(foundIndex);
3940 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
3942 var tab = this.CurrentTab;
3943 var post = this.CurrentPost;
3944 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
3945 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
3948 private async void VerUpMenuItem_Click(object sender, EventArgs e)
3949 => await this.CheckNewVersion(false);
3951 private void RunTweenUp()
3953 var pinfo = new ProcessStartInfo
3955 UseShellExecute = true,
3956 WorkingDirectory = this.settings.SettingsPath,
3957 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
3958 Arguments = "\"" + Application.StartupPath + "\"",
3963 Process.Start(pinfo);
3967 MessageBox.Show("Failed to execute TweenUp3.exe.");
3971 public readonly record struct VersionInfo(
3978 /// OpenTween の最新バージョンの情報を取得します
3980 public async Task<VersionInfo> GetVersionInfoAsync()
3982 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
3983 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
3985 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
3986 .ConfigureAwait(false);
3988 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
3989 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
3991 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
3992 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
3994 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
3996 return new VersionInfo
3998 Version = Version.Parse(msgHeader[0]),
3999 DownloadUri = new Uri(msgHeader[1]),
4000 ReleaseNote = msgBody,
4004 private async Task CheckNewVersion(bool startup = false)
4006 if (ApplicationSettings.VersionInfoUrl == null)
4007 return; // 更新チェック無効化
4011 var versionInfo = await this.GetVersionInfoAsync();
4013 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4018 var msgtext = string.Format(
4019 Properties.Resources.CheckNewVersionText7,
4020 MyCommon.GetReadableVersion(),
4021 MyCommon.GetReadableVersion(versionInfo.Version));
4022 msgtext = MyCommon.ReplaceAppName(msgtext);
4026 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4027 MessageBoxButtons.OK,
4028 MessageBoxIcon.Information);
4033 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4036 using var dialog = new UpdateDialog();
4038 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4039 MyCommon.GetReadableVersion(versionInfo.Version));
4040 dialog.DetailsText = versionInfo.ReleaseNote;
4042 if (dialog.ShowDialog(this) == DialogResult.Yes)
4044 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4046 else if (dialog.SkipButtonPressed)
4048 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4049 this.MarkSettingCommonModified();
4054 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4058 Properties.Resources.CheckNewVersionText10,
4059 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4060 MessageBoxButtons.OK,
4061 MessageBoxIcon.Exclamation,
4062 MessageBoxDefaultButton.Button2);
4067 private void UpdateSelectedPost()
4069 // 件数関連の場合、タイトル即時書き換え
4070 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4071 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4072 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4073 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4075 this.SetMainWindowTitle();
4077 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4078 this.SetStatusLabelUrl();
4080 if (this.settings.Common.TabIconDisp)
4082 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4084 if (tab.UnreadCount == 0)
4086 var tabPage = this.ListTab.TabPages[index];
4087 if (tabPage.ImageIndex == 0)
4088 tabPage.ImageIndex = -1;
4094 this.ListTab.Refresh();
4097 this.DispSelectedPost();
4100 private void DispSelectedPost()
4101 => this.DispSelectedPost(false);
4103 private PostClass displayPost = new();
4106 /// サムネイル表示に使用する CancellationToken の生成元
4108 private CancellationTokenSource? thumbnailTokenSource = null;
4110 private void DispSelectedPost(bool forceupdate)
4112 var currentPost = this.CurrentPost;
4113 if (currentPost == null)
4116 var oldDisplayPost = this.displayPost;
4117 this.displayPost = currentPost;
4119 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4122 var loadTasks = new TaskCollection();
4123 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4125 if (this.settings.Common.PreviewEnable)
4127 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4128 oldTokenSource?.Cancel();
4130 var token = this.thumbnailTokenSource!.Token;
4131 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4135 this.SplitContainer3.Panel2Collapsed = true;
4138 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4140 .IgnoreException(x => x is OperationCanceledException)
4144 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4146 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4148 var timeout = Task.Delay(100);
4149 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4151 token.ThrowIfCancellationRequested();
4153 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4154 this.SplitContainer3.Panel2Collapsed = true;
4158 token.ThrowIfCancellationRequested();
4160 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4163 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4164 => await this.OpenApplicationWebsite();
4166 private async Task OpenApplicationWebsite()
4167 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4169 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4170 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4172 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4174 var tab = this.CurrentTab;
4175 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4177 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4178 if (pnl.Controls["comboSearch"].Focused ||
4179 pnl.Controls["comboLang"].Focused ||
4180 pnl.Controls["buttonSearch"].Focused) return;
4183 if (e.Control || e.Shift || e.Alt)
4186 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4189 e.SuppressKeyPress = true;
4192 if (asyncTask != null)
4196 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4198 private void InitializeShortcuts()
4200 this.shortcutCommands = new[]
4202 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4203 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4204 .FocusedOn(FocusedControl.ListTab)
4205 .Do(() => SendKeys.Send("{DOWN}")),
4207 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4208 .FocusedOn(FocusedControl.ListTab)
4209 .Do(() => SendKeys.Send("{UP}")),
4211 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4212 .FocusedOn(FocusedControl.ListTab)
4213 .Do(() => SendKeys.Send("{PGDN}")),
4215 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4216 .FocusedOn(FocusedControl.ListTab)
4217 .Do(() => SendKeys.Send("{PGUP}")),
4219 ShortcutCommand.Create(Keys.F1)
4220 .Do(() => this.OpenApplicationWebsite()),
4222 ShortcutCommand.Create(Keys.F3)
4223 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4225 ShortcutCommand.Create(Keys.F5)
4226 .Do(() => this.DoRefresh()),
4228 ShortcutCommand.Create(Keys.F6)
4229 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4231 ShortcutCommand.Create(Keys.F7)
4232 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4234 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4235 .NotFocusedOn(FocusedControl.StatusText)
4238 this.CurrentTab.ClearAnchor();
4239 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4242 ShortcutCommand.Create(Keys.G)
4243 .NotFocusedOn(FocusedControl.StatusText)
4246 this.CurrentTab.ClearAnchor();
4247 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4250 ShortcutCommand.Create(Keys.Right, Keys.N)
4251 .FocusedOn(FocusedControl.ListTab)
4252 .Do(() => this.GoRelPost(forward: true)),
4254 ShortcutCommand.Create(Keys.Left, Keys.P)
4255 .FocusedOn(FocusedControl.ListTab)
4256 .Do(() => this.GoRelPost(forward: false)),
4258 ShortcutCommand.Create(Keys.OemPeriod)
4259 .FocusedOn(FocusedControl.ListTab)
4260 .Do(() => this.GoAnchor()),
4262 ShortcutCommand.Create(Keys.I)
4263 .FocusedOn(FocusedControl.ListTab)
4264 .OnlyWhen(() => this.StatusText.Enabled)
4265 .Do(() => this.StatusText.Focus()),
4267 ShortcutCommand.Create(Keys.Enter)
4268 .FocusedOn(FocusedControl.ListTab)
4269 .Do(() => this.ListItemDoubleClickAction()),
4271 ShortcutCommand.Create(Keys.R)
4272 .FocusedOn(FocusedControl.ListTab)
4273 .Do(() => this.DoRefresh()),
4275 ShortcutCommand.Create(Keys.L)
4276 .FocusedOn(FocusedControl.ListTab)
4279 this.CurrentTab.ClearAnchor();
4280 this.GoPost(forward: true);
4283 ShortcutCommand.Create(Keys.H)
4284 .FocusedOn(FocusedControl.ListTab)
4287 this.CurrentTab.ClearAnchor();
4288 this.GoPost(forward: false);
4291 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4292 .FocusedOn(FocusedControl.ListTab)
4295 this.CurrentTab.ClearAnchor();
4299 ShortcutCommand.Create(Keys.S)
4300 .FocusedOn(FocusedControl.ListTab)
4303 this.CurrentTab.ClearAnchor();
4304 this.GoNextTab(forward: true);
4307 ShortcutCommand.Create(Keys.A)
4308 .FocusedOn(FocusedControl.ListTab)
4311 this.CurrentTab.ClearAnchor();
4312 this.GoNextTab(forward: false);
4315 // ] in_reply_to参照元へ戻る
4316 ShortcutCommand.Create(Keys.Oem4)
4317 .FocusedOn(FocusedControl.ListTab)
4320 this.CurrentTab.ClearAnchor();
4321 return this.GoInReplyToPostTree();
4324 // [ in_reply_toへジャンプ
4325 ShortcutCommand.Create(Keys.Oem6)
4326 .FocusedOn(FocusedControl.ListTab)
4329 this.CurrentTab.ClearAnchor();
4330 this.GoBackInReplyToPostTree();
4333 ShortcutCommand.Create(Keys.Escape)
4334 .FocusedOn(FocusedControl.ListTab)
4337 this.CurrentTab.ClearAnchor();
4338 var tab = this.CurrentTab;
4339 var tabtype = tab.TabType;
4340 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4342 this.RemoveSpecifiedTab(tab.TabName, false);
4343 this.SaveConfigsTabs();
4347 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4348 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4349 .FocusedOn(FocusedControl.ListTab)
4350 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4352 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4353 ShortcutCommand.Create(Keys.Up, Keys.Down)
4354 .FocusedOn(FocusedControl.PostBrowser)
4357 ShortcutCommand.Create(Keys.Control | Keys.R)
4358 .Do(() => this.MakeReplyText()),
4360 ShortcutCommand.Create(Keys.Control | Keys.D)
4361 .Do(() => this.DoStatusDelete()),
4363 ShortcutCommand.Create(Keys.Control | Keys.M)
4364 .Do(() => this.MakeDirectMessageText()),
4366 ShortcutCommand.Create(Keys.Control | Keys.S)
4367 .Do(() => this.FavoriteChange(favAdd: true)),
4369 ShortcutCommand.Create(Keys.Control | Keys.I)
4370 .Do(() => this.DoRepliedStatusOpen()),
4372 ShortcutCommand.Create(Keys.Control | Keys.Q)
4373 .Do(() => this.DoQuoteOfficial()),
4375 ShortcutCommand.Create(Keys.Control | Keys.B)
4376 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4378 ShortcutCommand.Create(Keys.Control | Keys.T)
4379 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4381 ShortcutCommand.Create(Keys.Control | Keys.L)
4382 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4384 ShortcutCommand.Create(Keys.Control | Keys.Y)
4385 .NotFocusedOn(FocusedControl.PostBrowser)
4386 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4388 ShortcutCommand.Create(Keys.Control | Keys.F)
4389 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4391 ShortcutCommand.Create(Keys.Control | Keys.U)
4392 .Do(() => this.ShowUserTimeline()),
4394 ShortcutCommand.Create(Keys.Control | Keys.H)
4395 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4397 ShortcutCommand.Create(Keys.Control | Keys.O)
4398 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4400 ShortcutCommand.Create(Keys.Control | Keys.E)
4401 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4403 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4404 .FocusedOn(FocusedControl.ListTab)
4405 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4407 ShortcutCommand.Create(Keys.Control | Keys.N)
4408 .FocusedOn(FocusedControl.ListTab)
4409 .Do(() => this.GoNextTab(forward: true)),
4411 ShortcutCommand.Create(Keys.Control | Keys.P)
4412 .FocusedOn(FocusedControl.ListTab)
4413 .Do(() => this.GoNextTab(forward: false)),
4415 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4416 .FocusedOn(FocusedControl.ListTab)
4417 .Do(() => this.CopyStot()),
4419 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4420 ShortcutCommand.Create(Keys.Control | Keys.D1)
4421 .FocusedOn(FocusedControl.ListTab)
4422 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4423 .Do(() => this.ListTab.SelectedIndex = 0),
4425 ShortcutCommand.Create(Keys.Control | Keys.D2)
4426 .FocusedOn(FocusedControl.ListTab)
4427 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4428 .Do(() => this.ListTab.SelectedIndex = 1),
4430 ShortcutCommand.Create(Keys.Control | Keys.D3)
4431 .FocusedOn(FocusedControl.ListTab)
4432 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4433 .Do(() => this.ListTab.SelectedIndex = 2),
4435 ShortcutCommand.Create(Keys.Control | Keys.D4)
4436 .FocusedOn(FocusedControl.ListTab)
4437 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4438 .Do(() => this.ListTab.SelectedIndex = 3),
4440 ShortcutCommand.Create(Keys.Control | Keys.D5)
4441 .FocusedOn(FocusedControl.ListTab)
4442 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4443 .Do(() => this.ListTab.SelectedIndex = 4),
4445 ShortcutCommand.Create(Keys.Control | Keys.D6)
4446 .FocusedOn(FocusedControl.ListTab)
4447 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4448 .Do(() => this.ListTab.SelectedIndex = 5),
4450 ShortcutCommand.Create(Keys.Control | Keys.D7)
4451 .FocusedOn(FocusedControl.ListTab)
4452 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4453 .Do(() => this.ListTab.SelectedIndex = 6),
4455 ShortcutCommand.Create(Keys.Control | Keys.D8)
4456 .FocusedOn(FocusedControl.ListTab)
4457 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4458 .Do(() => this.ListTab.SelectedIndex = 7),
4460 ShortcutCommand.Create(Keys.Control | Keys.D9)
4461 .FocusedOn(FocusedControl.ListTab)
4462 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4464 ShortcutCommand.Create(Keys.Control | Keys.A)
4465 .FocusedOn(FocusedControl.StatusText)
4466 .Do(() => this.StatusText.SelectAll()),
4468 ShortcutCommand.Create(Keys.Control | Keys.V)
4469 .FocusedOn(FocusedControl.StatusText)
4470 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4472 ShortcutCommand.Create(Keys.Control | Keys.Up)
4473 .FocusedOn(FocusedControl.StatusText)
4474 .Do(() => this.StatusTextHistoryBack()),
4476 ShortcutCommand.Create(Keys.Control | Keys.Down)
4477 .FocusedOn(FocusedControl.StatusText)
4478 .Do(() => this.StatusTextHistoryForward()),
4480 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4481 .FocusedOn(FocusedControl.StatusText)
4484 if (this.ListTab.SelectedIndex == 0)
4486 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4490 this.ListTab.SelectedIndex -= 1;
4492 this.StatusText.Focus();
4495 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4496 .FocusedOn(FocusedControl.StatusText)
4499 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4501 this.ListTab.SelectedIndex = 0;
4505 this.ListTab.SelectedIndex += 1;
4507 this.StatusText.Focus();
4510 ShortcutCommand.Create(Keys.Control | Keys.Y)
4511 .FocusedOn(FocusedControl.PostBrowser)
4514 var multiline = !this.settings.Local.StatusMultiline;
4515 this.settings.Local.StatusMultiline = multiline;
4516 this.MultiLineMenuItem.Checked = multiline;
4517 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4520 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4521 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4523 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4524 .Do(() => this.DoRefreshMore()),
4526 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4527 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4529 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4530 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4532 ShortcutCommand.Create(Keys.Shift | Keys.R)
4533 .NotFocusedOn(FocusedControl.StatusText)
4534 .Do(() => this.DoRefreshMore()),
4536 ShortcutCommand.Create(Keys.Shift | Keys.H)
4537 .FocusedOn(FocusedControl.ListTab)
4538 .Do(() => this.GoTopEnd(goTop: true)),
4540 ShortcutCommand.Create(Keys.Shift | Keys.L)
4541 .FocusedOn(FocusedControl.ListTab)
4542 .Do(() => this.GoTopEnd(goTop: false)),
4544 ShortcutCommand.Create(Keys.Shift | Keys.M)
4545 .FocusedOn(FocusedControl.ListTab)
4546 .Do(() => this.GoMiddle()),
4548 ShortcutCommand.Create(Keys.Shift | Keys.G)
4549 .FocusedOn(FocusedControl.ListTab)
4550 .Do(() => this.GoLast()),
4552 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4553 .FocusedOn(FocusedControl.ListTab)
4554 .Do(() => this.MoveMiddle()),
4556 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4557 .FocusedOn(FocusedControl.ListTab)
4558 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4560 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4561 .FocusedOn(FocusedControl.ListTab)
4562 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4564 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4565 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4566 .FocusedOn(FocusedControl.ListTab)
4567 .Do(() => this.GoFav(forward: true)),
4569 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4570 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4571 .FocusedOn(FocusedControl.ListTab)
4572 .Do(() => this.GoFav(forward: false)),
4574 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4575 .FocusedOn(FocusedControl.ListTab)
4576 .Do(() => this.GoBackSelectPostChain()),
4578 ShortcutCommand.Create(Keys.Alt | Keys.R)
4579 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4581 ShortcutCommand.Create(Keys.Alt | Keys.P)
4582 .OnlyWhen(() => this.CurrentPost != null)
4583 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4585 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4586 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4588 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4589 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4591 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4592 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4594 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4595 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4597 // 別タブの同じ書き込みへ(ALT+←/→)
4598 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4599 .FocusedOn(FocusedControl.ListTab)
4600 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4602 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4603 .FocusedOn(FocusedControl.ListTab)
4604 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4606 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4607 .Do(() => this.MakeReplyText(atAll: true)),
4609 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4610 .Do(() => this.CopyIdUri()),
4612 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4613 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4614 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4616 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4617 .Do(() => this.DoQuoteOfficial()),
4619 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4620 .Do(() => this.FavoriteChange(favAdd: false)),
4622 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4623 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4625 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4626 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4628 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4629 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4631 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4632 .Do(() => this.DoMoveToRTHome()),
4634 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4635 .FocusedOn(FocusedControl.StatusText)
4638 var tab = this.CurrentTab;
4639 var selectedIndex = tab.SelectedIndex;
4640 if (selectedIndex != -1 && selectedIndex > 0)
4642 var listView = this.CurrentListView;
4643 var idx = selectedIndex - 1;
4644 this.SelectListItem(listView, idx);
4645 listView.EnsureVisible(idx);
4649 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4650 .FocusedOn(FocusedControl.StatusText)
4653 var tab = this.CurrentTab;
4654 var selectedIndex = tab.SelectedIndex;
4655 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4657 var listView = this.CurrentListView;
4658 var idx = selectedIndex + 1;
4659 this.SelectListItem(listView, idx);
4660 listView.EnsureVisible(idx);
4664 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4665 .FocusedOn(FocusedControl.StatusText)
4668 if (this.StatusText.SelectionStart > 0)
4670 var endidx = this.StatusText.SelectionStart - 1;
4672 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4674 var c = this.StatusText.Text[i];
4675 if (char.IsLetterOrDigit(c) || c == '_')
4681 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4682 var cnt = this.AtIdSupl.ItemCount;
4683 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4684 if (this.AtIdSupl.ItemCount != cnt)
4685 this.MarkSettingAtIdModified();
4689 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4690 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4700 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4701 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4702 .FocusedOn(FocusedControl.ListTab)
4703 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4705 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4706 .FocusedOn(FocusedControl.ListTab)
4707 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4709 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4710 .FocusedOn(FocusedControl.ListTab)
4711 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4713 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4714 .FocusedOn(FocusedControl.ListTab)
4715 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4717 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4718 .FocusedOn(FocusedControl.ListTab)
4719 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4721 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4722 .FocusedOn(FocusedControl.ListTab)
4723 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4725 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4726 .FocusedOn(FocusedControl.ListTab)
4727 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4729 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4730 .FocusedOn(FocusedControl.ListTab)
4731 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4733 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4734 .FocusedOn(FocusedControl.ListTab)
4735 .Do(() => this.SetSortLastColumn()),
4737 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4738 .FocusedOn(FocusedControl.ListTab)
4739 .Do(() => this.FavoritesRetweetOfficial()),
4741 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4742 .FocusedOn(FocusedControl.ListTab)
4743 .Do(() => this.FavoritesRetweetUnofficial()),
4745 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4746 .FocusedOn(FocusedControl.ListTab)
4747 .Do(() => this.OpenUserAppointUrl()),
4749 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4750 .FocusedOn(FocusedControl.PostBrowser)
4751 .Do(() => this.DoReTweetUnofficial()),
4753 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4754 .OnlyWhen(() => this.ExistCurrentPost)
4755 .Do(() => this.tweetDetailsView.DoTranslation()),
4757 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4758 .Do(() => this.DoReTweetUnofficial()),
4760 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4761 .Do(() => this.CopyUserId()),
4763 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4764 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4766 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4767 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4769 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4770 .FocusedOn(FocusedControl.ListTab)
4771 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4772 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4776 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4778 // Task を返す非同期処理があれば asyncTask に代入する
4781 // ShortcutCommand に対応しているコマンドはここで処理される
4782 foreach (var command in this.shortcutCommands)
4784 if (command.IsMatch(keyData, focusedOn))
4786 asyncTask = command.RunCommand();
4787 return command.PreventDefault;
4794 private void GoNextTab(bool forward)
4796 var idx = this.statuses.SelectedTabIndex;
4797 var tabCount = this.statuses.Tabs.Count;
4801 if (idx > tabCount - 1) idx = 0;
4806 if (idx < 0) idx = tabCount - 1;
4808 this.ListTab.SelectedIndex = idx;
4811 private void CopyStot()
4813 var sb = new StringBuilder();
4814 var tab = this.CurrentTab;
4815 var isProtected = false;
4816 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4817 foreach (var post in tab.SelectedPosts)
4819 if (post.IsDeleted) continue;
4822 if (post.RetweetedId != null)
4823 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4825 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4829 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4834 MessageBox.Show(Properties.Resources.CopyStotText1);
4838 var clstr = sb.ToString();
4841 Clipboard.SetDataObject(clstr, false, 5, 100);
4843 catch (Exception ex)
4845 MessageBox.Show(ex.Message);
4850 private void CopyIdUri()
4852 var tab = this.CurrentTab;
4853 if (tab == null || tab is DirectMessagesTabModel)
4856 var copyUrls = new List<string>();
4857 foreach (var post in tab.SelectedPosts)
4858 copyUrls.Add(MyCommon.GetStatusUrl(post));
4860 if (copyUrls.Count == 0)
4865 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4867 catch (ExternalException ex)
4869 MessageBox.Show(ex.Message);
4873 private void GoFav(bool forward)
4875 var tab = this.CurrentTab;
4876 if (tab.AllCount == 0)
4879 var selectedIndex = tab.SelectedIndex;
4887 if (selectedIndex == -1)
4893 fIdx = selectedIndex + 1;
4894 if (fIdx > tab.AllCount - 1)
4897 toIdx = tab.AllCount;
4902 if (selectedIndex == -1)
4904 fIdx = tab.AllCount - 1;
4908 fIdx = selectedIndex - 1;
4916 for (var idx = fIdx; idx != toIdx; idx += stp)
4920 var listView = this.CurrentListView;
4921 this.SelectListItem(listView, idx);
4922 listView.EnsureVisible(idx);
4928 private void GoSamePostToAnotherTab(bool left)
4930 var tab = this.CurrentTab;
4932 // Directタブは対象外(見つかるはずがない)
4933 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4936 var selectedStatusId = tab.SelectedStatusId;
4937 if (selectedStatusId == null)
4940 int fIdx, toIdx, stp;
4945 if (this.ListTab.SelectedIndex == 0)
4951 fIdx = this.ListTab.SelectedIndex - 1;
4959 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4965 fIdx = this.ListTab.SelectedIndex + 1;
4967 toIdx = this.ListTab.TabCount;
4971 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
4973 var targetTab = this.statuses.Tabs[tabidx];
4976 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
4979 var foundIndex = targetTab.IndexOf(selectedStatusId);
4980 if (foundIndex != -1)
4982 this.ListTab.SelectedIndex = tabidx;
4983 var listView = this.CurrentListView;
4984 this.SelectListItem(listView, foundIndex);
4985 listView.EnsureVisible(foundIndex);
4991 private void GoPost(bool forward)
4993 var tab = this.CurrentTab;
4994 var currentPost = this.CurrentPost;
4996 if (currentPost == null)
4999 var selectedIndex = tab.SelectedIndex;
5001 int fIdx, toIdx, stp;
5005 fIdx = selectedIndex + 1;
5006 if (fIdx > tab.AllCount - 1) return;
5007 toIdx = tab.AllCount;
5012 fIdx = selectedIndex - 1;
5013 if (fIdx < 0) return;
5019 if (currentPost.RetweetedBy == null)
5021 name = currentPost.ScreenName;
5025 name = currentPost.RetweetedBy;
5027 for (var idx = fIdx; idx != toIdx; idx += stp)
5029 var post = tab[idx];
5030 if (post.RetweetedId == null)
5032 if (post.ScreenName == name)
5034 var listView = this.CurrentListView;
5035 this.SelectListItem(listView, idx);
5036 listView.EnsureVisible(idx);
5042 if (post.RetweetedBy == name)
5044 var listView = this.CurrentListView;
5045 this.SelectListItem(listView, idx);
5046 listView.EnsureVisible(idx);
5053 private void GoRelPost(bool forward)
5055 var tab = this.CurrentTab;
5056 var selectedIndex = tab.SelectedIndex;
5058 if (selectedIndex == -1)
5061 int fIdx, toIdx, stp;
5065 fIdx = selectedIndex + 1;
5066 if (fIdx > tab.AllCount - 1) return;
5067 toIdx = tab.AllCount;
5072 fIdx = selectedIndex - 1;
5073 if (fIdx < 0) return;
5078 var anchorPost = tab.AnchorPost;
5079 if (anchorPost == null)
5081 var currentPost = this.CurrentPost;
5082 if (currentPost == null)
5085 anchorPost = currentPost;
5086 tab.AnchorPost = currentPost;
5089 for (var idx = fIdx; idx != toIdx; idx += stp)
5091 var post = tab[idx];
5092 if (post.ScreenName == anchorPost.ScreenName ||
5093 post.RetweetedBy == anchorPost.ScreenName ||
5094 post.ScreenName == anchorPost.RetweetedBy ||
5095 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5096 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5097 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5098 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5099 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5101 var listView = this.CurrentListView;
5102 this.SelectListItem(listView, idx);
5103 listView.EnsureVisible(idx);
5109 private void GoAnchor()
5111 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5112 if (anchorStatusId == null)
5115 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5119 var listView = this.CurrentListView;
5120 this.SelectListItem(listView, idx);
5121 listView.EnsureVisible(idx);
5124 private void GoTopEnd(bool goTop)
5126 var listView = this.CurrentListView;
5127 if (listView.VirtualListSize == 0)
5135 item = listView.GetItemAt(0, 25);
5143 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5145 idx = listView.VirtualListSize - 1;
5149 this.SelectListItem(listView, idx);
5152 private void GoMiddle()
5154 var listView = this.CurrentListView;
5155 if (listView.VirtualListSize == 0)
5163 item = listView.GetItemAt(0, 0);
5173 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5176 idx2 = listView.VirtualListSize - 1;
5182 idx3 = (idx1 + idx2) / 2;
5184 this.SelectListItem(listView, idx3);
5187 private void GoLast()
5189 var listView = this.CurrentListView;
5190 if (listView.VirtualListSize == 0) return;
5192 if (this.statuses.SortOrder == SortOrder.Ascending)
5194 this.SelectListItem(listView, listView.VirtualListSize - 1);
5195 listView.EnsureVisible(listView.VirtualListSize - 1);
5199 this.SelectListItem(listView, 0);
5200 listView.EnsureVisible(0);
5204 private void MoveTop()
5206 var listView = this.CurrentListView;
5207 if (listView.SelectedIndices.Count == 0) return;
5208 var idx = listView.SelectedIndices[0];
5209 if (this.statuses.SortOrder == SortOrder.Ascending)
5211 listView.EnsureVisible(listView.VirtualListSize - 1);
5215 listView.EnsureVisible(0);
5217 listView.EnsureVisible(idx);
5220 private async Task GoInReplyToPostTree()
5222 var curTabClass = this.CurrentTab;
5223 var currentPost = this.CurrentPost;
5225 if (currentPost == null)
5228 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5232 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5234 currentPost = currentPost with
5236 InReplyToStatusId = post.InReplyToStatusId,
5237 InReplyToUser = post.InReplyToUser,
5238 IsReply = post.IsReply,
5240 curTabClass.ReplacePost(currentPost);
5241 this.listCache?.PurgeCache();
5243 var index = curTabClass.SelectedIndex;
5244 this.CurrentListView.RedrawItems(index, index, false);
5246 catch (WebApiException ex)
5248 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5252 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5254 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5256 this.replyChains = new Stack<ReplyChain>();
5258 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5261 string inReplyToTabName;
5262 var inReplyToId = currentPost.InReplyToStatusId;
5263 var inReplyToUser = currentPost.InReplyToUser;
5265 var inReplyToPosts = from tab in this.statuses.Tabs
5266 orderby tab != curTabClass
5267 from post in tab.Posts.Values
5268 where post.StatusId == inReplyToId
5269 let index = tab.IndexOf(post.StatusId)
5271 select new { Tab = tab, Index = index };
5273 var inReplyPost = inReplyToPosts.FirstOrDefault();
5274 if (inReplyPost == null)
5278 await Task.Run(async () =>
5280 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5281 .ConfigureAwait(false);
5284 this.statuses.AddPost(post);
5285 this.statuses.DistributePosts();
5288 catch (WebApiException ex)
5290 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5291 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5295 this.RefreshTimeline();
5297 inReplyPost = inReplyToPosts.FirstOrDefault();
5298 if (inReplyPost == null)
5300 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5304 inReplyToTabName = inReplyPost.Tab.TabName;
5305 inReplyToIndex = inReplyPost.Index;
5307 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5308 var tabPage = this.ListTab.TabPages[tabIndex];
5309 var listView = (DetailsListView)tabPage.Tag;
5311 if (this.CurrentTabName != inReplyToTabName)
5313 this.ListTab.SelectedIndex = tabIndex;
5316 this.SelectListItem(listView, inReplyToIndex);
5317 listView.EnsureVisible(inReplyToIndex);
5320 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5322 var curTabClass = this.CurrentTab;
5323 var currentPost = this.CurrentPost;
5325 if (currentPost == null)
5330 if (currentPost.InReplyToStatusId != null)
5332 var posts = from t in this.statuses.Tabs
5334 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5335 let indexOf = t.IndexOf(p.Value.StatusId)
5337 orderby isForward ? indexOf : indexOf * -1
5338 orderby t != curTabClass
5339 select new { Tab = t, Post = p.Value, Index = indexOf };
5342 var postList = posts.ToList();
5343 for (var i = postList.Count - 1; i >= 0; i--)
5346 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5348 postList.RemoveAt(index);
5351 var currentIndex = this.CurrentTab.SelectedIndex;
5352 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5353 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5354 if (post == null) post = postList.First();
5355 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5356 this.ListTab.SelectedIndex = tabIndex;
5357 var listView = this.CurrentListView;
5358 this.SelectListItem(listView, post.Index);
5359 listView.EnsureVisible(post.Index);
5361 catch (InvalidOperationException)
5369 if (this.replyChains == null || this.replyChains.Count < 1)
5371 var posts = from t in this.statuses.Tabs
5373 where p.Value.InReplyToStatusId == currentPost.StatusId
5374 let indexOf = t.IndexOf(p.Value.StatusId)
5377 orderby t != curTabClass
5378 select new { Tab = t, Index = indexOf };
5381 var post = posts.First();
5382 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5383 this.ListTab.SelectedIndex = tabIndex;
5384 var listView = this.CurrentListView;
5385 this.SelectListItem(listView, post.Index);
5386 listView.EnsureVisible(post.Index);
5388 catch (InvalidOperationException)
5395 var chainHead = this.replyChains.Pop();
5396 if (chainHead.InReplyToId == currentPost.StatusId)
5398 var tab = chainHead.OriginalTab;
5399 if (!this.statuses.Tabs.Contains(tab))
5401 this.replyChains = null;
5405 var idx = tab.IndexOf(chainHead.OriginalId);
5408 this.replyChains = null;
5412 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5415 this.ListTab.SelectedIndex = tabIndex;
5419 this.replyChains = null;
5421 var listView = this.CurrentListView;
5422 this.SelectListItem(listView, idx);
5423 listView.EnsureVisible(idx);
5429 this.replyChains = null;
5430 this.GoBackInReplyToPostTree(parallel);
5436 private void GoBackSelectPostChain()
5438 if (this.selectPostChains.Count > 1)
5441 TabModel? foundTab = null;
5447 this.selectPostChains.Pop();
5448 var (tab, post) = this.selectPostChains.Peek();
5450 if (!this.statuses.Tabs.Contains(tab))
5451 continue; // 該当タブが存在しないので無視
5455 idx = tab.IndexOf(post.StatusId);
5456 if (idx == -1) continue; // 該当ポストが存在しないので無視
5461 this.selectPostChains.Pop();
5463 catch (InvalidOperationException)
5469 while (this.selectPostChains.Count > 1);
5471 if (foundTab == null)
5474 // 履歴が残り1つであればクリアしておく
5475 if (this.selectPostChains.Count == 1)
5476 this.selectPostChains.Clear();
5480 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5481 var tabPage = this.ListTab.TabPages[tabIndex];
5482 var lst = (DetailsListView)tabPage.Tag;
5483 this.ListTab.SelectedIndex = tabIndex;
5487 this.SelectListItem(lst, idx);
5488 lst.EnsureVisible(idx);
5494 private void PushSelectPostChain()
5496 var currentTab = this.CurrentTab;
5497 var currentPost = this.CurrentPost;
5499 var count = this.selectPostChains.Count;
5502 var (tab, post) = this.selectPostChains.Peek();
5503 if (tab == currentTab)
5505 if (post == currentPost) return; // 最新の履歴と同一
5506 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5509 if (count >= 2500) this.TrimPostChain();
5510 this.selectPostChains.Push((currentTab, currentPost));
5513 private void TrimPostChain()
5515 if (this.selectPostChains.Count <= 2000) return;
5516 var p = new Stack<(TabModel, PostClass?)>(2000);
5517 for (var i = 0; i < 2000; i++)
5519 p.Push(this.selectPostChains.Pop());
5521 this.selectPostChains.Clear();
5522 for (var i = 0; i < 2000; i++)
5524 this.selectPostChains.Push(p.Pop());
5528 private bool GoStatus(PostId statusId)
5530 var tab = this.statuses.Tabs
5531 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5532 .Where(x => x.Contains(statusId))
5538 var index = tab.IndexOf(statusId);
5540 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5541 this.ListTab.SelectedIndex = tabIndex;
5543 var listView = this.CurrentListView;
5544 this.SelectListItem(listView, index);
5545 listView.EnsureVisible(index);
5550 private bool GoDirectMessage(PostId statusId)
5552 var tab = this.statuses.DirectMessageTab;
5553 var index = tab.IndexOf(statusId);
5558 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5559 this.ListTab.SelectedIndex = tabIndex;
5561 var listView = this.CurrentListView;
5562 this.SelectListItem(listView, index);
5563 listView.EnsureVisible(index);
5568 private void MyList_MouseClick(object sender, MouseEventArgs e)
5569 => this.CurrentTab.ClearAnchor();
5571 private void StatusText_Enter(object sender, EventArgs e)
5573 // フォーカスの戻り先を StatusText に設定
5574 this.Tag = this.StatusText;
5575 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5578 public Color InputBackColor
5579 => this.themeManager.ColorInputBackcolor;
5581 private void StatusText_Leave(object sender, EventArgs e)
5583 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5584 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5585 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5588 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5590 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5593 e.SuppressKeyPress = true;
5596 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5598 if (asyncTask != null)
5602 private void SaveConfigsAll(bool ifModified)
5606 this.SaveConfigsCommon();
5607 this.SaveConfigsLocal();
5608 this.SaveConfigsTabs();
5609 this.SaveConfigsAtId();
5613 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5614 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5615 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5619 private void SaveConfigsAtId()
5621 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5623 this.ModifySettingAtId = false;
5624 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5625 this.settings.SaveAtIdList();
5628 private void SaveConfigsCommon()
5630 if (this.ignoreConfigSave) return;
5632 this.ModifySettingCommon = false;
5633 lock (this.syncObject)
5635 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5636 this.settings.Common.SortColumn = this.statuses.SortMode switch
5638 ComparerMode.Nickname => 1, // ニックネーム
5639 ComparerMode.Data => 2, // 本文
5640 ComparerMode.Id => 3, // 時刻=発言Id
5641 ComparerMode.Name => 4, // 名前
5642 ComparerMode.Source => 7, // Source
5643 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5645 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5646 if (this.HashMgr.IsPermanent)
5648 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5652 this.settings.Common.HashSelected = "";
5654 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5655 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5656 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5657 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5658 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5660 this.settings.SaveCommon();
5664 private void SaveConfigsLocal()
5666 if (this.ignoreConfigSave) return;
5667 lock (this.syncObject)
5669 this.ModifySettingLocal = false;
5670 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5671 this.settings.Local.FormSize = this.mySize;
5672 this.settings.Local.FormLocation = this.myLoc;
5673 this.settings.Local.SplitterDistance = this.mySpDis;
5674 this.settings.Local.PreviewDistance = this.mySpDis3;
5675 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5676 this.settings.Local.StatusTextHeight = this.mySpDis2;
5678 if (this.ignoreConfigSave) return;
5679 this.settings.SaveLocal();
5683 private void SaveConfigsTabs()
5685 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5687 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5689 foreach (var tab in tabs)
5691 if (!tab.IsPermanentTabType)
5694 var tabSetting = new SettingTabs.SettingTabItem
5696 TabName = tab.TabName,
5697 TabType = tab.TabType,
5698 UnreadManage = tab.UnreadManage,
5699 Protected = tab.Protected,
5700 Notify = tab.Notify,
5701 SoundFile = tab.SoundFile,
5706 case FilterTabModel filterTab:
5707 tabSetting.FilterArray = filterTab.FilterArray;
5709 case UserTimelineTabModel userTab:
5710 tabSetting.User = userTab.ScreenName;
5711 tabSetting.UserId = userTab.UserId;
5713 case PublicSearchTabModel searchTab:
5714 tabSetting.SearchWords = searchTab.SearchWords;
5715 tabSetting.SearchLang = searchTab.SearchLang;
5717 case ListTimelineTabModel listTab:
5718 tabSetting.ListInfo = listTab.ListInfo;
5722 tabSettingList.Add(tabSetting);
5725 this.settings.Tabs.Tabs = tabSettingList;
5726 this.settings.SaveTabs();
5729 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5731 static void ShowFormatErrorDialog(IWin32Window owner)
5735 Properties.Resources.OpenURL_InvalidFormat,
5736 Properties.Resources.OpenURL_Caption,
5737 MessageBoxButtons.OK,
5738 MessageBoxIcon.Error
5742 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5743 if (ret != DialogResult.OK)
5746 var match = Twitter.StatusUrlRegex.Match(inputText);
5749 ShowFormatErrorDialog(this);
5755 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5756 await this.OpenRelatedTab(statusId);
5758 catch (OverflowException)
5760 ShowFormatErrorDialog(this);
5762 catch (TabException ex)
5764 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5768 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5770 var tab = this.CurrentTab;
5772 var rslt = MessageBox.Show(
5773 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5774 Properties.Resources.SaveLogMenuItem_ClickText2,
5775 MessageBoxButtons.YesNoCancel,
5776 MessageBoxIcon.Question);
5777 if (rslt == DialogResult.Cancel) return;
5779 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5780 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5781 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5782 this.SaveFileDialog1.FilterIndex = 0;
5783 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5784 this.SaveFileDialog1.RestoreDirectory = true;
5786 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5788 if (!this.SaveFileDialog1.ValidateNames) return;
5789 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5790 if (rslt == DialogResult.Yes)
5793 for (var idx = 0; idx < tab.AllCount; idx++)
5795 var post = tab[idx];
5798 protect = "Protect";
5799 sw.WriteLine(post.Nickname + "\t" +
5800 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5801 post.CreatedAt.ToLocalTimeString() + "\t" +
5802 post.ScreenName + "\t" +
5803 post.StatusId.Id + "\t" +
5804 post.ImageUrl + "\t" +
5805 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5811 foreach (var post in this.CurrentTab.SelectedPosts)
5815 protect = "Protect";
5816 sw.WriteLine(post.Nickname + "\t" +
5817 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5818 post.CreatedAt.ToLocalTimeString() + "\t" +
5819 post.ScreenName + "\t" +
5820 post.StatusId.Id + "\t" +
5821 post.ImageUrl + "\t" +
5822 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5827 this.TopMost = this.settings.Common.AlwaysTop;
5830 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5834 using (var inputName = new InputTabName())
5836 inputName.TabName = origTabName;
5837 inputName.ShowDialog();
5838 if (inputName.DialogResult == DialogResult.Cancel) return false;
5839 newTabName = inputName.TabName;
5841 this.TopMost = this.settings.Common.AlwaysTop;
5842 if (!MyCommon.IsNullOrEmpty(newTabName))
5845 if (this.statuses.ContainsTab(newTabName))
5847 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5848 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5852 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5853 var tabPage = this.ListTab.TabPages[tabIndex];
5856 if (tabPage != null)
5857 tabPage.Text = newTabName;
5859 this.statuses.RenameTab(origTabName, newTabName);
5861 var state = this.listViewState[origTabName];
5862 this.listViewState.Remove(origTabName);
5863 this.listViewState[newTabName] = state;
5865 this.SaveConfigsCommon();
5866 this.SaveConfigsTabs();
5867 this.rclickTabName = newTabName;
5876 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5878 if (e.Button == MouseButtons.Middle)
5880 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5882 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5884 this.RemoveSpecifiedTab(tab.TabName, true);
5885 this.SaveConfigsTabs();
5892 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5893 => this.TabRename(this.CurrentTabName, out _);
5895 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5897 if (this.settings.Common.TabMouseLock) return;
5898 if (e.Button == MouseButtons.Left)
5900 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5902 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5904 this.tabDrag = true;
5905 this.tabMouseDownPoint = e.Location;
5912 this.tabDrag = false;
5916 private void ListTab_DragEnter(object sender, DragEventArgs e)
5918 if (e.Data.GetDataPresent(typeof(TabPage)))
5919 e.Effect = DragDropEffects.Move;
5921 e.Effect = DragDropEffects.None;
5924 private void ListTab_DragDrop(object sender, DragEventArgs e)
5926 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5928 this.tabDrag = false;
5931 var cpos = new Point(e.X, e.Y);
5932 var spos = this.ListTab.PointToClient(cpos);
5933 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5935 var rect = this.ListTab.GetTabRect(index);
5936 if (rect.Contains(spos))
5939 if (spos.X <= (rect.Left + rect.Right) / 2)
5948 // タブのないところにドロップ->最後尾へ移動
5949 if (MyCommon.IsNullOrEmpty(tn))
5951 var lastTab = this.statuses.Tabs.Last();
5952 tn = lastTab.TabName;
5956 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
5957 if (tp.Text == tn) return;
5959 this.ReOrderTab(tp.Text, tn, bef);
5962 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
5964 var baseIndex = this.GetTabPageIndex(baseTabText);
5965 if (baseIndex == -1)
5968 var targetIndex = this.GetTabPageIndex(targetTabText);
5969 if (targetIndex == -1)
5972 using (ControlTransaction.Layout(this.ListTab))
5974 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
5975 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
5976 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
5977 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
5979 var tab = this.statuses.Tabs[targetIndex];
5980 var tabPage = this.ListTab.TabPages[targetIndex];
5982 this.ListTab.TabPages.Remove(tabPage);
5984 if (targetIndex < baseIndex)
5987 if (!isBeforeBaseTab)
5990 this.statuses.MoveTab(baseIndex, tab);
5992 this.ListTab.TabPages.Insert(baseIndex, tabPage);
5995 this.SaveConfigsTabs();
5998 private void MakeDirectMessageText()
6000 var selectedPosts = this.CurrentTab.SelectedPosts;
6001 if (selectedPosts.Length > 1)
6004 var post = selectedPosts.Single();
6005 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6007 this.inReplyTo = null;
6008 this.StatusText.Text = text;
6009 this.StatusText.SelectionStart = text.Length;
6010 this.StatusText.Focus();
6013 private void MakeReplyText(bool atAll = false)
6015 var selectedPosts = this.CurrentTab.SelectedPosts;
6016 if (selectedPosts.Any(x => x.IsDm))
6018 this.MakeDirectMessageText();
6022 if (selectedPosts.Length == 1)
6024 var post = selectedPosts.Single();
6025 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6026 var inReplyToScreenName = post.ScreenName;
6027 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6031 this.inReplyTo = null;
6034 var selfScreenName = this.tw.Username;
6035 var targetScreenNames = new List<string>();
6036 foreach (var post in selectedPosts)
6038 if (post.ScreenName != selfScreenName)
6039 targetScreenNames.Add(post.ScreenName);
6043 foreach (var (_, screenName) in post.ReplyToList)
6045 if (screenName != selfScreenName)
6046 targetScreenNames.Add(screenName);
6051 if (this.inReplyTo != null)
6053 var (_, screenName) = this.inReplyTo.Value;
6054 if (screenName == selfScreenName)
6055 targetScreenNames.Insert(0, screenName);
6058 var text = this.StatusText.Text;
6059 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6061 var atText = $"@{screenName} ";
6062 if (!text.Contains(atText))
6063 text = atText + text;
6066 this.StatusText.Text = text;
6067 this.StatusText.SelectionStart = text.Length;
6068 this.StatusText.Focus();
6071 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6072 => this.tabDrag = false;
6074 private int iconCnt = 0;
6075 private int blinkCnt = 0;
6076 private bool blink = false;
6078 private void RefreshTasktrayIcon()
6080 void EnableTasktrayAnimation()
6081 => this.TimerRefreshIcon.Enabled = true;
6083 void DisableTasktrayAnimation()
6084 => this.TimerRefreshIcon.Enabled = false;
6086 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6090 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6093 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6094 this.myStatusError = false;
6095 EnableTasktrayAnimation();
6099 var replyIconType = this.settings.Common.ReplyIconState;
6101 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6103 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6104 if (replyTab != null && replyTab.UnreadCount > 0)
6108 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6111 if (this.blinkCnt > 10)
6114 if (this.blinkCnt == 0)
6115 this.blink = !this.blink;
6117 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6118 EnableTasktrayAnimation();
6122 DisableTasktrayAnimation();
6128 // 優先度:リプライ→エラー→オフライン→アイドル
6129 // エラーは更新アイコンでクリアされる
6130 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6131 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6132 else if (this.myStatusError)
6133 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6134 else if (this.myStatusOnline)
6135 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6137 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6140 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6141 => this.RefreshTasktrayIcon(); // 200ms
6143 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6145 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6146 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6147 this.rclickTabName = this.CurrentTabName;
6149 if (this.statuses == null) return;
6150 if (this.statuses.Tabs == null) return;
6152 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6155 this.NotifyDispMenuItem.Checked = tb.Notify;
6156 this.NotifyTbMenuItem.Checked = tb.Notify;
6158 this.soundfileListup = true;
6159 this.SoundFileComboBox.Items.Clear();
6160 this.SoundFileTbComboBox.Items.Clear();
6161 this.SoundFileComboBox.Items.Add("");
6162 this.SoundFileTbComboBox.Items.Add("");
6163 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6164 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6166 oDir = oDir.GetDirectories("Sounds")[0];
6168 foreach (var oFile in oDir.GetFiles("*.wav"))
6170 this.SoundFileComboBox.Items.Add(oFile.Name);
6171 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6173 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6174 if (idx == -1) idx = 0;
6175 this.SoundFileComboBox.SelectedIndex = idx;
6176 this.SoundFileTbComboBox.SelectedIndex = idx;
6177 this.soundfileListup = false;
6178 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6179 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6181 this.TabMenuControl(this.rclickTabName);
6184 private void TabMenuControl(string tabName)
6186 var tabInfo = this.statuses.GetTabByName(tabName)!;
6188 this.FilterEditMenuItem.Enabled = true;
6189 this.EditRuleTbMenuItem.Enabled = true;
6191 if (tabInfo.IsDefaultTabType)
6193 this.ProtectTabMenuItem.Enabled = false;
6194 this.ProtectTbMenuItem.Enabled = false;
6198 this.ProtectTabMenuItem.Enabled = true;
6199 this.ProtectTbMenuItem.Enabled = true;
6202 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6204 this.ProtectTabMenuItem.Checked = true;
6205 this.ProtectTbMenuItem.Checked = true;
6206 this.DeleteTabMenuItem.Enabled = false;
6207 this.DeleteTbMenuItem.Enabled = false;
6211 this.ProtectTabMenuItem.Checked = false;
6212 this.ProtectTbMenuItem.Checked = false;
6213 this.DeleteTabMenuItem.Enabled = true;
6214 this.DeleteTbMenuItem.Enabled = true;
6218 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6220 var checkState = ((ToolStripMenuItem)sender).Checked;
6223 this.ProtectTbMenuItem.Checked = checkState;
6224 this.ProtectTabMenuItem.Checked = checkState;
6227 this.DeleteTabMenuItem.Enabled = !checkState;
6228 this.DeleteTbMenuItem.Enabled = !checkState;
6230 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6231 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6233 this.SaveConfigsTabs();
6236 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6238 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6239 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6241 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6242 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6244 this.SaveConfigsTabs();
6247 public void ChangeTabUnreadManage(string tabName, bool isManage)
6249 var idx = this.GetTabPageIndex(tabName);
6253 var tab = this.statuses.Tabs[tabName];
6254 tab.UnreadManage = isManage;
6256 if (this.settings.Common.TabIconDisp)
6258 var tabPage = this.ListTab.TabPages[idx];
6259 if (tab.UnreadCount > 0)
6260 tabPage.ImageIndex = 0;
6262 tabPage.ImageIndex = -1;
6265 if (this.CurrentTabName == tabName)
6267 this.listCache?.PurgeCache();
6268 this.CurrentListView.Refresh();
6271 this.SetMainWindowTitle();
6272 this.SetStatusLabelUrl();
6273 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6276 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6278 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6279 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6281 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6283 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6285 this.SaveConfigsTabs();
6288 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6290 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6292 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6294 this.SaveConfigsTabs();
6297 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6299 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6300 this.rclickTabName = this.CurrentTabName;
6302 this.RemoveSpecifiedTab(this.rclickTabName, true);
6303 this.SaveConfigsTabs();
6306 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6308 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6310 using (var fltDialog = new FilterDialog())
6312 fltDialog.Owner = this;
6313 fltDialog.SetCurrent(this.rclickTabName);
6314 fltDialog.ShowDialog(this);
6316 this.TopMost = this.settings.Common.AlwaysTop;
6318 this.ApplyPostFilters();
6319 this.SaveConfigsTabs();
6322 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6324 string? tabName = null;
6325 MyCommon.TabUsageType tabUsage;
6326 using (var inputName = new InputTabName())
6328 inputName.TabName = this.statuses.MakeTabName("MyTab");
6329 inputName.IsShowUsage = true;
6330 inputName.ShowDialog();
6331 if (inputName.DialogResult == DialogResult.Cancel) return;
6332 tabName = inputName.TabName;
6333 tabUsage = inputName.Usage;
6335 this.TopMost = this.settings.Common.AlwaysTop;
6336 if (!MyCommon.IsNullOrEmpty(tabName))
6339 ListElement? list = null;
6340 if (tabUsage == MyCommon.TabUsageType.Lists)
6342 using var listAvail = new ListAvailable();
6343 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6345 if (listAvail.SelectedList == null)
6347 list = listAvail.SelectedList;
6353 case MyCommon.TabUsageType.UserDefined:
6354 tab = new FilterTabModel(tabName);
6356 case MyCommon.TabUsageType.PublicSearch:
6357 tab = new PublicSearchTabModel(tabName);
6359 case MyCommon.TabUsageType.Lists:
6360 tab = new ListTimelineTabModel(tabName, list!);
6366 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6368 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6369 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6374 this.SaveConfigsTabs();
6376 var tabIndex = this.statuses.Tabs.Count - 1;
6378 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6380 this.ListTab.SelectedIndex = tabIndex;
6381 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6383 if (tabUsage == MyCommon.TabUsageType.Lists)
6385 this.ListTab.SelectedIndex = tabIndex;
6386 await this.RefreshTabAsync(this.CurrentTab);
6392 private void TabMenuItem_Click(object sender, EventArgs e)
6395 foreach (var post in this.CurrentTab.SelectedPosts)
6398 if (!this.SelectTab(out var tab))
6401 using (var fltDialog = new FilterDialog())
6403 fltDialog.Owner = this;
6404 fltDialog.SetCurrent(tab.TabName);
6406 if (post.RetweetedBy == null)
6408 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6412 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6414 fltDialog.ShowDialog(this);
6417 this.TopMost = this.settings.Common.AlwaysTop;
6420 this.ApplyPostFilters();
6421 this.SaveConfigsTabs();
6424 protected override bool ProcessDialogKey(Keys keyData)
6426 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6427 if ((keyData & Keys.KeyCode) == Keys.Enter)
6429 if (this.StatusText.Focused)
6431 var newLine = false;
6434 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6436 if (this.StatusText.Multiline)
6438 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6440 if ((keyData & Keys.Control) == Keys.Control) post = true;
6444 if ((keyData & Keys.Control) == Keys.Control) post = true;
6447 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6449 if (this.StatusText.Multiline)
6451 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6453 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6457 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6462 if (this.StatusText.Multiline)
6464 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6466 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6467 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6471 if (((keyData & Keys.Shift) == Keys.Shift) ||
6472 (((keyData & Keys.Control) != Keys.Control) &&
6473 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6479 var pos1 = this.StatusText.SelectionStart;
6480 if (this.StatusText.SelectionLength > 0)
6482 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6484 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6485 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6490 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6496 var tab = this.CurrentTab;
6497 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6499 var tabPage = this.CurrentTabPage;
6500 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6501 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6503 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6510 return base.ProcessDialogKey(keyData);
6513 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6514 => this.MakeReplyText(atAll: true);
6516 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6518 var tab = this.CurrentTab;
6519 var selectedPosts = tab.SelectedPosts;
6522 if (selectedPosts.Length == 0)
6525 var screenNameArray = selectedPosts
6526 .Select(x => x.RetweetedBy ?? x.ScreenName)
6529 this.AddFilterRuleByScreenName(screenNameArray);
6531 if (screenNameArray.Length != 0)
6533 var atids = new List<string>();
6534 foreach (var screenName in screenNameArray)
6536 atids.Add("@" + screenName);
6538 var cnt = this.AtIdSupl.ItemCount;
6539 this.AtIdSupl.AddRangeItem(atids.ToArray());
6540 if (this.AtIdSupl.ItemCount != cnt)
6541 this.MarkSettingAtIdModified();
6545 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6547 var tab = this.CurrentTab;
6548 var selectedPosts = tab.SelectedPosts;
6550 if (selectedPosts.Length == 0)
6553 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6555 this.AddFilterRuleBySource(sourceArray);
6558 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6561 if (!this.SelectTab(out var tab)) return;
6565 if (tab.TabType != MyCommon.TabUsageType.Mute)
6567 this.MoveOrCopy(out mv, out mk);
6571 // ミュートタブでは常に MoveMatches を true にする
6576 foreach (var screenName in screenNameArray)
6578 tab.AddFilter(new PostFilterRule
6580 FilterName = screenName,
6581 UseNameField = true,
6585 FilterByUrl = false,
6589 this.ApplyPostFilters();
6590 this.SaveConfigsTabs();
6593 public void AddFilterRuleBySource(params string[] sourceArray)
6595 // タブ選択ダイアログを表示(or追加)
6596 if (!this.SelectTab(out var filterTab))
6601 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6603 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6604 this.MoveOrCopy(out mv, out mk);
6608 // ミュートタブでは常に MoveMatches を true にする
6613 // 振り分けルールに追加するSource
6614 foreach (var source in sourceArray)
6616 filterTab.AddFilter(new PostFilterRule
6618 FilterSource = source,
6622 FilterByUrl = false,
6626 this.ApplyPostFilters();
6627 this.SaveConfigsTabs();
6630 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6637 using (var dialog = new TabsDialog(this.statuses))
6639 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6641 tab = dialog.SelectedTab;
6644 this.CurrentTabPage.Focus();
6649 using (var inputName = new InputTabName())
6651 inputName.TabName = this.statuses.MakeTabName("MyTab");
6652 inputName.ShowDialog();
6653 if (inputName.DialogResult == DialogResult.Cancel) return false;
6654 tabName = inputName.TabName;
6656 this.TopMost = this.settings.Common.AlwaysTop;
6657 if (!MyCommon.IsNullOrEmpty(tabName))
6659 var newTab = new FilterTabModel(tabName);
6660 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6662 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6663 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6682 private void MoveOrCopy(out bool move, out bool mark)
6686 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6687 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6695 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6696 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6707 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6710 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6711 => this.CopyIdUri();
6713 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6715 if (this.StatusText.Focused)
6718 this.StatusText.SelectAll();
6722 // ListView上でのCtrl+A
6723 NativeMethods.SelectAllItems(this.CurrentListView);
6727 private void MoveMiddle()
6733 var listView = this.CurrentListView;
6734 if (listView.SelectedIndices.Count == 0) return;
6736 var idx = listView.SelectedIndices[0];
6738 item = listView.GetItemAt(0, 25);
6744 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6746 idx2 = listView.VirtualListSize - 1;
6750 idx -= Math.Abs(idx1 - idx2) / 2;
6751 if (idx < 0) idx = 0;
6753 listView.EnsureVisible(listView.VirtualListSize - 1);
6754 listView.EnsureVisible(idx);
6757 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6759 var linkElements = this.tweetDetailsView.GetLinkElements();
6761 if (linkElements.Length == 0)
6764 var links = new List<OpenUrlItem>(linkElements.Length);
6766 foreach (var linkElm in linkElements)
6768 var displayUrl = linkElm.GetAttribute("title");
6769 var href = linkElm.GetAttribute("href");
6770 var linkedText = linkElm.InnerText;
6772 if (MyCommon.IsNullOrEmpty(displayUrl))
6775 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6779 bool isReverseSettings;
6781 if (links.Count == 1)
6783 // ツイートに含まれる URL が 1 つのみの場合
6784 // => OpenURL ダイアログを表示せずにリンクを開く
6785 selectedUrl = links[0].Href;
6787 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6788 isReverseSettings = false;
6792 // ツイートに含まれる URL が複数ある場合
6793 // => OpenURL を表示しユーザーが選択したリンクを開く
6794 this.urlDialog.ClearUrl();
6796 foreach (var link in links)
6797 this.urlDialog.AddUrl(link);
6799 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6802 this.TopMost = this.settings.Common.AlwaysTop;
6804 selectedUrl = this.urlDialog.SelectedUrl;
6806 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6807 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6810 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6813 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6815 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6816 this.ClearTab(this.rclickTabName, true);
6819 private void ClearTab(string tabName, bool showWarning)
6823 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6824 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6830 this.statuses.ClearTabIds(tabName);
6831 if (this.CurrentTabName == tabName)
6833 this.CurrentTab.ClearAnchor();
6834 this.listCache?.PurgeCache();
6835 this.listCache?.UpdateListSize();
6838 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6839 var tabPage = this.ListTab.TabPages[tabIndex];
6840 tabPage.ImageIndex = -1;
6842 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6844 this.SetMainWindowTitle();
6845 this.SetStatusLabelUrl();
6848 private static long followers = 0;
6850 private void SetMainWindowTitle()
6852 // メインウインドウタイトルの書き換え
6853 var ttl = new StringBuilder(256);
6856 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6857 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6858 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6859 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6861 foreach (var tab in this.statuses.Tabs)
6863 ur += tab.UnreadCount;
6868 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6869 ttl.Append(ApplicationSettings.ApplicationName);
6871 switch (this.settings.Common.DispLatestPost)
6873 case MyCommon.DispTitleEnum.Ver:
6874 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6876 case MyCommon.DispTitleEnum.Post:
6877 if (this.history.Peek() is { } lastItem)
6878 ttl.Append(lastItem.Status.Replace("\r\n", " "));
6880 case MyCommon.DispTitleEnum.UnreadRepCount:
6881 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6883 case MyCommon.DispTitleEnum.UnreadAllCount:
6884 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6886 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6887 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6889 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6890 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6892 case MyCommon.DispTitleEnum.OwnStatus:
6893 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6894 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6900 this.Text = ttl.ToString();
6902 catch (AccessViolationException)
6904 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6908 private string GetStatusLabelText()
6911 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6912 if (this.statuses == null) return "";
6913 var tbRep = this.statuses.MentionTab;
6914 var tbDm = this.statuses.DirectMessageTab;
6915 if (tbRep == null || tbDm == null) return "";
6916 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6921 var slbl = new StringBuilder(256);
6924 foreach (var tab in this.statuses.Tabs)
6926 ur += tab.UnreadCount;
6928 if (tab.TabName == this.CurrentTabName)
6930 tur = tab.UnreadCount;
6940 this.unreadCounter = ur;
6941 this.unreadAtCounter = urat;
6943 var homeTab = this.statuses.HomeTab;
6945 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
6946 if (this.settings.Common.TimelinePeriod == 0)
6948 slbl.Append(Properties.Resources.SetStatusLabelText2);
6952 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
6954 return slbl.ToString();
6957 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
6961 if (this.InvokeRequired && !this.IsDisposed)
6963 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
6967 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
6968 this.SetApiStatusLabel(endpointName);
6971 catch (ObjectDisposedException)
6975 catch (InvalidOperationException)
6981 private void SetApiStatusLabel(string? endpointName = null)
6983 var tabType = this.CurrentTab.TabType;
6985 if (endpointName == null)
6987 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
6990 endpointName = tabType switch
6992 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
6993 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
6994 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
6995 MyCommon.TabUsageType.Favorites => "/favorites/list",
6996 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
6997 MyCommon.TabUsageType.UserTimeline =>
6998 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
6999 MyCommon.TabUsageType.Lists =>
7000 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7001 MyCommon.TabUsageType.PublicSearch =>
7002 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7003 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7006 this.toolStripApiGauge.ApiEndpoint = endpointName;
7010 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7011 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7015 private void SetStatusLabelUrl()
7016 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7018 public void SetStatusLabel(string text)
7019 => this.StatusLabel.Text = text;
7021 private void SetNotifyIconText()
7023 var ur = new StringBuilder(64);
7025 // タスクトレイアイコンのツールチップテキスト書き換え
7027 ur.Remove(0, ur.Length);
7028 if (this.settings.Common.DispUsername)
7030 ur.Append(this.tw.Username);
7033 ur.Append(ApplicationSettings.ApplicationName);
7035 ur.Append("(Debug Build)");
7037 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7040 ur.Append(this.unreadCounter);
7042 ur.Append(this.unreadAtCounter);
7045 this.NotifyIcon1.Text = ur.ToString();
7048 internal void CheckReplyTo(string statusText)
7052 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7054 foreach (Match hm in m)
7056 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7058 hstr += "#" + hm.Result("$3") + " ";
7059 this.HashSupl.AddItem("#" + hm.Result("$3"));
7062 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7064 hstr += this.HashMgr.UseHash;
7066 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7068 // 本当にリプライ先指定すべきかどうかの判定
7069 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7071 if (this.settings.Common.UseAtIdSupplement)
7073 var bCnt = this.AtIdSupl.ItemCount;
7074 foreach (Match mid in m)
7076 this.AtIdSupl.AddItem(mid.Result("${id}"));
7078 if (bCnt != this.AtIdSupl.ItemCount)
7079 this.MarkSettingAtIdModified();
7082 // リプライ先ステータスIDの指定がない場合は指定しない
7083 if (this.inReplyTo == null)
7087 // 次の条件を満たす場合に in_reply_to_status_id 指定
7088 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7089 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7090 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7094 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7095 if (statusText.StartsWith("@", StringComparison.Ordinal))
7097 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7101 foreach (Match mid in m)
7103 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7108 this.inReplyTo = null;
7111 private void TweenMain_Resize(object sender, EventArgs e)
7113 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7115 this.Visible = false;
7117 if (this.WindowState != FormWindowState.Minimized)
7119 this.formWindowState = this.WindowState;
7123 private void ApplyLayoutFromSettings()
7125 // 現在の DPI と設定保存時の DPI との比を取得する
7126 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7128 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7131 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7132 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7133 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7135 this.SplitContainer1.SplitterDistance = splitterDistance;
7139 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7140 if (this.StatusText.Multiline)
7142 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7143 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7144 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7146 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7148 this.StatusText.Height = statusTextHeight;
7152 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7154 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7158 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7159 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7161 this.SplitContainer3.SplitterDistance = previewDistance;
7164 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7165 this.SplitContainer3.Panel2Collapsed = true;
7166 this.initialLayout = false;
7169 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7171 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7172 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7173 if (this.PlaySoundMenuItem.Checked)
7175 this.settings.Common.PlaySound = true;
7179 this.settings.Common.PlaySound = false;
7181 this.MarkSettingCommonModified();
7184 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7186 if (this.initialLayout)
7189 int splitterDistance;
7190 switch (this.WindowState)
7192 case FormWindowState.Normal:
7193 splitterDistance = this.SplitContainer1.SplitterDistance;
7195 case FormWindowState.Maximized:
7196 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7197 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7198 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7199 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7205 this.mySpDis = splitterDistance;
7206 this.MarkSettingLocalModified();
7209 private async Task DoRepliedStatusOpen()
7211 var currentPost = this.CurrentPost;
7212 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7214 if (MyCommon.IsKeyDown(Keys.Shift))
7216 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7219 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7221 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7225 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7227 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7228 repPost = tb.Posts[currentPost.InReplyToStatusId];
7229 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7232 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7237 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7238 => await this.DoRepliedStatusOpen();
7240 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7242 if (this.initialLayout)
7243 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7245 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7246 if (multiline != this.StatusText.Multiline)
7248 this.StatusText.Multiline = multiline;
7249 this.settings.Local.StatusMultiline = multiline;
7250 this.MarkSettingLocalModified();
7254 private void StatusText_MultilineChanged(object sender, EventArgs e)
7256 if (this.StatusText.Multiline)
7257 this.StatusText.ScrollBars = ScrollBars.Vertical;
7259 this.StatusText.ScrollBars = ScrollBars.None;
7261 if (!this.initialLayout)
7262 this.MarkSettingLocalModified();
7265 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7268 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7269 this.StatusText.Multiline = menuItemChecked;
7270 this.settings.Local.StatusMultiline = menuItemChecked;
7271 if (menuItemChecked)
7273 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7274 this.SplitContainer2.SplitterDistance = 0;
7276 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7280 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7282 this.MarkSettingLocalModified();
7285 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7287 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7289 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7290 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7291 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7293 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7298 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7299 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7300 // Appendix A. Collected ABNF for URI
7301 // http://www.ietf.org/rfc/rfc3986.txt
7303 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7306 if (this.StatusText.SelectionLength > 0)
7308 var tmp = this.StatusText.SelectedText;
7309 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7310 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7312 // 文字列が選択されている場合はその文字列について処理
7314 // nico.ms使用、nicovideoにマッチしたら変換
7315 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7317 result = Nicoms.Shorten(tmp);
7319 else if (converterType != MyCommon.UrlConverter.Nicoms)
7324 var srcUri = new Uri(tmp);
7325 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7326 result = resultUri.AbsoluteUri;
7328 catch (WebApiException e)
7330 this.StatusLabel.Text = converterType + ":" + e.Message;
7333 catch (UriFormatException e)
7335 this.StatusLabel.Text = converterType + ":" + e.Message;
7344 if (!MyCommon.IsNullOrEmpty(result))
7346 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7347 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7348 if (origUrlIndex == -1)
7351 this.StatusText.Select(origUrlIndex, tmp.Length);
7352 this.StatusText.SelectedText = result;
7355 var undo = new UrlUndo
7361 if (this.urlUndoBuffer == null)
7363 this.urlUndoBuffer = new List<UrlUndo>();
7364 this.UrlUndoToolStripMenuItem.Enabled = true;
7367 this.urlUndoBuffer.Add(undo);
7373 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7374 @"(?<url>(?<protocol>https?://)" +
7375 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7376 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7377 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7378 // 正規表現にマッチしたURL文字列をtinyurl化
7379 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7381 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7383 var tmp = mt.Result("${url}");
7384 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7385 tmp = "http://" + tmp;
7388 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7390 // nico.ms使用、nicovideoにマッチしたら変換
7391 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7393 result = Nicoms.Shorten(tmp);
7395 else if (converterType != MyCommon.UrlConverter.Nicoms)
7400 var srcUri = new Uri(tmp);
7401 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7402 result = resultUri.AbsoluteUri;
7404 catch (HttpRequestException e)
7406 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7407 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7408 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7410 this.StatusLabel.Text = converterType + ":" + message;
7413 catch (WebApiException e)
7415 this.StatusLabel.Text = converterType + ":" + e.Message;
7418 catch (UriFormatException e)
7420 this.StatusLabel.Text = converterType + ":" + e.Message;
7429 if (!MyCommon.IsNullOrEmpty(result))
7431 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7432 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7433 if (origUrlIndex == -1)
7436 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7437 this.StatusText.SelectedText = result;
7439 var undo = new UrlUndo
7441 Before = mt.Result("${url}"),
7445 if (this.urlUndoBuffer == null)
7447 this.urlUndoBuffer = new List<UrlUndo>();
7448 this.UrlUndoToolStripMenuItem.Enabled = true;
7451 this.urlUndoBuffer.Add(undo);
7459 private void DoUrlUndo()
7461 if (this.urlUndoBuffer != null)
7463 var tmp = this.StatusText.Text;
7464 foreach (var data in this.urlUndoBuffer)
7466 tmp = tmp.Replace(data.After, data.Before);
7468 this.StatusText.Text = tmp;
7469 this.urlUndoBuffer = null;
7470 this.UrlUndoToolStripMenuItem.Enabled = false;
7471 this.StatusText.SelectionStart = 0;
7472 this.StatusText.SelectionLength = 0;
7476 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7477 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7479 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7480 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7482 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7483 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7485 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7487 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7489 var rnd = new Random();
7491 MyCommon.UrlConverter svc;
7492 // 前回使用した短縮URLサービス以外を選択する
7495 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7497 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7498 await this.UrlConvertAsync(svc);
7502 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7503 => this.DoUrlUndo();
7505 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7507 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7508 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7509 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7510 this.MarkSettingCommonModified();
7513 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7515 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7516 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7517 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7518 this.MarkSettingCommonModified();
7521 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7523 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7524 this.MenuStrip1.Tag = new object();
7525 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7528 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7530 var currentTabPage = this.CurrentTabPage;
7531 if (this.Tag != null) // 設定された戻り先へ遷移
7533 if (this.Tag == currentTabPage)
7534 ((Control)currentTabPage.Tag).Select();
7536 ((Control)this.Tag).Select();
7538 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7540 this.Tag = currentTabPage.Tag;
7541 ((Control)this.Tag).Select();
7543 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7544 this.MenuStrip1.Tag = null;
7547 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7549 if (this.Use2ColumnsMode)
7555 var lst = (DetailsListView)sender;
7556 var columnsCount = lst.Columns.Count;
7558 var darr = new int[columnsCount];
7559 for (var i = 0; i < columnsCount; i++)
7560 darr[lst.Columns[i].DisplayIndex] = i;
7562 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7564 for (var i = 0; i < columnsCount; i++)
7565 this.settings.Local.ColumnsOrder[darr[i]] = i;
7567 this.MarkSettingLocalModified();
7568 this.isColumnChanged = true;
7571 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7573 var lst = (DetailsListView)sender;
7574 if (this.settings.Local == null) return;
7576 var modified = false;
7577 if (this.Use2ColumnsMode)
7579 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7581 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7584 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7586 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7592 var columnsCount = lst.Columns.Count;
7593 for (var i = 0; i < columnsCount; i++)
7595 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7598 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7604 this.MarkSettingLocalModified();
7605 this.isColumnChanged = true;
7609 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7611 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7612 this.MarkSettingLocalModified();
7615 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7617 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7619 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7621 this.SelectMedia_DragDrop(e);
7624 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7626 var (url, title) = GetUrlFromDataObject(e.Data);
7632 appendText = title + " " + url;
7634 if (this.StatusText.TextLength == 0)
7635 this.StatusText.Text = appendText;
7637 this.StatusText.Text += " " + appendText;
7639 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7641 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7643 this.StatusText.Text += text;
7645 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7647 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7648 if (data != null) this.StatusText.Text += data;
7653 /// IDataObject から URL とタイトルの対を取得します
7656 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7658 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7659 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7660 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7662 if (data.GetDataPresent("text/x-moz-url"))
7664 // Firefox, Google Chrome で利用可能
7665 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7667 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7668 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7669 if (lines.Length < 2)
7670 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7672 return (lines[0], lines[1]);
7674 else if (data.GetDataPresent("IESiteModeToUrl"))
7676 // Internet Exproler 用
7677 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7679 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7680 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7681 if (lines.Length < 2)
7682 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7684 return (lines[0], lines[1]);
7686 else if (data.GetDataPresent("UniformResourceLocatorW"))
7690 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7691 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7695 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7698 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7700 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7702 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7704 this.SelectMedia_DragEnter(e);
7708 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7710 e.Effect = DragDropEffects.Copy;
7713 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7715 e.Effect = DragDropEffects.Copy;
7718 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7720 e.Effect = DragDropEffects.Copy;
7724 e.Effect = DragDropEffects.None;
7727 private void TweenMain_DragOver(object sender, DragEventArgs e)
7731 public bool IsNetworkAvailable()
7733 var nw = MyCommon.IsNetworkAvailable();
7734 this.myStatusOnline = nw;
7738 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7740 var uriStr = uri.AbsoluteUri;
7742 // OpenTween 内部で使用する URL
7743 if (uri.Authority == "opentween")
7745 await this.OpenInternalUriAsync(uri);
7749 // ハッシュタグを含む Twitter 検索
7750 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7753 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7754 var pos = unescapedQuery.IndexOf('#');
7755 if (pos == -1) return;
7757 var hash = unescapedQuery.Substring(pos);
7758 this.HashSupl.AddItem(hash);
7759 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7760 this.AddNewTabForSearch(hash);
7765 // フラグが立っている場合は設定と逆の動作をする
7766 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7767 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7769 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7770 if (userUriMatch.Success)
7772 var screenName = userUriMatch.Groups["ScreenName"].Value;
7773 if (this.IsTwitterId(screenName))
7775 await this.AddNewTabForUserTimeline(screenName);
7782 await MyCommon.OpenInBrowserAsync(this, uriStr);
7786 /// OpenTween 内部の機能を呼び出すための URL を開きます
7788 private async Task OpenInternalUriAsync(Uri uri)
7790 // ツイートを開く (//opentween/status/:status_id)
7791 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7794 var statusId = new TwitterStatusId(match.Groups[1].Value);
7795 await this.OpenRelatedTab(statusId);
7800 private void ListTabSelect(TabPage tabPage)
7802 this.SetListProperty();
7804 var previousTabName = this.CurrentTabName;
7805 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7806 previousListViewState.Save(this.ListLockMenuItem.Checked);
7808 this.listCache?.PurgeCache();
7810 this.statuses.SelectTab(tabPage.Text);
7812 this.InitializeTimelineListView();
7814 var tab = this.CurrentTab;
7817 var listView = this.CurrentListView;
7819 var currentListViewState = this.listViewState[tab.TabName];
7820 currentListViewState.Restore(forceScroll: true);
7822 if (this.Use2ColumnsMode)
7824 listView.Columns[1].Text = this.columnText[2];
7828 for (var i = 0; i < listView.Columns.Count; i++)
7830 listView.Columns[i].Text = this.columnText[i];
7835 private void InitializeTimelineListView()
7837 var listView = this.CurrentListView;
7838 var tab = this.CurrentTab;
7840 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7841 (this.listCache, var oldCache) = (newCache, this.listCache);
7842 oldCache?.Dispose();
7844 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7845 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7846 oldDrawer?.Dispose();
7848 newDrawer.IconSize = this.settings.Common.IconSize;
7849 newDrawer.UpdateItemHeight();
7852 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7853 => this.ListTabSelect(e.TabPage);
7855 private void SelectListItem(DetailsListView lView, int index)
7858 var bnd = new Rectangle();
7860 var item = lView.FocusedItem;
7869 lView.SelectedIndices.Clear();
7871 while (lView.SelectedIndices.Count > 0);
7872 item = lView.Items[index];
7873 item.Selected = true;
7874 item.Focused = true;
7876 if (flg) lView.Invalidate(bnd);
7879 private async void TweenMain_Shown(object sender, EventArgs e)
7881 this.NotifyIcon1.Visible = true;
7884 if (this.settings.IsFirstRun)
7886 // 初回起動時だけ右下のメニューを目立たせる
7887 this.HashStripSplitButton.ShowDropDown();
7890 if (this.IsNetworkAvailable())
7892 var loadTasks = new TaskCollection();
7896 this.RefreshMuteUserIdsAsync,
7897 this.RefreshBlockIdsAsync,
7898 this.RefreshNoRetweetIdsAsync,
7899 this.RefreshTwitterConfigurationAsync,
7900 this.RefreshTabAsync<HomeTabModel>,
7901 this.RefreshTabAsync<MentionsTabModel>,
7902 this.RefreshTabAsync<DirectMessagesTabModel>,
7903 this.RefreshTabAsync<PublicSearchTabModel>,
7904 this.RefreshTabAsync<UserTimelineTabModel>,
7905 this.RefreshTabAsync<ListTimelineTabModel>,
7908 if (this.settings.Common.StartupFollowers)
7909 loadTasks.Add(this.RefreshFollowerIdsAsync);
7911 if (this.settings.Common.GetFav)
7912 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7914 var allTasks = loadTasks.RunAll();
7919 var timeout = Task.Delay(5000);
7920 if (await Task.WhenAny(allTasks, timeout) != timeout)
7924 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7926 if (MyCommon.EndingFlag)
7930 if (MyCommon.EndingFlag) return;
7932 if (ApplicationSettings.VersionInfoUrl != null)
7934 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7935 if (this.settings.Common.StartupVersion)
7936 await this.CheckNewVersion(true);
7940 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
7941 this.VerUpMenuItem.Enabled = false;
7942 this.VerUpMenuItem.Available = false;
7943 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
7946 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
7947 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
7949 MessageBox.Show(Properties.Resources.ReAuthorizeText);
7950 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
7954 var reloadTasks = new TaskCollection();
7956 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
7957 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
7959 if (!this.tw.GetNoRetweetSuccess)
7960 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
7962 if (this.tw.Configuration.PhotoSizeLimit == 0)
7963 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
7965 await reloadTasks.RunAll();
7968 this.initial = false;
7971 private void StartTimers()
7973 if (!this.StopRefreshAllMenuItem.Checked)
7974 this.timelineScheduler.Enabled = true;
7976 this.selectionDebouncer.Enabled = true;
7977 this.saveConfigDebouncer.Enabled = true;
7978 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
7981 private async Task DoGetFollowersMenu()
7983 await this.RefreshFollowerIdsAsync();
7984 this.DispSelectedPost(true);
7987 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
7988 => await this.DoGetFollowersMenu();
7990 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
7991 => this.DoReTweetUnofficial();
7993 private async Task DoReTweetOfficial(bool isConfirm)
7996 if (this.ExistCurrentPost)
7998 var selectedPosts = this.CurrentTab.SelectedPosts;
8000 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8002 if (selectedPosts.Any(x => x.IsProtect))
8003 MessageBox.Show("Protected.");
8005 this.doFavRetweetFlags = false;
8009 if (selectedPosts.Length > 15)
8011 MessageBox.Show(Properties.Resources.RetweetLimitText);
8012 this.doFavRetweetFlags = false;
8015 else if (selectedPosts.Length > 1)
8017 var questionText = Properties.Resources.RetweetQuestion2;
8018 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8019 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8021 case DialogResult.Cancel:
8022 case DialogResult.No:
8023 this.doFavRetweetFlags = false;
8029 if (!this.settings.Common.RetweetNoConfirm)
8031 var questiontext = Properties.Resources.RetweetQuestion1;
8032 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8033 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8035 this.doFavRetweetFlags = false;
8041 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8043 await this.RetweetAsync(statusIds);
8047 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8048 => await this.DoReTweetOfficial(true);
8050 private async Task FavoritesRetweetOfficial()
8052 if (!this.ExistCurrentPost) return;
8053 this.doFavRetweetFlags = true;
8055 var tasks = new TaskCollection();
8056 tasks.Add(() => this.DoReTweetOfficial(true));
8058 if (this.doFavRetweetFlags)
8060 this.doFavRetweetFlags = false;
8061 tasks.Add(() => this.FavoriteChange(true, false));
8064 await tasks.RunAll();
8067 private async Task FavoritesRetweetUnofficial()
8069 var post = this.CurrentPost;
8070 if (this.ExistCurrentPost && post != null && !post.IsDm)
8072 this.doFavRetweetFlags = true;
8073 var favoriteTask = this.FavoriteChange(true);
8074 if (!post.IsProtect && this.doFavRetweetFlags)
8076 this.doFavRetweetFlags = false;
8077 this.DoReTweetUnofficial();
8085 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8087 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8088 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8089 /// <returns>復元されたツイート本文</returns>
8090 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8092 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8095 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8097 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8099 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8101 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8105 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8107 statusHtml = statusHtml.Replace("<br>", " ");
8109 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8110 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8111 statusHtml = statusHtml.Replace(" ", " ");
8113 return WebUtility.HtmlDecode(statusHtml);
8116 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8118 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8120 if (this.CurrentPost != null)
8121 this.DispSelectedPost(true);
8124 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8126 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8127 this.DebugModeToolStripMenuItem.Visible = true;
8129 this.DebugModeToolStripMenuItem.Visible = false;
8132 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8133 => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8135 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8136 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8138 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8139 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8141 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8143 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8144 this.MarkSettingCommonModified();
8147 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8149 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8150 this.MarkSettingCommonModified();
8153 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8155 this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8156 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8157 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8158 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8159 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8160 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8163 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8165 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8166 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8167 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8168 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8169 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8170 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8173 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8175 if (this.TraceOutToolStripMenuItem.Checked)
8176 MyCommon.TraceFlag = true;
8178 MyCommon.TraceFlag = false;
8181 private void TweenMain_Deactivate(object sender, EventArgs e)
8182 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8184 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8186 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8188 _ = this.TabRename(this.rclickTabName, out _);
8191 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8192 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8194 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8195 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8197 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8199 TwitterApiStatus? apiStatus;
8201 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8203 var cancellationToken = dialog.EnableCancellation();
8207 var task = this.tw.GetInfoApi();
8208 apiStatus = await dialog.WaitForAsync(this, task);
8210 catch (WebApiException)
8215 if (cancellationToken.IsCancellationRequested)
8218 if (apiStatus == null)
8220 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8225 using var apiDlg = new ApiInfoDialog();
8226 apiDlg.ShowDialog(this);
8229 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8231 var id = this.CurrentPost?.ScreenName ?? "";
8233 await this.FollowCommand(id);
8236 internal async Task FollowCommand(string id)
8238 using (var inputName = new InputTabName())
8240 inputName.FormTitle = "Follow";
8241 inputName.FormDescription = Properties.Resources.FRMessage1;
8242 inputName.TabName = id;
8244 if (inputName.ShowDialog(this) != DialogResult.OK)
8246 if (string.IsNullOrWhiteSpace(inputName.TabName))
8249 id = inputName.TabName.Trim();
8252 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8256 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8257 await dialog.WaitForAsync(this, task);
8259 catch (WebApiException ex)
8261 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8266 MessageBox.Show(Properties.Resources.FRMessage3);
8269 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8271 var id = this.CurrentPost?.ScreenName ?? "";
8273 await this.RemoveCommand(id, false);
8276 internal async Task RemoveCommand(string id, bool skipInput)
8280 using var inputName = new InputTabName();
8281 inputName.FormTitle = "Unfollow";
8282 inputName.FormDescription = Properties.Resources.FRMessage1;
8283 inputName.TabName = id;
8285 if (inputName.ShowDialog(this) != DialogResult.OK)
8287 if (string.IsNullOrWhiteSpace(inputName.TabName))
8290 id = inputName.TabName.Trim();
8293 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8297 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8298 await dialog.WaitForAsync(this, task);
8300 catch (WebApiException ex)
8302 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8307 MessageBox.Show(Properties.Resources.FRMessage3);
8310 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8312 var id = this.CurrentPost?.ScreenName ?? "";
8314 await this.ShowFriendship(id);
8317 internal async Task ShowFriendship(string id)
8319 using (var inputName = new InputTabName())
8321 inputName.FormTitle = "Show Friendships";
8322 inputName.FormDescription = Properties.Resources.FRMessage1;
8323 inputName.TabName = id;
8325 if (inputName.ShowDialog(this) != DialogResult.OK)
8327 if (string.IsNullOrWhiteSpace(inputName.TabName))
8330 id = inputName.TabName.Trim();
8333 bool isFollowing, isFollowed;
8335 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8337 var cancellationToken = dialog.EnableCancellation();
8341 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8342 var friendship = await dialog.WaitForAsync(this, task);
8344 isFollowing = friendship.Relationship.Source.Following;
8345 isFollowed = friendship.Relationship.Source.FollowedBy;
8347 catch (WebApiException ex)
8349 if (!cancellationToken.IsCancellationRequested)
8350 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8354 if (cancellationToken.IsCancellationRequested)
8361 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8365 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8369 result += Properties.Resources.GetFriendshipInfo3;
8373 result += Properties.Resources.GetFriendshipInfo4;
8375 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8376 MessageBox.Show(result);
8379 internal async Task ShowFriendship(string[] ids)
8381 foreach (var id in ids)
8383 bool isFollowing, isFollowed;
8385 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8387 var cancellationToken = dialog.EnableCancellation();
8391 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8392 var friendship = await dialog.WaitForAsync(this, task);
8394 isFollowing = friendship.Relationship.Source.Following;
8395 isFollowed = friendship.Relationship.Source.FollowedBy;
8397 catch (WebApiException ex)
8399 if (!cancellationToken.IsCancellationRequested)
8400 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8404 if (cancellationToken.IsCancellationRequested)
8414 ff += Properties.Resources.GetFriendshipInfo1;
8418 ff += Properties.Resources.GetFriendshipInfo2;
8421 ff += System.Environment.NewLine + " ";
8424 ff += Properties.Resources.GetFriendshipInfo3;
8428 ff += Properties.Resources.GetFriendshipInfo4;
8430 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8433 if (MessageBox.Show(
8434 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8435 Properties.Resources.GetFriendshipInfo8,
8436 MessageBoxButtons.YesNo,
8437 MessageBoxIcon.Question,
8438 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8440 await this.RemoveCommand(id, true);
8445 MessageBox.Show(result);
8450 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8451 => await this.DoShowUserStatus(this.tw.Username, false);
8453 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8456 public bool IsTwitterId(string name)
8458 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8459 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8461 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8464 private void DoQuoteOfficial()
8466 var post = this.CurrentPost;
8467 if (this.ExistCurrentPost && post != null)
8469 if (post.IsDm || !this.StatusText.Enabled)
8474 MessageBox.Show("Protected.");
8478 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8480 this.inReplyTo = null;
8482 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8484 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8485 this.StatusText.Focus();
8489 private void DoReTweetUnofficial()
8492 var post = this.CurrentPost;
8493 if (this.ExistCurrentPost && post != null)
8495 if (post.IsDm || !this.StatusText.Enabled)
8500 MessageBox.Show("Protected.");
8503 var rtdata = post.Text;
8504 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8506 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8508 // 投稿時に in_reply_to_status_id を付加する
8509 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8510 var inReplyToScreenName = post.ScreenName;
8511 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8513 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8515 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8516 this.StatusText.Focus();
8520 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8521 => this.DoQuoteOfficial();
8523 private async void SearchButton_Click(object sender, EventArgs e)
8526 var pnl = ((Control)sender).Parent;
8527 if (pnl == null) return;
8528 var tbName = pnl.Parent.Text;
8529 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8530 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8531 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8532 cmb.Text = cmb.Text.Trim();
8533 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8535 var buf = new StringBuilder();
8536 var c = cmb.Text.ToCharArray();
8537 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8539 if (cnt > cmb.Text.Length - 4)
8541 buf.Append(cmb.Text.Substring(cnt));
8550 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8559 cmb.Text = buf.ToString();
8561 var listView = (DetailsListView)pnl.Parent.Tag;
8563 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8565 tb.SearchWords = cmb.Text;
8566 tb.SearchLang = cmbLang.Text;
8567 if (MyCommon.IsNullOrEmpty(cmb.Text))
8570 this.SaveConfigsTabs();
8575 var idx = cmb.Items.IndexOf(tb.SearchWords);
8576 if (idx > -1) cmb.Items.RemoveAt(idx);
8577 cmb.Items.Insert(0, tb.SearchWords);
8578 cmb.Text = tb.SearchWords;
8580 this.statuses.ClearTabIds(tbName);
8581 this.listCache?.PurgeCache();
8582 this.listCache?.UpdateListSize();
8583 this.SaveConfigsTabs(); // 検索条件の保存
8587 await this.RefreshTabAsync(tb);
8590 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8591 => await this.DoRefreshMore(); // もっと前を取得
8594 /// 指定されたタブのListTabにおける位置を返します
8597 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8599 public int GetTabPageIndex(string tabName)
8600 => this.statuses.Tabs.IndexOf(tabName);
8602 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8606 var restoredTab = this.statuses.UndoRemovedTab();
8607 this.AddNewTab(restoredTab, startup: false);
8609 var tabIndex = this.statuses.Tabs.Count - 1;
8610 this.ListTab.SelectedIndex = tabIndex;
8612 this.SaveConfigsTabs();
8614 catch (TabException ex)
8616 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8620 private async Task DoMoveToRTHome()
8622 var post = this.CurrentPost;
8623 if (post != null && post.RetweetedId != null)
8624 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8627 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8628 => await this.DoMoveToRTHome();
8630 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8632 var screenName = this.CurrentPost?.ScreenName;
8633 if (screenName != null)
8634 this.ListManageUserContext(screenName);
8637 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8639 var screenName = this.CurrentPost?.RetweetedBy;
8640 if (screenName != null)
8641 this.ListManageUserContext(screenName);
8644 public void ListManageUserContext(string screenName)
8646 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8647 listSelectForm.ShowDialog(this);
8650 private void SearchControls_Enter(object sender, EventArgs e)
8652 var pnl = (Control)sender;
8653 foreach (Control ctl in pnl.Controls)
8659 private void SearchControls_Leave(object sender, EventArgs e)
8661 var pnl = (Control)sender;
8662 foreach (Control ctl in pnl.Controls)
8664 ctl.TabStop = false;
8668 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8670 var tab = this.CurrentTab;
8671 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8672 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8675 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8676 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8678 private void HashManageMenuItem_Click(object sender, EventArgs e)
8683 rslt = this.HashMgr.ShowDialog();
8689 this.TopMost = this.settings.Common.AlwaysTop;
8690 if (rslt == DialogResult.Cancel) return;
8691 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8693 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8694 this.HashTogglePullDownMenuItem.Checked = true;
8695 this.HashToggleMenuItem.Checked = true;
8699 this.HashStripSplitButton.Text = "#[-]";
8700 this.HashTogglePullDownMenuItem.Checked = false;
8701 this.HashToggleMenuItem.Checked = false;
8704 this.MarkSettingCommonModified();
8705 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8708 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8710 this.HashMgr.ToggleHash();
8711 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8713 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8714 this.HashToggleMenuItem.Checked = true;
8715 this.HashTogglePullDownMenuItem.Checked = true;
8719 this.HashStripSplitButton.Text = "#[-]";
8720 this.HashToggleMenuItem.Checked = false;
8721 this.HashTogglePullDownMenuItem.Checked = false;
8723 this.MarkSettingCommonModified();
8724 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8727 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8728 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8730 public void SetPermanentHashtag(string hashtag)
8732 this.HashMgr.SetPermanentHash("#" + hashtag);
8733 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8734 this.HashTogglePullDownMenuItem.Checked = true;
8735 this.HashToggleMenuItem.Checked = true;
8737 this.MarkSettingCommonModified();
8740 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8742 var tab = this.CurrentTab;
8743 var post = this.CurrentPost;
8744 if (!this.ExistCurrentPost)
8746 this.ReplyOpMenuItem.Enabled = false;
8747 this.ReplyAllOpMenuItem.Enabled = false;
8748 this.DmOpMenuItem.Enabled = false;
8749 this.CreateTabRuleOpMenuItem.Enabled = false;
8750 this.CreateIdRuleOpMenuItem.Enabled = false;
8751 this.CreateSourceRuleOpMenuItem.Enabled = false;
8752 this.ReadOpMenuItem.Enabled = false;
8753 this.UnreadOpMenuItem.Enabled = false;
8754 this.AuthorMenuItem.Visible = false;
8755 this.RetweetedByMenuItem.Visible = false;
8759 this.ReplyOpMenuItem.Enabled = true;
8760 this.ReplyAllOpMenuItem.Enabled = true;
8761 this.DmOpMenuItem.Enabled = true;
8762 this.CreateTabRuleOpMenuItem.Enabled = true;
8763 this.CreateIdRuleOpMenuItem.Enabled = true;
8764 this.CreateSourceRuleOpMenuItem.Enabled = true;
8765 this.ReadOpMenuItem.Enabled = true;
8766 this.UnreadOpMenuItem.Enabled = true;
8767 this.AuthorMenuItem.Visible = true;
8768 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8769 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8770 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8773 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8775 this.FavOpMenuItem.Enabled = false;
8776 this.UnFavOpMenuItem.Enabled = false;
8777 this.OpenStatusOpMenuItem.Enabled = false;
8778 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8779 this.RtOpMenuItem.Enabled = false;
8780 this.RtUnOpMenuItem.Enabled = false;
8781 this.QtOpMenuItem.Enabled = false;
8782 this.FavoriteRetweetMenuItem.Enabled = false;
8783 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8787 this.FavOpMenuItem.Enabled = true;
8788 this.UnFavOpMenuItem.Enabled = true;
8789 this.OpenStatusOpMenuItem.Enabled = true;
8790 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8792 if (!post.CanRetweetBy(this.tw.UserId))
8794 this.RtOpMenuItem.Enabled = false;
8795 this.RtUnOpMenuItem.Enabled = false;
8796 this.QtOpMenuItem.Enabled = false;
8797 this.FavoriteRetweetMenuItem.Enabled = false;
8798 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8802 this.RtOpMenuItem.Enabled = true;
8803 this.RtUnOpMenuItem.Enabled = true;
8804 this.QtOpMenuItem.Enabled = true;
8805 this.FavoriteRetweetMenuItem.Enabled = true;
8806 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8810 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8812 this.RefreshPrevOpMenuItem.Enabled = true;
8816 this.RefreshPrevOpMenuItem.Enabled = false;
8818 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8820 this.OpenRepSourceOpMenuItem.Enabled = false;
8824 this.OpenRepSourceOpMenuItem.Enabled = true;
8827 if (this.ExistCurrentPost && post != null)
8829 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8833 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8834 => this.ContextMenuTabProperty_Opening(sender, null!);
8836 public Twitter TwitterInstance
8839 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8841 if (this.initialLayout)
8844 int splitterDistance;
8845 switch (this.WindowState)
8847 case FormWindowState.Normal:
8848 splitterDistance = this.SplitContainer3.SplitterDistance;
8850 case FormWindowState.Maximized:
8851 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8852 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8853 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8854 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8860 this.mySpDis3 = splitterDistance;
8861 this.MarkSettingLocalModified();
8864 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8866 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8868 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8869 this.PublicSearchQueryMenuItem.Enabled = true;
8871 this.PublicSearchQueryMenuItem.Enabled = false;
8873 var post = this.CurrentPost;
8874 if (!this.ExistCurrentPost || post == null)
8876 this.CopySTOTMenuItem.Enabled = false;
8877 this.CopyURLMenuItem.Enabled = false;
8878 this.CopyUserIdStripMenuItem.Enabled = false;
8882 this.CopySTOTMenuItem.Enabled = true;
8883 this.CopyURLMenuItem.Enabled = true;
8884 this.CopyUserIdStripMenuItem.Enabled = true;
8886 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8887 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8891 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8892 => this.SetNotifyIconText();
8894 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8895 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8897 private async Task DoShowUserStatus(string id, bool showInputDialog)
8899 TwitterUser? user = null;
8901 if (showInputDialog)
8903 using var inputName = new InputTabName();
8904 inputName.FormTitle = "Show UserStatus";
8905 inputName.FormDescription = Properties.Resources.FRMessage1;
8906 inputName.TabName = id;
8908 if (inputName.ShowDialog(this) != DialogResult.OK)
8910 if (string.IsNullOrWhiteSpace(inputName.TabName))
8913 id = inputName.TabName.Trim();
8916 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8918 var cancellationToken = dialog.EnableCancellation();
8922 var task = this.tw.GetUserInfo(id);
8923 user = await dialog.WaitForAsync(this, task);
8925 catch (WebApiException ex)
8927 if (!cancellationToken.IsCancellationRequested)
8928 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8932 if (cancellationToken.IsCancellationRequested)
8936 await this.DoShowUserStatus(user);
8939 private async Task DoShowUserStatus(TwitterUser user)
8941 using var userDialog = new UserInfoDialog(this, this.tw.Api, this.detailsHtmlBuilder);
8942 var showUserTask = userDialog.ShowUserAsync(user);
8943 userDialog.ShowDialog(this);
8946 this.BringToFront();
8948 // ユーザー情報の表示が完了するまで userDialog を破棄しない
8952 internal Task ShowUserStatus(string id, bool showInputDialog)
8953 => this.DoShowUserStatus(id, showInputDialog);
8955 internal Task ShowUserStatus(string id)
8956 => this.DoShowUserStatus(id, true);
8958 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
8960 var post = this.CurrentPost;
8963 await this.ShowUserStatus(post.ScreenName, false);
8967 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
8969 var retweetedBy = this.CurrentPost?.RetweetedBy;
8970 if (retweetedBy != null)
8972 await this.ShowUserStatus(retweetedBy, false);
8976 private async void RtCountMenuItem_Click(object sender, EventArgs e)
8978 var post = this.CurrentPost;
8979 if (!this.ExistCurrentPost || post == null)
8982 var statusId = post.RetweetedId ?? post.StatusId;
8983 TwitterStatus status;
8985 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
8987 var cancellationToken = dialog.EnableCancellation();
8991 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
8992 status = await dialog.WaitForAsync(this, task);
8994 catch (WebApiException ex)
8996 if (!cancellationToken.IsCancellationRequested)
8997 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9001 if (cancellationToken.IsCancellationRequested)
9005 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9008 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9010 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9013 this.Visible = false;
9015 else if (Form.ActiveForm == null)
9017 this.Visible = true;
9018 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9020 this.BringToFront();
9021 this.StatusText.Focus();
9025 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9026 => this.MultiLinePullDownMenuItem.PerformClick();
9029 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9031 if (this.ImageSelector.Visible)
9032 this.ImageSelector.EndSelection();
9034 this.ImageSelector.BeginSelection();
9037 private void SelectMedia_DragEnter(DragEventArgs e)
9039 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9041 e.Effect = DragDropEffects.Copy;
9044 e.Effect = DragDropEffects.None;
9047 private void SelectMedia_DragDrop(DragEventArgs e)
9050 this.BringToFront();
9052 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9053 this.ImageSelector.BeginSelection();
9054 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9055 this.StatusText.Focus();
9058 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9060 this.TimelinePanel.Visible = false;
9061 this.TimelinePanel.Enabled = false;
9064 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9066 this.TimelinePanel.Visible = true;
9067 this.TimelinePanel.Enabled = true;
9068 this.CurrentListView.Focus();
9071 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9072 => this.AllowDrop = false;
9074 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9075 => this.AllowDrop = true;
9077 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9079 if (this.ImageSelector.Visible)
9081 this.MarkSettingCommonModified();
9082 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9086 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9087 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9090 /// StatusTextでCtrl+Vが押下された時の処理
9092 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9096 if (Clipboard.ContainsText())
9098 // clipboardにテキストがある場合は貼り付け処理
9099 this.StatusText.Paste(Clipboard.GetText());
9101 else if (Clipboard.ContainsImage())
9104 using var image = Clipboard.GetImage();
9105 this.ImageSelector.BeginSelection();
9106 this.ImageSelector.Model.AddMediaItemFromImage(image);
9108 else if (Clipboard.ContainsFileDropList())
9110 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9111 this.ImageSelector.BeginSelection();
9112 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9115 catch (ExternalException ex)
9117 MessageBox.Show(ex.Message);
9122 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9124 using var form = new ListManage(this.tw);
9125 form.ShowDialog(this);
9128 private bool ModifySettingCommon { get; set; }
9130 private bool ModifySettingLocal { get; set; }
9132 private bool ModifySettingAtId { get; set; }
9134 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9136 var post = this.CurrentPost;
9137 if (this.ExistCurrentPost && post != null && !post.IsDm)
9138 this.RtCountMenuItem.Enabled = true;
9140 this.RtCountMenuItem.Enabled = false;
9143 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9144 => this.CopyUserId();
9146 private void CopyUserId()
9148 var post = this.CurrentPost;
9149 if (post == null) return;
9150 var clstr = post.ScreenName;
9153 Clipboard.SetDataObject(clstr, false, 5, 100);
9155 catch (Exception ex)
9157 MessageBox.Show(ex.Message);
9161 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9163 var post = this.CurrentPost;
9164 if (this.ExistCurrentPost && post != null && !post.IsDm)
9168 await this.OpenRelatedTab(post);
9170 catch (TabException ex)
9172 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9178 /// 指定されたツイートに対する関連発言タブを開きます
9180 /// <param name="statusId">表示するツイートのID</param>
9181 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9182 public async Task OpenRelatedTab(PostId statusId)
9184 var post = this.statuses[statusId];
9189 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9191 catch (WebApiException ex)
9193 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9198 await this.OpenRelatedTab(post);
9202 /// 指定されたツイートに対する関連発言タブを開きます
9204 /// <param name="post">表示する対象となるツイート</param>
9205 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9206 private async Task OpenRelatedTab(PostClass post)
9208 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9209 if (tabRelated != null)
9211 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9214 var tabName = this.statuses.MakeTabName("Related Tweets");
9216 tabRelated = new RelatedPostsTabModel(tabName, post)
9218 UnreadManage = false,
9222 this.statuses.AddTab(tabRelated);
9223 this.AddNewTab(tabRelated, startup: false);
9225 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9227 await this.RefreshTabAsync(tabRelated);
9229 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9233 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9235 var tabPage = this.ListTab.TabPages[tabIndex];
9236 var listView = (DetailsListView)tabPage.Tag;
9237 var targetPost = tabRelated.TargetPost;
9238 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9240 if (index != -1 && index < listView.Items.Count)
9242 listView.SelectedIndices.Add(index);
9243 listView.Items[index].Focused = true;
9248 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9250 var buf = new StringBuilder();
9251 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9252 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9253 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9256 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9258 MyCommon.EndingFlag = true;
9262 Application.Restart();
9266 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9270 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9271 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9273 private bool ExistCurrentPost
9277 var post = this.CurrentPost;
9278 return post != null && !post.IsDeleted;
9282 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9283 => await this.ShowUserTimeline();
9285 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9286 => await this.ShowRetweeterTimeline();
9288 private string GetUserIdFromCurPostOrInput(string caption)
9290 var id = this.CurrentPost?.ScreenName ?? "";
9292 using var inputName = new InputTabName();
9293 inputName.FormTitle = caption;
9294 inputName.FormDescription = Properties.Resources.FRMessage1;
9295 inputName.TabName = id;
9297 if (inputName.ShowDialog() == DialogResult.OK &&
9298 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9300 id = inputName.TabName.Trim();
9309 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9311 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9312 if (!MyCommon.IsNullOrEmpty(id))
9314 await this.AddNewTabForUserTimeline(id);
9318 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9320 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9321 this.timelineScheduler.SystemResumed();
9324 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9326 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9328 TimeZoneInfo.ClearCachedData();
9330 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9332 if (curTimeOffset != prevTimeOffset)
9335 this.listCache?.PurgeCache();
9336 this.CurrentListView.Refresh();
9338 this.DispSelectedPost(forceupdate: true);
9341 this.timelineScheduler.Reset();
9344 private void TimelineRefreshEnableChange(bool isEnable)
9346 this.timelineScheduler.Enabled = isEnable;
9349 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9350 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9352 private async Task OpenUserAppointUrl()
9354 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9356 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9358 var post = this.CurrentPost;
9361 var xUrl = this.settings.Common.UserAppointUrl;
9362 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9364 var statusId = post.RetweetedId ?? post.StatusId;
9365 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9367 await MyCommon.OpenInBrowserAsync(this, xUrl);
9372 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9377 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9378 => await this.OpenUserAppointUrl();
9380 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9382 if (Form.ActiveForm == null)
9384 await this.InvokeAsync(() =>
9386 this.Visible = true;
9387 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9389 this.BringToFront();
9390 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9392 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9396 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9402 private void ReplaceAppName()
9404 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9405 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9408 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9409 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9411 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9413 if (e.KeyCode == Keys.Space)
9415 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9417 e.SuppressKeyPress = true;
9421 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9423 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9424 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9425 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9426 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9427 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9429 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9432 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9433 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9435 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9436 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9438 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9439 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9441 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9442 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9444 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9445 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9447 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9449 if (this.settings.Common.IconSize == iconSize) return;
9451 var oldIconCol = this.Use2ColumnsMode;
9453 this.settings.Common.IconSize = iconSize;
9454 this.ApplyListViewIconSize(iconSize);
9456 if (this.Use2ColumnsMode != oldIconCol)
9458 foreach (TabPage tp in this.ListTab.TabPages)
9460 this.ResetColumns((DetailsListView)tp.Tag);
9464 this.CurrentListView.Refresh();
9465 this.MarkSettingCommonModified();
9468 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9470 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9471 if (this.settings.Common.SortOrderLock == state) return;
9473 this.settings.Common.SortOrderLock = state;
9474 this.MarkSettingCommonModified();
9477 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9479 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9481 this.StatusLabelUrl.Text = e.StatusText;
9485 this.SetStatusLabelUrl();