1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Connection;
56 using OpenTween.MediaUploadServices;
57 using OpenTween.Models;
58 using OpenTween.OpenTweenCustomControl;
59 using OpenTween.Setting;
60 using OpenTween.Thumbnail;
64 public partial class TweenMain : OTBaseForm
68 /// <summary>画面サイズ</summary>
71 /// <summary>画面位置</summary>
74 /// <summary>区切り位置</summary>
77 /// <summary>発言欄区切り位置</summary>
80 /// <summary>プレビュー区切り位置</summary>
84 private bool initial; // true:起動時処理中
85 private bool initialLayout = true;
86 private bool ignoreConfigSave; // true:起動時処理中
88 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
91 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
92 private Point tabMouseDownPoint;
94 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
95 private string? rclickTabName;
97 private readonly object syncObject = new(); // ロック用
99 private const string DetailHtmlFormatHead =
100 "<head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
101 + "<style type=\"text/css\"><!-- "
102 + "body, p, pre {margin: 0;} "
103 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
104 + "pre {font-family: inherit;} "
105 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
106 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
107 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
108 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
109 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
113 private const string DetailHtmlFormatTemplateMono =
114 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
116 private const string DetailHtmlFormatTemplateNormal =
117 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
119 private string detailHtmlFormatPreparedTemplate = null!;
121 private bool myStatusError = false;
122 private bool myStatusOnline = false;
123 private bool soundfileListup = false;
124 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
127 private readonly SettingManager settings;
130 private readonly Twitter tw;
133 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
137 /// <summary>検索画面インスタンス</summary>
138 internal SearchWordDialog SearchDialog = new();
140 private readonly OpenURL urlDialog = new();
142 /// <summary>@id補助</summary>
143 public AtIdSupplement AtIdSupl = null!;
145 /// <summary>Hashtag補助</summary>
146 public AtIdSupplement HashSupl = null!;
148 public HashtagManage HashMgr = null!;
151 private ThemeManager themeManager;
153 /// <summary>アイコン画像リスト</summary>
154 private readonly ImageCache iconCache;
156 private readonly IconAssetsManager iconAssets;
158 private readonly ThumbnailGenerator thumbGenerator;
160 /// <summary>発言履歴</summary>
161 private readonly List<StatusTextHistory> history = new();
163 /// <summary>発言履歴カレントインデックス</summary>
166 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
168 /// <summary>リプライ先のステータスID・スクリーン名</summary>
169 private (long StatusId, string ScreenName)? inReplyTo = null;
172 private readonly List<DateTimeUtc> postTimestamps = new();
173 private readonly List<DateTimeUtc> favTimestamps = new();
176 private readonly StringFormat sfTab = new();
178 //////////////////////////////////////////////////////////////////////////////////////////////////////////
180 /// <summary>発言保持クラス</summary>
181 private readonly TabInformations statuses;
183 private TimelineListViewCache? listCache;
184 private TimelineListViewDrawer? listDrawer;
186 private bool isColumnChanged = false;
188 private const int MaxWorderThreads = 20;
189 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
190 private readonly CancellationTokenSource workerCts = new();
191 private readonly IProgress<string> workerProgress = null!;
193 private int unreadCounter = -1;
194 private int unreadAtCounter = -1;
196 private readonly string[] columnOrgText = new string[9];
197 private readonly string[] columnText = new string[9];
199 private bool doFavRetweetFlags = false;
201 //////////////////////////////////////////////////////////////////////////////////////////////////////////
203 private readonly TimelineScheduler timelineScheduler = new();
204 private readonly DebounceTimer selectionDebouncer;
205 private readonly DebounceTimer saveConfigDebouncer;
207 private readonly string recommendedStatusFooter;
208 private bool urlMultibyteSplit = false;
209 private bool preventSmsCommand = true;
212 private readonly record struct UrlUndo(
217 private List<UrlUndo>? urlUndoBuffer = null;
219 private readonly record struct ReplyChain(
225 /// <summary>[, ]でのリプライ移動の履歴</summary>
226 private Stack<ReplyChain>? replyChains;
228 /// <summary>ポスト選択履歴</summary>
229 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
231 public TabModel CurrentTab
232 => this.statuses.SelectedTab;
234 public string CurrentTabName
235 => this.statuses.SelectedTabName;
237 public TabPage CurrentTabPage
238 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
240 public DetailsListView CurrentListView
241 => (DetailsListView)this.CurrentTabPage.Tag;
243 public PostClass? CurrentPost
244 => this.CurrentTab.SelectedPost;
246 public bool Use2ColumnsMode
247 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
249 /// <summary>検索処理タイプ</summary>
250 internal enum SEARCHTYPE
257 private readonly record struct StatusTextHistory(
259 (long StatusId, string ScreenName)? InReplyTo = null
262 private readonly HookGlobalHotkey hookGlobalHotkey;
264 private void TweenMain_Activated(object sender, EventArgs e)
266 // 画面がアクティブになったら、発言欄の背景色戻す
267 if (this.StatusText.Focused)
269 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
273 private bool disposed = false;
276 /// 使用中のリソースをすべてクリーンアップします。
278 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
279 protected override void Dispose(bool disposing)
281 base.Dispose(disposing);
288 this.components?.Dispose();
291 this.SearchDialog.Dispose();
292 this.urlDialog.Dispose();
293 this.themeManager.Dispose();
294 this.sfTab.Dispose();
296 this.timelineScheduler.Dispose();
297 this.workerCts.Cancel();
298 this.thumbnailTokenSource?.Dispose();
300 this.hookGlobalHotkey.Dispose();
303 // 終了時にRemoveHandlerしておかないとメモリリークする
304 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
305 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
306 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
308 this.disposed = true;
311 private void InitColumns(ListView list, bool startup)
313 this.InitColumnText();
315 ColumnHeader[]? columns = null;
318 if (this.Use2ColumnsMode)
322 new ColumnHeader(), // アイコン
323 new ColumnHeader(), // 本文
326 columns[0].Text = this.columnText[0];
327 columns[1].Text = this.columnText[2];
331 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
333 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
334 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
335 columns[0].DisplayIndex = 0;
336 columns[1].DisplayIndex = 1;
341 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
343 columns[idx].Width = curListColumn.Width;
344 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
353 new ColumnHeader(), // アイコン
354 new ColumnHeader(), // ニックネーム
355 new ColumnHeader(), // 本文
356 new ColumnHeader(), // 日付
357 new ColumnHeader(), // ユーザID
358 new ColumnHeader(), // 未読
359 new ColumnHeader(), // マーク&プロテクト
360 new ColumnHeader(), // ソース
363 foreach (var i in Enumerable.Range(0, columns.Length))
364 columns[i].Text = this.columnText[i];
368 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
370 foreach (var (column, index) in columns.WithIndex())
372 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
373 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
379 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
381 columns[idx].Width = curListColumn.Width;
382 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
388 list.Columns.AddRange(columns);
396 foreach (var column in columns)
402 private void InitColumnText()
404 this.columnText[0] = "";
405 this.columnText[1] = Properties.Resources.AddNewTabText2;
406 this.columnText[2] = Properties.Resources.AddNewTabText3;
407 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
408 this.columnText[4] = Properties.Resources.AddNewTabText5;
409 this.columnText[5] = "";
410 this.columnText[6] = "";
411 this.columnText[7] = "Source";
413 this.columnOrgText[0] = "";
414 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
415 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
416 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
417 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
418 this.columnOrgText[5] = "";
419 this.columnOrgText[6] = "";
420 this.columnOrgText[7] = "Source";
422 var c = this.statuses.SortMode switch
424 ComparerMode.Nickname => 1, // ニックネーム
425 ComparerMode.Data => 2, // 本文
426 ComparerMode.Id => 3, // 時刻=発言Id
427 ComparerMode.Name => 4, // 名前
428 ComparerMode.Source => 7, // Source
432 if (this.Use2ColumnsMode)
434 if (this.statuses.SortOrder == SortOrder.Descending)
436 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
437 this.columnText[2] = this.columnOrgText[2] + "▾";
441 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
442 this.columnText[2] = this.columnOrgText[2] + "▴";
447 if (this.statuses.SortOrder == SortOrder.Descending)
449 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
450 this.columnText[c] = this.columnOrgText[c] + "▾";
454 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
455 this.columnText[c] = this.columnOrgText[c] + "▴";
461 SettingManager settingManager,
462 TabInformations tabInfo,
464 ImageCache imageCache,
465 IconAssetsManager iconAssets,
466 ThumbnailGenerator thumbGenerator
469 this.settings = settingManager;
470 this.statuses = tabInfo;
472 this.iconCache = imageCache;
473 this.iconAssets = iconAssets;
474 this.thumbGenerator = thumbGenerator;
476 this.InitializeComponent();
478 if (!this.DesignMode)
480 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
481 this.StatusText.Dock = DockStyle.Fill;
484 this.hookGlobalHotkey = new HookGlobalHotkey(this);
486 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
487 this.gh.NotifyClicked += this.GrowlHelper_Callback;
489 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
490 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
492 this.ImageSelector.Visible = false;
493 this.ImageSelector.Enabled = false;
494 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
496 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
498 this.ReplaceAppName();
499 this.InitializeShortcuts();
501 this.ignoreConfigSave = true;
502 this.Visible = false;
504 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
506 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
508 Regex.CacheSize = 100;
511 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
512 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
513 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
515 // <<<<<<<<<設定関連>>>>>>>>>
519 // 現在の DPI と設定保存時の DPI との比を取得する
520 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
523 this.tw.Initialize(this.settings.Common.Token, this.settings.Common.TokenSecret, this.settings.Common.UserName, this.settings.Common.UserId);
527 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
528 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
530 // アクセストークンが有効であるか確認する
531 // ここが Twitter API への最初のアクセスになるようにすること
534 this.tw.VerifyCredentials();
536 catch (WebApiException ex)
540 string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
541 ApplicationSettings.ApplicationName,
542 MessageBoxButtons.OK,
543 MessageBoxIcon.Warning);
547 // プロキシ設定等の通信まわりの初期化が済んでから処理する
548 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
549 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
550 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
551 imgazyobizinet.AutoUpdate = true;
553 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
556 this.ImageSelector.Initialize(this.tw, this.tw.Configuration, this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
558 this.tweetThumbnail1.Initialize(this.thumbGenerator);
561 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
562 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
563 this.HashMgr = new HashtagManage(this.HashSupl,
564 this.settings.Common.HashTags.ToArray(),
565 this.settings.Common.HashSelected,
566 this.settings.Common.HashIsPermanent,
567 this.settings.Common.HashIsHead,
568 this.settings.Common.HashIsNotAddToAtReply);
569 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
572 this.themeManager = new(this.settings.Local);
573 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
575 // StringFormatオブジェクトへの事前設定
576 this.sfTab.Alignment = StringAlignment.Center;
577 this.sfTab.LineAlignment = StringAlignment.Center;
579 this.InitDetailHtmlFormat();
580 this.tweetDetailsView.ClearPostBrowser();
582 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
584 this.history.Add(new StatusTextHistory(""));
586 this.inReplyTo = null;
589 this.SearchDialog.Owner = this;
590 this.urlDialog.Owner = this;
593 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
594 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
596 // 新着取得時のリストスクロールをするか。trueならスクロールしない
597 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
598 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
600 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
601 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
604 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
605 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
606 this.myLoc = this.settings.Local.FormLocation;
608 if (this.WindowState != FormWindowState.Minimized)
610 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
611 var outOfScreen = true;
612 if (Screen.AllScreens.Length == 1) // ハングするとの報告
614 foreach (var scr in Screen.AllScreens)
616 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
624 this.myLoc = new Point(0, 0);
626 this.DesktopLocation = this.myLoc;
628 this.TopMost = this.settings.Common.AlwaysTop;
629 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
630 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
631 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
633 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
634 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
636 this.StatusText.Font = this.themeManager.FontInputFont;
637 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
639 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
640 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
641 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
643 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
644 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
646 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
647 if (this.settings.Common.UnreadManage == false)
649 this.ReadedStripMenuItem.Enabled = false;
650 this.UnreadStripMenuItem.Enabled = false;
653 // リンク先URL表示部の初期化(画面左下)
654 this.StatusLabelUrl.Text = "";
656 this.StatusLabel.Text = "";
657 this.StatusLabel.AutoToolTip = false;
658 this.StatusLabel.ToolTipText = "";
660 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
662 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
663 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
664 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
665 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
667 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
668 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
669 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
670 this.SplitContainer2.Panel2.AccessibleName = "";
672 ////////////////////////////////////////////////////////////////////////////////
673 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
674 var mode = this.settings.Common.SortColumn switch
676 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
677 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
678 1 => ComparerMode.Nickname, // ニックネーム
679 2 => ComparerMode.Data, // 本文
680 3 => ComparerMode.Id, // 時刻=発言Id
681 4 => ComparerMode.Name, // 名前
682 7 => ComparerMode.Source, // Source
683 _ => ComparerMode.Id,
685 this.statuses.SetSortMode(mode, sortOrder);
686 ////////////////////////////////////////////////////////////////////////////////
688 this.ApplyListViewIconSize(this.settings.Common.IconSize);
690 // <<<<<<<<タブ関連>>>>>>>
691 foreach (var tab in this.statuses.Tabs)
693 if (!this.AddNewTab(tab, startup: true))
694 throw new TabException(Properties.Resources.TweenMain_LoadText1);
697 this.ListTabSelect(this.ListTab.SelectedTab);
700 this.SetTabAlignment();
702 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
703 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
705 if (this.settings.Common.TabIconDisp)
707 this.ListTab.DrawMode = TabDrawMode.Normal;
711 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
712 this.ListTab.DrawItem += this.ListTab_DrawItem;
713 this.ListTab.ImageList = null;
716 if (this.settings.Common.HotkeyEnabled)
719 var modKey = HookGlobalHotkey.ModKeys.None;
720 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
721 modKey |= HookGlobalHotkey.ModKeys.Alt;
722 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
723 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
724 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
725 modKey |= HookGlobalHotkey.ModKeys.Shift;
726 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
727 modKey |= HookGlobalHotkey.ModKeys.Win;
729 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
732 if (this.settings.Common.IsUseNotifyGrowl)
733 this.gh.RegisterGrowl();
735 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
737 this.SetMainWindowTitle();
738 this.SetNotifyIconText();
740 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
747 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
748 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
749 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
750 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
751 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
752 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
753 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
755 this.DoGetFollowersMenu(),
756 this.RefreshBlockIdsAsync(),
757 this.RefreshMuteUserIdsAsync(),
758 this.RefreshNoRetweetIdsAsync(),
759 this.RefreshTwitterConfigurationAsync(),
761 this.RefreshTimelineScheduler();
763 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
764 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
767 this.TimerRefreshIcon.Interval = 200;
768 this.TimerRefreshIcon.Enabled = false;
770 this.ignoreConfigSave = false;
771 this.TweenMain_Resize(this, EventArgs.Empty);
773 if (this.settings.IsFirstRun)
775 // 初回起動時だけ右下のメニューを目立たせる
776 this.HashStripSplitButton.ShowDropDown();
780 private void InitDetailHtmlFormat()
782 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
784 static string ColorToRGBString(Color color)
785 => $"{color.R},{color.G},{color.B}";
787 this.detailHtmlFormatPreparedTemplate = htmlTemplate
788 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
789 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
790 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
791 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
792 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
793 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
796 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
801 txt = this.statuses.Tabs[e.Index].TabName;
808 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
809 if (e.State == DrawItemState.Selected)
811 e.DrawFocusRectangle();
816 if (this.statuses.Tabs[txt].UnreadCount > 0)
819 fore = System.Drawing.SystemBrushes.ControlText;
823 fore = System.Drawing.SystemBrushes.ControlText;
825 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
828 private void LoadConfig()
830 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
831 this.statuses.AddDefaultTabs();
834 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
836 this.RefreshTimelineScheduler();
839 private void RefreshTimelineScheduler()
841 static TimeSpan IntervalSecondsOrDisabled(int seconds)
842 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
844 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
845 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
846 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
847 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
848 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
849 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
850 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
851 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
853 this.timelineScheduler.RefreshSchedule();
856 private void MarkSettingCommonModified()
858 if (this.saveConfigDebouncer == null)
861 this.ModifySettingCommon = true;
862 _ = this.saveConfigDebouncer.Call();
865 private void MarkSettingLocalModified()
867 if (this.saveConfigDebouncer == null)
870 this.ModifySettingLocal = true;
871 _ = this.saveConfigDebouncer.Call();
874 internal void MarkSettingAtIdModified()
876 if (this.saveConfigDebouncer == null)
879 this.ModifySettingAtId = true;
880 _ = this.saveConfigDebouncer.Call();
883 private void RefreshTimeline()
885 var curTabModel = this.CurrentTab;
886 var curListView = this.CurrentListView;
888 // 現在表示中のタブのスクロール位置を退避
889 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
891 // 各タブのリスト上の選択位置などを退避
892 var listSelections = this.SaveListViewSelection();
896 addCount = this.statuses.SubmitUpdate(
899 out var newMentionOrDm,
902 if (MyCommon.EndingFlag) return;
905 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
907 using (ControlTransaction.Update(curListView))
909 this.listCache.PurgeCache();
910 this.listCache.UpdateListSize();
913 this.RestoreListViewSelection(curListView, curTabModel, listSelections[curTabModel.TabName]);
919 if (this.settings.Common.TabIconDisp)
921 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
923 var tabPage = this.ListTab.TabPages[index];
924 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
925 tabPage.ImageIndex = 0; // 未読アイコン
930 this.ListTab.Refresh();
935 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
938 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
940 this.SetMainWindowTitle();
941 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
943 this.HashSupl.AddRangeItem(this.tw.GetHashList());
946 internal readonly record struct ListViewScroll(
947 ScrollLockMode ScrollLockMode,
948 long? TopItemStatusId
951 internal enum ScrollLockMode
953 /// <summary>固定しない</summary>
956 /// <summary>最上部に固定する</summary>
959 /// <summary>最下部に固定する</summary>
962 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
967 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
969 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
971 var lockMode = this.GetScrollLockMode(listView);
972 long? topItemStatusId = null;
974 if (lockMode == ScrollLockMode.FixedToItem)
976 var topItemIndex = listView.TopItem?.Index ?? -1;
977 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
978 topItemStatusId = tab.GetStatusIdAt(topItemIndex);
981 return new ListViewScroll
983 ScrollLockMode = lockMode,
984 TopItemStatusId = topItemStatusId,
988 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
990 if (this.statuses.SortMode == ComparerMode.Id)
992 if (this.statuses.SortOrder == SortOrder.Ascending)
995 if (this.ListLockMenuItem.Checked)
996 return ScrollLockMode.None;
998 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1001 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1002 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1003 return ScrollLockMode.FixedToBottom;
1005 return ScrollLockMode.None;
1010 if (this.ListLockMenuItem.Checked)
1011 return ScrollLockMode.FixedToItem;
1013 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1014 var topItem = listView.TopItem;
1015 if (topItem == null || topItem.Index == 0)
1016 return ScrollLockMode.FixedToTop;
1018 return ScrollLockMode.FixedToItem;
1023 return ScrollLockMode.FixedToItem;
1027 internal readonly record struct ListViewSelection(
1028 long[]? SelectedStatusIds,
1029 long? SelectionMarkStatusId,
1030 long? FocusedStatusId
1034 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1036 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1038 var listsDict = new Dictionary<string, ListViewSelection>();
1040 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
1042 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1043 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1050 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1052 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1054 if (listView.VirtualListSize == 0)
1056 return new ListViewSelection
1058 SelectedStatusIds = Array.Empty<long>(),
1059 SelectionMarkStatusId = null,
1060 FocusedStatusId = null,
1064 return new ListViewSelection
1066 SelectedStatusIds = tab.SelectedStatusIds,
1067 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1068 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1072 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1074 var index = listView.FocusedItem?.Index ?? -1;
1076 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1079 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1081 var index = listView.SelectionMark;
1083 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1087 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1089 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1091 if (listView.VirtualListSize == 0)
1094 switch (listScroll.ScrollLockMode)
1096 case ScrollLockMode.FixedToTop:
1097 listView.EnsureVisible(0);
1099 case ScrollLockMode.FixedToBottom:
1100 listView.EnsureVisible(listView.VirtualListSize - 1);
1102 case ScrollLockMode.FixedToItem:
1103 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1106 var topItem = listView.Items[topIndex];
1109 listView.TopItem = topItem;
1111 catch (NullReferenceException)
1113 listView.EnsureVisible(listView.VirtualListSize - 1);
1114 listView.EnsureVisible(topIndex);
1118 case ScrollLockMode.None:
1125 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1127 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1129 // status_id から ListView 上のインデックスに変換
1130 int[]? selectedIndices = null;
1131 if (listSelection.SelectedStatusIds != null)
1132 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1134 var focusedIndex = -1;
1135 if (listSelection.FocusedStatusId != null)
1136 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1138 var selectionMarkIndex = -1;
1139 if (listSelection.SelectionMarkStatusId != null)
1140 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1142 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1145 private bool BalloonRequired()
1150 if (NativeMethods.IsScreenSaverRunning())
1154 if (!this.NewPostPopMenuItem.Checked)
1157 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1158 if (this.settings.Common.LimitBalloon)
1160 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1167 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1169 if (this.settings.Common.ReadOwnPost)
1171 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
1176 if (this.BalloonRequired())
1178 if (notifyPosts != null && notifyPosts.Length > 0)
1180 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1181 if (this.settings.Common.IsUseNotifyGrowl)
1183 var sb = new StringBuilder();
1187 foreach (var post in notifyPosts)
1189 if (!(notifyPosts.Length > 3))
1195 if (post.IsReply && !post.IsExcludeReply) reply = true;
1196 if (post.IsDm) dm = true;
1197 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1198 switch (this.settings.Common.NameBalloon)
1200 case MyCommon.NameBalloonEnum.UserID:
1201 sb.Append(post.ScreenName).Append(" : ");
1203 case MyCommon.NameBalloonEnum.NickName:
1204 sb.Append(post.Nickname).Append(" : ");
1207 sb.Append(post.TextFromApi);
1208 if (notifyPosts.Length > 3)
1210 if (notifyPosts.Last() != post) continue;
1213 var title = new StringBuilder();
1214 GrowlHelper.NotifyType nt;
1215 if (this.settings.Common.DispUsername)
1217 title.Append(this.tw.Username);
1218 title.Append(" - ");
1223 title.Append(ApplicationSettings.ApplicationName);
1224 title.Append(" [DM] ");
1225 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1226 nt = GrowlHelper.NotifyType.DirectMessage;
1230 title.Append(ApplicationSettings.ApplicationName);
1231 title.Append(" [Reply!] ");
1232 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1233 nt = GrowlHelper.NotifyType.Reply;
1237 title.Append(ApplicationSettings.ApplicationName);
1239 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1240 nt = GrowlHelper.NotifyType.Notify;
1242 var bText = sb.ToString();
1243 if (MyCommon.IsNullOrEmpty(bText)) return;
1245 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1246 this.gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1251 var sb = new StringBuilder();
1254 foreach (var post in notifyPosts)
1256 if (post.IsReply && !post.IsExcludeReply) reply = true;
1257 if (post.IsDm) dm = true;
1258 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1259 switch (this.settings.Common.NameBalloon)
1261 case MyCommon.NameBalloonEnum.UserID:
1262 sb.Append(post.ScreenName).Append(" : ");
1264 case MyCommon.NameBalloonEnum.NickName:
1265 sb.Append(post.Nickname).Append(" : ");
1268 sb.Append(post.TextFromApi);
1271 var title = new StringBuilder();
1273 if (this.settings.Common.DispUsername)
1275 title.Append(this.tw.Username);
1276 title.Append(" - ");
1281 ntIcon = ToolTipIcon.Warning;
1282 title.Append(ApplicationSettings.ApplicationName);
1283 title.Append(" [DM] ");
1284 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1288 ntIcon = ToolTipIcon.Warning;
1289 title.Append(ApplicationSettings.ApplicationName);
1290 title.Append(" [Reply!] ");
1291 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1295 ntIcon = ToolTipIcon.Info;
1296 title.Append(ApplicationSettings.ApplicationName);
1298 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1300 var bText = sb.ToString();
1301 if (MyCommon.IsNullOrEmpty(bText)) return;
1303 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1304 this.NotifyIcon1.BalloonTipText = bText;
1305 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1306 this.NotifyIcon1.ShowBalloonTip(500);
1312 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1316 var dir = Application.StartupPath;
1317 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1319 dir = Path.Combine(dir, "Sounds");
1321 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1329 // mentions新着時に画面ブリンク
1330 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1332 NativeMethods.FlashMyWindow(this.Handle, 3);
1336 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1338 var listView = this.CurrentListView;
1339 if (listView != sender)
1342 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1343 this.CurrentTab.SelectPosts(indices);
1345 if (indices.Length != 1)
1348 var index = indices[0];
1349 if (index > listView.VirtualListSize - 1) return;
1351 this.PushSelectPostChain();
1353 var post = this.CurrentPost!;
1354 this.statuses.SetReadAllTab(post.StatusId, read: true);
1356 this.listCache?.RefreshStyle();
1357 await this.selectionDebouncer.Call();
1360 private void StatusTextHistoryBack()
1362 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1363 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1366 if (this.hisIdx < 0)
1369 var historyItem = this.history[this.hisIdx];
1370 this.inReplyTo = historyItem.InReplyTo;
1371 this.StatusText.Text = historyItem.Status;
1372 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1375 private void StatusTextHistoryForward()
1377 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1378 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1381 if (this.hisIdx > this.history.Count - 1)
1382 this.hisIdx = this.history.Count - 1;
1384 var historyItem = this.history[this.hisIdx];
1385 this.inReplyTo = historyItem.InReplyTo;
1386 this.StatusText.Text = historyItem.Status;
1387 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1390 private async void PostButton_Click(object sender, EventArgs e)
1392 if (this.StatusText.Text.Trim().Length == 0)
1394 if (!this.ImageSelector.Enabled)
1396 await this.DoRefresh();
1401 var currentPost = this.CurrentPost;
1402 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1404 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1406 MessageBoxButtons.YesNoCancel,
1407 MessageBoxIcon.Question);
1410 case DialogResult.Yes:
1411 this.StatusText.Text = "";
1412 await this.DoReTweetOfficial(false);
1414 case DialogResult.Cancel:
1419 if (TextContainsOnlyMentions(this.StatusText.Text))
1421 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1422 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1424 if (ret != DialogResult.OK)
1428 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1430 if (this.settings.Common.Nicoms)
1432 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1433 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1436 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1437 this.CheckReplyTo(this.StatusText.Text);
1439 var status = new PostStatusParams();
1441 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1442 if (this.GetRestStatusCount(statusTextCompat) >= 0)
1444 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1445 // 収まる場合はこれらのオプションを使用せずに投稿する
1446 status.Text = statusTextCompat;
1447 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1451 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1452 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1454 status.AttachmentUrl = attachmentUrl;
1456 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1458 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1459 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1461 status.AutoPopulateReplyMetadata = true;
1463 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1464 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1469 if (this.GetRestStatusCount(status.Text) < 0)
1471 // 文字数制限を超えているが強制的に投稿するか
1472 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1473 if (ret != DialogResult.OK)
1477 IMediaUploadService? uploadService = null;
1478 IMediaItem[]? uploadItems = null;
1479 if (this.ImageSelector.Visible)
1482 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1485 uploadService = this.ImageSelector.GetService(serviceName);
1488 this.inReplyTo = null;
1489 this.StatusText.Text = "";
1490 this.history.Add(new StatusTextHistory(""));
1491 this.hisIdx = this.history.Count - 1;
1492 if (!this.settings.Common.FocusLockToStatusText)
1493 this.CurrentListView.Focus();
1494 this.urlUndoBuffer = null;
1495 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1498 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1500 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1501 await MyCommon.OpenInBrowserAsync(this, tmp);
1504 await this.PostMessageAsync(status, uploadService, uploadItems);
1507 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1509 MyCommon.EndingFlag = true;
1513 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1515 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1517 // _endingFlag=false:フォームの×ボタン
1519 this.Visible = false;
1523 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1524 this.ignoreConfigSave = true;
1525 MyCommon.EndingFlag = true;
1526 this.timelineScheduler.Enabled = false;
1527 this.TimerRefreshIcon.Enabled = false;
1531 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1533 this.Visible = true;
1534 if (this.WindowState == FormWindowState.Minimized)
1536 this.WindowState = FormWindowState.Normal;
1539 this.BringToFront();
1542 private static int errorCount = 0;
1544 private static bool CheckAccountValid()
1546 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1552 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1561 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1562 private Task RefreshTabAsync<T>()
1564 => this.RefreshTabAsync<T>(backward: false);
1566 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1567 private Task RefreshTabAsync<T>(bool backward)
1571 from tab in this.statuses.GetTabsByType<T>()
1572 select this.RefreshTabAsync(tab, backward);
1574 return Task.WhenAll(loadTasks);
1577 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1578 private Task RefreshTabAsync(TabModel tab)
1579 => this.RefreshTabAsync(tab, backward: false);
1581 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1582 private async Task RefreshTabAsync(TabModel tab, bool backward)
1584 await this.workerSemaphore.WaitAsync();
1588 this.RefreshTasktrayIcon();
1589 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1591 catch (WebApiException ex)
1593 this.myStatusError = true;
1594 var tabType = tab switch
1596 HomeTabModel => "GetTimeline",
1597 MentionsTabModel => "GetTimeline",
1598 DirectMessagesTabModel => "GetDirectMessage",
1599 FavoritesTabModel => "GetFavorites",
1600 PublicSearchTabModel => "GetSearch",
1601 UserTimelineTabModel => "GetUserTimeline",
1602 ListTimelineTabModel => "GetListStatus",
1603 RelatedPostsTabModel => "GetRelatedTweets",
1604 _ => tab.GetType().Name.Replace("Model", ""),
1606 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1610 this.RefreshTimeline();
1611 this.workerSemaphore.Release();
1615 private async Task FavAddAsync(long statusId, TabModel tab)
1617 await this.workerSemaphore.WaitAsync();
1621 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1623 this.RefreshTasktrayIcon();
1624 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1626 catch (WebApiException ex)
1628 this.myStatusError = true;
1629 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1633 this.workerSemaphore.Release();
1637 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
1639 if (ct.IsCancellationRequested)
1642 if (!CheckAccountValid())
1643 throw new WebApiException("Auth error. Check your account");
1645 if (!tab.Posts.TryGetValue(statusId, out var post))
1651 await Task.Run(async () =>
1653 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1659 await this.tw.Api.FavoritesCreate(post.RetweetedId ?? post.StatusId)
1661 .ConfigureAwait(false);
1663 catch (TwitterApiException ex)
1664 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1666 // エラーコード 139 のみの場合は成功と見なす
1669 if (this.settings.Common.RestrictFavCheck)
1671 var status = await this.tw.Api.StatusesShow(post.RetweetedId ?? post.StatusId)
1672 .ConfigureAwait(false);
1674 if (status.Favorited != true)
1675 throw new WebApiException("NG(Restricted?)");
1678 this.favTimestamps.Add(DateTimeUtc.Now);
1681 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1683 postTl.IsFav = true;
1685 var favTab = this.statuses.FavoriteTab;
1686 favTab.AddPostQueue(postTl);
1689 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1690 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1692 if (tb.Contains(statusId))
1693 tb.Posts[statusId].IsFav = true;
1696 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1698 catch (WebApiException)
1700 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1705 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1706 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1708 if (this.favTimestamps[i] < oneHour)
1709 this.favTimestamps.RemoveAt(i);
1712 this.statuses.DistributePosts();
1715 if (ct.IsCancellationRequested)
1718 this.RefreshTimeline();
1720 if (this.CurrentTabName == tab.TabName)
1722 using (ControlTransaction.Update(this.CurrentListView))
1724 var idx = tab.IndexOf(statusId);
1726 this.listCache?.RefreshStyle(idx);
1729 var currentPost = this.CurrentPost;
1730 if (currentPost != null && statusId == currentPost.StatusId)
1731 this.DispSelectedPost(true); // 選択アイテム再表示
1735 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
1737 await this.workerSemaphore.WaitAsync();
1741 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1743 this.RefreshTasktrayIcon();
1744 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1746 catch (WebApiException ex)
1748 this.myStatusError = true;
1749 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1753 this.workerSemaphore.Release();
1757 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
1759 if (ct.IsCancellationRequested)
1762 if (!CheckAccountValid())
1763 throw new WebApiException("Auth error. Check your account");
1765 var successIds = new List<long>();
1767 await Task.Run(async () =>
1771 var failedCount = 0;
1772 foreach (var statusId in statusIds)
1776 var post = tab.Posts[statusId];
1778 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1785 await this.tw.Api.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
1787 .ConfigureAwait(false);
1789 catch (WebApiException)
1795 successIds.Add(statusId);
1796 post.IsFav = false; // リスト再描画必要
1798 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1799 tabinfoPost.IsFav = false;
1801 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1802 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1804 if (tb.Contains(statusId))
1805 tb.Posts[statusId].IsFav = false;
1810 if (ct.IsCancellationRequested)
1813 var favTab = this.statuses.FavoriteTab;
1814 foreach (var statusId in successIds)
1816 // ツイートが削除された訳ではないので IsDeleted はセットしない
1817 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1820 this.RefreshTimeline();
1822 if (this.CurrentTabName == tab.TabName)
1824 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1830 using (ControlTransaction.Update(this.CurrentListView))
1832 foreach (var statusId in successIds)
1834 var idx = tab.IndexOf(statusId);
1836 this.listCache?.RefreshStyle(idx);
1840 var currentPost = this.CurrentPost;
1841 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1842 this.DispSelectedPost(true); // 選択アイテム再表示
1847 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1849 await this.workerSemaphore.WaitAsync();
1853 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1855 this.RefreshTasktrayIcon();
1856 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1858 catch (WebApiException ex)
1860 this.myStatusError = true;
1861 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1865 this.workerSemaphore.Release();
1869 private async Task PostMessageAsyncInternal(
1870 IProgress<string> p,
1871 CancellationToken ct,
1872 PostStatusParams postParams,
1873 IMediaUploadService? uploadService,
1874 IMediaItem[]? uploadItems)
1876 if (ct.IsCancellationRequested)
1879 if (!CheckAccountValid())
1880 throw new WebApiException("Auth error. Check your account");
1882 p.Report("Posting...");
1884 PostClass? post = null;
1889 await Task.Run(async () =>
1891 var postParamsWithMedia = postParams;
1893 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1895 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1896 .ConfigureAwait(false);
1899 post = await this.tw.PostStatus(postParamsWithMedia)
1900 .ConfigureAwait(false);
1903 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1905 catch (WebApiException ex)
1907 // 処理は中断せずエラーの表示のみ行う
1908 errMsg = $"Err:{ex.Message}(PostMessage)";
1910 this.myStatusError = true;
1912 catch (UnauthorizedAccessException ex)
1914 // アップロード対象のファイルが開けなかった場合など
1915 errMsg = $"Err:{ex.Message}(PostMessage)";
1917 this.myStatusError = true;
1921 // 使い終わった MediaItem は破棄する
1922 if (uploadItems != null)
1924 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1926 disposableItem.Dispose();
1931 if (ct.IsCancellationRequested)
1934 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1935 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1936 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1938 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1940 var ret = MessageBox.Show(
1942 "Failed to update status",
1943 MessageBoxButtons.RetryCancel,
1944 MessageBoxIcon.Question);
1946 if (ret == DialogResult.Retry)
1948 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1952 this.StatusTextHistoryBack();
1953 this.StatusText.Focus();
1955 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1956 if (this.settings.Common.FocusLockToStatusText)
1957 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1962 this.postTimestamps.Add(DateTimeUtc.Now);
1964 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1965 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1967 if (this.postTimestamps[i] < oneHour)
1968 this.postTimestamps.RemoveAt(i);
1971 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1973 this.HashMgr.ClearHashtag();
1974 this.HashStripSplitButton.Text = "#[-]";
1975 this.HashTogglePullDownMenuItem.Checked = false;
1976 this.HashToggleMenuItem.Checked = false;
1979 this.SetMainWindowTitle();
1982 if (this.settings.Common.PostAndGet)
1984 await this.RefreshTabAsync<HomeTabModel>();
1990 this.statuses.AddPost(post);
1991 this.statuses.DistributePosts();
1993 this.RefreshTimeline();
1997 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
1999 await this.workerSemaphore.WaitAsync();
2003 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2005 this.RefreshTasktrayIcon();
2006 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2008 catch (WebApiException ex)
2010 this.myStatusError = true;
2011 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2015 this.workerSemaphore.Release();
2019 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2021 if (ct.IsCancellationRequested)
2024 if (!CheckAccountValid())
2025 throw new WebApiException("Auth error. Check your account");
2028 if (!this.settings.Common.UnreadManage)
2031 read = this.initial && this.settings.Common.Read;
2033 p.Report("Posting...");
2035 var posts = new List<PostClass>();
2037 await Task.Run(async () =>
2039 foreach (var statusId in statusIds)
2041 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2042 if (post != null) posts.Add(post);
2046 if (ct.IsCancellationRequested)
2049 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2051 this.postTimestamps.Add(DateTimeUtc.Now);
2053 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2054 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
2056 if (this.postTimestamps[i] < oneHour)
2057 this.postTimestamps.RemoveAt(i);
2060 // 自分のRTはTLの更新では取得できない場合があるので、
2061 // 投稿時取得の有無に関わらず追加しておく
2062 posts.ForEach(post => this.statuses.AddPost(post));
2064 if (this.settings.Common.PostAndGet)
2066 await this.RefreshTabAsync<HomeTabModel>();
2070 this.statuses.DistributePosts();
2071 this.RefreshTimeline();
2075 private async Task RefreshFollowerIdsAsync()
2077 await this.workerSemaphore.WaitAsync();
2081 this.RefreshTasktrayIcon();
2082 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2084 await this.tw.RefreshFollowerIds();
2086 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2088 this.RefreshTimeline();
2089 this.listCache?.PurgeCache();
2090 this.CurrentListView.Refresh();
2092 catch (WebApiException ex)
2094 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2098 this.workerSemaphore.Release();
2102 private async Task RefreshNoRetweetIdsAsync()
2104 await this.workerSemaphore.WaitAsync();
2108 this.RefreshTasktrayIcon();
2109 await this.tw.RefreshNoRetweetIds();
2111 this.StatusLabel.Text = "NoRetweetIds refreshed";
2113 catch (WebApiException ex)
2115 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2119 this.workerSemaphore.Release();
2123 private async Task RefreshBlockIdsAsync()
2125 await this.workerSemaphore.WaitAsync();
2129 this.RefreshTasktrayIcon();
2130 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2132 await this.tw.RefreshBlockIds();
2134 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2136 catch (WebApiException ex)
2138 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2142 this.workerSemaphore.Release();
2146 private async Task RefreshTwitterConfigurationAsync()
2148 await this.workerSemaphore.WaitAsync();
2152 this.RefreshTasktrayIcon();
2153 await this.tw.RefreshConfiguration();
2155 if (this.tw.Configuration.PhotoSizeLimit != 0)
2157 foreach (var service in this.ImageSelector.GetServices())
2159 service.UpdateTwitterConfiguration(this.tw.Configuration);
2163 this.listCache?.PurgeCache();
2164 this.CurrentListView.Refresh();
2166 catch (WebApiException ex)
2168 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2172 this.workerSemaphore.Release();
2176 private async Task RefreshMuteUserIdsAsync()
2178 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2182 await this.tw.RefreshMuteUserIdsAsync();
2184 catch (WebApiException ex)
2186 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2190 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
2193 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2195 if (e.Button == MouseButtons.Left)
2197 this.Visible = true;
2198 if (this.WindowState == FormWindowState.Minimized)
2200 this.WindowState = this.formWindowState;
2203 this.BringToFront();
2207 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2208 => await this.ListItemDoubleClickAction();
2210 private async Task ListItemDoubleClickAction()
2212 switch (this.settings.Common.ListDoubleClickAction)
2214 case MyCommon.ListItemDoubleClickActionType.Reply:
2215 this.MakeReplyText();
2217 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2218 this.MakeReplyText(atAll: true);
2220 case MyCommon.ListItemDoubleClickActionType.Favorite:
2221 await this.FavoriteChange(true);
2223 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2224 var post = this.CurrentPost;
2226 await this.ShowUserStatus(post.ScreenName, false);
2228 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2229 await this.ShowUserTimeline();
2231 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2232 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2234 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2235 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2237 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2238 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2240 case MyCommon.ListItemDoubleClickActionType.None:
2247 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2248 => await this.FavoriteChange(true);
2250 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2251 => await this.FavoriteChange(false);
2253 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2254 => await this.FavoritesRetweetOfficial();
2256 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2257 => await this.FavoritesRetweetUnofficial();
2259 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2261 var tab = this.CurrentTab;
2262 var posts = tab.SelectedPosts;
2264 // trueでFavAdd,falseでFavRemove
2265 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2266 || !this.ExistCurrentPost) return;
2268 if (posts.Length > 1)
2273 // https://support.twitter.com/articles/76915#favoriting
2274 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2275 this.doFavRetweetFlags = false;
2280 if (multiFavoriteChangeDialogEnable)
2282 var confirm = MessageBox.Show(
2283 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2284 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2285 MessageBoxButtons.OKCancel,
2286 MessageBoxIcon.Question);
2288 if (confirm == DialogResult.Cancel)
2296 var selectedPost = posts.Single();
2297 if (selectedPost.IsFav)
2299 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2303 await this.FavAddAsync(selectedPost.StatusId, tab);
2307 var selectedPosts = posts.Where(x => x.IsFav);
2308 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2309 if (statusIds.Length == 0)
2311 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2315 await this.FavRemoveAsync(statusIds, tab);
2319 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2321 var post = this.CurrentPost;
2323 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2325 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2328 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2330 if ((!this.initialLayout) && this.Visible)
2332 if (this.WindowState == FormWindowState.Normal)
2334 this.mySize = this.ClientSize;
2335 this.mySpDis = this.SplitContainer1.SplitterDistance;
2336 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2337 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2338 this.MarkSettingLocalModified();
2343 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2345 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2346 if (comparerMode == null)
2349 this.SetSortColumn(comparerMode.Value);
2353 /// 列インデックスからソートを行う ComparerMode を求める
2355 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2356 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2357 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2359 if (this.Use2ColumnsMode)
2360 return ComparerMode.Id;
2362 return columnIndex switch
2364 1 => ComparerMode.Nickname, // ニックネーム
2365 2 => ComparerMode.Data, // 本文
2366 3 => ComparerMode.Id, // 時刻=発言Id
2367 4 => ComparerMode.Name, // 名前
2368 7 => ComparerMode.Source, // Source
2369 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2374 /// 発言一覧の指定した位置の列でソートする
2376 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2377 private void SetSortColumnByDisplayIndex(int columnIndex)
2379 // 表示上の列の位置から ColumnHeader を求める
2380 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2381 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2386 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2387 if (comparerMode == null)
2390 this.SetSortColumn(comparerMode.Value);
2394 /// 発言一覧の最後列の項目でソートする
2396 private void SetSortLastColumn()
2398 // 表示上の最後列にある ColumnHeader を求める
2399 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2400 .OrderByDescending(x => x.DisplayIndex)
2403 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2404 if (comparerMode == null)
2407 this.SetSortColumn(comparerMode.Value);
2411 /// 発言一覧を指定された ComparerMode に基づいてソートする
2413 private void SetSortColumn(ComparerMode sortColumn)
2415 if (this.settings.Common.SortOrderLock)
2418 this.statuses.ToggleSortOrder(sortColumn);
2419 this.InitColumnText();
2421 var list = this.CurrentListView;
2422 if (this.Use2ColumnsMode)
2424 list.Columns[0].Text = this.columnText[0];
2425 list.Columns[1].Text = this.columnText[2];
2429 for (var i = 0; i <= 7; i++)
2431 list.Columns[i].Text = this.columnText[i];
2435 this.listCache?.PurgeCache();
2437 var tab = this.CurrentTab;
2438 var post = this.CurrentPost;
2439 if (tab.AllCount > 0 && post != null)
2441 var idx = tab.IndexOf(post.StatusId);
2444 this.SelectListItem(list, idx);
2445 list.EnsureVisible(idx);
2450 this.MarkSettingCommonModified();
2453 private void TweenMain_LocationChanged(object sender, EventArgs e)
2455 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2457 this.myLoc = this.DesktopLocation;
2458 this.MarkSettingLocalModified();
2462 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2464 var post = this.CurrentPost;
2465 if (!this.ExistCurrentPost)
2467 this.ReplyStripMenuItem.Enabled = false;
2468 this.ReplyAllStripMenuItem.Enabled = false;
2469 this.DMStripMenuItem.Enabled = false;
2470 this.TabMenuItem.Enabled = false;
2471 this.IDRuleMenuItem.Enabled = false;
2472 this.SourceRuleMenuItem.Enabled = false;
2473 this.ReadedStripMenuItem.Enabled = false;
2474 this.UnreadStripMenuItem.Enabled = false;
2475 this.AuthorContextMenuItem.Visible = false;
2476 this.RetweetedByContextMenuItem.Visible = false;
2480 this.ReplyStripMenuItem.Enabled = true;
2481 this.ReplyAllStripMenuItem.Enabled = true;
2482 this.DMStripMenuItem.Enabled = true;
2483 this.TabMenuItem.Enabled = true;
2484 this.IDRuleMenuItem.Enabled = true;
2485 this.SourceRuleMenuItem.Enabled = true;
2486 this.ReadedStripMenuItem.Enabled = true;
2487 this.UnreadStripMenuItem.Enabled = true;
2488 this.AuthorContextMenuItem.Visible = true;
2489 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2490 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2491 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2493 var tab = this.CurrentTab;
2494 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2496 this.FavAddToolStripMenuItem.Enabled = false;
2497 this.FavRemoveToolStripMenuItem.Enabled = false;
2498 this.StatusOpenMenuItem.Enabled = false;
2499 this.ShowRelatedStatusesMenuItem.Enabled = false;
2501 this.ReTweetStripMenuItem.Enabled = false;
2502 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2503 this.QuoteStripMenuItem.Enabled = false;
2504 this.FavoriteRetweetContextMenu.Enabled = false;
2505 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2509 this.FavAddToolStripMenuItem.Enabled = true;
2510 this.FavRemoveToolStripMenuItem.Enabled = true;
2511 this.StatusOpenMenuItem.Enabled = true;
2512 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2514 if (!post.CanRetweetBy(this.tw.UserId))
2516 this.ReTweetStripMenuItem.Enabled = false;
2517 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2518 this.QuoteStripMenuItem.Enabled = false;
2519 this.FavoriteRetweetContextMenu.Enabled = false;
2520 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2524 this.ReTweetStripMenuItem.Enabled = true;
2525 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2526 this.QuoteStripMenuItem.Enabled = true;
2527 this.FavoriteRetweetContextMenu.Enabled = true;
2528 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2532 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2534 this.RepliedStatusOpenMenuItem.Enabled = false;
2538 this.RepliedStatusOpenMenuItem.Enabled = true;
2541 if (this.ExistCurrentPost && post != null)
2543 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2544 if (post.RetweetedByUserId == this.tw.UserId)
2545 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2547 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2551 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2552 => this.MakeReplyText();
2554 private void DMStripMenuItem_Click(object sender, EventArgs e)
2555 => this.MakeDirectMessageText();
2557 private async Task DoStatusDelete()
2559 var posts = this.CurrentTab.SelectedPosts;
2560 if (posts.Length == 0)
2563 // 選択されたツイートの中に削除可能なものが一つでもあるか
2564 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2567 var ret = MessageBox.Show(
2569 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2570 Properties.Resources.DeleteStripMenuItem_ClickText2,
2571 MessageBoxButtons.OKCancel,
2572 MessageBoxIcon.Question);
2574 if (ret != DialogResult.OK)
2577 var currentListView = this.CurrentListView;
2578 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2580 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2582 Exception? lastException = null;
2583 foreach (var post in posts)
2585 if (!post.CanDeleteBy(this.tw.UserId))
2592 await this.tw.Api.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
2596 if (post.RetweetedByUserId == this.tw.UserId)
2598 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2600 await this.tw.Api.StatusesDestroy(post.StatusId)
2605 if (post.UserId == this.tw.UserId)
2607 if (post.RetweetedId != null)
2609 // 他人に RT された自分のツイート
2610 // => RT 元の自分のツイートを削除
2611 await this.tw.Api.StatusesDestroy(post.RetweetedId.Value)
2618 await this.tw.Api.StatusesDestroy(post.StatusId)
2625 catch (WebApiException ex)
2631 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2634 if (lastException == null)
2635 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2637 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2639 using (ControlTransaction.Update(currentListView))
2641 this.listCache?.PurgeCache();
2642 this.listCache?.UpdateListSize();
2644 currentListView.SelectedIndices.Clear();
2646 var currentTab = this.CurrentTab;
2647 if (currentTab.AllCount != 0)
2650 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2651 selectedIndex = focusedIndex;
2653 selectedIndex = currentTab.AllCount - 1;
2655 currentListView.SelectedIndices.Add(selectedIndex);
2656 currentListView.EnsureVisible(selectedIndex);
2657 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2661 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2663 var tabPage = this.ListTab.TabPages[index];
2664 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2666 if (tabPage.ImageIndex == 0)
2667 tabPage.ImageIndex = -1; // タブアイコン
2671 if (!this.settings.Common.TabIconDisp)
2672 this.ListTab.Refresh();
2676 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2677 => await this.DoStatusDelete();
2679 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2681 using (ControlTransaction.Update(this.CurrentListView))
2683 var tab = this.CurrentTab;
2684 foreach (var statusId in tab.SelectedStatusIds)
2686 this.statuses.SetReadAllTab(statusId, read: true);
2687 var idx = tab.IndexOf(statusId);
2688 this.listCache?.RefreshStyle(idx);
2691 if (this.settings.Common.TabIconDisp)
2693 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2695 if (tab.UnreadCount == 0)
2697 var tabPage = this.ListTab.TabPages[index];
2698 if (tabPage.ImageIndex == 0)
2699 tabPage.ImageIndex = -1; // タブアイコン
2703 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2706 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2708 using (ControlTransaction.Update(this.CurrentListView))
2710 var tab = this.CurrentTab;
2711 foreach (var statusId in tab.SelectedStatusIds)
2713 this.statuses.SetReadAllTab(statusId, read: false);
2714 var idx = tab.IndexOf(statusId);
2715 this.listCache?.RefreshStyle(idx);
2718 if (this.settings.Common.TabIconDisp)
2720 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2722 if (tab.UnreadCount > 0)
2724 var tabPage = this.ListTab.TabPages[index];
2725 if (tabPage.ImageIndex == -1)
2726 tabPage.ImageIndex = 0; // タブアイコン
2730 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2733 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2734 => await this.DoRefresh();
2736 private async Task DoRefresh()
2737 => await this.RefreshTabAsync(this.CurrentTab);
2739 private async Task DoRefreshMore()
2740 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2742 private DialogResult ShowSettingDialog()
2744 using var settingDialog = new AppendSettingDialog();
2745 settingDialog.Icon = this.iconAssets.IconMain;
2746 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2748 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2750 DialogResult result;
2753 result = settingDialog.ShowDialog(this);
2757 return DialogResult.Abort;
2760 if (result == DialogResult.OK)
2762 lock (this.syncObject)
2764 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2771 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2774 var previousUserId = this.settings.Common.UserId;
2775 var oldIconCol = this.Use2ColumnsMode;
2777 if (this.ShowSettingDialog() == DialogResult.OK)
2779 lock (this.syncObject)
2781 this.settings.ApplySettings();
2783 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2784 this.tw.ClearAuthInfo();
2786 this.tw.Initialize(this.settings.Common.Token, this.settings.Common.TokenSecret, this.settings.Common.UserName, this.settings.Common.UserId);
2787 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2788 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2790 this.ImageSelector.Reset(this.tw, this.tw.Configuration);
2794 if (this.settings.Common.TabIconDisp)
2796 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2797 this.ListTab.DrawMode = TabDrawMode.Normal;
2798 this.ListTab.ImageList = this.TabImage;
2802 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2803 this.ListTab.DrawItem += this.ListTab_DrawItem;
2804 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2805 this.ListTab.ImageList = null;
2808 catch (Exception ex)
2810 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2811 ex.Data["IsTerminatePermission"] = false;
2817 if (!this.settings.Common.UnreadManage)
2819 this.ReadedStripMenuItem.Enabled = false;
2820 this.UnreadStripMenuItem.Enabled = false;
2821 if (this.settings.Common.TabIconDisp)
2823 foreach (TabPage myTab in this.ListTab.TabPages)
2825 myTab.ImageIndex = -1;
2831 this.ReadedStripMenuItem.Enabled = true;
2832 this.UnreadStripMenuItem.Enabled = true;
2835 catch (Exception ex)
2837 ex.Data["Instance"] = "ListTab(UnreadManage)";
2838 ex.Data["IsTerminatePermission"] = false;
2843 this.SetTabAlignment();
2845 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2847 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2848 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2849 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2851 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2852 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2853 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2854 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2856 var newTheme = new ThemeManager(this.settings.Local);
2857 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2858 this.tweetDetailsView.Theme = this.themeManager;
2859 if (this.listDrawer != null)
2860 this.listDrawer.Theme = this.themeManager;
2865 if (this.StatusText.Focused)
2866 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2868 this.StatusText.Font = this.themeManager.FontInputFont;
2869 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2871 catch (Exception ex)
2873 MessageBox.Show(ex.Message);
2878 this.InitDetailHtmlFormat();
2880 catch (Exception ex)
2882 ex.Data["Instance"] = "Font";
2883 ex.Data["IsTerminatePermission"] = false;
2889 if (this.settings.Common.TabIconDisp)
2891 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2893 var tabPage = this.ListTab.TabPages[index];
2894 if (tab.UnreadCount == 0)
2895 tabPage.ImageIndex = -1;
2897 tabPage.ImageIndex = 0;
2901 catch (Exception ex)
2903 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2904 ex.Data["IsTerminatePermission"] = false;
2910 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2912 foreach (TabPage tp in this.ListTab.TabPages)
2914 var lst = (DetailsListView)tp.Tag;
2916 using (ControlTransaction.Update(lst))
2918 lst.GridLines = this.settings.Common.ShowGrid;
2919 lst.Font = this.themeManager.FontReaded;
2920 lst.BackColor = this.themeManager.ColorListBackcolor;
2922 if (this.Use2ColumnsMode != oldIconCol)
2923 this.ResetColumns(lst);
2927 catch (Exception ex)
2929 ex.Data["Instance"] = "ListView(IconSize)";
2930 ex.Data["IsTerminatePermission"] = false;
2934 this.SetMainWindowTitle();
2935 this.SetNotifyIconText();
2937 this.listCache?.PurgeCache();
2938 this.CurrentListView.Refresh();
2939 this.ListTab.Refresh();
2941 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2942 if (this.settings.Common.HotkeyEnabled)
2944 // グローバルホットキーの登録。設定で変更可能にするかも
2945 var modKey = HookGlobalHotkey.ModKeys.None;
2946 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2947 modKey |= HookGlobalHotkey.ModKeys.Alt;
2948 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2949 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2950 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2951 modKey |= HookGlobalHotkey.ModKeys.Shift;
2952 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2953 modKey |= HookGlobalHotkey.ModKeys.Win;
2955 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2958 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2961 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2969 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2971 this.TopMost = this.settings.Common.AlwaysTop;
2972 this.SaveConfigsAll(false);
2974 if (this.tw.UserId != previousUserId)
2975 await this.DoGetFollowersMenu();
2981 private void SetTabAlignment()
2983 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2984 if (this.ListTab.Alignment == newAlignment) return;
2986 // 各タブのリスト上の選択位置などを退避
2987 var listSelections = this.SaveListViewSelection();
2989 this.ListTab.Alignment = newAlignment;
2991 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2993 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
2994 using (ControlTransaction.Update(lst))
2997 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3002 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3005 if (this.listDrawer != null)
3006 this.listDrawer.IconSize = iconSz;
3008 this.listCache?.PurgeCache();
3011 private void ResetColumns(DetailsListView list)
3013 using (ControlTransaction.Update(list))
3014 using (ControlTransaction.Layout(list, false))
3017 list.ColumnClick -= this.MyList_ColumnClick;
3018 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3019 list.ColumnReordered -= this.MyList_ColumnReordered;
3020 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3022 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3023 list.Columns.Clear();
3024 cols.ForEach(col => col.Dispose());
3027 this.InitColumns(list, true);
3029 list.ColumnClick += this.MyList_ColumnClick;
3030 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
3031 list.ColumnReordered += this.MyList_ColumnReordered;
3032 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3036 public void AddNewTabForSearch(string searchWord)
3038 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3039 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
3041 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
3043 var tabIndex = this.statuses.Tabs.IndexOf(tb);
3044 this.ListTab.SelectedIndex = tabIndex;
3049 var tabName = searchWord;
3050 for (var i = 0; i <= 100; i++)
3052 if (this.statuses.ContainsTab(tabName))
3058 var tab = new PublicSearchTabModel(tabName);
3059 this.statuses.AddTab(tab);
3060 this.AddNewTab(tab, startup: false);
3062 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
3064 var tabPage = this.CurrentTabPage;
3065 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3066 cmb.Items.Add(searchWord);
3067 cmb.Text = searchWord;
3068 this.SaveConfigsTabs();
3070 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
3073 private async Task ShowUserTimeline()
3075 var post = this.CurrentPost;
3076 if (post == null || !this.ExistCurrentPost) return;
3077 await this.AddNewTabForUserTimeline(post.ScreenName);
3080 private async Task ShowRetweeterTimeline()
3082 var retweetedBy = this.CurrentPost?.RetweetedBy;
3083 if (retweetedBy == null || !this.ExistCurrentPost) return;
3084 await this.AddNewTabForUserTimeline(retweetedBy);
3087 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3089 if (e.KeyCode == Keys.Escape)
3091 this.RemoveSpecifiedTab(this.CurrentTabName, false);
3092 this.SaveConfigsTabs();
3093 e.SuppressKeyPress = true;
3097 public async Task AddNewTabForUserTimeline(string user)
3099 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3100 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
3102 if (tb.ScreenName == user)
3104 var tabIndex = this.statuses.Tabs.IndexOf(tb);
3105 this.ListTab.SelectedIndex = tabIndex;
3110 var tabName = "user:" + user;
3111 while (this.statuses.ContainsTab(tabName))
3116 var tab = new UserTimelineTabModel(tabName, user);
3117 this.statuses.AddTab(tab);
3118 this.AddNewTab(tab, startup: false);
3120 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
3121 this.SaveConfigsTabs();
3123 await this.RefreshTabAsync(tab);
3126 public bool AddNewTab(TabModel tab, bool startup)
3129 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
3133 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
3135 var tabPage = new TabPage();
3136 var listCustom = new DetailsListView();
3138 var cnt = this.statuses.Tabs.Count;
3140 // ToDo:Create and set controls follow tabtypes
3142 using (ControlTransaction.Update(listCustom))
3143 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3144 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3145 using (ControlTransaction.Layout(this.SplitContainer1, false))
3146 using (ControlTransaction.Layout(this.ListTab, false))
3147 using (ControlTransaction.Layout(this))
3148 using (ControlTransaction.Layout(tabPage, false))
3150 tabPage.Controls.Add(listCustom);
3153 var userTab = tab as UserTimelineTabModel;
3154 var listTab = tab as ListTimelineTabModel;
3155 var searchTab = tab as PublicSearchTabModel;
3157 if (userTab != null || listTab != null)
3159 var label = new Label
3161 Dock = DockStyle.Top,
3166 if (listTab != null)
3168 label.Text = listTab.ListInfo.ToString();
3170 else if (userTab != null)
3172 label.Text = userTab.ScreenName + "'s Timeline";
3174 label.TextAlign = ContentAlignment.MiddleLeft;
3175 using (var tmpComboBox = new ComboBox())
3177 label.Height = tmpComboBox.Height;
3179 tabPage.Controls.Add(label);
3182 else if (searchTab != null)
3184 var pnl = new Panel();
3186 var lbl = new Label();
3187 var cmb = new ComboBox();
3188 var btn = new Button();
3189 var cmbLang = new ComboBox();
3191 using (ControlTransaction.Layout(pnl, false))
3193 pnl.Controls.Add(cmb);
3194 pnl.Controls.Add(cmbLang);
3195 pnl.Controls.Add(btn);
3196 pnl.Controls.Add(lbl);
3197 pnl.Name = "panelSearch";
3199 pnl.Dock = DockStyle.Top;
3200 pnl.Height = cmb.Height;
3201 pnl.Enter += this.SearchControls_Enter;
3202 pnl.Leave += this.SearchControls_Leave;
3205 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3206 cmb.Dock = DockStyle.Fill;
3207 cmb.Name = "comboSearch";
3208 cmb.DropDownStyle = ComboBoxStyle.DropDown;
3209 cmb.ImeMode = ImeMode.NoControl;
3210 cmb.TabStop = false;
3212 cmb.AutoCompleteMode = AutoCompleteMode.None;
3213 cmb.KeyDown += this.SearchComboBox_KeyDown;
3216 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3217 cmbLang.Dock = DockStyle.Right;
3219 cmbLang.Name = "comboLang";
3220 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3221 cmbLang.TabStop = false;
3222 cmbLang.TabIndex = 2;
3223 cmbLang.Items.Add("");
3224 cmbLang.Items.Add("ja");
3225 cmbLang.Items.Add("en");
3226 cmbLang.Items.Add("ar");
3227 cmbLang.Items.Add("da");
3228 cmbLang.Items.Add("nl");
3229 cmbLang.Items.Add("fa");
3230 cmbLang.Items.Add("fi");
3231 cmbLang.Items.Add("fr");
3232 cmbLang.Items.Add("de");
3233 cmbLang.Items.Add("hu");
3234 cmbLang.Items.Add("is");
3235 cmbLang.Items.Add("it");
3236 cmbLang.Items.Add("no");
3237 cmbLang.Items.Add("pl");
3238 cmbLang.Items.Add("pt");
3239 cmbLang.Items.Add("ru");
3240 cmbLang.Items.Add("es");
3241 cmbLang.Items.Add("sv");
3242 cmbLang.Items.Add("th");
3244 lbl.Text = "Search(C-S-f)";
3245 lbl.Name = "label1";
3246 lbl.Dock = DockStyle.Left;
3248 lbl.Height = cmb.Height;
3249 lbl.TextAlign = ContentAlignment.MiddleLeft;
3252 btn.Text = "Search";
3253 btn.Name = "buttonSearch";
3254 btn.UseVisualStyleBackColor = true;
3255 btn.Dock = DockStyle.Right;
3256 btn.TabStop = false;
3258 btn.Click += this.SearchButton_Click;
3260 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3262 cmb.Items.Add(searchTab.SearchWords);
3263 cmb.Text = searchTab.SearchWords;
3266 cmbLang.Text = searchTab.SearchLang;
3268 tabPage.Controls.Add(pnl);
3272 tabPage.Tag = listCustom;
3273 this.ListTab.Controls.Add(tabPage);
3275 tabPage.Location = new Point(4, 4);
3276 tabPage.Name = "CTab" + cnt;
3277 tabPage.Size = new Size(380, 260);
3278 tabPage.TabIndex = 2 + cnt;
3279 tabPage.Text = tab.TabName;
3280 tabPage.UseVisualStyleBackColor = true;
3281 tabPage.AccessibleRole = AccessibleRole.PageTab;
3283 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3284 listCustom.TabIndex = 1;
3285 listCustom.AllowColumnReorder = true;
3286 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3287 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3288 listCustom.Dock = DockStyle.Fill;
3289 listCustom.FullRowSelect = true;
3290 listCustom.HideSelection = false;
3291 listCustom.Location = new Point(0, 0);
3292 listCustom.Margin = new Padding(0);
3293 listCustom.Name = "CList" + Environment.TickCount;
3294 listCustom.ShowItemToolTips = true;
3295 listCustom.Size = new Size(380, 260);
3296 listCustom.UseCompatibleStateImageBehavior = false;
3297 listCustom.View = View.Details;
3298 listCustom.OwnerDraw = true;
3299 listCustom.VirtualMode = true;
3300 listCustom.Font = this.themeManager.FontReaded;
3301 listCustom.BackColor = this.themeManager.ColorListBackcolor;
3303 listCustom.GridLines = this.settings.Common.ShowGrid;
3304 listCustom.AllowDrop = true;
3306 this.InitColumns(listCustom, startup);
3308 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3309 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3310 listCustom.ColumnClick += this.MyList_ColumnClick;
3311 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3312 listCustom.DragDrop += this.TweenMain_DragDrop;
3313 listCustom.DragEnter += this.TweenMain_DragEnter;
3314 listCustom.DragOver += this.TweenMain_DragOver;
3315 listCustom.MouseClick += this.MyList_MouseClick;
3316 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3317 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3318 listCustom.HScrolled += this.MyList_HScrolled;
3324 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3326 var tabInfo = this.statuses.GetTabByName(tabName);
3327 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3332 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3333 var result = MessageBox.Show(
3335 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3336 MessageBoxButtons.OKCancel,
3337 MessageBoxIcon.Question,
3338 MessageBoxDefaultButton.Button2);
3339 if (result == DialogResult.Cancel)
3345 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3349 var tabPage = this.ListTab.TabPages[tabIndex];
3351 this.SetListProperty(); // 他のタブに列幅等を反映
3354 var listCustom = (DetailsListView)tabPage.Tag;
3357 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3358 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3359 using (ControlTransaction.Layout(this.SplitContainer1, false))
3360 using (ControlTransaction.Layout(this.ListTab, false))
3361 using (ControlTransaction.Layout(this))
3362 using (ControlTransaction.Layout(tabPage, false))
3364 if (this.CurrentTabName == tabName)
3366 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3367 this.beforeSelectedTab = null;
3369 this.ListTab.Controls.Remove(tabPage);
3372 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3374 using var label = tabPage.Controls["labelUser"];
3375 tabPage.Controls.Remove(label);
3377 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3379 using var pnl = tabPage.Controls["panelSearch"];
3381 pnl.Enter -= this.SearchControls_Enter;
3382 pnl.Leave -= this.SearchControls_Leave;
3383 tabPage.Controls.Remove(pnl);
3385 foreach (Control ctrl in pnl.Controls)
3387 if (ctrl.Name == "buttonSearch")
3389 ctrl.Click -= this.SearchButton_Click;
3391 else if (ctrl.Name == "comboSearch")
3393 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3395 pnl.Controls.Remove(ctrl);
3400 tabPage.Controls.Remove(listCustom);
3402 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3403 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3404 listCustom.ColumnClick -= this.MyList_ColumnClick;
3405 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3406 listCustom.DragDrop -= this.TweenMain_DragDrop;
3407 listCustom.DragEnter -= this.TweenMain_DragEnter;
3408 listCustom.DragOver -= this.TweenMain_DragOver;
3409 listCustom.MouseClick -= this.MyList_MouseClick;
3410 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3411 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3412 listCustom.HScrolled -= this.MyList_HScrolled;
3414 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3415 listCustom.Columns.Clear();
3416 cols.ForEach(col => col.Dispose());
3419 listCustom.ContextMenuStrip = null;
3420 listCustom.ColumnHeaderContextMenuStrip = null;
3421 listCustom.Font = null;
3423 listCustom.SmallImageList = null;
3424 listCustom.ListViewItemSorter = null;
3427 this.listCache?.PurgeCache();
3431 listCustom.Dispose();
3432 this.statuses.RemoveTab(tabName);
3437 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3439 this.listCache?.PurgeCache();
3440 this.beforeSelectedTab = e.TabPage;
3443 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3447 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3450 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3451 if (!dragEnableRectangle.Contains(e.Location))
3453 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3454 tn = this.CurrentTabName;
3457 if (MyCommon.IsNullOrEmpty(tn)) return;
3459 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3462 var tabPage = this.ListTab.TabPages[tabIndex];
3463 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3468 this.tabDrag = false;
3471 var cpos = new Point(e.X, e.Y);
3472 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3474 var rect = this.ListTab.GetTabRect(index);
3475 if (rect.Contains(cpos))
3477 this.rclickTabName = tab.TabName;
3483 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3485 this.SetMainWindowTitle();
3486 this.SetStatusLabelUrl();
3487 this.SetApiStatusLabel();
3488 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3489 this.Tag = this.ListTab.Tag;
3490 this.TabMenuControl(this.CurrentTabName);
3491 this.PushSelectPostChain();
3492 this.DispSelectedPost();
3495 private void SetListProperty()
3497 if (!this.isColumnChanged) return;
3499 var currentListView = this.CurrentListView;
3501 var dispOrder = new int[currentListView.Columns.Count];
3502 for (var i = 0; i < currentListView.Columns.Count; i++)
3504 for (var j = 0; j < currentListView.Columns.Count; j++)
3506 if (currentListView.Columns[j].DisplayIndex == i)
3515 foreach (TabPage tb in this.ListTab.TabPages)
3517 if (tb.Text == this.CurrentTabName)
3520 if (tb.Tag != null && tb.Controls.Count > 0)
3522 var lst = (DetailsListView)tb.Tag;
3523 for (var i = 0; i < lst.Columns.Count; i++)
3525 lst.Columns[dispOrder[i]].DisplayIndex = i;
3526 lst.Columns[i].Width = currentListView.Columns[i].Width;
3531 this.isColumnChanged = false;
3534 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3536 if (e.KeyChar == '@')
3538 if (!this.settings.Common.UseAtIdSupplement) return;
3540 var cnt = this.AtIdSupl.ItemCount;
3541 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3542 if (cnt != this.AtIdSupl.ItemCount)
3543 this.MarkSettingAtIdModified();
3546 else if (e.KeyChar == '#')
3548 if (!this.settings.Common.UseHashSupplement) return;
3549 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3554 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3555 => this.ShowSuplDialog(owner, dialog, 0, "");
3557 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3558 => this.ShowSuplDialog(owner, dialog, offset, "");
3560 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3562 dialog.StartsWith = startswith;
3569 dialog.ShowDialog();
3571 this.TopMost = this.settings.Common.AlwaysTop;
3572 var selStart = owner.SelectionStart;
3575 if (dialog.DialogResult == DialogResult.OK)
3577 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3581 fHalf = owner.Text.Substring(0, selStart - offset);
3583 if (selStart < owner.Text.Length)
3585 eHalf = owner.Text.Substring(selStart);
3587 owner.Text = fHalf + dialog.InputText + eHalf;
3588 owner.SelectionStart = selStart + dialog.InputText.Length;
3595 fHalf = owner.Text.Substring(0, selStart);
3597 if (selStart < owner.Text.Length)
3599 eHalf = owner.Text.Substring(selStart);
3601 owner.Text = fHalf + eHalf;
3604 owner.SelectionStart = selStart;
3610 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3613 if (!e.Alt && !e.Control && !e.Shift)
3615 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3617 var isSpace = false;
3618 foreach (var c in this.StatusText.Text)
3620 if (c == ' ' || c == ' ')
3633 this.StatusText.Text = "";
3634 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3638 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3641 private void StatusText_TextChanged(object sender, EventArgs e)
3644 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3645 this.lblLen.Text = pLen.ToString();
3648 this.StatusText.ForeColor = Color.Red;
3652 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3655 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3657 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3659 this.inReplyTo = null;
3664 /// メンション以外の文字列が含まれていないテキストであるか判定します
3666 internal static bool TextContainsOnlyMentions(string text)
3668 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3671 foreach (var mention in mentions)
3673 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3675 if (!string.IsNullOrWhiteSpace(textPart))
3678 startIndex = mention.Indices[1];
3681 var textPartLast = text.Substring(startIndex);
3683 if (!string.IsNullOrWhiteSpace(textPartLast))
3690 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3692 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3694 var autoPopulatedUserIdList = new List<long>();
3696 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3697 if (replyToPost != null)
3699 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3701 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3702 autoPopulatedUserIdList.Add(replyToPost.UserId);
3704 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3706 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3708 statusText = statusText.Substring(screenName.Length + 2);
3709 autoPopulatedUserIdList.Add(userId);
3715 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3721 /// attachment_url に指定可能な URL が含まれていれば除去
3723 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3725 attachmentUrl = null;
3727 // attachment_url は media_id と同時に使用できない
3728 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
3731 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3735 attachmentUrl = match.Value;
3738 statusText = statusText.Substring(0, match.Index);
3740 // テキストと URL の間にスペースが含まれていれば除去
3741 return statusText.TrimEnd(' ');
3744 private string FormatStatusTextExtended(string statusText)
3745 => this.FormatStatusTextExtended(statusText, out _, out _);
3748 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3750 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3752 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3754 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3756 return this.FormatStatusText(statusText);
3760 /// ツイート投稿前のフッター付与などの前処理を行います
3762 private string FormatStatusText(string statusText)
3764 statusText = statusText.Replace("\r\n", "\n");
3766 if (this.urlMultibyteSplit)
3769 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3772 if (this.settings.Common.WideSpaceConvert)
3774 // 文中の全角スペースを半角スペース1個にする
3775 statusText = statusText.Replace(" ", " ");
3778 // DM の場合はこれ以降の処理を行わない
3779 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3783 if (this.settings.Common.PostShiftEnter)
3785 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3789 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3790 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3792 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3795 if (statusText.Contains("RT @"))
3796 disableFooter = true;
3798 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3799 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3801 var mentionSelf = $"@{this.tw.Username} ";
3802 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3804 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3805 statusText = statusText.Substring(mentionSelf.Length);
3812 var hashtag = this.HashMgr.UseHash;
3813 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3815 if (this.HashMgr.IsHead)
3816 header = this.HashMgr.UseHash + " ";
3818 footer = " " + this.HashMgr.UseHash;
3823 if (this.settings.Local.UseRecommendStatus)
3826 footer += this.recommendedStatusFooter;
3828 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3830 // テキストボックスに入力されている文字列を使用する
3831 footer += " " + this.settings.Local.StatusText.Trim();
3835 statusText = header + statusText + footer;
3837 if (this.preventSmsCommand)
3839 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3840 // 参照: https://support.twitter.com/articles/14020
3842 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3843 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3845 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3846 statusText = '\u200b' + statusText;
3854 /// 投稿欄に表示する入力可能な文字数を計算します
3856 private int GetRestStatusCount(string statusText)
3858 var remainCount = this.tw.GetTextLengthRemain(statusText);
3860 var uploadService = this.GetSelectedImageService();
3861 if (uploadService != null)
3863 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3864 remainCount -= uploadService.GetReservedTextLength(1);
3870 private IMediaUploadService? GetSelectedImageService()
3871 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
3874 /// 全てのタブの振り分けルールを反映し直します
3876 private void ApplyPostFilters()
3878 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3880 this.statuses.FilterAll();
3882 var listView = this.CurrentListView;
3883 using (ControlTransaction.Update(listView))
3885 this.listCache?.PurgeCache();
3886 this.listCache?.UpdateListSize();
3889 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3891 var tabPage = this.ListTab.TabPages[index];
3893 if (this.settings.Common.TabIconDisp)
3895 if (tab.UnreadCount > 0)
3896 tabPage.ImageIndex = 0;
3898 tabPage.ImageIndex = -1;
3902 if (!this.settings.Common.TabIconDisp)
3903 this.ListTab.Refresh();
3905 this.SetMainWindowTitle();
3906 this.SetStatusLabelUrl();
3910 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3911 => e.DrawDefault = true;
3913 private void MyList_HScrolled(object sender, EventArgs e)
3914 => ((DetailsListView)sender).Refresh();
3916 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3918 base.ScaleControl(factor, specified);
3920 ScaleChildControl(this.TabImage, factor);
3922 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3923 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3925 foreach (var listview in listviews)
3927 ScaleChildControl(listview, factor);
3931 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3933 var tab = this.CurrentTab;
3935 if (tab.AllCount == 0)
3937 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3941 var selectedIndex = tab.SelectedIndex;
3946 case SEARCHTYPE.NextSearch: // 次を検索
3947 if (selectedIndex != -1)
3948 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3952 case SEARCHTYPE.PrevSearch: // 前を検索
3953 if (selectedIndex != -1)
3954 startIndex = Math.Max(selectedIndex - 1, 0);
3956 startIndex = tab.AllCount - 1;
3958 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3960 if (selectedIndex != -1)
3961 startIndex = selectedIndex;
3967 Func<string, bool> stringComparer;
3970 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3972 catch (ArgumentException)
3974 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3978 var reverse = searchType == SEARCHTYPE.PrevSearch;
3979 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3980 .DefaultIfEmpty(-1).First();
3982 if (foundIndex == -1)
3984 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3988 var listView = this.CurrentListView;
3989 this.SelectListItem(listView, foundIndex);
3990 listView.EnsureVisible(foundIndex);
3993 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3994 => this.ShowSearchDialog(); // 検索メニュー
3996 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3998 var previousSearch = this.SearchDialog.ResultOptions;
3999 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
4001 this.SearchDialog.Reset();
4002 this.ShowSearchDialog();
4008 previousSearch.Query,
4009 previousSearch.CaseSensitive,
4010 previousSearch.UseRegex,
4011 SEARCHTYPE.NextSearch);
4014 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
4016 var previousSearch = this.SearchDialog.ResultOptions;
4017 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
4019 this.SearchDialog.Reset();
4020 this.ShowSearchDialog();
4026 previousSearch.Query,
4027 previousSearch.CaseSensitive,
4028 previousSearch.UseRegex,
4029 SEARCHTYPE.PrevSearch);
4033 /// 検索ダイアログを表示し、検索を実行します
4035 private void ShowSearchDialog()
4037 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
4039 this.TopMost = this.settings.Common.AlwaysTop;
4042 this.TopMost = this.settings.Common.AlwaysTop;
4044 var searchOptions = this.SearchDialog.ResultOptions!;
4045 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
4047 if (searchOptions.NewTab)
4049 var tabName = Properties.Resources.SearchResults_TabName;
4053 tabName = this.statuses.MakeTabName(tabName);
4055 catch (TabException ex)
4057 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
4060 var resultTab = new LocalSearchTabModel(tabName);
4061 this.AddNewTab(resultTab, startup: false);
4062 this.statuses.AddTab(resultTab);
4064 var targetTab = this.CurrentTab;
4066 Func<string, bool> stringComparer;
4069 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
4071 catch (ArgumentException)
4073 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
4077 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
4078 if (foundIndices.Length == 0)
4080 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
4084 var foundPosts = foundIndices.Select(x => targetTab[x]);
4085 foreach (var post in foundPosts)
4087 resultTab.AddPostQueue(post);
4090 this.statuses.DistributePosts();
4091 this.RefreshTimeline();
4093 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
4094 this.ListTab.SelectedIndex = tabIndex;
4099 searchOptions.Query,
4100 searchOptions.CaseSensitive,
4101 searchOptions.UseRegex,
4102 SEARCHTYPE.DialogSearch);
4105 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
4107 this.AddNewTabForSearch(searchOptions.Query);
4111 /// <summary>発言検索に使用するメソッドを生成します</summary>
4112 /// <exception cref="ArgumentException">
4113 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
4115 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
4119 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
4120 var regex = new Regex(query, regexOption);
4122 return x => regex.IsMatch(x);
4126 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
4128 return x => x.IndexOf(query, comparisonType) != -1;
4132 private void AboutMenuItem_Click(object sender, EventArgs e)
4134 using (var about = new TweenAboutBox())
4136 about.ShowDialog(this);
4138 this.TopMost = this.settings.Common.AlwaysTop;
4141 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
4143 var bgnIdx = this.statuses.SelectedTabIndex;
4145 if (this.ImageSelector.Enabled)
4148 TabModel? foundTab = null;
4152 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
4154 var unreadIndex = tab.NextUnreadIndex;
4155 if (unreadIndex != -1)
4157 this.ListTab.SelectedIndex = index;
4159 foundIndex = unreadIndex;
4164 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
4165 if (foundTab == null && bgnIdx > 0)
4167 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
4169 var unreadIndex = tab.NextUnreadIndex;
4170 if (unreadIndex != -1)
4172 this.ListTab.SelectedIndex = index;
4174 foundIndex = unreadIndex;
4180 DetailsListView lst;
4182 if (foundTab == null)
4184 // 全部調べたが未読見つからず→先頭タブの最新発言へ
4185 this.ListTab.SelectedIndex = 0;
4186 var tabPage = this.ListTab.TabPages[0];
4187 var tab = this.statuses.Tabs[0];
4189 if (tab.AllCount == 0)
4192 if (this.statuses.SortOrder == SortOrder.Ascending)
4193 foundIndex = tab.AllCount - 1;
4197 lst = (DetailsListView)tabPage.Tag;
4201 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
4202 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
4205 this.SelectListItem(lst, foundIndex);
4207 if (this.statuses.SortMode == ComparerMode.Id)
4209 var rowHeight = lst.SmallImageList.ImageSize.Height;
4210 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4211 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4217 lst.EnsureVisible(foundIndex);
4222 lst.EnsureVisible(foundIndex);
4228 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4230 var tab = this.CurrentTab;
4231 var post = this.CurrentPost;
4232 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4233 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4236 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4237 => await this.CheckNewVersion(false);
4239 private void RunTweenUp()
4241 var pinfo = new ProcessStartInfo
4243 UseShellExecute = true,
4244 WorkingDirectory = this.settings.SettingsPath,
4245 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4246 Arguments = "\"" + Application.StartupPath + "\"",
4251 Process.Start(pinfo);
4255 MessageBox.Show("Failed to execute TweenUp3.exe.");
4259 public readonly record struct VersionInfo(
4266 /// OpenTween の最新バージョンの情報を取得します
4268 public async Task<VersionInfo> GetVersionInfoAsync()
4270 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4271 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4273 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4274 .ConfigureAwait(false);
4276 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4277 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4279 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4280 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4282 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4284 return new VersionInfo
4286 Version = Version.Parse(msgHeader[0]),
4287 DownloadUri = new Uri(msgHeader[1]),
4288 ReleaseNote = msgBody,
4292 private async Task CheckNewVersion(bool startup = false)
4294 if (ApplicationSettings.VersionInfoUrl == null)
4295 return; // 更新チェック無効化
4299 var versionInfo = await this.GetVersionInfoAsync();
4301 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4306 var msgtext = string.Format(
4307 Properties.Resources.CheckNewVersionText7,
4308 MyCommon.GetReadableVersion(),
4309 MyCommon.GetReadableVersion(versionInfo.Version));
4310 msgtext = MyCommon.ReplaceAppName(msgtext);
4314 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4315 MessageBoxButtons.OK,
4316 MessageBoxIcon.Information);
4321 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4324 using var dialog = new UpdateDialog();
4326 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4327 MyCommon.GetReadableVersion(versionInfo.Version));
4328 dialog.DetailsText = versionInfo.ReleaseNote;
4330 if (dialog.ShowDialog(this) == DialogResult.Yes)
4332 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri.OriginalString);
4334 else if (dialog.SkipButtonPressed)
4336 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4337 this.MarkSettingCommonModified();
4342 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4346 Properties.Resources.CheckNewVersionText10,
4347 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4348 MessageBoxButtons.OK,
4349 MessageBoxIcon.Exclamation,
4350 MessageBoxDefaultButton.Button2);
4355 private void UpdateSelectedPost()
4357 // 件数関連の場合、タイトル即時書き換え
4358 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4359 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4360 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4361 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4363 this.SetMainWindowTitle();
4365 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4366 this.SetStatusLabelUrl();
4368 if (this.settings.Common.TabIconDisp)
4370 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4372 if (tab.UnreadCount == 0)
4374 var tabPage = this.ListTab.TabPages[index];
4375 if (tabPage.ImageIndex == 0)
4376 tabPage.ImageIndex = -1;
4382 this.ListTab.Refresh();
4385 this.DispSelectedPost();
4388 public string CreateDetailHtml(string orgdata)
4389 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4391 private void DispSelectedPost()
4392 => this.DispSelectedPost(false);
4394 private PostClass displayPost = new();
4397 /// サムネイル表示に使用する CancellationToken の生成元
4399 private CancellationTokenSource? thumbnailTokenSource = null;
4401 private void DispSelectedPost(bool forceupdate)
4403 var currentPost = this.CurrentPost;
4404 if (currentPost == null)
4407 var oldDisplayPost = this.displayPost;
4408 this.displayPost = currentPost;
4410 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4413 var loadTasks = new List<Task>
4415 this.tweetDetailsView.ShowPostDetails(currentPost),
4418 this.SplitContainer3.Panel2Collapsed = true;
4420 if (this.settings.Common.PreviewEnable)
4422 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4423 oldTokenSource?.Cancel();
4425 var token = this.thumbnailTokenSource!.Token;
4426 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
4429 async Task DelayedTasks()
4433 await Task.WhenAll(loadTasks);
4435 catch (OperationCanceledException)
4440 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4444 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4445 => await this.OpenApplicationWebsite();
4447 private async Task OpenApplicationWebsite()
4448 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4450 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4451 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4453 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4455 var tab = this.CurrentTab;
4456 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4458 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4459 if (pnl.Controls["comboSearch"].Focused ||
4460 pnl.Controls["comboLang"].Focused ||
4461 pnl.Controls["buttonSearch"].Focused) return;
4464 if (e.Control || e.Shift || e.Alt)
4467 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4470 e.SuppressKeyPress = true;
4473 if (asyncTask != null)
4477 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4479 private void InitializeShortcuts()
4481 this.shortcutCommands = new[]
4483 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4484 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4485 .FocusedOn(FocusedControl.ListTab)
4486 .Do(() => SendKeys.Send("{DOWN}")),
4488 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4489 .FocusedOn(FocusedControl.ListTab)
4490 .Do(() => SendKeys.Send("{UP}")),
4492 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4493 .FocusedOn(FocusedControl.ListTab)
4494 .Do(() => SendKeys.Send("{PGDN}")),
4496 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4497 .FocusedOn(FocusedControl.ListTab)
4498 .Do(() => SendKeys.Send("{PGUP}")),
4500 ShortcutCommand.Create(Keys.F1)
4501 .Do(() => this.OpenApplicationWebsite()),
4503 ShortcutCommand.Create(Keys.F3)
4504 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4506 ShortcutCommand.Create(Keys.F5)
4507 .Do(() => this.DoRefresh()),
4509 ShortcutCommand.Create(Keys.F6)
4510 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4512 ShortcutCommand.Create(Keys.F7)
4513 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4515 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4516 .NotFocusedOn(FocusedControl.StatusText)
4519 this.CurrentTab.ClearAnchor();
4520 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4523 ShortcutCommand.Create(Keys.G)
4524 .NotFocusedOn(FocusedControl.StatusText)
4527 this.CurrentTab.ClearAnchor();
4528 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4531 ShortcutCommand.Create(Keys.Right, Keys.N)
4532 .FocusedOn(FocusedControl.ListTab)
4533 .Do(() => this.GoRelPost(forward: true)),
4535 ShortcutCommand.Create(Keys.Left, Keys.P)
4536 .FocusedOn(FocusedControl.ListTab)
4537 .Do(() => this.GoRelPost(forward: false)),
4539 ShortcutCommand.Create(Keys.OemPeriod)
4540 .FocusedOn(FocusedControl.ListTab)
4541 .Do(() => this.GoAnchor()),
4543 ShortcutCommand.Create(Keys.I)
4544 .FocusedOn(FocusedControl.ListTab)
4545 .OnlyWhen(() => this.StatusText.Enabled)
4546 .Do(() => this.StatusText.Focus()),
4548 ShortcutCommand.Create(Keys.Enter)
4549 .FocusedOn(FocusedControl.ListTab)
4550 .Do(() => this.ListItemDoubleClickAction()),
4552 ShortcutCommand.Create(Keys.R)
4553 .FocusedOn(FocusedControl.ListTab)
4554 .Do(() => this.DoRefresh()),
4556 ShortcutCommand.Create(Keys.L)
4557 .FocusedOn(FocusedControl.ListTab)
4560 this.CurrentTab.ClearAnchor();
4561 this.GoPost(forward: true);
4564 ShortcutCommand.Create(Keys.H)
4565 .FocusedOn(FocusedControl.ListTab)
4568 this.CurrentTab.ClearAnchor();
4569 this.GoPost(forward: false);
4572 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4573 .FocusedOn(FocusedControl.ListTab)
4576 this.CurrentTab.ClearAnchor();
4580 ShortcutCommand.Create(Keys.S)
4581 .FocusedOn(FocusedControl.ListTab)
4584 this.CurrentTab.ClearAnchor();
4585 this.GoNextTab(forward: true);
4588 ShortcutCommand.Create(Keys.A)
4589 .FocusedOn(FocusedControl.ListTab)
4592 this.CurrentTab.ClearAnchor();
4593 this.GoNextTab(forward: false);
4596 // ] in_reply_to参照元へ戻る
4597 ShortcutCommand.Create(Keys.Oem4)
4598 .FocusedOn(FocusedControl.ListTab)
4601 this.CurrentTab.ClearAnchor();
4602 return this.GoInReplyToPostTree();
4605 // [ in_reply_toへジャンプ
4606 ShortcutCommand.Create(Keys.Oem6)
4607 .FocusedOn(FocusedControl.ListTab)
4610 this.CurrentTab.ClearAnchor();
4611 this.GoBackInReplyToPostTree();
4614 ShortcutCommand.Create(Keys.Escape)
4615 .FocusedOn(FocusedControl.ListTab)
4618 this.CurrentTab.ClearAnchor();
4619 var tab = this.CurrentTab;
4620 var tabtype = tab.TabType;
4621 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4623 this.RemoveSpecifiedTab(tab.TabName, false);
4624 this.SaveConfigsTabs();
4628 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4629 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4630 .FocusedOn(FocusedControl.ListTab)
4631 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4633 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4634 ShortcutCommand.Create(Keys.Up, Keys.Down)
4635 .FocusedOn(FocusedControl.PostBrowser)
4638 ShortcutCommand.Create(Keys.Control | Keys.R)
4639 .Do(() => this.MakeReplyText()),
4641 ShortcutCommand.Create(Keys.Control | Keys.D)
4642 .Do(() => this.DoStatusDelete()),
4644 ShortcutCommand.Create(Keys.Control | Keys.M)
4645 .Do(() => this.MakeDirectMessageText()),
4647 ShortcutCommand.Create(Keys.Control | Keys.S)
4648 .Do(() => this.FavoriteChange(favAdd: true)),
4650 ShortcutCommand.Create(Keys.Control | Keys.I)
4651 .Do(() => this.DoRepliedStatusOpen()),
4653 ShortcutCommand.Create(Keys.Control | Keys.Q)
4654 .Do(() => this.DoQuoteOfficial()),
4656 ShortcutCommand.Create(Keys.Control | Keys.B)
4657 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4659 ShortcutCommand.Create(Keys.Control | Keys.T)
4660 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4662 ShortcutCommand.Create(Keys.Control | Keys.L)
4663 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4665 ShortcutCommand.Create(Keys.Control | Keys.Y)
4666 .NotFocusedOn(FocusedControl.PostBrowser)
4667 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4669 ShortcutCommand.Create(Keys.Control | Keys.F)
4670 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4672 ShortcutCommand.Create(Keys.Control | Keys.U)
4673 .Do(() => this.ShowUserTimeline()),
4675 ShortcutCommand.Create(Keys.Control | Keys.H)
4676 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4678 ShortcutCommand.Create(Keys.Control | Keys.O)
4679 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4681 ShortcutCommand.Create(Keys.Control | Keys.E)
4682 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4684 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4685 .FocusedOn(FocusedControl.ListTab)
4686 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4688 ShortcutCommand.Create(Keys.Control | Keys.N)
4689 .FocusedOn(FocusedControl.ListTab)
4690 .Do(() => this.GoNextTab(forward: true)),
4692 ShortcutCommand.Create(Keys.Control | Keys.P)
4693 .FocusedOn(FocusedControl.ListTab)
4694 .Do(() => this.GoNextTab(forward: false)),
4696 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4697 .FocusedOn(FocusedControl.ListTab)
4698 .Do(() => this.CopyStot()),
4700 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4701 ShortcutCommand.Create(Keys.Control | Keys.D1)
4702 .FocusedOn(FocusedControl.ListTab)
4703 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4704 .Do(() => this.ListTab.SelectedIndex = 0),
4706 ShortcutCommand.Create(Keys.Control | Keys.D2)
4707 .FocusedOn(FocusedControl.ListTab)
4708 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4709 .Do(() => this.ListTab.SelectedIndex = 1),
4711 ShortcutCommand.Create(Keys.Control | Keys.D3)
4712 .FocusedOn(FocusedControl.ListTab)
4713 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4714 .Do(() => this.ListTab.SelectedIndex = 2),
4716 ShortcutCommand.Create(Keys.Control | Keys.D4)
4717 .FocusedOn(FocusedControl.ListTab)
4718 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4719 .Do(() => this.ListTab.SelectedIndex = 3),
4721 ShortcutCommand.Create(Keys.Control | Keys.D5)
4722 .FocusedOn(FocusedControl.ListTab)
4723 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4724 .Do(() => this.ListTab.SelectedIndex = 4),
4726 ShortcutCommand.Create(Keys.Control | Keys.D6)
4727 .FocusedOn(FocusedControl.ListTab)
4728 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4729 .Do(() => this.ListTab.SelectedIndex = 5),
4731 ShortcutCommand.Create(Keys.Control | Keys.D7)
4732 .FocusedOn(FocusedControl.ListTab)
4733 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4734 .Do(() => this.ListTab.SelectedIndex = 6),
4736 ShortcutCommand.Create(Keys.Control | Keys.D8)
4737 .FocusedOn(FocusedControl.ListTab)
4738 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4739 .Do(() => this.ListTab.SelectedIndex = 7),
4741 ShortcutCommand.Create(Keys.Control | Keys.D9)
4742 .FocusedOn(FocusedControl.ListTab)
4743 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4745 ShortcutCommand.Create(Keys.Control | Keys.A)
4746 .FocusedOn(FocusedControl.StatusText)
4747 .Do(() => this.StatusText.SelectAll()),
4749 ShortcutCommand.Create(Keys.Control | Keys.V)
4750 .FocusedOn(FocusedControl.StatusText)
4751 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4753 ShortcutCommand.Create(Keys.Control | Keys.Up)
4754 .FocusedOn(FocusedControl.StatusText)
4755 .Do(() => this.StatusTextHistoryBack()),
4757 ShortcutCommand.Create(Keys.Control | Keys.Down)
4758 .FocusedOn(FocusedControl.StatusText)
4759 .Do(() => this.StatusTextHistoryForward()),
4761 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4762 .FocusedOn(FocusedControl.StatusText)
4765 if (this.ListTab.SelectedIndex == 0)
4767 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4771 this.ListTab.SelectedIndex -= 1;
4773 this.StatusText.Focus();
4776 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4777 .FocusedOn(FocusedControl.StatusText)
4780 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4782 this.ListTab.SelectedIndex = 0;
4786 this.ListTab.SelectedIndex += 1;
4788 this.StatusText.Focus();
4791 ShortcutCommand.Create(Keys.Control | Keys.Y)
4792 .FocusedOn(FocusedControl.PostBrowser)
4795 var multiline = !this.settings.Local.StatusMultiline;
4796 this.settings.Local.StatusMultiline = multiline;
4797 this.MultiLineMenuItem.Checked = multiline;
4798 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4801 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4802 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4804 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4805 .Do(() => this.DoRefreshMore()),
4807 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4808 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4810 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4811 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4813 ShortcutCommand.Create(Keys.Shift | Keys.R)
4814 .NotFocusedOn(FocusedControl.StatusText)
4815 .Do(() => this.DoRefreshMore()),
4817 ShortcutCommand.Create(Keys.Shift | Keys.H)
4818 .FocusedOn(FocusedControl.ListTab)
4819 .Do(() => this.GoTopEnd(goTop: true)),
4821 ShortcutCommand.Create(Keys.Shift | Keys.L)
4822 .FocusedOn(FocusedControl.ListTab)
4823 .Do(() => this.GoTopEnd(goTop: false)),
4825 ShortcutCommand.Create(Keys.Shift | Keys.M)
4826 .FocusedOn(FocusedControl.ListTab)
4827 .Do(() => this.GoMiddle()),
4829 ShortcutCommand.Create(Keys.Shift | Keys.G)
4830 .FocusedOn(FocusedControl.ListTab)
4831 .Do(() => this.GoLast()),
4833 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4834 .FocusedOn(FocusedControl.ListTab)
4835 .Do(() => this.MoveMiddle()),
4837 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4838 .FocusedOn(FocusedControl.ListTab)
4839 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4841 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4842 .FocusedOn(FocusedControl.ListTab)
4843 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4845 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4846 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4847 .FocusedOn(FocusedControl.ListTab)
4848 .Do(() => this.GoFav(forward: true)),
4850 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4851 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4852 .FocusedOn(FocusedControl.ListTab)
4853 .Do(() => this.GoFav(forward: false)),
4855 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4856 .FocusedOn(FocusedControl.ListTab)
4857 .Do(() => this.GoBackSelectPostChain()),
4859 ShortcutCommand.Create(Keys.Alt | Keys.R)
4860 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4862 ShortcutCommand.Create(Keys.Alt | Keys.P)
4863 .OnlyWhen(() => this.CurrentPost != null)
4864 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4866 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4867 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4869 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4870 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4872 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4873 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4875 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4876 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4878 // 別タブの同じ書き込みへ(ALT+←/→)
4879 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4880 .FocusedOn(FocusedControl.ListTab)
4881 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4883 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4884 .FocusedOn(FocusedControl.ListTab)
4885 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4887 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4888 .Do(() => this.MakeReplyText(atAll: true)),
4890 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4891 .Do(() => this.CopyIdUri()),
4893 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4894 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4895 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4897 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4898 .Do(() => this.FavoriteChange(favAdd: false)),
4900 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4901 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4903 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4904 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4906 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4907 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4909 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4910 .Do(() => this.DoMoveToRTHome()),
4912 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4913 .FocusedOn(FocusedControl.StatusText)
4916 var tab = this.CurrentTab;
4917 var selectedIndex = tab.SelectedIndex;
4918 if (selectedIndex != -1 && selectedIndex > 0)
4920 var listView = this.CurrentListView;
4921 var idx = selectedIndex - 1;
4922 this.SelectListItem(listView, idx);
4923 listView.EnsureVisible(idx);
4927 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4928 .FocusedOn(FocusedControl.StatusText)
4931 var tab = this.CurrentTab;
4932 var selectedIndex = tab.SelectedIndex;
4933 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4935 var listView = this.CurrentListView;
4936 var idx = selectedIndex + 1;
4937 this.SelectListItem(listView, idx);
4938 listView.EnsureVisible(idx);
4942 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4943 .FocusedOn(FocusedControl.StatusText)
4946 if (this.StatusText.SelectionStart > 0)
4948 var endidx = this.StatusText.SelectionStart - 1;
4950 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4952 var c = this.StatusText.Text[i];
4953 if (char.IsLetterOrDigit(c) || c == '_')
4959 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4960 var cnt = this.AtIdSupl.ItemCount;
4961 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4962 if (this.AtIdSupl.ItemCount != cnt)
4963 this.MarkSettingAtIdModified();
4967 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4968 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4978 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4979 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4980 .FocusedOn(FocusedControl.ListTab)
4981 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4983 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4984 .FocusedOn(FocusedControl.ListTab)
4985 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4987 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4988 .FocusedOn(FocusedControl.ListTab)
4989 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4991 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4992 .FocusedOn(FocusedControl.ListTab)
4993 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4995 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4996 .FocusedOn(FocusedControl.ListTab)
4997 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4999 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
5000 .FocusedOn(FocusedControl.ListTab)
5001 .Do(() => this.SetSortColumnByDisplayIndex(5)),
5003 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
5004 .FocusedOn(FocusedControl.ListTab)
5005 .Do(() => this.SetSortColumnByDisplayIndex(6)),
5007 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
5008 .FocusedOn(FocusedControl.ListTab)
5009 .Do(() => this.SetSortColumnByDisplayIndex(7)),
5011 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
5012 .FocusedOn(FocusedControl.ListTab)
5013 .Do(() => this.SetSortLastColumn()),
5015 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
5016 .FocusedOn(FocusedControl.ListTab)
5017 .Do(() => this.FavoritesRetweetOfficial()),
5019 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
5020 .FocusedOn(FocusedControl.ListTab)
5021 .Do(() => this.FavoritesRetweetUnofficial()),
5023 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
5024 .FocusedOn(FocusedControl.ListTab)
5025 .Do(() => this.OpenUserAppointUrl()),
5027 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
5028 .FocusedOn(FocusedControl.PostBrowser)
5029 .Do(() => this.DoReTweetUnofficial()),
5031 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
5032 .OnlyWhen(() => this.ExistCurrentPost)
5033 .Do(() => this.tweetDetailsView.DoTranslation()),
5035 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
5036 .Do(() => this.DoReTweetUnofficial()),
5038 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
5039 .Do(() => this.CopyUserId()),
5041 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
5042 .Do(() => this.tweetThumbnail1.ScrollUp()),
5044 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
5045 .Do(() => this.tweetThumbnail1.ScrollDown()),
5047 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
5048 .FocusedOn(FocusedControl.ListTab)
5049 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
5050 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
5054 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
5056 // Task を返す非同期処理があれば asyncTask に代入する
5059 // ShortcutCommand に対応しているコマンドはここで処理される
5060 foreach (var command in this.shortcutCommands)
5062 if (command.IsMatch(keyData, focusedOn))
5064 asyncTask = command.RunCommand();
5065 return command.PreventDefault;
5072 private void GoNextTab(bool forward)
5074 var idx = this.statuses.SelectedTabIndex;
5075 var tabCount = this.statuses.Tabs.Count;
5079 if (idx > tabCount - 1) idx = 0;
5084 if (idx < 0) idx = tabCount - 1;
5086 this.ListTab.SelectedIndex = idx;
5089 private void CopyStot()
5091 var sb = new StringBuilder();
5092 var tab = this.CurrentTab;
5093 var isProtected = false;
5094 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
5095 foreach (var post in tab.SelectedPosts)
5097 if (post.IsDeleted) continue;
5100 if (post.RetweetedId != null)
5101 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
5103 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
5107 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
5112 MessageBox.Show(Properties.Resources.CopyStotText1);
5116 var clstr = sb.ToString();
5119 Clipboard.SetDataObject(clstr, false, 5, 100);
5121 catch (Exception ex)
5123 MessageBox.Show(ex.Message);
5128 private void CopyIdUri()
5130 var tab = this.CurrentTab;
5131 if (tab == null || tab is DirectMessagesTabModel)
5134 var copyUrls = new List<string>();
5135 foreach (var post in tab.SelectedPosts)
5136 copyUrls.Add(MyCommon.GetStatusUrl(post));
5138 if (copyUrls.Count == 0)
5143 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
5145 catch (ExternalException ex)
5147 MessageBox.Show(ex.Message);
5151 private void GoFav(bool forward)
5153 var tab = this.CurrentTab;
5154 if (tab.AllCount == 0)
5157 var selectedIndex = tab.SelectedIndex;
5165 if (selectedIndex == -1)
5171 fIdx = selectedIndex + 1;
5172 if (fIdx > tab.AllCount - 1)
5175 toIdx = tab.AllCount;
5180 if (selectedIndex == -1)
5182 fIdx = tab.AllCount - 1;
5186 fIdx = selectedIndex - 1;
5194 for (var idx = fIdx; idx != toIdx; idx += stp)
5198 var listView = this.CurrentListView;
5199 this.SelectListItem(listView, idx);
5200 listView.EnsureVisible(idx);
5206 private void GoSamePostToAnotherTab(bool left)
5208 var tab = this.CurrentTab;
5210 // Directタブは対象外(見つかるはずがない)
5211 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5214 var selectedStatusId = tab.SelectedStatusId;
5215 if (selectedStatusId == -1)
5218 int fIdx, toIdx, stp;
5223 if (this.ListTab.SelectedIndex == 0)
5229 fIdx = this.ListTab.SelectedIndex - 1;
5237 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5243 fIdx = this.ListTab.SelectedIndex + 1;
5245 toIdx = this.ListTab.TabCount;
5249 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5251 var targetTab = this.statuses.Tabs[tabidx];
5254 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5257 var foundIndex = targetTab.IndexOf(selectedStatusId);
5258 if (foundIndex != -1)
5260 this.ListTab.SelectedIndex = tabidx;
5261 var listView = this.CurrentListView;
5262 this.SelectListItem(listView, foundIndex);
5263 listView.EnsureVisible(foundIndex);
5269 private void GoPost(bool forward)
5271 var tab = this.CurrentTab;
5272 var currentPost = this.CurrentPost;
5274 if (currentPost == null)
5277 var selectedIndex = tab.SelectedIndex;
5279 int fIdx, toIdx, stp;
5283 fIdx = selectedIndex + 1;
5284 if (fIdx > tab.AllCount - 1) return;
5285 toIdx = tab.AllCount;
5290 fIdx = selectedIndex - 1;
5291 if (fIdx < 0) return;
5297 if (currentPost.RetweetedBy == null)
5299 name = currentPost.ScreenName;
5303 name = currentPost.RetweetedBy;
5305 for (var idx = fIdx; idx != toIdx; idx += stp)
5307 var post = tab[idx];
5308 if (post.RetweetedId == null)
5310 if (post.ScreenName == name)
5312 var listView = this.CurrentListView;
5313 this.SelectListItem(listView, idx);
5314 listView.EnsureVisible(idx);
5320 if (post.RetweetedBy == name)
5322 var listView = this.CurrentListView;
5323 this.SelectListItem(listView, idx);
5324 listView.EnsureVisible(idx);
5331 private void GoRelPost(bool forward)
5333 var tab = this.CurrentTab;
5334 var selectedIndex = tab.SelectedIndex;
5336 if (selectedIndex == -1)
5339 int fIdx, toIdx, stp;
5343 fIdx = selectedIndex + 1;
5344 if (fIdx > tab.AllCount - 1) return;
5345 toIdx = tab.AllCount;
5350 fIdx = selectedIndex - 1;
5351 if (fIdx < 0) return;
5356 var anchorPost = tab.AnchorPost;
5357 if (anchorPost == null)
5359 var currentPost = this.CurrentPost;
5360 if (currentPost == null)
5363 anchorPost = currentPost;
5364 tab.AnchorPost = currentPost;
5367 for (var idx = fIdx; idx != toIdx; idx += stp)
5369 var post = tab[idx];
5370 if (post.ScreenName == anchorPost.ScreenName ||
5371 post.RetweetedBy == anchorPost.ScreenName ||
5372 post.ScreenName == anchorPost.RetweetedBy ||
5373 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5374 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5375 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5376 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5377 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5379 var listView = this.CurrentListView;
5380 this.SelectListItem(listView, idx);
5381 listView.EnsureVisible(idx);
5387 private void GoAnchor()
5389 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5390 if (anchorStatusId == null)
5393 var idx = this.CurrentTab.IndexOf(anchorStatusId.Value);
5397 var listView = this.CurrentListView;
5398 this.SelectListItem(listView, idx);
5399 listView.EnsureVisible(idx);
5402 private void GoTopEnd(bool goTop)
5404 var listView = this.CurrentListView;
5405 if (listView.VirtualListSize == 0)
5413 item = listView.GetItemAt(0, 25);
5421 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5423 idx = listView.VirtualListSize - 1;
5427 this.SelectListItem(listView, idx);
5430 private void GoMiddle()
5432 var listView = this.CurrentListView;
5433 if (listView.VirtualListSize == 0)
5441 item = listView.GetItemAt(0, 0);
5451 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5454 idx2 = listView.VirtualListSize - 1;
5460 idx3 = (idx1 + idx2) / 2;
5462 this.SelectListItem(listView, idx3);
5465 private void GoLast()
5467 var listView = this.CurrentListView;
5468 if (listView.VirtualListSize == 0) return;
5470 if (this.statuses.SortOrder == SortOrder.Ascending)
5472 this.SelectListItem(listView, listView.VirtualListSize - 1);
5473 listView.EnsureVisible(listView.VirtualListSize - 1);
5477 this.SelectListItem(listView, 0);
5478 listView.EnsureVisible(0);
5482 private void MoveTop()
5484 var listView = this.CurrentListView;
5485 if (listView.SelectedIndices.Count == 0) return;
5486 var idx = listView.SelectedIndices[0];
5487 if (this.statuses.SortOrder == SortOrder.Ascending)
5489 listView.EnsureVisible(listView.VirtualListSize - 1);
5493 listView.EnsureVisible(0);
5495 listView.EnsureVisible(idx);
5498 private async Task GoInReplyToPostTree()
5500 var curTabClass = this.CurrentTab;
5501 var currentPost = this.CurrentPost;
5503 if (currentPost == null)
5506 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5510 var post = await this.tw.GetStatusApi(false, currentPost.StatusId);
5512 currentPost.InReplyToStatusId = post.InReplyToStatusId;
5513 currentPost.InReplyToUser = post.InReplyToUser;
5514 currentPost.IsReply = post.IsReply;
5515 this.listCache?.PurgeCache();
5517 var index = curTabClass.SelectedIndex;
5518 this.CurrentListView.RedrawItems(index, index, false);
5520 catch (WebApiException ex)
5522 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5526 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5528 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5530 this.replyChains = new Stack<ReplyChain>();
5532 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
5535 string inReplyToTabName;
5536 var inReplyToId = currentPost.InReplyToStatusId.Value;
5537 var inReplyToUser = currentPost.InReplyToUser;
5539 var inReplyToPosts = from tab in this.statuses.Tabs
5540 orderby tab != curTabClass
5541 from post in tab.Posts.Values
5542 where post.StatusId == inReplyToId
5543 let index = tab.IndexOf(post.StatusId)
5545 select new { Tab = tab, Index = index };
5547 var inReplyPost = inReplyToPosts.FirstOrDefault();
5548 if (inReplyPost == null)
5552 await Task.Run(async () =>
5554 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
5555 .ConfigureAwait(false);
5558 this.statuses.AddPost(post);
5559 this.statuses.DistributePosts();
5562 catch (WebApiException ex)
5564 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5565 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5569 this.RefreshTimeline();
5571 inReplyPost = inReplyToPosts.FirstOrDefault();
5572 if (inReplyPost == null)
5574 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5578 inReplyToTabName = inReplyPost.Tab.TabName;
5579 inReplyToIndex = inReplyPost.Index;
5581 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5582 var tabPage = this.ListTab.TabPages[tabIndex];
5583 var listView = (DetailsListView)tabPage.Tag;
5585 if (this.CurrentTabName != inReplyToTabName)
5587 this.ListTab.SelectedIndex = tabIndex;
5590 this.SelectListItem(listView, inReplyToIndex);
5591 listView.EnsureVisible(inReplyToIndex);
5594 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5596 var curTabClass = this.CurrentTab;
5597 var currentPost = this.CurrentPost;
5599 if (currentPost == null)
5604 if (currentPost.InReplyToStatusId != null)
5606 var posts = from t in this.statuses.Tabs
5608 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5609 let indexOf = t.IndexOf(p.Value.StatusId)
5611 orderby isForward ? indexOf : indexOf * -1
5612 orderby t != curTabClass
5613 select new { Tab = t, Post = p.Value, Index = indexOf };
5616 var postList = posts.ToList();
5617 for (var i = postList.Count - 1; i >= 0; i--)
5620 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5622 postList.RemoveAt(index);
5625 var currentIndex = this.CurrentTab.SelectedIndex;
5626 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5627 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5628 if (post == null) post = postList.First();
5629 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5630 this.ListTab.SelectedIndex = tabIndex;
5631 var listView = this.CurrentListView;
5632 this.SelectListItem(listView, post.Index);
5633 listView.EnsureVisible(post.Index);
5635 catch (InvalidOperationException)
5643 if (this.replyChains == null || this.replyChains.Count < 1)
5645 var posts = from t in this.statuses.Tabs
5647 where p.Value.InReplyToStatusId == currentPost.StatusId
5648 let indexOf = t.IndexOf(p.Value.StatusId)
5651 orderby t != curTabClass
5652 select new { Tab = t, Index = indexOf };
5655 var post = posts.First();
5656 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5657 this.ListTab.SelectedIndex = tabIndex;
5658 var listView = this.CurrentListView;
5659 this.SelectListItem(listView, post.Index);
5660 listView.EnsureVisible(post.Index);
5662 catch (InvalidOperationException)
5669 var chainHead = this.replyChains.Pop();
5670 if (chainHead.InReplyToId == currentPost.StatusId)
5672 var tab = chainHead.OriginalTab;
5673 if (!this.statuses.Tabs.Contains(tab))
5675 this.replyChains = null;
5679 var idx = tab.IndexOf(chainHead.OriginalId);
5682 this.replyChains = null;
5686 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5689 this.ListTab.SelectedIndex = tabIndex;
5693 this.replyChains = null;
5695 var listView = this.CurrentListView;
5696 this.SelectListItem(listView, idx);
5697 listView.EnsureVisible(idx);
5703 this.replyChains = null;
5704 this.GoBackInReplyToPostTree(parallel);
5710 private void GoBackSelectPostChain()
5712 if (this.selectPostChains.Count > 1)
5715 TabModel? foundTab = null;
5721 this.selectPostChains.Pop();
5722 var (tab, post) = this.selectPostChains.Peek();
5724 if (!this.statuses.Tabs.Contains(tab))
5725 continue; // 該当タブが存在しないので無視
5729 idx = tab.IndexOf(post.StatusId);
5730 if (idx == -1) continue; // 該当ポストが存在しないので無視
5735 this.selectPostChains.Pop();
5737 catch (InvalidOperationException)
5743 while (this.selectPostChains.Count > 1);
5745 if (foundTab == null)
5748 // 履歴が残り1つであればクリアしておく
5749 if (this.selectPostChains.Count == 1)
5750 this.selectPostChains.Clear();
5754 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5755 var tabPage = this.ListTab.TabPages[tabIndex];
5756 var lst = (DetailsListView)tabPage.Tag;
5757 this.ListTab.SelectedIndex = tabIndex;
5761 this.SelectListItem(lst, idx);
5762 lst.EnsureVisible(idx);
5768 private void PushSelectPostChain()
5770 var currentTab = this.CurrentTab;
5771 var currentPost = this.CurrentPost;
5773 var count = this.selectPostChains.Count;
5776 var (tab, post) = this.selectPostChains.Peek();
5777 if (tab == currentTab)
5779 if (post == currentPost) return; // 最新の履歴と同一
5780 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5783 if (count >= 2500) this.TrimPostChain();
5784 this.selectPostChains.Push((currentTab, currentPost));
5787 private void TrimPostChain()
5789 if (this.selectPostChains.Count <= 2000) return;
5790 var p = new Stack<(TabModel, PostClass?)>(2000);
5791 for (var i = 0; i < 2000; i++)
5793 p.Push(this.selectPostChains.Pop());
5795 this.selectPostChains.Clear();
5796 for (var i = 0; i < 2000; i++)
5798 this.selectPostChains.Push(p.Pop());
5802 private bool GoStatus(long statusId)
5804 if (statusId == 0) return false;
5806 var tab = this.statuses.Tabs
5807 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5808 .Where(x => x.Contains(statusId))
5814 var index = tab.IndexOf(statusId);
5816 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5817 this.ListTab.SelectedIndex = tabIndex;
5819 var listView = this.CurrentListView;
5820 this.SelectListItem(listView, index);
5821 listView.EnsureVisible(index);
5826 private bool GoDirectMessage(long statusId)
5828 if (statusId == 0) return false;
5830 var tab = this.statuses.DirectMessageTab;
5831 var index = tab.IndexOf(statusId);
5836 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5837 this.ListTab.SelectedIndex = tabIndex;
5839 var listView = this.CurrentListView;
5840 this.SelectListItem(listView, index);
5841 listView.EnsureVisible(index);
5846 private void MyList_MouseClick(object sender, MouseEventArgs e)
5847 => this.CurrentTab.ClearAnchor();
5849 private void StatusText_Enter(object sender, EventArgs e)
5851 // フォーカスの戻り先を StatusText に設定
5852 this.Tag = this.StatusText;
5853 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5856 public Color InputBackColor
5857 => this.themeManager.ColorInputBackcolor;
5859 private void StatusText_Leave(object sender, EventArgs e)
5861 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5862 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5863 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5866 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5868 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5871 e.SuppressKeyPress = true;
5874 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5876 if (asyncTask != null)
5880 private void SaveConfigsAll(bool ifModified)
5884 this.SaveConfigsCommon();
5885 this.SaveConfigsLocal();
5886 this.SaveConfigsTabs();
5887 this.SaveConfigsAtId();
5891 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5892 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5893 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5897 private void SaveConfigsAtId()
5899 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5901 this.ModifySettingAtId = false;
5902 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5903 this.settings.SaveAtIdList();
5906 private void SaveConfigsCommon()
5908 if (this.ignoreConfigSave) return;
5910 this.ModifySettingCommon = false;
5911 lock (this.syncObject)
5913 this.settings.Common.UserName = this.tw.Username;
5914 this.settings.Common.UserId = this.tw.UserId;
5915 this.settings.Common.Token = this.tw.AccessToken;
5916 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5917 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5918 this.settings.Common.SortColumn = this.statuses.SortMode switch
5920 ComparerMode.Nickname => 1, // ニックネーム
5921 ComparerMode.Data => 2, // 本文
5922 ComparerMode.Id => 3, // 時刻=発言Id
5923 ComparerMode.Name => 4, // 名前
5924 ComparerMode.Source => 7, // Source
5925 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5927 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5928 if (this.HashMgr.IsPermanent)
5930 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5934 this.settings.Common.HashSelected = "";
5936 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5937 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5938 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5939 this.settings.Common.UseImageService = this.ImageSelector.ServiceIndex;
5940 this.settings.Common.UseImageServiceName = this.ImageSelector.ServiceName;
5942 this.settings.SaveCommon();
5946 private void SaveConfigsLocal()
5948 if (this.ignoreConfigSave) return;
5949 lock (this.syncObject)
5951 this.ModifySettingLocal = false;
5952 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5953 this.settings.Local.FormSize = this.mySize;
5954 this.settings.Local.FormLocation = this.myLoc;
5955 this.settings.Local.SplitterDistance = this.mySpDis;
5956 this.settings.Local.PreviewDistance = this.mySpDis3;
5957 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5958 this.settings.Local.StatusTextHeight = this.mySpDis2;
5960 if (this.ignoreConfigSave) return;
5961 this.settings.SaveLocal();
5965 private void SaveConfigsTabs()
5967 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5969 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5971 foreach (var tab in tabs)
5973 if (!tab.IsPermanentTabType)
5976 var tabSetting = new SettingTabs.SettingTabItem
5978 TabName = tab.TabName,
5979 TabType = tab.TabType,
5980 UnreadManage = tab.UnreadManage,
5981 Protected = tab.Protected,
5982 Notify = tab.Notify,
5983 SoundFile = tab.SoundFile,
5988 case FilterTabModel filterTab:
5989 tabSetting.FilterArray = filterTab.FilterArray;
5991 case UserTimelineTabModel userTab:
5992 tabSetting.User = userTab.ScreenName;
5994 case PublicSearchTabModel searchTab:
5995 tabSetting.SearchWords = searchTab.SearchWords;
5996 tabSetting.SearchLang = searchTab.SearchLang;
5998 case ListTimelineTabModel listTab:
5999 tabSetting.ListInfo = listTab.ListInfo;
6003 tabSettingList.Add(tabSetting);
6006 this.settings.Tabs.Tabs = tabSettingList;
6007 this.settings.SaveTabs();
6010 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
6012 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
6013 if (ret != DialogResult.OK)
6016 var match = Twitter.StatusUrlRegex.Match(inputText);
6021 Properties.Resources.OpenURL_InvalidFormat,
6022 Properties.Resources.OpenURL_Caption,
6023 MessageBoxButtons.OK,
6024 MessageBoxIcon.Error);
6030 var statusId = long.Parse(match.Groups["StatusId"].Value);
6031 await this.OpenRelatedTab(statusId);
6033 catch (TabException ex)
6035 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
6039 private void SaveLogMenuItem_Click(object sender, EventArgs e)
6041 var tab = this.CurrentTab;
6043 var rslt = MessageBox.Show(
6044 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
6045 Properties.Resources.SaveLogMenuItem_ClickText2,
6046 MessageBoxButtons.YesNoCancel,
6047 MessageBoxIcon.Question);
6048 if (rslt == DialogResult.Cancel) return;
6050 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
6051 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
6052 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
6053 this.SaveFileDialog1.FilterIndex = 0;
6054 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
6055 this.SaveFileDialog1.RestoreDirectory = true;
6057 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
6059 if (!this.SaveFileDialog1.ValidateNames) return;
6060 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
6061 if (rslt == DialogResult.Yes)
6064 for (var idx = 0; idx < tab.AllCount; idx++)
6066 var post = tab[idx];
6069 protect = "Protect";
6070 sw.WriteLine(post.Nickname + "\t" +
6071 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
6072 post.CreatedAt.ToLocalTimeString() + "\t" +
6073 post.ScreenName + "\t" +
6074 post.StatusId + "\t" +
6075 post.ImageUrl + "\t" +
6076 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
6082 foreach (var post in this.CurrentTab.SelectedPosts)
6086 protect = "Protect";
6087 sw.WriteLine(post.Nickname + "\t" +
6088 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
6089 post.CreatedAt.ToLocalTimeString() + "\t" +
6090 post.ScreenName + "\t" +
6091 post.StatusId + "\t" +
6092 post.ImageUrl + "\t" +
6093 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
6098 this.TopMost = this.settings.Common.AlwaysTop;
6101 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
6105 using (var inputName = new InputTabName())
6107 inputName.TabName = origTabName;
6108 inputName.ShowDialog();
6109 if (inputName.DialogResult == DialogResult.Cancel) return false;
6110 newTabName = inputName.TabName;
6112 this.TopMost = this.settings.Common.AlwaysTop;
6113 if (!MyCommon.IsNullOrEmpty(newTabName))
6116 if (this.statuses.ContainsTab(newTabName))
6118 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
6119 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6123 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
6124 var tabPage = this.ListTab.TabPages[tabIndex];
6127 if (tabPage != null)
6128 tabPage.Text = newTabName;
6130 this.statuses.RenameTab(origTabName, newTabName);
6132 this.SaveConfigsCommon();
6133 this.SaveConfigsTabs();
6134 this.rclickTabName = newTabName;
6143 private void ListTab_MouseClick(object sender, MouseEventArgs e)
6145 if (e.Button == MouseButtons.Middle)
6147 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6149 if (this.ListTab.GetTabRect(index).Contains(e.Location))
6151 this.RemoveSpecifiedTab(tab.TabName, true);
6152 this.SaveConfigsTabs();
6159 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
6160 => this.TabRename(this.CurrentTabName, out _);
6162 private void ListTab_MouseDown(object sender, MouseEventArgs e)
6164 if (this.settings.Common.TabMouseLock) return;
6165 if (e.Button == MouseButtons.Left)
6167 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
6169 if (this.ListTab.GetTabRect(i).Contains(e.Location))
6171 this.tabDrag = true;
6172 this.tabMouseDownPoint = e.Location;
6179 this.tabDrag = false;
6183 private void ListTab_DragEnter(object sender, DragEventArgs e)
6185 if (e.Data.GetDataPresent(typeof(TabPage)))
6186 e.Effect = DragDropEffects.Move;
6188 e.Effect = DragDropEffects.None;
6191 private void ListTab_DragDrop(object sender, DragEventArgs e)
6193 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
6195 this.tabDrag = false;
6198 var cpos = new Point(e.X, e.Y);
6199 var spos = this.ListTab.PointToClient(cpos);
6200 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6202 var rect = this.ListTab.GetTabRect(index);
6203 if (rect.Contains(spos))
6206 if (spos.X <= (rect.Left + rect.Right) / 2)
6215 // タブのないところにドロップ->最後尾へ移動
6216 if (MyCommon.IsNullOrEmpty(tn))
6218 var lastTab = this.statuses.Tabs.Last();
6219 tn = lastTab.TabName;
6223 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6224 if (tp.Text == tn) return;
6226 this.ReOrderTab(tp.Text, tn, bef);
6229 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6231 var baseIndex = this.GetTabPageIndex(baseTabText);
6232 if (baseIndex == -1)
6235 var targetIndex = this.GetTabPageIndex(targetTabText);
6236 if (targetIndex == -1)
6239 using (ControlTransaction.Layout(this.ListTab))
6241 var tab = this.statuses.Tabs[targetIndex];
6242 var tabPage = this.ListTab.TabPages[targetIndex];
6244 this.ListTab.TabPages.Remove(tabPage);
6246 if (targetIndex < baseIndex)
6249 if (!isBeforeBaseTab)
6252 this.statuses.MoveTab(baseIndex, tab);
6254 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6257 this.SaveConfigsTabs();
6260 private void MakeDirectMessageText()
6262 var selectedPosts = this.CurrentTab.SelectedPosts;
6263 if (selectedPosts.Length > 1)
6266 var post = selectedPosts.Single();
6267 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6269 this.inReplyTo = null;
6270 this.StatusText.Text = text;
6271 this.StatusText.SelectionStart = text.Length;
6272 this.StatusText.Focus();
6275 private void MakeReplyText(bool atAll = false)
6277 var selectedPosts = this.CurrentTab.SelectedPosts;
6278 if (selectedPosts.Any(x => x.IsDm))
6280 this.MakeDirectMessageText();
6284 if (selectedPosts.Length == 1)
6286 var post = selectedPosts.Single();
6287 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6288 var inReplyToScreenName = post.ScreenName;
6289 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6293 this.inReplyTo = null;
6296 var selfScreenName = this.tw.Username;
6297 var targetScreenNames = new List<string>();
6298 foreach (var post in selectedPosts)
6300 if (post.ScreenName != selfScreenName)
6301 targetScreenNames.Add(post.ScreenName);
6305 foreach (var (_, screenName) in post.ReplyToList)
6307 if (screenName != selfScreenName)
6308 targetScreenNames.Add(screenName);
6313 if (this.inReplyTo != null)
6315 var (_, screenName) = this.inReplyTo.Value;
6316 if (screenName == selfScreenName)
6317 targetScreenNames.Insert(0, screenName);
6320 var text = this.StatusText.Text;
6321 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6323 var atText = $"@{screenName} ";
6324 if (!text.Contains(atText))
6325 text = atText + text;
6328 this.StatusText.Text = text;
6329 this.StatusText.SelectionStart = text.Length;
6330 this.StatusText.Focus();
6333 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6334 => this.tabDrag = false;
6336 private int iconCnt = 0;
6337 private int blinkCnt = 0;
6338 private bool blink = false;
6340 private void RefreshTasktrayIcon()
6342 void EnableTasktrayAnimation()
6343 => this.TimerRefreshIcon.Enabled = true;
6345 void DisableTasktrayAnimation()
6346 => this.TimerRefreshIcon.Enabled = false;
6348 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6352 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6355 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6356 this.myStatusError = false;
6357 EnableTasktrayAnimation();
6361 var replyIconType = this.settings.Common.ReplyIconState;
6363 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6365 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6366 if (replyTab != null && replyTab.UnreadCount > 0)
6370 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6373 if (this.blinkCnt > 10)
6376 if (this.blinkCnt == 0)
6377 this.blink = !this.blink;
6379 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6380 EnableTasktrayAnimation();
6384 DisableTasktrayAnimation();
6390 // 優先度:リプライ→エラー→オフライン→アイドル
6391 // エラーは更新アイコンでクリアされる
6392 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6393 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6394 else if (this.myStatusError)
6395 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6396 else if (this.myStatusOnline)
6397 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6399 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6402 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6403 => this.RefreshTasktrayIcon(); // 200ms
6405 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6407 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6408 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6409 this.rclickTabName = this.CurrentTabName;
6411 if (this.statuses == null) return;
6412 if (this.statuses.Tabs == null) return;
6414 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6417 this.NotifyDispMenuItem.Checked = tb.Notify;
6418 this.NotifyTbMenuItem.Checked = tb.Notify;
6420 this.soundfileListup = true;
6421 this.SoundFileComboBox.Items.Clear();
6422 this.SoundFileTbComboBox.Items.Clear();
6423 this.SoundFileComboBox.Items.Add("");
6424 this.SoundFileTbComboBox.Items.Add("");
6425 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6426 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6428 oDir = oDir.GetDirectories("Sounds")[0];
6430 foreach (var oFile in oDir.GetFiles("*.wav"))
6432 this.SoundFileComboBox.Items.Add(oFile.Name);
6433 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6435 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6436 if (idx == -1) idx = 0;
6437 this.SoundFileComboBox.SelectedIndex = idx;
6438 this.SoundFileTbComboBox.SelectedIndex = idx;
6439 this.soundfileListup = false;
6440 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6441 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6443 this.TabMenuControl(this.rclickTabName);
6446 private void TabMenuControl(string tabName)
6448 var tabInfo = this.statuses.GetTabByName(tabName)!;
6450 this.FilterEditMenuItem.Enabled = true;
6451 this.EditRuleTbMenuItem.Enabled = true;
6453 if (tabInfo.IsDefaultTabType)
6455 this.ProtectTabMenuItem.Enabled = false;
6456 this.ProtectTbMenuItem.Enabled = false;
6460 this.ProtectTabMenuItem.Enabled = true;
6461 this.ProtectTbMenuItem.Enabled = true;
6464 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6466 this.ProtectTabMenuItem.Checked = true;
6467 this.ProtectTbMenuItem.Checked = true;
6468 this.DeleteTabMenuItem.Enabled = false;
6469 this.DeleteTbMenuItem.Enabled = false;
6473 this.ProtectTabMenuItem.Checked = false;
6474 this.ProtectTbMenuItem.Checked = false;
6475 this.DeleteTabMenuItem.Enabled = true;
6476 this.DeleteTbMenuItem.Enabled = true;
6480 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6482 var checkState = ((ToolStripMenuItem)sender).Checked;
6485 this.ProtectTbMenuItem.Checked = checkState;
6486 this.ProtectTabMenuItem.Checked = checkState;
6489 this.DeleteTabMenuItem.Enabled = !checkState;
6490 this.DeleteTbMenuItem.Enabled = !checkState;
6492 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6493 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6495 this.SaveConfigsTabs();
6498 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6500 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6501 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6503 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6504 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6506 this.SaveConfigsTabs();
6509 public void ChangeTabUnreadManage(string tabName, bool isManage)
6511 var idx = this.GetTabPageIndex(tabName);
6515 var tab = this.statuses.Tabs[tabName];
6516 tab.UnreadManage = isManage;
6518 if (this.settings.Common.TabIconDisp)
6520 var tabPage = this.ListTab.TabPages[idx];
6521 if (tab.UnreadCount > 0)
6522 tabPage.ImageIndex = 0;
6524 tabPage.ImageIndex = -1;
6527 if (this.CurrentTabName == tabName)
6529 this.listCache?.PurgeCache();
6530 this.CurrentListView.Refresh();
6533 this.SetMainWindowTitle();
6534 this.SetStatusLabelUrl();
6535 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6538 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6540 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6541 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6543 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6545 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6547 this.SaveConfigsTabs();
6550 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6552 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6554 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6556 this.SaveConfigsTabs();
6559 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6561 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6562 this.rclickTabName = this.CurrentTabName;
6564 this.RemoveSpecifiedTab(this.rclickTabName, true);
6565 this.SaveConfigsTabs();
6568 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6570 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6572 using (var fltDialog = new FilterDialog())
6574 fltDialog.Owner = this;
6575 fltDialog.SetCurrent(this.rclickTabName);
6576 fltDialog.ShowDialog(this);
6578 this.TopMost = this.settings.Common.AlwaysTop;
6580 this.ApplyPostFilters();
6581 this.SaveConfigsTabs();
6584 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6586 string? tabName = null;
6587 MyCommon.TabUsageType tabUsage;
6588 using (var inputName = new InputTabName())
6590 inputName.TabName = this.statuses.MakeTabName("MyTab");
6591 inputName.IsShowUsage = true;
6592 inputName.ShowDialog();
6593 if (inputName.DialogResult == DialogResult.Cancel) return;
6594 tabName = inputName.TabName;
6595 tabUsage = inputName.Usage;
6597 this.TopMost = this.settings.Common.AlwaysTop;
6598 if (!MyCommon.IsNullOrEmpty(tabName))
6601 ListElement? list = null;
6602 if (tabUsage == MyCommon.TabUsageType.Lists)
6604 using var listAvail = new ListAvailable();
6605 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6607 if (listAvail.SelectedList == null)
6609 list = listAvail.SelectedList;
6615 case MyCommon.TabUsageType.UserDefined:
6616 tab = new FilterTabModel(tabName);
6618 case MyCommon.TabUsageType.PublicSearch:
6619 tab = new PublicSearchTabModel(tabName);
6621 case MyCommon.TabUsageType.Lists:
6622 tab = new ListTimelineTabModel(tabName, list!);
6628 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6630 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6631 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6636 this.SaveConfigsTabs();
6638 var tabIndex = this.statuses.Tabs.Count - 1;
6640 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6642 this.ListTab.SelectedIndex = tabIndex;
6643 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6645 if (tabUsage == MyCommon.TabUsageType.Lists)
6647 this.ListTab.SelectedIndex = tabIndex;
6648 await this.RefreshTabAsync(this.CurrentTab);
6654 private void TabMenuItem_Click(object sender, EventArgs e)
6657 foreach (var post in this.CurrentTab.SelectedPosts)
6660 if (!this.SelectTab(out var tab))
6663 using (var fltDialog = new FilterDialog())
6665 fltDialog.Owner = this;
6666 fltDialog.SetCurrent(tab.TabName);
6668 if (post.RetweetedBy == null)
6670 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6674 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6676 fltDialog.ShowDialog(this);
6679 this.TopMost = this.settings.Common.AlwaysTop;
6682 this.ApplyPostFilters();
6683 this.SaveConfigsTabs();
6686 protected override bool ProcessDialogKey(Keys keyData)
6688 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6689 if ((keyData & Keys.KeyCode) == Keys.Enter)
6691 if (this.StatusText.Focused)
6693 var newLine = false;
6696 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6698 if (this.StatusText.Multiline)
6700 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6702 if ((keyData & Keys.Control) == Keys.Control) post = true;
6706 if ((keyData & Keys.Control) == Keys.Control) post = true;
6709 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6711 if (this.StatusText.Multiline)
6713 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6715 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6719 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6724 if (this.StatusText.Multiline)
6726 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6728 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6729 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6733 if (((keyData & Keys.Shift) == Keys.Shift) ||
6734 (((keyData & Keys.Control) != Keys.Control) &&
6735 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6741 var pos1 = this.StatusText.SelectionStart;
6742 if (this.StatusText.SelectionLength > 0)
6744 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6746 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6747 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6752 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6758 var tab = this.CurrentTab;
6759 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6761 var tabPage = this.CurrentTabPage;
6762 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6763 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6765 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6772 return base.ProcessDialogKey(keyData);
6775 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6776 => this.MakeReplyText(atAll: true);
6778 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6780 var tab = this.CurrentTab;
6781 var selectedPosts = tab.SelectedPosts;
6784 if (selectedPosts.Length == 0)
6787 var screenNameArray = selectedPosts
6788 .Select(x => x.RetweetedBy ?? x.ScreenName)
6791 this.AddFilterRuleByScreenName(screenNameArray);
6793 if (screenNameArray.Length != 0)
6795 var atids = new List<string>();
6796 foreach (var screenName in screenNameArray)
6798 atids.Add("@" + screenName);
6800 var cnt = this.AtIdSupl.ItemCount;
6801 this.AtIdSupl.AddRangeItem(atids.ToArray());
6802 if (this.AtIdSupl.ItemCount != cnt)
6803 this.MarkSettingAtIdModified();
6807 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6809 var tab = this.CurrentTab;
6810 var selectedPosts = tab.SelectedPosts;
6812 if (selectedPosts.Length == 0)
6815 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6817 this.AddFilterRuleBySource(sourceArray);
6820 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6823 if (!this.SelectTab(out var tab)) return;
6827 if (tab.TabType != MyCommon.TabUsageType.Mute)
6829 this.MoveOrCopy(out mv, out mk);
6833 // ミュートタブでは常に MoveMatches を true にする
6838 foreach (var screenName in screenNameArray)
6840 tab.AddFilter(new PostFilterRule
6842 FilterName = screenName,
6843 UseNameField = true,
6847 FilterByUrl = false,
6851 this.ApplyPostFilters();
6852 this.SaveConfigsTabs();
6855 public void AddFilterRuleBySource(params string[] sourceArray)
6857 // タブ選択ダイアログを表示(or追加)
6858 if (!this.SelectTab(out var filterTab))
6863 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6865 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6866 this.MoveOrCopy(out mv, out mk);
6870 // ミュートタブでは常に MoveMatches を true にする
6875 // 振り分けルールに追加するSource
6876 foreach (var source in sourceArray)
6878 filterTab.AddFilter(new PostFilterRule
6880 FilterSource = source,
6884 FilterByUrl = false,
6888 this.ApplyPostFilters();
6889 this.SaveConfigsTabs();
6892 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6899 using (var dialog = new TabsDialog(this.statuses))
6901 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6903 tab = dialog.SelectedTab;
6906 this.CurrentTabPage.Focus();
6911 using (var inputName = new InputTabName())
6913 inputName.TabName = this.statuses.MakeTabName("MyTab");
6914 inputName.ShowDialog();
6915 if (inputName.DialogResult == DialogResult.Cancel) return false;
6916 tabName = inputName.TabName;
6918 this.TopMost = this.settings.Common.AlwaysTop;
6919 if (!MyCommon.IsNullOrEmpty(tabName))
6921 var newTab = new FilterTabModel(tabName);
6922 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6924 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6925 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6944 private void MoveOrCopy(out bool move, out bool mark)
6948 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6949 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6957 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6958 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6969 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6972 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6973 => this.CopyIdUri();
6975 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6977 if (this.StatusText.Focused)
6980 this.StatusText.SelectAll();
6984 // ListView上でのCtrl+A
6985 NativeMethods.SelectAllItems(this.CurrentListView);
6989 private void MoveMiddle()
6995 var listView = this.CurrentListView;
6996 if (listView.SelectedIndices.Count == 0) return;
6998 var idx = listView.SelectedIndices[0];
7000 item = listView.GetItemAt(0, 25);
7006 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
7008 idx2 = listView.VirtualListSize - 1;
7012 idx -= Math.Abs(idx1 - idx2) / 2;
7013 if (idx < 0) idx = 0;
7015 listView.EnsureVisible(listView.VirtualListSize - 1);
7016 listView.EnsureVisible(idx);
7019 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
7021 var linkElements = this.tweetDetailsView.GetLinkElements();
7023 if (linkElements.Length == 0)
7026 var links = new List<OpenUrlItem>(linkElements.Length);
7028 foreach (var linkElm in linkElements)
7030 var displayUrl = linkElm.GetAttribute("title");
7031 var href = linkElm.GetAttribute("href");
7032 var linkedText = linkElm.InnerText;
7034 if (MyCommon.IsNullOrEmpty(displayUrl))
7037 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
7041 bool isReverseSettings;
7043 if (links.Count == 1)
7045 // ツイートに含まれる URL が 1 つのみの場合
7046 // => OpenURL ダイアログを表示せずにリンクを開く
7047 selectedUrl = links[0].Href;
7049 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
7050 isReverseSettings = false;
7054 // ツイートに含まれる URL が複数ある場合
7055 // => OpenURL を表示しユーザーが選択したリンクを開く
7056 this.urlDialog.ClearUrl();
7058 foreach (var link in links)
7059 this.urlDialog.AddUrl(link);
7061 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
7064 this.TopMost = this.settings.Common.AlwaysTop;
7066 selectedUrl = this.urlDialog.SelectedUrl;
7068 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
7069 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
7072 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
7075 private void ClearTabMenuItem_Click(object sender, EventArgs e)
7077 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
7078 this.ClearTab(this.rclickTabName, true);
7081 private void ClearTab(string tabName, bool showWarning)
7085 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
7086 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
7092 this.statuses.ClearTabIds(tabName);
7093 if (this.CurrentTabName == tabName)
7095 this.CurrentTab.ClearAnchor();
7096 this.listCache?.PurgeCache();
7097 this.listCache?.UpdateListSize();
7100 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
7101 var tabPage = this.ListTab.TabPages[tabIndex];
7102 tabPage.ImageIndex = -1;
7104 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
7106 this.SetMainWindowTitle();
7107 this.SetStatusLabelUrl();
7110 private static long followers = 0;
7112 private void SetMainWindowTitle()
7114 // メインウインドウタイトルの書き換え
7115 var ttl = new StringBuilder(256);
7118 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
7119 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
7120 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
7121 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
7123 foreach (var tab in this.statuses.Tabs)
7125 ur += tab.UnreadCount;
7130 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
7131 ttl.Append(ApplicationSettings.ApplicationName);
7133 switch (this.settings.Common.DispLatestPost)
7135 case MyCommon.DispTitleEnum.Ver:
7136 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
7138 case MyCommon.DispTitleEnum.Post:
7139 if (this.history != null && this.history.Count > 1)
7140 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
7142 case MyCommon.DispTitleEnum.UnreadRepCount:
7143 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
7145 case MyCommon.DispTitleEnum.UnreadAllCount:
7146 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
7148 case MyCommon.DispTitleEnum.UnreadAllRepCount:
7149 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
7151 case MyCommon.DispTitleEnum.UnreadCountAllCount:
7152 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
7154 case MyCommon.DispTitleEnum.OwnStatus:
7155 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
7156 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
7162 this.Text = ttl.ToString();
7164 catch (AccessViolationException)
7166 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
7170 private string GetStatusLabelText()
7173 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
7174 if (this.statuses == null) return "";
7175 var tbRep = this.statuses.MentionTab;
7176 var tbDm = this.statuses.DirectMessageTab;
7177 if (tbRep == null || tbDm == null) return "";
7178 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
7183 var slbl = new StringBuilder(256);
7186 foreach (var tab in this.statuses.Tabs)
7188 ur += tab.UnreadCount;
7190 if (tab.TabName == this.CurrentTabName)
7192 tur = tab.UnreadCount;
7202 this.unreadCounter = ur;
7203 this.unreadAtCounter = urat;
7205 var homeTab = this.statuses.HomeTab;
7207 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7208 if (this.settings.Common.TimelinePeriod == 0)
7210 slbl.Append(Properties.Resources.SetStatusLabelText2);
7214 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7216 return slbl.ToString();
7219 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7223 if (this.InvokeRequired && !this.IsDisposed)
7225 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7229 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7230 this.SetApiStatusLabel(endpointName);
7233 catch (ObjectDisposedException)
7237 catch (InvalidOperationException)
7243 private void SetApiStatusLabel(string? endpointName = null)
7245 var tabType = this.CurrentTab.TabType;
7247 if (endpointName == null)
7250 endpointName = tabType switch
7252 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
7253 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7254 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7255 MyCommon.TabUsageType.Favorites => "/favorites/list",
7256 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7257 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7258 MyCommon.TabUsageType.Lists => "/lists/statuses",
7259 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7260 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7263 this.toolStripApiGauge.ApiEndpoint = endpointName;
7267 // 表示中のタブに関連する endpoint であれば更新
7268 var update = endpointName switch
7270 "/statuses/home_timeline" => tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined,
7271 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7272 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7273 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7274 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7275 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7276 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7277 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7282 this.toolStripApiGauge.ApiEndpoint = endpointName;
7287 private void SetStatusLabelUrl()
7288 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7290 public void SetStatusLabel(string text)
7291 => this.StatusLabel.Text = text;
7293 private void SetNotifyIconText()
7295 var ur = new StringBuilder(64);
7297 // タスクトレイアイコンのツールチップテキスト書き換え
7299 ur.Remove(0, ur.Length);
7300 if (this.settings.Common.DispUsername)
7302 ur.Append(this.tw.Username);
7305 ur.Append(ApplicationSettings.ApplicationName);
7307 ur.Append("(Debug Build)");
7309 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7312 ur.Append(this.unreadCounter);
7314 ur.Append(this.unreadAtCounter);
7317 this.NotifyIcon1.Text = ur.ToString();
7320 internal void CheckReplyTo(string statusText)
7324 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7326 foreach (Match hm in m)
7328 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7330 hstr += "#" + hm.Result("$3") + " ";
7331 this.HashSupl.AddItem("#" + hm.Result("$3"));
7334 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7336 hstr += this.HashMgr.UseHash;
7338 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7340 // 本当にリプライ先指定すべきかどうかの判定
7341 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7343 if (this.settings.Common.UseAtIdSupplement)
7345 var bCnt = this.AtIdSupl.ItemCount;
7346 foreach (Match mid in m)
7348 this.AtIdSupl.AddItem(mid.Result("${id}"));
7350 if (bCnt != this.AtIdSupl.ItemCount)
7351 this.MarkSettingAtIdModified();
7354 // リプライ先ステータスIDの指定がない場合は指定しない
7355 if (this.inReplyTo == null)
7359 // 次の条件を満たす場合に in_reply_to_status_id 指定
7360 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7361 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7362 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7366 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7367 if (statusText.StartsWith("@", StringComparison.Ordinal))
7369 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7373 foreach (Match mid in m)
7375 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7380 this.inReplyTo = null;
7383 private void TweenMain_Resize(object sender, EventArgs e)
7385 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7387 this.Visible = false;
7389 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7391 // 現在の DPI と設定保存時の DPI との比を取得する
7392 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7394 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7397 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7398 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7399 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7401 this.SplitContainer1.SplitterDistance = splitterDistance;
7405 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7406 if (this.StatusText.Multiline)
7408 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7409 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7410 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7412 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7414 this.StatusText.Height = statusTextHeight;
7418 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7420 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7424 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7425 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7427 this.SplitContainer3.SplitterDistance = previewDistance;
7430 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7431 this.SplitContainer3.Panel2Collapsed = true;
7433 this.initialLayout = false;
7435 if (this.WindowState != FormWindowState.Minimized)
7437 this.formWindowState = this.WindowState;
7441 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7443 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7444 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7445 if (this.PlaySoundMenuItem.Checked)
7447 this.settings.Common.PlaySound = true;
7451 this.settings.Common.PlaySound = false;
7453 this.MarkSettingCommonModified();
7456 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7458 if (this.initialLayout)
7461 int splitterDistance;
7462 switch (this.WindowState)
7464 case FormWindowState.Normal:
7465 splitterDistance = this.SplitContainer1.SplitterDistance;
7467 case FormWindowState.Maximized:
7468 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7469 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7470 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7471 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7477 this.mySpDis = splitterDistance;
7478 this.MarkSettingLocalModified();
7481 private async Task DoRepliedStatusOpen()
7483 var currentPost = this.CurrentPost;
7484 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7486 if (MyCommon.IsKeyDown(Keys.Shift))
7488 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7491 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
7493 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7497 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7499 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
7500 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
7501 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7504 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7509 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7510 => await this.DoRepliedStatusOpen();
7512 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7514 if (this.initialLayout)
7515 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7517 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7518 if (multiline != this.StatusText.Multiline)
7520 this.StatusText.Multiline = multiline;
7521 this.settings.Local.StatusMultiline = multiline;
7522 this.MarkSettingLocalModified();
7526 private void StatusText_MultilineChanged(object sender, EventArgs e)
7528 if (this.StatusText.Multiline)
7529 this.StatusText.ScrollBars = ScrollBars.Vertical;
7531 this.StatusText.ScrollBars = ScrollBars.None;
7533 if (!this.initialLayout)
7534 this.MarkSettingLocalModified();
7537 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7540 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7541 this.StatusText.Multiline = menuItemChecked;
7542 this.settings.Local.StatusMultiline = menuItemChecked;
7543 if (menuItemChecked)
7545 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7546 this.SplitContainer2.SplitterDistance = 0;
7548 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7552 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7554 this.MarkSettingLocalModified();
7557 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7559 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7561 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7562 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7563 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7565 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7570 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7571 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7572 // Appendix A. Collected ABNF for URI
7573 // http://www.ietf.org/rfc/rfc3986.txt
7575 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7578 if (this.StatusText.SelectionLength > 0)
7580 var tmp = this.StatusText.SelectedText;
7581 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7582 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7584 // 文字列が選択されている場合はその文字列について処理
7586 // nico.ms使用、nicovideoにマッチしたら変換
7587 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7589 result = Nicoms.Shorten(tmp);
7591 else if (converterType != MyCommon.UrlConverter.Nicoms)
7596 var srcUri = new Uri(tmp);
7597 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7598 result = resultUri.AbsoluteUri;
7600 catch (WebApiException e)
7602 this.StatusLabel.Text = converterType + ":" + e.Message;
7605 catch (UriFormatException e)
7607 this.StatusLabel.Text = converterType + ":" + e.Message;
7616 if (!MyCommon.IsNullOrEmpty(result))
7618 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7619 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7620 if (origUrlIndex == -1)
7623 this.StatusText.Select(origUrlIndex, tmp.Length);
7624 this.StatusText.SelectedText = result;
7627 var undo = new UrlUndo
7633 if (this.urlUndoBuffer == null)
7635 this.urlUndoBuffer = new List<UrlUndo>();
7636 this.UrlUndoToolStripMenuItem.Enabled = true;
7639 this.urlUndoBuffer.Add(undo);
7645 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7646 @"(?<url>(?<protocol>https?://)" +
7647 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7648 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7649 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7650 // 正規表現にマッチしたURL文字列をtinyurl化
7651 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7653 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7655 var tmp = mt.Result("${url}");
7656 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7657 tmp = "http://" + tmp;
7660 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7662 // nico.ms使用、nicovideoにマッチしたら変換
7663 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7665 result = Nicoms.Shorten(tmp);
7667 else if (converterType != MyCommon.UrlConverter.Nicoms)
7672 var srcUri = new Uri(tmp);
7673 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7674 result = resultUri.AbsoluteUri;
7676 catch (HttpRequestException e)
7678 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7679 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7680 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7682 this.StatusLabel.Text = converterType + ":" + message;
7685 catch (WebApiException e)
7687 this.StatusLabel.Text = converterType + ":" + e.Message;
7690 catch (UriFormatException e)
7692 this.StatusLabel.Text = converterType + ":" + e.Message;
7701 if (!MyCommon.IsNullOrEmpty(result))
7703 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7704 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7705 if (origUrlIndex == -1)
7708 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7709 this.StatusText.SelectedText = result;
7711 var undo = new UrlUndo
7713 Before = mt.Result("${url}"),
7717 if (this.urlUndoBuffer == null)
7719 this.urlUndoBuffer = new List<UrlUndo>();
7720 this.UrlUndoToolStripMenuItem.Enabled = true;
7723 this.urlUndoBuffer.Add(undo);
7731 private void DoUrlUndo()
7733 if (this.urlUndoBuffer != null)
7735 var tmp = this.StatusText.Text;
7736 foreach (var data in this.urlUndoBuffer)
7738 tmp = tmp.Replace(data.After, data.Before);
7740 this.StatusText.Text = tmp;
7741 this.urlUndoBuffer = null;
7742 this.UrlUndoToolStripMenuItem.Enabled = false;
7743 this.StatusText.SelectionStart = 0;
7744 this.StatusText.SelectionLength = 0;
7748 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7749 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7751 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7752 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7754 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7755 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7757 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7759 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7761 var rnd = new Random();
7763 MyCommon.UrlConverter svc;
7764 // 前回使用した短縮URLサービス以外を選択する
7767 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7769 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7770 await this.UrlConvertAsync(svc);
7774 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7775 => this.DoUrlUndo();
7777 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7779 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7780 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7781 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7782 this.MarkSettingCommonModified();
7785 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7787 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7788 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7789 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7790 this.MarkSettingCommonModified();
7793 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7795 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7796 this.MenuStrip1.Tag = new object();
7797 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7800 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7802 var currentTabPage = this.CurrentTabPage;
7803 if (this.Tag != null) // 設定された戻り先へ遷移
7805 if (this.Tag == currentTabPage)
7806 ((Control)currentTabPage.Tag).Select();
7808 ((Control)this.Tag).Select();
7810 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7812 this.Tag = currentTabPage.Tag;
7813 ((Control)this.Tag).Select();
7815 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7816 this.MenuStrip1.Tag = null;
7819 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7821 if (this.Use2ColumnsMode)
7827 var lst = (DetailsListView)sender;
7828 var columnsCount = lst.Columns.Count;
7830 var darr = new int[columnsCount];
7831 for (var i = 0; i < columnsCount; i++)
7832 darr[lst.Columns[i].DisplayIndex] = i;
7834 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7836 for (var i = 0; i < columnsCount; i++)
7837 this.settings.Local.ColumnsOrder[darr[i]] = i;
7839 this.MarkSettingLocalModified();
7840 this.isColumnChanged = true;
7843 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7845 var lst = (DetailsListView)sender;
7846 if (this.settings.Local == null) return;
7848 var modified = false;
7849 if (this.Use2ColumnsMode)
7851 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7853 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7856 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7858 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7864 var columnsCount = lst.Columns.Count;
7865 for (var i = 0; i < columnsCount; i++)
7867 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7870 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7876 this.MarkSettingLocalModified();
7877 this.isColumnChanged = true;
7881 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7883 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7884 this.MarkSettingLocalModified();
7887 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7889 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7891 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7893 this.SelectMedia_DragDrop(e);
7896 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7898 var (url, title) = GetUrlFromDataObject(e.Data);
7904 appendText = title + " " + url;
7906 if (this.StatusText.TextLength == 0)
7907 this.StatusText.Text = appendText;
7909 this.StatusText.Text += " " + appendText;
7911 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7913 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7915 this.StatusText.Text += text;
7917 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7919 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7920 if (data != null) this.StatusText.Text += data;
7925 /// IDataObject から URL とタイトルの対を取得します
7928 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7930 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7931 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7932 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7934 if (data.GetDataPresent("text/x-moz-url"))
7936 // Firefox, Google Chrome で利用可能
7937 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7939 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7940 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7941 if (lines.Length < 2)
7942 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7944 return (lines[0], lines[1]);
7946 else if (data.GetDataPresent("IESiteModeToUrl"))
7948 // Internet Exproler 用
7949 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7951 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7952 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7953 if (lines.Length < 2)
7954 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7956 return (lines[0], lines[1]);
7958 else if (data.GetDataPresent("UniformResourceLocatorW"))
7962 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7963 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7967 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7970 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7972 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7974 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7976 this.SelectMedia_DragEnter(e);
7980 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7982 e.Effect = DragDropEffects.Copy;
7985 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7987 e.Effect = DragDropEffects.Copy;
7990 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7992 e.Effect = DragDropEffects.Copy;
7996 e.Effect = DragDropEffects.None;
7999 private void TweenMain_DragOver(object sender, DragEventArgs e)
8003 public bool IsNetworkAvailable()
8005 var nw = MyCommon.IsNetworkAvailable();
8006 this.myStatusOnline = nw;
8010 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
8012 var uriStr = uri.AbsoluteUri;
8014 // OpenTween 内部で使用する URL
8015 if (uri.Authority == "opentween")
8017 await this.OpenInternalUriAsync(uri);
8021 // ハッシュタグを含む Twitter 検索
8022 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
8025 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
8026 var pos = unescapedQuery.IndexOf('#');
8027 if (pos == -1) return;
8029 var hash = unescapedQuery.Substring(pos);
8030 this.HashSupl.AddItem(hash);
8031 this.HashMgr.AddHashToHistory(hash.Trim(), false);
8032 this.AddNewTabForSearch(hash);
8037 // フラグが立っている場合は設定と逆の動作をする
8038 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
8039 !this.settings.Common.OpenUserTimeline && isReverseSettings)
8041 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
8042 if (userUriMatch.Success)
8044 var screenName = userUriMatch.Groups["ScreenName"].Value;
8045 if (this.IsTwitterId(screenName))
8047 await this.AddNewTabForUserTimeline(screenName);
8054 await MyCommon.OpenInBrowserAsync(this, uriStr);
8058 /// OpenTween 内部の機能を呼び出すための URL を開きます
8060 private async Task OpenInternalUriAsync(Uri uri)
8062 // ツイートを開く (//opentween/status/:status_id)
8063 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
8066 var statusId = long.Parse(match.Groups[1].Value);
8067 await this.OpenRelatedTab(statusId);
8072 private void ListTabSelect(TabPage tabPage)
8074 this.SetListProperty();
8076 this.listCache?.PurgeCache();
8078 this.statuses.SelectTab(tabPage.Text);
8080 this.InitializeTimelineListView();
8082 var tab = this.CurrentTab;
8085 var listView = this.CurrentListView;
8086 listView.SelectItems(tab.SelectedIndices);
8088 if (this.Use2ColumnsMode)
8090 listView.Columns[1].Text = this.columnText[2];
8094 for (var i = 0; i < listView.Columns.Count; i++)
8096 listView.Columns[i].Text = this.columnText[i];
8101 private void InitializeTimelineListView()
8103 var listView = this.CurrentListView;
8104 var tab = this.CurrentTab;
8106 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
8107 (this.listCache, var oldCache) = (newCache, this.listCache);
8108 oldCache?.Dispose();
8110 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager)
8112 IconSize = this.settings.Common.IconSize,
8114 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
8115 oldDrawer?.Dispose();
8118 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
8119 => this.ListTabSelect(e.TabPage);
8121 private void SelectListItem(DetailsListView lView, int index)
8124 var bnd = new Rectangle();
8126 var item = lView.FocusedItem;
8135 lView.SelectedIndices.Clear();
8137 while (lView.SelectedIndices.Count > 0);
8138 item = lView.Items[index];
8139 item.Selected = true;
8140 item.Focused = true;
8142 if (flg) lView.Invalidate(bnd);
8145 private void SelectListItem(DetailsListView lView, int[]? index, int focusedIndex, int selectionMarkIndex)
8148 var bnd = new Rectangle();
8150 var item = lView.FocusedItem;
8159 lView.SelectItems(index);
8161 if (selectionMarkIndex > -1 && lView.VirtualListSize > selectionMarkIndex)
8163 lView.SelectionMark = selectionMarkIndex;
8165 if (focusedIndex > -1 && lView.VirtualListSize > focusedIndex)
8167 lView.Items[focusedIndex].Focused = true;
8169 else if (index != null && index.Length != 0)
8171 lView.Items[index.Last()].Focused = true;
8174 if (flg) lView.Invalidate(bnd);
8177 private async void TweenMain_Shown(object sender, EventArgs e)
8179 this.NotifyIcon1.Visible = true;
8181 if (this.IsNetworkAvailable())
8183 var loadTasks = new List<Task>
8185 this.RefreshMuteUserIdsAsync(),
8186 this.RefreshBlockIdsAsync(),
8187 this.RefreshNoRetweetIdsAsync(),
8188 this.RefreshTwitterConfigurationAsync(),
8189 this.RefreshTabAsync<HomeTabModel>(),
8190 this.RefreshTabAsync<MentionsTabModel>(),
8191 this.RefreshTabAsync<DirectMessagesTabModel>(),
8192 this.RefreshTabAsync<PublicSearchTabModel>(),
8193 this.RefreshTabAsync<UserTimelineTabModel>(),
8194 this.RefreshTabAsync<ListTimelineTabModel>(),
8197 if (this.settings.Common.StartupFollowers)
8198 loadTasks.Add(this.RefreshFollowerIdsAsync());
8200 if (this.settings.Common.GetFav)
8201 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
8203 var allTasks = Task.WhenAll(loadTasks);
8208 var timeout = Task.Delay(5000);
8209 if (await Task.WhenAny(allTasks, timeout) != timeout)
8213 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
8215 if (MyCommon.EndingFlag)
8219 if (MyCommon.EndingFlag) return;
8221 if (ApplicationSettings.VersionInfoUrl != null)
8223 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8224 if (this.settings.Common.StartupVersion)
8225 await this.CheckNewVersion(true);
8229 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8230 this.VerUpMenuItem.Enabled = false;
8231 this.VerUpMenuItem.Available = false;
8232 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8235 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8236 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8238 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8239 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8243 var reloadTasks = new List<Task>();
8245 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8246 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8248 if (!this.tw.GetNoRetweetSuccess)
8249 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8251 if (this.tw.Configuration.PhotoSizeLimit == 0)
8252 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8254 await Task.WhenAll(reloadTasks);
8257 this.initial = false;
8259 this.timelineScheduler.Enabled = true;
8262 private async Task DoGetFollowersMenu()
8264 await this.RefreshFollowerIdsAsync();
8265 this.DispSelectedPost(true);
8268 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8269 => await this.DoGetFollowersMenu();
8271 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8272 => this.DoReTweetUnofficial();
8274 private async Task DoReTweetOfficial(bool isConfirm)
8277 if (this.ExistCurrentPost)
8279 var selectedPosts = this.CurrentTab.SelectedPosts;
8281 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8283 if (selectedPosts.Any(x => x.IsProtect))
8284 MessageBox.Show("Protected.");
8286 this.doFavRetweetFlags = false;
8290 if (selectedPosts.Length > 15)
8292 MessageBox.Show(Properties.Resources.RetweetLimitText);
8293 this.doFavRetweetFlags = false;
8296 else if (selectedPosts.Length > 1)
8298 var questionText = Properties.Resources.RetweetQuestion2;
8299 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8300 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8302 case DialogResult.Cancel:
8303 case DialogResult.No:
8304 this.doFavRetweetFlags = false;
8310 if (!this.settings.Common.RetweetNoConfirm)
8312 var questiontext = Properties.Resources.RetweetQuestion1;
8313 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8314 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8316 this.doFavRetweetFlags = false;
8322 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8324 await this.RetweetAsync(statusIds);
8328 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8329 => await this.DoReTweetOfficial(true);
8331 private async Task FavoritesRetweetOfficial()
8333 if (!this.ExistCurrentPost) return;
8334 this.doFavRetweetFlags = true;
8335 var retweetTask = this.DoReTweetOfficial(true);
8336 if (this.doFavRetweetFlags)
8338 this.doFavRetweetFlags = false;
8339 var favoriteTask = this.FavoriteChange(true, false);
8341 await Task.WhenAll(retweetTask, favoriteTask);
8349 private async Task FavoritesRetweetUnofficial()
8351 var post = this.CurrentPost;
8352 if (this.ExistCurrentPost && post != null && !post.IsDm)
8354 this.doFavRetweetFlags = true;
8355 var favoriteTask = this.FavoriteChange(true);
8356 if (!post.IsProtect && this.doFavRetweetFlags)
8358 this.doFavRetweetFlags = false;
8359 this.DoReTweetUnofficial();
8367 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8369 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8370 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8371 /// <returns>復元されたツイート本文</returns>
8372 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8374 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8377 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
8379 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8381 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8383 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
8387 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8389 statusHtml = statusHtml.Replace("<br>", " ");
8391 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8392 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8393 statusHtml = statusHtml.Replace(" ", " ");
8395 return WebUtility.HtmlDecode(statusHtml);
8398 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8400 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8402 if (this.CurrentPost != null)
8403 this.DispSelectedPost(true);
8406 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8408 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8409 this.DebugModeToolStripMenuItem.Visible = true;
8411 this.DebugModeToolStripMenuItem.Visible = false;
8414 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8415 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8417 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8418 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8420 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8421 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8423 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8425 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8426 this.MarkSettingCommonModified();
8429 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8431 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8432 this.MarkSettingCommonModified();
8435 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8437 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8438 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8439 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8440 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8441 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8442 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8445 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8447 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8448 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8449 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8450 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8451 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8452 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8455 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8457 if (this.TraceOutToolStripMenuItem.Checked)
8458 MyCommon.TraceFlag = true;
8460 MyCommon.TraceFlag = false;
8463 private void TweenMain_Deactivate(object sender, EventArgs e)
8464 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8466 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8468 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8470 _ = this.TabRename(this.rclickTabName, out _);
8473 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8474 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8476 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8477 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8479 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8481 TwitterApiStatus? apiStatus;
8483 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8485 var cancellationToken = dialog.EnableCancellation();
8489 var task = this.tw.GetInfoApi();
8490 apiStatus = await dialog.WaitForAsync(this, task);
8492 catch (WebApiException)
8497 if (cancellationToken.IsCancellationRequested)
8500 if (apiStatus == null)
8502 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8507 using var apiDlg = new ApiInfoDialog();
8508 apiDlg.ShowDialog(this);
8511 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8513 var id = this.CurrentPost?.ScreenName ?? "";
8515 await this.FollowCommand(id);
8518 internal async Task FollowCommand(string id)
8520 using (var inputName = new InputTabName())
8522 inputName.FormTitle = "Follow";
8523 inputName.FormDescription = Properties.Resources.FRMessage1;
8524 inputName.TabName = id;
8526 if (inputName.ShowDialog(this) != DialogResult.OK)
8528 if (string.IsNullOrWhiteSpace(inputName.TabName))
8531 id = inputName.TabName.Trim();
8534 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8538 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8539 await dialog.WaitForAsync(this, task);
8541 catch (WebApiException ex)
8543 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8548 MessageBox.Show(Properties.Resources.FRMessage3);
8551 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8553 var id = this.CurrentPost?.ScreenName ?? "";
8555 await this.RemoveCommand(id, false);
8558 internal async Task RemoveCommand(string id, bool skipInput)
8562 using var inputName = new InputTabName();
8563 inputName.FormTitle = "Unfollow";
8564 inputName.FormDescription = Properties.Resources.FRMessage1;
8565 inputName.TabName = id;
8567 if (inputName.ShowDialog(this) != DialogResult.OK)
8569 if (string.IsNullOrWhiteSpace(inputName.TabName))
8572 id = inputName.TabName.Trim();
8575 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8579 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8580 await dialog.WaitForAsync(this, task);
8582 catch (WebApiException ex)
8584 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8589 MessageBox.Show(Properties.Resources.FRMessage3);
8592 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8594 var id = this.CurrentPost?.ScreenName ?? "";
8596 await this.ShowFriendship(id);
8599 internal async Task ShowFriendship(string id)
8601 using (var inputName = new InputTabName())
8603 inputName.FormTitle = "Show Friendships";
8604 inputName.FormDescription = Properties.Resources.FRMessage1;
8605 inputName.TabName = id;
8607 if (inputName.ShowDialog(this) != DialogResult.OK)
8609 if (string.IsNullOrWhiteSpace(inputName.TabName))
8612 id = inputName.TabName.Trim();
8615 bool isFollowing, isFollowed;
8617 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8619 var cancellationToken = dialog.EnableCancellation();
8623 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8624 var friendship = await dialog.WaitForAsync(this, task);
8626 isFollowing = friendship.Relationship.Source.Following;
8627 isFollowed = friendship.Relationship.Source.FollowedBy;
8629 catch (WebApiException ex)
8631 if (!cancellationToken.IsCancellationRequested)
8632 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8636 if (cancellationToken.IsCancellationRequested)
8643 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8647 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8651 result += Properties.Resources.GetFriendshipInfo3;
8655 result += Properties.Resources.GetFriendshipInfo4;
8657 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8658 MessageBox.Show(result);
8661 internal async Task ShowFriendship(string[] ids)
8663 foreach (var id in ids)
8665 bool isFollowing, isFollowed;
8667 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8669 var cancellationToken = dialog.EnableCancellation();
8673 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8674 var friendship = await dialog.WaitForAsync(this, task);
8676 isFollowing = friendship.Relationship.Source.Following;
8677 isFollowed = friendship.Relationship.Source.FollowedBy;
8679 catch (WebApiException ex)
8681 if (!cancellationToken.IsCancellationRequested)
8682 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8686 if (cancellationToken.IsCancellationRequested)
8696 ff += Properties.Resources.GetFriendshipInfo1;
8700 ff += Properties.Resources.GetFriendshipInfo2;
8703 ff += System.Environment.NewLine + " ";
8706 ff += Properties.Resources.GetFriendshipInfo3;
8710 ff += Properties.Resources.GetFriendshipInfo4;
8712 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8715 if (MessageBox.Show(
8716 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8717 Properties.Resources.GetFriendshipInfo8,
8718 MessageBoxButtons.YesNo,
8719 MessageBoxIcon.Question,
8720 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8722 await this.RemoveCommand(id, true);
8727 MessageBox.Show(result);
8732 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8733 => await this.DoShowUserStatus(this.tw.Username, false);
8735 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8738 public bool IsTwitterId(string name)
8740 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8741 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8743 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8746 private void DoQuoteOfficial()
8748 var post = this.CurrentPost;
8749 if (this.ExistCurrentPost && post != null)
8751 if (post.IsDm || !this.StatusText.Enabled)
8756 MessageBox.Show("Protected.");
8760 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8762 this.inReplyTo = null;
8764 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8766 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8767 this.StatusText.Focus();
8771 private void DoReTweetUnofficial()
8774 var post = this.CurrentPost;
8775 if (this.ExistCurrentPost && post != null)
8777 if (post.IsDm || !this.StatusText.Enabled)
8782 MessageBox.Show("Protected.");
8785 var rtdata = post.Text;
8786 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8788 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8790 // 投稿時に in_reply_to_status_id を付加する
8791 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8792 var inReplyToScreenName = post.ScreenName;
8793 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8795 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8797 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8798 this.StatusText.Focus();
8802 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8803 => this.DoQuoteOfficial();
8805 private async void SearchButton_Click(object sender, EventArgs e)
8808 var pnl = ((Control)sender).Parent;
8809 if (pnl == null) return;
8810 var tbName = pnl.Parent.Text;
8811 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8812 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8813 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8814 cmb.Text = cmb.Text.Trim();
8815 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8817 var buf = new StringBuilder();
8818 var c = cmb.Text.ToCharArray();
8819 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8821 if (cnt > cmb.Text.Length - 4)
8823 buf.Append(cmb.Text.Substring(cnt));
8832 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8841 cmb.Text = buf.ToString();
8843 var listView = (DetailsListView)pnl.Parent.Tag;
8845 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8847 tb.SearchWords = cmb.Text;
8848 tb.SearchLang = cmbLang.Text;
8849 if (MyCommon.IsNullOrEmpty(cmb.Text))
8852 this.SaveConfigsTabs();
8857 var idx = cmb.Items.IndexOf(tb.SearchWords);
8858 if (idx > -1) cmb.Items.RemoveAt(idx);
8859 cmb.Items.Insert(0, tb.SearchWords);
8860 cmb.Text = tb.SearchWords;
8862 this.statuses.ClearTabIds(tbName);
8863 this.listCache?.PurgeCache();
8864 this.listCache?.UpdateListSize();
8865 this.SaveConfigsTabs(); // 検索条件の保存
8869 await this.RefreshTabAsync(tb);
8872 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8873 => await this.DoRefreshMore(); // もっと前を取得
8876 /// 指定されたタブのListTabにおける位置を返します
8879 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8881 public int GetTabPageIndex(string tabName)
8882 => this.statuses.Tabs.IndexOf(tabName);
8884 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8886 if (this.statuses.RemovedTab.Count == 0)
8888 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
8893 var tb = this.statuses.RemovedTab.Pop();
8894 if (tb.TabType == MyCommon.TabUsageType.Related)
8896 var relatedTab = this.statuses.GetTabByType(MyCommon.TabUsageType.Related);
8897 if (relatedTab != null)
8899 // 関連発言なら既存のタブを置き換える
8900 tb.TabName = relatedTab.TabName;
8901 this.ClearTab(tb.TabName, false);
8903 this.statuses.ReplaceTab(tb);
8905 var tabIndex = this.statuses.Tabs.IndexOf(tb);
8906 this.ListTab.SelectedIndex = tabIndex;
8910 const string TabName = "Related Tweets";
8911 var renamed = TabName;
8912 for (var i = 2; i <= 100; i++)
8914 if (!this.statuses.ContainsTab(renamed))
8916 renamed = TabName + i;
8918 tb.TabName = renamed;
8920 this.statuses.AddTab(tb);
8921 this.AddNewTab(tb, startup: false);
8923 var tabIndex = this.statuses.Tabs.Count - 1;
8924 this.ListTab.SelectedIndex = tabIndex;
8929 var renamed = tb.TabName;
8930 for (var i = 1; i < int.MaxValue; i++)
8932 if (!this.statuses.ContainsTab(renamed))
8934 renamed = tb.TabName + "(" + i + ")";
8936 tb.TabName = renamed;
8938 this.statuses.AddTab(tb);
8939 this.AddNewTab(tb, startup: false);
8941 var tabIndex = this.statuses.Tabs.Count - 1;
8942 this.ListTab.SelectedIndex = tabIndex;
8944 this.SaveConfigsTabs();
8948 private async Task DoMoveToRTHome()
8950 var post = this.CurrentPost;
8951 if (post != null && post.RetweetedId != null)
8952 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8955 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8956 => await this.DoMoveToRTHome();
8958 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8960 var screenName = this.CurrentPost?.ScreenName;
8961 if (screenName != null)
8962 this.ListManageUserContext(screenName);
8965 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8967 var screenName = this.CurrentPost?.RetweetedBy;
8968 if (screenName != null)
8969 this.ListManageUserContext(screenName);
8972 public void ListManageUserContext(string screenName)
8974 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8975 listSelectForm.ShowDialog(this);
8978 private void SearchControls_Enter(object sender, EventArgs e)
8980 var pnl = (Control)sender;
8981 foreach (Control ctl in pnl.Controls)
8987 private void SearchControls_Leave(object sender, EventArgs e)
8989 var pnl = (Control)sender;
8990 foreach (Control ctl in pnl.Controls)
8992 ctl.TabStop = false;
8996 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8998 var tab = this.CurrentTab;
8999 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
9000 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
9003 private void StatusLabel_DoubleClick(object sender, EventArgs e)
9004 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
9006 private void HashManageMenuItem_Click(object sender, EventArgs e)
9011 rslt = this.HashMgr.ShowDialog();
9017 this.TopMost = this.settings.Common.AlwaysTop;
9018 if (rslt == DialogResult.Cancel) return;
9019 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
9021 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
9022 this.HashTogglePullDownMenuItem.Checked = true;
9023 this.HashToggleMenuItem.Checked = true;
9027 this.HashStripSplitButton.Text = "#[-]";
9028 this.HashTogglePullDownMenuItem.Checked = false;
9029 this.HashToggleMenuItem.Checked = false;
9032 this.MarkSettingCommonModified();
9033 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9036 private void HashToggleMenuItem_Click(object sender, EventArgs e)
9038 this.HashMgr.ToggleHash();
9039 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
9041 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
9042 this.HashToggleMenuItem.Checked = true;
9043 this.HashTogglePullDownMenuItem.Checked = true;
9047 this.HashStripSplitButton.Text = "#[-]";
9048 this.HashToggleMenuItem.Checked = false;
9049 this.HashTogglePullDownMenuItem.Checked = false;
9051 this.MarkSettingCommonModified();
9052 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9055 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
9056 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
9058 public void SetPermanentHashtag(string hashtag)
9060 this.HashMgr.SetPermanentHash("#" + hashtag);
9061 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
9062 this.HashTogglePullDownMenuItem.Checked = true;
9063 this.HashToggleMenuItem.Checked = true;
9065 this.MarkSettingCommonModified();
9068 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
9070 var tab = this.CurrentTab;
9071 var post = this.CurrentPost;
9072 if (!this.ExistCurrentPost)
9074 this.ReplyOpMenuItem.Enabled = false;
9075 this.ReplyAllOpMenuItem.Enabled = false;
9076 this.DmOpMenuItem.Enabled = false;
9077 this.CreateTabRuleOpMenuItem.Enabled = false;
9078 this.CreateIdRuleOpMenuItem.Enabled = false;
9079 this.CreateSourceRuleOpMenuItem.Enabled = false;
9080 this.ReadOpMenuItem.Enabled = false;
9081 this.UnreadOpMenuItem.Enabled = false;
9082 this.AuthorMenuItem.Visible = false;
9083 this.RetweetedByMenuItem.Visible = false;
9087 this.ReplyOpMenuItem.Enabled = true;
9088 this.ReplyAllOpMenuItem.Enabled = true;
9089 this.DmOpMenuItem.Enabled = true;
9090 this.CreateTabRuleOpMenuItem.Enabled = true;
9091 this.CreateIdRuleOpMenuItem.Enabled = true;
9092 this.CreateSourceRuleOpMenuItem.Enabled = true;
9093 this.ReadOpMenuItem.Enabled = true;
9094 this.UnreadOpMenuItem.Enabled = true;
9095 this.AuthorMenuItem.Visible = true;
9096 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
9097 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
9098 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
9101 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
9103 this.FavOpMenuItem.Enabled = false;
9104 this.UnFavOpMenuItem.Enabled = false;
9105 this.OpenStatusOpMenuItem.Enabled = false;
9106 this.ShowRelatedStatusesMenuItem2.Enabled = false;
9107 this.RtOpMenuItem.Enabled = false;
9108 this.RtUnOpMenuItem.Enabled = false;
9109 this.QtOpMenuItem.Enabled = false;
9110 this.FavoriteRetweetMenuItem.Enabled = false;
9111 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
9115 this.FavOpMenuItem.Enabled = true;
9116 this.UnFavOpMenuItem.Enabled = true;
9117 this.OpenStatusOpMenuItem.Enabled = true;
9118 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
9120 if (!post.CanRetweetBy(this.tw.UserId))
9122 this.RtOpMenuItem.Enabled = false;
9123 this.RtUnOpMenuItem.Enabled = false;
9124 this.QtOpMenuItem.Enabled = false;
9125 this.FavoriteRetweetMenuItem.Enabled = false;
9126 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
9130 this.RtOpMenuItem.Enabled = true;
9131 this.RtUnOpMenuItem.Enabled = true;
9132 this.QtOpMenuItem.Enabled = true;
9133 this.FavoriteRetweetMenuItem.Enabled = true;
9134 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
9138 if (tab.TabType != MyCommon.TabUsageType.Favorites)
9140 this.RefreshPrevOpMenuItem.Enabled = true;
9144 this.RefreshPrevOpMenuItem.Enabled = false;
9146 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
9148 this.OpenRepSourceOpMenuItem.Enabled = false;
9152 this.OpenRepSourceOpMenuItem.Enabled = true;
9155 if (this.ExistCurrentPost && post != null)
9157 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
9161 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
9162 => this.ContextMenuTabProperty_Opening(sender, null!);
9164 public Twitter TwitterInstance
9167 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
9169 if (this.initialLayout)
9172 int splitterDistance;
9173 switch (this.WindowState)
9175 case FormWindowState.Normal:
9176 splitterDistance = this.SplitContainer3.SplitterDistance;
9178 case FormWindowState.Maximized:
9179 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9180 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
9181 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
9182 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
9188 this.mySpDis3 = splitterDistance;
9189 this.MarkSettingLocalModified();
9192 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
9194 if (this.statuses.RemovedTab.Count == 0)
9196 this.UndoRemoveTabMenuItem.Enabled = false;
9200 this.UndoRemoveTabMenuItem.Enabled = true;
9203 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
9204 this.PublicSearchQueryMenuItem.Enabled = true;
9206 this.PublicSearchQueryMenuItem.Enabled = false;
9208 var post = this.CurrentPost;
9209 if (!this.ExistCurrentPost || post == null)
9211 this.CopySTOTMenuItem.Enabled = false;
9212 this.CopyURLMenuItem.Enabled = false;
9213 this.CopyUserIdStripMenuItem.Enabled = false;
9217 this.CopySTOTMenuItem.Enabled = true;
9218 this.CopyURLMenuItem.Enabled = true;
9219 this.CopyUserIdStripMenuItem.Enabled = true;
9221 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
9222 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
9226 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
9227 => this.SetNotifyIconText();
9229 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
9230 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
9232 private async Task DoShowUserStatus(string id, bool showInputDialog)
9234 TwitterUser? user = null;
9236 if (showInputDialog)
9238 using var inputName = new InputTabName();
9239 inputName.FormTitle = "Show UserStatus";
9240 inputName.FormDescription = Properties.Resources.FRMessage1;
9241 inputName.TabName = id;
9243 if (inputName.ShowDialog(this) != DialogResult.OK)
9245 if (string.IsNullOrWhiteSpace(inputName.TabName))
9248 id = inputName.TabName.Trim();
9251 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9253 var cancellationToken = dialog.EnableCancellation();
9257 var task = this.tw.Api.UsersShow(id);
9258 user = await dialog.WaitForAsync(this, task);
9260 catch (WebApiException ex)
9262 if (!cancellationToken.IsCancellationRequested)
9263 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9267 if (cancellationToken.IsCancellationRequested)
9271 await this.DoShowUserStatus(user);
9274 private async Task DoShowUserStatus(TwitterUser user)
9276 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9277 var showUserTask = userDialog.ShowUserAsync(user);
9278 userDialog.ShowDialog(this);
9281 this.BringToFront();
9283 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9287 internal Task ShowUserStatus(string id, bool showInputDialog)
9288 => this.DoShowUserStatus(id, showInputDialog);
9290 internal Task ShowUserStatus(string id)
9291 => this.DoShowUserStatus(id, true);
9293 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9295 var post = this.CurrentPost;
9298 await this.ShowUserStatus(post.ScreenName, false);
9302 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9304 var retweetedBy = this.CurrentPost?.RetweetedBy;
9305 if (retweetedBy != null)
9307 await this.ShowUserStatus(retweetedBy, false);
9311 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9313 var post = this.CurrentPost;
9314 if (!this.ExistCurrentPost || post == null)
9317 var statusId = post.RetweetedId ?? post.StatusId;
9318 TwitterStatus status;
9320 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9322 var cancellationToken = dialog.EnableCancellation();
9326 var task = this.tw.Api.StatusesShow(statusId);
9327 status = await dialog.WaitForAsync(this, task);
9329 catch (WebApiException ex)
9331 if (!cancellationToken.IsCancellationRequested)
9332 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9336 if (cancellationToken.IsCancellationRequested)
9340 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9343 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9345 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9348 this.Visible = false;
9350 else if (Form.ActiveForm == null)
9352 this.Visible = true;
9353 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9355 this.BringToFront();
9356 this.StatusText.Focus();
9360 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9361 => this.MultiLinePullDownMenuItem.PerformClick();
9364 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9366 if (this.ImageSelector.Visible)
9367 this.ImageSelector.EndSelection();
9369 this.ImageSelector.BeginSelection();
9372 private void SelectMedia_DragEnter(DragEventArgs e)
9374 if (this.ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9376 e.Effect = DragDropEffects.Copy;
9379 e.Effect = DragDropEffects.None;
9382 private void SelectMedia_DragDrop(DragEventArgs e)
9385 this.BringToFront();
9386 this.ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
9387 this.StatusText.Focus();
9390 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9392 this.TimelinePanel.Visible = false;
9393 this.TimelinePanel.Enabled = false;
9396 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9398 this.TimelinePanel.Visible = true;
9399 this.TimelinePanel.Enabled = true;
9400 this.CurrentListView.Focus();
9403 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9404 => this.AllowDrop = false;
9406 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9407 => this.AllowDrop = true;
9409 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9411 if (this.ImageSelector.Visible)
9413 this.MarkSettingCommonModified();
9414 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9418 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9419 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9422 /// StatusTextでCtrl+Vが押下された時の処理
9424 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9428 if (Clipboard.ContainsText())
9430 // clipboardにテキストがある場合は貼り付け処理
9431 this.StatusText.Paste(Clipboard.GetText());
9433 else if (Clipboard.ContainsImage())
9436 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
9437 Properties.Resources.PostPictureWarn4,
9438 MessageBoxButtons.OKCancel,
9439 MessageBoxIcon.Question,
9440 MessageBoxDefaultButton.Button2)
9444 using var image = Clipboard.GetImage();
9445 this.ImageSelector.BeginSelection(image);
9448 else if (Clipboard.ContainsFileDropList())
9450 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9451 this.ImageSelector.BeginSelection(files);
9454 catch (ExternalException ex)
9456 MessageBox.Show(ex.Message);
9461 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9463 using var form = new ListManage(this.tw);
9464 form.ShowDialog(this);
9467 private bool ModifySettingCommon { get; set; }
9469 private bool ModifySettingLocal { get; set; }
9471 private bool ModifySettingAtId { get; set; }
9473 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9475 var post = this.CurrentPost;
9476 if (this.ExistCurrentPost && post != null && !post.IsDm)
9477 this.RtCountMenuItem.Enabled = true;
9479 this.RtCountMenuItem.Enabled = false;
9482 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9483 => this.CopyUserId();
9485 private void CopyUserId()
9487 var post = this.CurrentPost;
9488 if (post == null) return;
9489 var clstr = post.ScreenName;
9492 Clipboard.SetDataObject(clstr, false, 5, 100);
9494 catch (Exception ex)
9496 MessageBox.Show(ex.Message);
9500 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9502 var post = this.CurrentPost;
9503 if (this.ExistCurrentPost && post != null && !post.IsDm)
9507 await this.OpenRelatedTab(post);
9509 catch (TabException ex)
9511 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9517 /// 指定されたツイートに対する関連発言タブを開きます
9519 /// <param name="statusId">表示するツイートのID</param>
9520 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9521 public async Task OpenRelatedTab(long statusId)
9523 var post = this.statuses[statusId];
9528 post = await this.tw.GetStatusApi(false, statusId);
9530 catch (WebApiException ex)
9532 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9537 await this.OpenRelatedTab(post);
9541 /// 指定されたツイートに対する関連発言タブを開きます
9543 /// <param name="post">表示する対象となるツイート</param>
9544 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9545 private async Task OpenRelatedTab(PostClass post)
9547 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9548 if (tabRelated != null)
9550 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9553 var tabName = this.statuses.MakeTabName("Related Tweets");
9555 tabRelated = new RelatedPostsTabModel(tabName, post)
9557 UnreadManage = false,
9561 this.statuses.AddTab(tabRelated);
9562 this.AddNewTab(tabRelated, startup: false);
9564 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9566 await this.RefreshTabAsync(tabRelated);
9568 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9572 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9574 var tabPage = this.ListTab.TabPages[tabIndex];
9575 var listView = (DetailsListView)tabPage.Tag;
9576 var targetPost = tabRelated.TargetPost;
9577 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9579 if (index != -1 && index < listView.Items.Count)
9581 listView.SelectedIndices.Add(index);
9582 listView.Items[index].Focused = true;
9587 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9589 var buf = new StringBuilder();
9590 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9591 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9592 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9595 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9597 MyCommon.EndingFlag = true;
9601 Application.Restart();
9605 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9609 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9610 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9612 private bool ExistCurrentPost
9616 var post = this.CurrentPost;
9617 return post != null && !post.IsDeleted;
9621 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9622 => await this.ShowUserTimeline();
9624 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9625 => await this.ShowRetweeterTimeline();
9627 private string GetUserIdFromCurPostOrInput(string caption)
9629 var id = this.CurrentPost?.ScreenName ?? "";
9631 using var inputName = new InputTabName();
9632 inputName.FormTitle = caption;
9633 inputName.FormDescription = Properties.Resources.FRMessage1;
9634 inputName.TabName = id;
9636 if (inputName.ShowDialog() == DialogResult.OK &&
9637 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9639 id = inputName.TabName.Trim();
9648 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9650 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9651 if (!MyCommon.IsNullOrEmpty(id))
9653 await this.AddNewTabForUserTimeline(id);
9657 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9659 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9660 this.timelineScheduler.SystemResumed();
9663 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9665 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9667 TimeZoneInfo.ClearCachedData();
9669 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9671 if (curTimeOffset != prevTimeOffset)
9674 this.listCache?.PurgeCache();
9675 this.CurrentListView.Refresh();
9677 this.DispSelectedPost(forceupdate: true);
9680 this.timelineScheduler.Reset();
9683 private void TimelineRefreshEnableChange(bool isEnable)
9685 this.timelineScheduler.Enabled = isEnable;
9688 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9689 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9691 private async Task OpenUserAppointUrl()
9693 if (this.settings.Common.UserAppointUrl != null)
9695 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9697 var post = this.CurrentPost;
9700 var xUrl = this.settings.Common.UserAppointUrl;
9701 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9703 var statusId = post.RetweetedId ?? post.StatusId;
9704 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
9706 await MyCommon.OpenInBrowserAsync(this, xUrl);
9711 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9716 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9717 => await this.OpenUserAppointUrl();
9719 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9721 if (Form.ActiveForm == null)
9723 await this.InvokeAsync(() =>
9725 this.Visible = true;
9726 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9728 this.BringToFront();
9729 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9731 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
9735 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
9741 private void ReplaceAppName()
9743 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9744 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9747 private void TweetThumbnail_ThumbnailLoading(object sender, EventArgs e)
9748 => this.SplitContainer3.Panel2Collapsed = false;
9750 private async void TweetThumbnail_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
9751 => await this.OpenThumbnailPicture(e.Thumbnail);
9753 private async void TweetThumbnail_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
9754 => await MyCommon.OpenInBrowserAsync(this, e.ImageUrl);
9756 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
9758 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
9760 await MyCommon.OpenInBrowserAsync(this, url);
9763 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9764 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9766 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9768 if (e.KeyCode == Keys.Space)
9770 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9772 e.SuppressKeyPress = true;
9776 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9778 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9779 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9780 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9781 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9782 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9784 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9787 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9788 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9790 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9791 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9793 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9794 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9796 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9797 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9799 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9800 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9802 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9804 if (this.settings.Common.IconSize == iconSize) return;
9806 var oldIconCol = this.Use2ColumnsMode;
9808 this.settings.Common.IconSize = iconSize;
9809 this.ApplyListViewIconSize(iconSize);
9811 if (this.Use2ColumnsMode != oldIconCol)
9813 foreach (TabPage tp in this.ListTab.TabPages)
9815 this.ResetColumns((DetailsListView)tp.Tag);
9819 this.CurrentListView.Refresh();
9820 this.MarkSettingCommonModified();
9823 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9825 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9826 if (this.settings.Common.SortOrderLock == state) return;
9828 this.settings.Common.SortOrderLock = state;
9829 this.MarkSettingCommonModified();
9832 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9834 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9836 this.StatusLabelUrl.Text = e.StatusText;
9840 this.SetStatusLabelUrl();