1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.Thumbnail;
66 public partial class TweenMain : OTBaseForm
70 /// <summary>画面サイズ</summary>
73 /// <summary>画面位置</summary>
76 /// <summary>区切り位置</summary>
79 /// <summary>発言欄区切り位置</summary>
82 /// <summary>プレビュー区切り位置</summary>
86 private bool initial; // true:起動時処理中
87 private bool initialLayout = true;
88 private bool ignoreConfigSave; // true:起動時処理中
90 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
93 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
94 private Point tabMouseDownPoint;
96 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
97 private string? rclickTabName;
99 private readonly object syncObject = new(); // ロック用
101 private const string DetailHtmlFormatHead =
102 """<head><meta http-equiv="X-UA-Compatible" content="IE=8">"""
103 + """<style type="text/css"><!-- """
104 + "body, p, pre {margin: 0;} "
105 + """body {font-family: "%FONT_FAMILY%", "Segoe UI Emoji", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} """
106 + "pre {font-family: inherit;} "
107 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
108 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
109 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
110 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
111 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
115 private const string DetailHtmlFormatTemplateMono =
116 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
118 private const string DetailHtmlFormatTemplateNormal =
119 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
121 private string detailHtmlFormatPreparedTemplate = null!;
123 private bool myStatusError = false;
124 private bool myStatusOnline = false;
125 private bool soundfileListup = false;
126 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
129 private readonly SettingManager settings;
132 private readonly Twitter tw;
135 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
139 /// <summary>検索画面インスタンス</summary>
140 internal SearchWordDialog SearchDialog = new();
142 private readonly OpenURL urlDialog = new();
144 /// <summary>@id補助</summary>
145 public AtIdSupplement AtIdSupl = null!;
147 /// <summary>Hashtag補助</summary>
148 public AtIdSupplement HashSupl = null!;
150 public HashtagManage HashMgr = null!;
153 private ThemeManager themeManager;
155 /// <summary>アイコン画像リスト</summary>
156 private readonly ImageCache iconCache;
158 private readonly IconAssetsManager iconAssets;
160 private readonly ThumbnailGenerator thumbGenerator;
162 /// <summary>発言履歴</summary>
163 private readonly List<StatusTextHistory> history = new();
165 /// <summary>発言履歴カレントインデックス</summary>
168 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
170 /// <summary>リプライ先のステータスID・スクリーン名</summary>
171 private (PostId StatusId, string ScreenName)? inReplyTo = null;
174 private readonly List<DateTimeUtc> postTimestamps = new();
175 private readonly List<DateTimeUtc> favTimestamps = new();
178 private readonly StringFormat sfTab = new();
180 //////////////////////////////////////////////////////////////////////////////////////////////////////////
182 /// <summary>発言保持クラス</summary>
183 private readonly TabInformations statuses;
185 private TimelineListViewCache? listCache;
186 private TimelineListViewDrawer? listDrawer;
187 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
189 private bool isColumnChanged = false;
191 private const int MaxWorderThreads = 20;
192 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
193 private readonly CancellationTokenSource workerCts = new();
194 private readonly IProgress<string> workerProgress = null!;
196 private int unreadCounter = -1;
197 private int unreadAtCounter = -1;
199 private readonly string[] columnOrgText = new string[9];
200 private readonly string[] columnText = new string[9];
202 private bool doFavRetweetFlags = false;
204 //////////////////////////////////////////////////////////////////////////////////////////////////////////
206 private readonly TimelineScheduler timelineScheduler = new();
207 private readonly DebounceTimer selectionDebouncer;
208 private readonly DebounceTimer saveConfigDebouncer;
210 private readonly string recommendedStatusFooter;
211 private bool urlMultibyteSplit = false;
212 private bool preventSmsCommand = true;
215 private readonly record struct UrlUndo(
220 private List<UrlUndo>? urlUndoBuffer = null;
222 private readonly record struct ReplyChain(
228 /// <summary>[, ]でのリプライ移動の履歴</summary>
229 private Stack<ReplyChain>? replyChains;
231 /// <summary>ポスト選択履歴</summary>
232 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
234 public TabModel CurrentTab
235 => this.statuses.SelectedTab;
237 public string CurrentTabName
238 => this.statuses.SelectedTabName;
240 public TabPage CurrentTabPage
241 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
243 public DetailsListView CurrentListView
244 => (DetailsListView)this.CurrentTabPage.Tag;
246 public PostClass? CurrentPost
247 => this.CurrentTab.SelectedPost;
249 public bool Use2ColumnsMode
250 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
252 /// <summary>検索処理タイプ</summary>
253 internal enum SEARCHTYPE
260 private readonly record struct StatusTextHistory(
262 (PostId StatusId, string ScreenName)? InReplyTo = null
265 private readonly HookGlobalHotkey hookGlobalHotkey;
268 SettingManager settingManager,
269 TabInformations tabInfo,
271 ImageCache imageCache,
272 IconAssetsManager iconAssets,
273 ThumbnailGenerator thumbGenerator
276 this.settings = settingManager;
277 this.statuses = tabInfo;
279 this.iconCache = imageCache;
280 this.iconAssets = iconAssets;
281 this.thumbGenerator = thumbGenerator;
283 this.InitializeComponent();
285 if (!this.DesignMode)
287 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
288 this.StatusText.Dock = DockStyle.Fill;
291 this.hookGlobalHotkey = new HookGlobalHotkey(this);
293 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
294 this.gh.NotifyClicked += this.GrowlHelper_Callback;
296 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
297 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
299 this.ImageSelector.Visible = false;
300 this.ImageSelector.Enabled = false;
301 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
303 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
305 this.ReplaceAppName();
306 this.InitializeShortcuts();
308 this.ignoreConfigSave = true;
309 this.Visible = false;
311 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
313 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
315 Regex.CacheSize = 100;
318 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
319 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
320 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
322 // <<<<<<<<<設定関連>>>>>>>>>
326 // 現在の DPI と設定保存時の DPI との比を取得する
327 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
332 // プロキシ設定等の通信まわりの初期化が済んでから処理する
333 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
334 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
335 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
337 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
340 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
341 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
343 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
346 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
347 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
348 this.HashMgr = new HashtagManage(this.HashSupl,
349 this.settings.Common.HashTags.ToArray(),
350 this.settings.Common.HashSelected,
351 this.settings.Common.HashIsPermanent,
352 this.settings.Common.HashIsHead,
353 this.settings.Common.HashIsNotAddToAtReply);
354 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
357 this.themeManager = new(this.settings.Local);
358 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
360 // StringFormatオブジェクトへの事前設定
361 this.sfTab.Alignment = StringAlignment.Center;
362 this.sfTab.LineAlignment = StringAlignment.Center;
364 this.InitDetailHtmlFormat();
365 this.tweetDetailsView.ClearPostBrowser();
367 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
369 this.history.Add(new StatusTextHistory(""));
371 this.inReplyTo = null;
374 this.SearchDialog.Owner = this;
375 this.urlDialog.Owner = this;
378 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
379 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
381 // 新着取得時のリストスクロールをするか。trueならスクロールしない
382 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
383 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
385 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
386 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
389 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
390 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
391 this.myLoc = this.settings.Local.FormLocation;
393 if (this.WindowState != FormWindowState.Minimized)
395 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
396 var outOfScreen = true;
397 if (Screen.AllScreens.Length == 1) // ハングするとの報告
399 foreach (var scr in Screen.AllScreens)
401 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
409 this.myLoc = new Point(0, 0);
411 this.DesktopLocation = this.myLoc;
413 this.TopMost = this.settings.Common.AlwaysTop;
414 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
415 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
416 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
418 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
419 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
421 this.StatusText.Font = this.themeManager.FontInputFont;
422 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
424 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
425 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
426 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
428 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
429 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
431 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
432 if (this.settings.Common.UnreadManage == false)
434 this.ReadedStripMenuItem.Enabled = false;
435 this.UnreadStripMenuItem.Enabled = false;
438 // リンク先URL表示部の初期化(画面左下)
439 this.StatusLabelUrl.Text = "";
441 this.StatusLabel.Text = "";
442 this.StatusLabel.AutoToolTip = false;
443 this.StatusLabel.ToolTipText = "";
445 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
447 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
448 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
449 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
450 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
452 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
453 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
454 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
455 this.SplitContainer2.Panel2.AccessibleName = "";
457 ////////////////////////////////////////////////////////////////////////////////
458 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
459 var mode = this.settings.Common.SortColumn switch
461 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
462 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
463 1 => ComparerMode.Nickname, // ニックネーム
464 2 => ComparerMode.Data, // 本文
465 3 => ComparerMode.Id, // 時刻=発言Id
466 4 => ComparerMode.Name, // 名前
467 7 => ComparerMode.Source, // Source
468 _ => ComparerMode.Id,
470 this.statuses.SetSortMode(mode, sortOrder);
471 ////////////////////////////////////////////////////////////////////////////////
473 this.ApplyListViewIconSize(this.settings.Common.IconSize);
475 // <<<<<<<<タブ関連>>>>>>>
476 foreach (var tab in this.statuses.Tabs)
478 if (!this.AddNewTab(tab, startup: true))
479 throw new TabException(Properties.Resources.TweenMain_LoadText1);
482 this.ListTabSelect(this.ListTab.SelectedTab);
485 this.SetTabAlignment();
487 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
488 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
490 if (this.settings.Common.TabIconDisp)
492 this.ListTab.DrawMode = TabDrawMode.Normal;
496 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
497 this.ListTab.DrawItem += this.ListTab_DrawItem;
498 this.ListTab.ImageList = null;
501 if (this.settings.Common.HotkeyEnabled)
504 var modKey = HookGlobalHotkey.ModKeys.None;
505 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
506 modKey |= HookGlobalHotkey.ModKeys.Alt;
507 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
508 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
509 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
510 modKey |= HookGlobalHotkey.ModKeys.Shift;
511 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
512 modKey |= HookGlobalHotkey.ModKeys.Win;
514 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
517 if (this.settings.Common.IsUseNotifyGrowl)
518 this.gh.RegisterGrowl();
520 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
522 this.SetMainWindowTitle();
523 this.SetNotifyIconText();
525 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
532 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
533 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
534 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
535 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
536 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
537 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
538 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
540 this.DoGetFollowersMenu(),
541 this.RefreshBlockIdsAsync(),
542 this.RefreshMuteUserIdsAsync(),
543 this.RefreshNoRetweetIdsAsync(),
544 this.RefreshTwitterConfigurationAsync(),
546 this.RefreshTimelineScheduler();
548 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
549 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
552 this.TimerRefreshIcon.Interval = 200;
553 this.TimerRefreshIcon.Enabled = false;
555 this.ignoreConfigSave = false;
556 this.TweenMain_Resize(this, EventArgs.Empty);
559 private void TweenMain_Activated(object sender, EventArgs e)
561 // 画面がアクティブになったら、発言欄の背景色戻す
562 if (this.StatusText.Focused)
564 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
568 private bool disposed = false;
571 /// 使用中のリソースをすべてクリーンアップします。
573 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
574 protected override void Dispose(bool disposing)
576 base.Dispose(disposing);
583 this.components?.Dispose();
586 this.SearchDialog.Dispose();
587 this.urlDialog.Dispose();
588 this.themeManager.Dispose();
589 this.sfTab.Dispose();
591 this.timelineScheduler.Dispose();
592 this.workerCts.Cancel();
593 this.thumbnailTokenSource?.Dispose();
595 this.hookGlobalHotkey.Dispose();
598 // 終了時にRemoveHandlerしておかないとメモリリークする
599 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
600 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
601 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
603 this.disposed = true;
606 private void InitColumns(ListView list, bool startup)
608 this.InitColumnText();
610 ColumnHeader[]? columns = null;
613 if (this.Use2ColumnsMode)
617 new ColumnHeader(), // アイコン
618 new ColumnHeader(), // 本文
621 columns[0].Text = this.columnText[0];
622 columns[1].Text = this.columnText[2];
626 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
628 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
629 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
630 columns[0].DisplayIndex = 0;
631 columns[1].DisplayIndex = 1;
636 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
638 columns[idx].Width = curListColumn.Width;
639 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
648 new ColumnHeader(), // アイコン
649 new ColumnHeader(), // ニックネーム
650 new ColumnHeader(), // 本文
651 new ColumnHeader(), // 日付
652 new ColumnHeader(), // ユーザID
653 new ColumnHeader(), // 未読
654 new ColumnHeader(), // マーク&プロテクト
655 new ColumnHeader(), // ソース
658 foreach (var i in Enumerable.Range(0, columns.Length))
659 columns[i].Text = this.columnText[i];
663 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
665 foreach (var (column, index) in columns.WithIndex())
667 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
668 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
674 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
676 columns[idx].Width = curListColumn.Width;
677 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
683 list.Columns.AddRange(columns);
691 foreach (var column in columns)
697 private void InitColumnText()
699 this.columnText[0] = "";
700 this.columnText[1] = Properties.Resources.AddNewTabText2;
701 this.columnText[2] = Properties.Resources.AddNewTabText3;
702 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
703 this.columnText[4] = Properties.Resources.AddNewTabText5;
704 this.columnText[5] = "";
705 this.columnText[6] = "";
706 this.columnText[7] = "Source";
708 this.columnOrgText[0] = "";
709 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
710 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
711 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
712 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
713 this.columnOrgText[5] = "";
714 this.columnOrgText[6] = "";
715 this.columnOrgText[7] = "Source";
717 var c = this.statuses.SortMode switch
719 ComparerMode.Nickname => 1, // ニックネーム
720 ComparerMode.Data => 2, // 本文
721 ComparerMode.Id => 3, // 時刻=発言Id
722 ComparerMode.Name => 4, // 名前
723 ComparerMode.Source => 7, // Source
727 if (this.Use2ColumnsMode)
729 if (this.statuses.SortOrder == SortOrder.Descending)
731 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
732 this.columnText[2] = this.columnOrgText[2] + "▾";
736 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
737 this.columnText[2] = this.columnOrgText[2] + "▴";
742 if (this.statuses.SortOrder == SortOrder.Descending)
744 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
745 this.columnText[c] = this.columnOrgText[c] + "▾";
749 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
750 this.columnText[c] = this.columnOrgText[c] + "▴";
755 private void InitDetailHtmlFormat()
757 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
759 static string ColorToRGBString(Color color)
760 => $"{color.R},{color.G},{color.B}";
762 this.detailHtmlFormatPreparedTemplate = htmlTemplate
763 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
764 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
765 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
766 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
767 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
768 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
771 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
776 txt = this.statuses.Tabs[e.Index].TabName;
783 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
784 if (e.State == DrawItemState.Selected)
786 e.DrawFocusRectangle();
791 if (this.statuses.Tabs[txt].UnreadCount > 0)
794 fore = System.Drawing.SystemBrushes.ControlText;
798 fore = System.Drawing.SystemBrushes.ControlText;
800 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
803 private void LoadConfig()
805 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
806 this.statuses.AddDefaultTabs();
809 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
811 this.RefreshTimelineScheduler();
814 private void RefreshTimelineScheduler()
816 static TimeSpan IntervalSecondsOrDisabled(int seconds)
817 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
819 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
820 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
821 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
822 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
823 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
824 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
825 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
826 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
828 this.timelineScheduler.RefreshSchedule();
831 private void MarkSettingCommonModified()
833 if (this.saveConfigDebouncer == null)
836 this.ModifySettingCommon = true;
837 _ = this.saveConfigDebouncer.Call();
840 private void MarkSettingLocalModified()
842 if (this.saveConfigDebouncer == null)
845 this.ModifySettingLocal = true;
846 _ = this.saveConfigDebouncer.Call();
849 internal void MarkSettingAtIdModified()
851 if (this.saveConfigDebouncer == null)
854 this.ModifySettingAtId = true;
855 _ = this.saveConfigDebouncer.Call();
858 private void RefreshTimeline()
860 var curListView = this.CurrentListView;
862 // 現在表示中のタブのスクロール位置を退避
863 var currentListViewState = this.listViewState[this.CurrentTabName];
864 currentListViewState.Save(this.ListLockMenuItem.Checked);
868 addCount = this.statuses.SubmitUpdate(
871 out var newMentionOrDm,
874 if (MyCommon.EndingFlag) return;
877 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
879 using (ControlTransaction.Update(curListView))
881 this.listCache.PurgeCache();
882 this.listCache.UpdateListSize();
885 currentListViewState.RestoreSelection();
891 if (this.settings.Common.TabIconDisp)
893 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
895 var tabPage = this.ListTab.TabPages[index];
896 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
897 tabPage.ImageIndex = 0; // 未読アイコン
902 this.ListTab.Refresh();
907 currentListViewState.RestoreScroll();
910 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
912 this.SetMainWindowTitle();
913 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
915 this.HashSupl.AddRangeItem(this.tw.GetHashList());
918 private bool BalloonRequired()
923 if (NativeMethods.IsScreenSaverRunning())
927 if (!this.NewPostPopMenuItem.Checked)
930 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
931 if (this.settings.Common.LimitBalloon)
933 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
940 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
942 if (this.settings.Common.ReadOwnPost)
944 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
949 if (this.BalloonRequired())
951 if (notifyPosts != null && notifyPosts.Length > 0)
953 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
954 if (this.settings.Common.IsUseNotifyGrowl)
956 var sb = new StringBuilder();
960 foreach (var post in notifyPosts)
962 if (!(notifyPosts.Length > 3))
968 if (post.IsReply && !post.IsExcludeReply) reply = true;
969 if (post.IsDm) dm = true;
970 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
971 switch (this.settings.Common.NameBalloon)
973 case MyCommon.NameBalloonEnum.UserID:
974 sb.Append(post.ScreenName).Append(" : ");
976 case MyCommon.NameBalloonEnum.NickName:
977 sb.Append(post.Nickname).Append(" : ");
980 sb.Append(post.TextFromApi);
981 if (notifyPosts.Length > 3)
983 if (notifyPosts.Last() != post) continue;
986 var title = new StringBuilder();
987 GrowlHelper.NotifyType nt;
988 if (this.settings.Common.DispUsername)
990 title.Append(this.tw.Username);
996 title.Append(ApplicationSettings.ApplicationName);
997 title.Append(" [DM] ");
998 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
999 nt = GrowlHelper.NotifyType.DirectMessage;
1003 title.Append(ApplicationSettings.ApplicationName);
1004 title.Append(" [Reply!] ");
1005 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1006 nt = GrowlHelper.NotifyType.Reply;
1010 title.Append(ApplicationSettings.ApplicationName);
1012 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1013 nt = GrowlHelper.NotifyType.Notify;
1015 var bText = sb.ToString();
1016 if (MyCommon.IsNullOrEmpty(bText)) return;
1018 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1019 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
1024 var sb = new StringBuilder();
1027 foreach (var post in notifyPosts)
1029 if (post.IsReply && !post.IsExcludeReply) reply = true;
1030 if (post.IsDm) dm = true;
1031 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1032 switch (this.settings.Common.NameBalloon)
1034 case MyCommon.NameBalloonEnum.UserID:
1035 sb.Append(post.ScreenName).Append(" : ");
1037 case MyCommon.NameBalloonEnum.NickName:
1038 sb.Append(post.Nickname).Append(" : ");
1041 sb.Append(post.TextFromApi);
1044 var title = new StringBuilder();
1046 if (this.settings.Common.DispUsername)
1048 title.Append(this.tw.Username);
1049 title.Append(" - ");
1054 ntIcon = ToolTipIcon.Warning;
1055 title.Append(ApplicationSettings.ApplicationName);
1056 title.Append(" [DM] ");
1057 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1061 ntIcon = ToolTipIcon.Warning;
1062 title.Append(ApplicationSettings.ApplicationName);
1063 title.Append(" [Reply!] ");
1064 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1068 ntIcon = ToolTipIcon.Info;
1069 title.Append(ApplicationSettings.ApplicationName);
1071 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1073 var bText = sb.ToString();
1074 if (MyCommon.IsNullOrEmpty(bText)) return;
1076 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1077 this.NotifyIcon1.BalloonTipText = bText;
1078 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1079 this.NotifyIcon1.ShowBalloonTip(500);
1085 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1089 var dir = Application.StartupPath;
1090 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1092 dir = Path.Combine(dir, "Sounds");
1094 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1102 // mentions新着時に画面ブリンク
1103 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1105 NativeMethods.FlashMyWindow(this.Handle, 3);
1109 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1111 var listView = this.CurrentListView;
1112 if (listView != sender)
1115 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1116 this.CurrentTab.SelectPosts(indices);
1118 if (indices.Length != 1)
1121 var index = indices[0];
1122 if (index > listView.VirtualListSize - 1) return;
1124 this.PushSelectPostChain();
1126 var post = this.CurrentPost!;
1127 this.statuses.SetReadAllTab(post.StatusId, read: true);
1129 this.listCache?.RefreshStyle();
1130 await this.selectionDebouncer.Call();
1133 private void StatusTextHistoryBack()
1135 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1136 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1139 if (this.hisIdx < 0)
1142 var historyItem = this.history[this.hisIdx];
1143 this.inReplyTo = historyItem.InReplyTo;
1144 this.StatusText.Text = historyItem.Status;
1145 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1148 private void StatusTextHistoryForward()
1150 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1151 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1154 if (this.hisIdx > this.history.Count - 1)
1155 this.hisIdx = this.history.Count - 1;
1157 var historyItem = this.history[this.hisIdx];
1158 this.inReplyTo = historyItem.InReplyTo;
1159 this.StatusText.Text = historyItem.Status;
1160 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1163 private async void PostButton_Click(object sender, EventArgs e)
1165 if (this.StatusText.Text.Trim().Length == 0)
1167 if (!this.ImageSelector.Enabled)
1169 await this.DoRefresh();
1174 var currentPost = this.CurrentPost;
1175 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1177 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1179 MessageBoxButtons.YesNoCancel,
1180 MessageBoxIcon.Question);
1183 case DialogResult.Yes:
1184 this.StatusText.Text = "";
1185 await this.DoReTweetOfficial(false);
1187 case DialogResult.Cancel:
1192 if (TextContainsOnlyMentions(this.StatusText.Text))
1194 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1195 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1197 if (ret != DialogResult.OK)
1201 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1203 if (this.settings.Common.Nicoms)
1205 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1206 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1209 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1210 this.CheckReplyTo(this.StatusText.Text);
1212 var status = new PostStatusParams();
1214 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1215 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AppToken.AuthType == APIAuthType.OAuth1)
1217 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1218 // 収まる場合はこれらのオプションを使用せずに投稿する
1219 status.Text = statusTextCompat;
1220 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1224 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1225 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1227 status.AttachmentUrl = attachmentUrl;
1229 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1231 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1232 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1234 status.AutoPopulateReplyMetadata = true;
1236 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1237 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1242 if (this.GetRestStatusCount(status.Text) < 0)
1244 // 文字数制限を超えているが強制的に投稿するか
1245 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1246 if (ret != DialogResult.OK)
1250 IMediaUploadService? uploadService = null;
1251 IMediaItem[]? uploadItems = null;
1252 if (this.ImageSelector.Visible)
1255 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1258 this.ImageSelector.EndSelection();
1259 uploadService = this.ImageSelector.Model.GetService(serviceName);
1262 this.inReplyTo = null;
1263 this.StatusText.Text = "";
1264 this.history.Add(new StatusTextHistory(""));
1265 this.hisIdx = this.history.Count - 1;
1266 if (!this.settings.Common.FocusLockToStatusText)
1267 this.CurrentListView.Focus();
1268 this.urlUndoBuffer = null;
1269 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1272 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1274 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1275 await MyCommon.OpenInBrowserAsync(this, tmp);
1278 await this.PostMessageAsync(status, uploadService, uploadItems);
1281 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1283 MyCommon.EndingFlag = true;
1287 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1289 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1291 // _endingFlag=false:フォームの×ボタン
1293 this.Visible = false;
1297 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1298 this.ignoreConfigSave = true;
1299 MyCommon.EndingFlag = true;
1300 this.timelineScheduler.Enabled = false;
1301 this.TimerRefreshIcon.Enabled = false;
1305 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1307 this.Visible = true;
1308 if (this.WindowState == FormWindowState.Minimized)
1310 this.WindowState = FormWindowState.Normal;
1313 this.BringToFront();
1316 private static int errorCount = 0;
1318 private static bool CheckAccountValid()
1320 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1326 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1335 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1336 private Task RefreshTabAsync<T>()
1338 => this.RefreshTabAsync<T>(backward: false);
1340 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1341 private Task RefreshTabAsync<T>(bool backward)
1345 from tab in this.statuses.GetTabsByType<T>()
1346 select this.RefreshTabAsync(tab, backward);
1348 return Task.WhenAll(loadTasks);
1351 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1352 private Task RefreshTabAsync(TabModel tab)
1353 => this.RefreshTabAsync(tab, backward: false);
1355 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1356 private async Task RefreshTabAsync(TabModel tab, bool backward)
1358 await this.workerSemaphore.WaitAsync();
1362 this.RefreshTasktrayIcon();
1363 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1365 catch (WebApiException ex)
1367 this.myStatusError = true;
1368 var tabType = tab switch
1370 HomeTabModel => "GetTimeline",
1371 MentionsTabModel => "GetTimeline",
1372 DirectMessagesTabModel => "GetDirectMessage",
1373 FavoritesTabModel => "GetFavorites",
1374 PublicSearchTabModel => "GetSearch",
1375 UserTimelineTabModel => "GetUserTimeline",
1376 ListTimelineTabModel => "GetListStatus",
1377 RelatedPostsTabModel => "GetRelatedTweets",
1378 _ => tab.GetType().Name.Replace("Model", ""),
1380 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1384 this.RefreshTimeline();
1385 this.workerSemaphore.Release();
1389 private async Task FavAddAsync(PostId statusId, TabModel tab)
1391 await this.workerSemaphore.WaitAsync();
1395 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1397 this.RefreshTasktrayIcon();
1398 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1400 catch (WebApiException ex)
1402 this.myStatusError = true;
1403 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1407 this.workerSemaphore.Release();
1411 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1413 if (ct.IsCancellationRequested)
1416 if (!CheckAccountValid())
1417 throw new WebApiException("Auth error. Check your account");
1419 if (!tab.Posts.TryGetValue(statusId, out var post))
1425 await Task.Run(async () =>
1427 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1431 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1434 await this.tw.Api.FavoritesCreate(twitterStatusId)
1436 .ConfigureAwait(false);
1438 catch (TwitterApiException ex)
1439 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1441 // エラーコード 139 のみの場合は成功と見なす
1444 if (this.settings.Common.RestrictFavCheck)
1446 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1447 .ConfigureAwait(false);
1449 if (status.Favorited != true)
1450 throw new WebApiException("NG(Restricted?)");
1453 this.favTimestamps.Add(DateTimeUtc.Now);
1456 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1458 postTl.IsFav = true;
1460 var favTab = this.statuses.FavoriteTab;
1461 favTab.AddPostQueue(postTl);
1464 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1465 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1467 if (tb.Contains(statusId))
1468 tb.Posts[statusId].IsFav = true;
1471 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1473 catch (WebApiException)
1475 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1480 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1481 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1483 if (this.favTimestamps[i] < oneHour)
1484 this.favTimestamps.RemoveAt(i);
1487 this.statuses.DistributePosts();
1490 if (ct.IsCancellationRequested)
1493 this.RefreshTimeline();
1495 if (this.CurrentTabName == tab.TabName)
1497 using (ControlTransaction.Update(this.CurrentListView))
1499 var idx = tab.IndexOf(statusId);
1501 this.listCache?.RefreshStyle(idx);
1504 var currentPost = this.CurrentPost;
1505 if (currentPost != null && statusId == currentPost.StatusId)
1506 this.DispSelectedPost(true); // 選択アイテム再表示
1510 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1512 await this.workerSemaphore.WaitAsync();
1516 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1518 this.RefreshTasktrayIcon();
1519 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1521 catch (WebApiException ex)
1523 this.myStatusError = true;
1524 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1528 this.workerSemaphore.Release();
1532 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1534 if (ct.IsCancellationRequested)
1537 if (!CheckAccountValid())
1538 throw new WebApiException("Auth error. Check your account");
1540 var successIds = new List<PostId>();
1542 await Task.Run(async () =>
1546 var failedCount = 0;
1547 foreach (var statusId in statusIds)
1551 var post = tab.Posts[statusId];
1553 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1558 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1562 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1564 .ConfigureAwait(false);
1566 catch (WebApiException)
1572 successIds.Add(statusId);
1573 post.IsFav = false; // リスト再描画必要
1575 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1576 tabinfoPost.IsFav = false;
1578 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1579 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1581 if (tb.Contains(statusId))
1582 tb.Posts[statusId].IsFav = false;
1587 if (ct.IsCancellationRequested)
1590 var favTab = this.statuses.FavoriteTab;
1591 foreach (var statusId in successIds)
1593 // ツイートが削除された訳ではないので IsDeleted はセットしない
1594 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1597 this.RefreshTimeline();
1599 if (this.CurrentTabName == tab.TabName)
1601 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1607 using (ControlTransaction.Update(this.CurrentListView))
1609 foreach (var statusId in successIds)
1611 var idx = tab.IndexOf(statusId);
1613 this.listCache?.RefreshStyle(idx);
1617 var currentPost = this.CurrentPost;
1618 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1619 this.DispSelectedPost(true); // 選択アイテム再表示
1624 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1626 await this.workerSemaphore.WaitAsync();
1630 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1632 this.RefreshTasktrayIcon();
1633 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1635 catch (WebApiException ex)
1637 this.myStatusError = true;
1638 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1642 this.workerSemaphore.Release();
1646 private async Task PostMessageAsyncInternal(
1647 IProgress<string> p,
1648 CancellationToken ct,
1649 PostStatusParams postParams,
1650 IMediaUploadService? uploadService,
1651 IMediaItem[]? uploadItems)
1653 if (ct.IsCancellationRequested)
1656 if (!CheckAccountValid())
1657 throw new WebApiException("Auth error. Check your account");
1659 p.Report("Posting...");
1661 PostClass? post = null;
1666 await Task.Run(async () =>
1668 var postParamsWithMedia = postParams;
1670 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1672 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1673 .ConfigureAwait(false);
1676 post = await this.tw.PostStatus(postParamsWithMedia)
1677 .ConfigureAwait(false);
1680 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1682 catch (WebApiException ex)
1684 // 処理は中断せずエラーの表示のみ行う
1685 errMsg = $"Err:{ex.Message}(PostMessage)";
1687 this.myStatusError = true;
1689 catch (UnauthorizedAccessException ex)
1691 // アップロード対象のファイルが開けなかった場合など
1692 errMsg = $"Err:{ex.Message}(PostMessage)";
1694 this.myStatusError = true;
1698 // 使い終わった MediaItem は破棄する
1699 if (uploadItems != null)
1701 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1703 disposableItem.Dispose();
1708 if (ct.IsCancellationRequested)
1711 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1712 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1713 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1715 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1717 var ret = MessageBox.Show(
1719 "Failed to update status",
1720 MessageBoxButtons.RetryCancel,
1721 MessageBoxIcon.Question);
1723 if (ret == DialogResult.Retry)
1725 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1729 this.StatusTextHistoryBack();
1730 this.StatusText.Focus();
1732 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1733 if (this.settings.Common.FocusLockToStatusText)
1734 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1739 this.postTimestamps.Add(DateTimeUtc.Now);
1741 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1742 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1744 if (this.postTimestamps[i] < oneHour)
1745 this.postTimestamps.RemoveAt(i);
1748 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1750 this.HashMgr.ClearHashtag();
1751 this.HashStripSplitButton.Text = "#[-]";
1752 this.HashTogglePullDownMenuItem.Checked = false;
1753 this.HashToggleMenuItem.Checked = false;
1756 this.SetMainWindowTitle();
1761 this.statuses.AddPost(post);
1762 this.statuses.DistributePosts();
1763 this.RefreshTimeline();
1766 if (this.settings.Common.PostAndGet)
1767 await this.RefreshTabAsync<HomeTabModel>();
1770 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1772 await this.workerSemaphore.WaitAsync();
1776 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1778 this.RefreshTasktrayIcon();
1779 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1781 catch (WebApiException ex)
1783 this.myStatusError = true;
1784 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1788 this.workerSemaphore.Release();
1792 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1794 if (ct.IsCancellationRequested)
1797 if (!CheckAccountValid())
1798 throw new WebApiException("Auth error. Check your account");
1801 if (!this.settings.Common.UnreadManage)
1804 read = this.initial && this.settings.Common.Read;
1806 p.Report("Posting...");
1808 var posts = new List<PostClass>();
1810 await Task.Run(async () =>
1812 foreach (var statusId in statusIds)
1814 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1815 if (post != null) posts.Add(post);
1819 if (ct.IsCancellationRequested)
1822 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1824 this.postTimestamps.Add(DateTimeUtc.Now);
1826 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1827 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1829 if (this.postTimestamps[i] < oneHour)
1830 this.postTimestamps.RemoveAt(i);
1833 // 自分のRTはTLの更新では取得できない場合があるので、
1834 // 投稿時取得の有無に関わらず追加しておく
1835 posts.ForEach(post => this.statuses.AddPost(post));
1837 if (this.settings.Common.PostAndGet)
1839 await this.RefreshTabAsync<HomeTabModel>();
1843 this.statuses.DistributePosts();
1844 this.RefreshTimeline();
1848 private async Task RefreshFollowerIdsAsync()
1850 await this.workerSemaphore.WaitAsync();
1854 this.RefreshTasktrayIcon();
1855 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1857 await this.tw.RefreshFollowerIds();
1859 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1861 this.RefreshTimeline();
1862 this.listCache?.PurgeCache();
1863 this.CurrentListView.Refresh();
1865 catch (WebApiException ex)
1867 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1871 this.workerSemaphore.Release();
1875 private async Task RefreshNoRetweetIdsAsync()
1877 await this.workerSemaphore.WaitAsync();
1881 this.RefreshTasktrayIcon();
1882 await this.tw.RefreshNoRetweetIds();
1884 this.StatusLabel.Text = "NoRetweetIds refreshed";
1886 catch (WebApiException ex)
1888 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1892 this.workerSemaphore.Release();
1896 private async Task RefreshBlockIdsAsync()
1898 await this.workerSemaphore.WaitAsync();
1902 this.RefreshTasktrayIcon();
1903 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1905 await this.tw.RefreshBlockIds();
1907 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1909 catch (WebApiException ex)
1911 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1915 this.workerSemaphore.Release();
1919 private async Task RefreshTwitterConfigurationAsync()
1921 await this.workerSemaphore.WaitAsync();
1925 this.RefreshTasktrayIcon();
1926 await this.tw.RefreshConfiguration();
1928 if (this.tw.Configuration.PhotoSizeLimit != 0)
1930 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1932 service.UpdateTwitterConfiguration(this.tw.Configuration);
1936 this.listCache?.PurgeCache();
1937 this.CurrentListView.Refresh();
1939 catch (WebApiException ex)
1941 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1945 this.workerSemaphore.Release();
1949 private async Task RefreshMuteUserIdsAsync()
1951 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1955 await this.tw.RefreshMuteUserIdsAsync();
1957 catch (WebApiException ex)
1959 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1963 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1966 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1968 if (e.Button == MouseButtons.Left)
1970 this.Visible = true;
1971 if (this.WindowState == FormWindowState.Minimized)
1973 this.WindowState = this.formWindowState;
1976 this.BringToFront();
1980 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1981 => await this.ListItemDoubleClickAction();
1983 private async Task ListItemDoubleClickAction()
1985 switch (this.settings.Common.ListDoubleClickAction)
1987 case MyCommon.ListItemDoubleClickActionType.Reply:
1988 this.MakeReplyText();
1990 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1991 this.MakeReplyText(atAll: true);
1993 case MyCommon.ListItemDoubleClickActionType.Favorite:
1994 await this.FavoriteChange(true);
1996 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1997 var post = this.CurrentPost;
1999 await this.ShowUserStatus(post.ScreenName, false);
2001 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2002 await this.ShowUserTimeline();
2004 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2005 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2007 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2008 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2010 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2011 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2013 case MyCommon.ListItemDoubleClickActionType.None:
2020 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2021 => await this.FavoriteChange(true);
2023 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2024 => await this.FavoriteChange(false);
2026 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2027 => await this.FavoritesRetweetOfficial();
2029 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2030 => await this.FavoritesRetweetUnofficial();
2032 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2034 var tab = this.CurrentTab;
2035 var posts = tab.SelectedPosts;
2037 // trueでFavAdd,falseでFavRemove
2038 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2039 || !this.ExistCurrentPost) return;
2041 if (posts.Length > 1)
2046 // https://support.twitter.com/articles/76915#favoriting
2047 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2048 this.doFavRetweetFlags = false;
2053 if (multiFavoriteChangeDialogEnable)
2055 var confirm = MessageBox.Show(
2056 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2057 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2058 MessageBoxButtons.OKCancel,
2059 MessageBoxIcon.Question);
2061 if (confirm == DialogResult.Cancel)
2069 var selectedPost = posts.Single();
2070 if (selectedPost.IsFav)
2072 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2076 await this.FavAddAsync(selectedPost.StatusId, tab);
2080 var selectedPosts = posts.Where(x => x.IsFav);
2081 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2082 if (statusIds.Length == 0)
2084 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2088 await this.FavRemoveAsync(statusIds, tab);
2092 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2094 var post = this.CurrentPost;
2096 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2098 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2101 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2103 if ((!this.initialLayout) && this.Visible)
2105 if (this.WindowState == FormWindowState.Normal)
2107 this.mySize = this.ClientSize;
2108 this.mySpDis = this.SplitContainer1.SplitterDistance;
2109 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2110 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2111 this.MarkSettingLocalModified();
2116 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2118 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2119 if (comparerMode == null)
2122 this.SetSortColumn(comparerMode.Value);
2126 /// 列インデックスからソートを行う ComparerMode を求める
2128 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2129 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2130 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2132 if (this.Use2ColumnsMode)
2133 return ComparerMode.Id;
2135 return columnIndex switch
2137 1 => ComparerMode.Nickname, // ニックネーム
2138 2 => ComparerMode.Data, // 本文
2139 3 => ComparerMode.Id, // 時刻=発言Id
2140 4 => ComparerMode.Name, // 名前
2141 7 => ComparerMode.Source, // Source
2142 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2147 /// 発言一覧の指定した位置の列でソートする
2149 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2150 private void SetSortColumnByDisplayIndex(int columnIndex)
2152 // 表示上の列の位置から ColumnHeader を求める
2153 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2154 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2159 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2160 if (comparerMode == null)
2163 this.SetSortColumn(comparerMode.Value);
2167 /// 発言一覧の最後列の項目でソートする
2169 private void SetSortLastColumn()
2171 // 表示上の最後列にある ColumnHeader を求める
2172 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2173 .OrderByDescending(x => x.DisplayIndex)
2176 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2177 if (comparerMode == null)
2180 this.SetSortColumn(comparerMode.Value);
2184 /// 発言一覧を指定された ComparerMode に基づいてソートする
2186 private void SetSortColumn(ComparerMode sortColumn)
2188 if (this.settings.Common.SortOrderLock)
2191 this.statuses.ToggleSortOrder(sortColumn);
2192 this.InitColumnText();
2194 var list = this.CurrentListView;
2195 if (this.Use2ColumnsMode)
2197 list.Columns[0].Text = this.columnText[0];
2198 list.Columns[1].Text = this.columnText[2];
2202 for (var i = 0; i <= 7; i++)
2204 list.Columns[i].Text = this.columnText[i];
2208 this.listCache?.PurgeCache();
2210 var tab = this.CurrentTab;
2211 var post = this.CurrentPost;
2212 if (tab.AllCount > 0 && post != null)
2214 var idx = tab.IndexOf(post.StatusId);
2217 this.SelectListItem(list, idx);
2218 list.EnsureVisible(idx);
2223 this.MarkSettingCommonModified();
2226 private void TweenMain_LocationChanged(object sender, EventArgs e)
2228 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2230 this.myLoc = this.DesktopLocation;
2231 this.MarkSettingLocalModified();
2235 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2237 var post = this.CurrentPost;
2238 if (!this.ExistCurrentPost)
2240 this.ReplyStripMenuItem.Enabled = false;
2241 this.ReplyAllStripMenuItem.Enabled = false;
2242 this.DMStripMenuItem.Enabled = false;
2243 this.TabMenuItem.Enabled = false;
2244 this.IDRuleMenuItem.Enabled = false;
2245 this.SourceRuleMenuItem.Enabled = false;
2246 this.ReadedStripMenuItem.Enabled = false;
2247 this.UnreadStripMenuItem.Enabled = false;
2248 this.AuthorContextMenuItem.Visible = false;
2249 this.RetweetedByContextMenuItem.Visible = false;
2253 this.ReplyStripMenuItem.Enabled = true;
2254 this.ReplyAllStripMenuItem.Enabled = true;
2255 this.DMStripMenuItem.Enabled = true;
2256 this.TabMenuItem.Enabled = true;
2257 this.IDRuleMenuItem.Enabled = true;
2258 this.SourceRuleMenuItem.Enabled = true;
2259 this.ReadedStripMenuItem.Enabled = true;
2260 this.UnreadStripMenuItem.Enabled = true;
2261 this.AuthorContextMenuItem.Visible = true;
2262 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2263 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2264 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2266 var tab = this.CurrentTab;
2267 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2269 this.FavAddToolStripMenuItem.Enabled = false;
2270 this.FavRemoveToolStripMenuItem.Enabled = false;
2271 this.StatusOpenMenuItem.Enabled = false;
2272 this.ShowRelatedStatusesMenuItem.Enabled = false;
2274 this.ReTweetStripMenuItem.Enabled = false;
2275 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2276 this.QuoteStripMenuItem.Enabled = false;
2277 this.FavoriteRetweetContextMenu.Enabled = false;
2278 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2282 this.FavAddToolStripMenuItem.Enabled = true;
2283 this.FavRemoveToolStripMenuItem.Enabled = true;
2284 this.StatusOpenMenuItem.Enabled = true;
2285 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2287 if (!post.CanRetweetBy(this.tw.UserId))
2289 this.ReTweetStripMenuItem.Enabled = false;
2290 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2291 this.QuoteStripMenuItem.Enabled = false;
2292 this.FavoriteRetweetContextMenu.Enabled = false;
2293 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2297 this.ReTweetStripMenuItem.Enabled = true;
2298 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2299 this.QuoteStripMenuItem.Enabled = true;
2300 this.FavoriteRetweetContextMenu.Enabled = true;
2301 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2305 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2307 this.RepliedStatusOpenMenuItem.Enabled = false;
2311 this.RepliedStatusOpenMenuItem.Enabled = true;
2314 if (this.ExistCurrentPost && post != null)
2316 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2317 if (post.RetweetedByUserId == this.tw.UserId)
2318 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2320 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2324 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2325 => this.MakeReplyText();
2327 private void DMStripMenuItem_Click(object sender, EventArgs e)
2328 => this.MakeDirectMessageText();
2330 private async Task DoStatusDelete()
2332 var posts = this.CurrentTab.SelectedPosts;
2333 if (posts.Length == 0)
2336 // 選択されたツイートの中に削除可能なものが一つでもあるか
2337 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2340 var ret = MessageBox.Show(
2342 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2343 Properties.Resources.DeleteStripMenuItem_ClickText2,
2344 MessageBoxButtons.OKCancel,
2345 MessageBoxIcon.Question);
2347 if (ret != DialogResult.OK)
2350 var currentListView = this.CurrentListView;
2351 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2353 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2355 Exception? lastException = null;
2356 foreach (var post in posts)
2358 if (!post.CanDeleteBy(this.tw.UserId))
2363 if (post.StatusId is TwitterDirectMessageId dmId)
2365 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2369 if (post.RetweetedByUserId == this.tw.UserId)
2371 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2373 await this.tw.DeleteRetweet(post);
2377 if (post.UserId == this.tw.UserId)
2379 if (post.RetweetedId != null)
2381 // 他人に RT された自分のツイート
2382 // => RT 元の自分のツイートを削除
2383 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2389 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2395 catch (WebApiException ex)
2401 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2404 if (lastException == null)
2405 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2407 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2409 using (ControlTransaction.Update(currentListView))
2411 this.listCache?.PurgeCache();
2412 this.listCache?.UpdateListSize();
2414 currentListView.SelectedIndices.Clear();
2416 var currentTab = this.CurrentTab;
2417 if (currentTab.AllCount != 0)
2420 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2421 selectedIndex = focusedIndex;
2423 selectedIndex = currentTab.AllCount - 1;
2425 currentListView.SelectedIndices.Add(selectedIndex);
2426 currentListView.EnsureVisible(selectedIndex);
2427 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2431 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2433 var tabPage = this.ListTab.TabPages[index];
2434 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2436 if (tabPage.ImageIndex == 0)
2437 tabPage.ImageIndex = -1; // タブアイコン
2441 if (!this.settings.Common.TabIconDisp)
2442 this.ListTab.Refresh();
2446 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2447 => await this.DoStatusDelete();
2449 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2451 using (ControlTransaction.Update(this.CurrentListView))
2453 var tab = this.CurrentTab;
2454 foreach (var statusId in tab.SelectedStatusIds)
2456 this.statuses.SetReadAllTab(statusId, read: true);
2457 var idx = tab.IndexOf(statusId);
2458 this.listCache?.RefreshStyle(idx);
2461 if (this.settings.Common.TabIconDisp)
2463 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2465 if (tab.UnreadCount == 0)
2467 var tabPage = this.ListTab.TabPages[index];
2468 if (tabPage.ImageIndex == 0)
2469 tabPage.ImageIndex = -1; // タブアイコン
2473 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2476 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2478 using (ControlTransaction.Update(this.CurrentListView))
2480 var tab = this.CurrentTab;
2481 foreach (var statusId in tab.SelectedStatusIds)
2483 this.statuses.SetReadAllTab(statusId, read: false);
2484 var idx = tab.IndexOf(statusId);
2485 this.listCache?.RefreshStyle(idx);
2488 if (this.settings.Common.TabIconDisp)
2490 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2492 if (tab.UnreadCount > 0)
2494 var tabPage = this.ListTab.TabPages[index];
2495 if (tabPage.ImageIndex == -1)
2496 tabPage.ImageIndex = 0; // タブアイコン
2500 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2503 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2504 => await this.DoRefresh();
2506 private async Task DoRefresh()
2507 => await this.RefreshTabAsync(this.CurrentTab);
2509 private async Task DoRefreshMore()
2510 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2512 private DialogResult ShowSettingDialog()
2514 using var settingDialog = new AppendSettingDialog();
2515 settingDialog.Icon = this.iconAssets.IconMain;
2516 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2518 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2520 DialogResult result;
2523 result = settingDialog.ShowDialog(this);
2527 return DialogResult.Abort;
2530 if (result == DialogResult.OK)
2532 lock (this.syncObject)
2534 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2541 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2544 var previousUserId = this.settings.Common.UserId;
2545 var oldIconCol = this.Use2ColumnsMode;
2547 if (this.ShowSettingDialog() == DialogResult.OK)
2549 lock (this.syncObject)
2551 this.settings.ApplySettings();
2553 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2554 this.tw.ClearAuthInfo();
2556 var account = this.settings.Common.SelectedAccount;
2557 if (account != null)
2558 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
2560 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
2562 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2563 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2565 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2569 if (this.settings.Common.TabIconDisp)
2571 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2572 this.ListTab.DrawMode = TabDrawMode.Normal;
2573 this.ListTab.ImageList = this.TabImage;
2577 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2578 this.ListTab.DrawItem += this.ListTab_DrawItem;
2579 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2580 this.ListTab.ImageList = null;
2583 catch (Exception ex)
2585 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2586 ex.Data["IsTerminatePermission"] = false;
2592 if (!this.settings.Common.UnreadManage)
2594 this.ReadedStripMenuItem.Enabled = false;
2595 this.UnreadStripMenuItem.Enabled = false;
2596 if (this.settings.Common.TabIconDisp)
2598 foreach (TabPage myTab in this.ListTab.TabPages)
2600 myTab.ImageIndex = -1;
2606 this.ReadedStripMenuItem.Enabled = true;
2607 this.UnreadStripMenuItem.Enabled = true;
2610 catch (Exception ex)
2612 ex.Data["Instance"] = "ListTab(UnreadManage)";
2613 ex.Data["IsTerminatePermission"] = false;
2618 this.SetTabAlignment();
2620 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2622 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2623 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2624 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2626 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2627 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2628 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2629 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2631 var newTheme = new ThemeManager(this.settings.Local);
2632 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2633 this.tweetDetailsView.Theme = this.themeManager;
2634 if (this.listDrawer != null)
2635 this.listDrawer.Theme = this.themeManager;
2640 if (this.StatusText.Focused)
2641 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2643 this.StatusText.Font = this.themeManager.FontInputFont;
2644 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2646 catch (Exception ex)
2648 MessageBox.Show(ex.Message);
2653 this.InitDetailHtmlFormat();
2655 catch (Exception ex)
2657 ex.Data["Instance"] = "Font";
2658 ex.Data["IsTerminatePermission"] = false;
2664 if (this.settings.Common.TabIconDisp)
2666 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2668 var tabPage = this.ListTab.TabPages[index];
2669 if (tab.UnreadCount == 0)
2670 tabPage.ImageIndex = -1;
2672 tabPage.ImageIndex = 0;
2676 catch (Exception ex)
2678 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2679 ex.Data["IsTerminatePermission"] = false;
2685 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2687 foreach (TabPage tp in this.ListTab.TabPages)
2689 var lst = (DetailsListView)tp.Tag;
2691 using (ControlTransaction.Update(lst))
2693 lst.GridLines = this.settings.Common.ShowGrid;
2695 if (this.Use2ColumnsMode != oldIconCol)
2696 this.ResetColumns(lst);
2700 catch (Exception ex)
2702 ex.Data["Instance"] = "ListView(IconSize)";
2703 ex.Data["IsTerminatePermission"] = false;
2707 this.SetMainWindowTitle();
2708 this.SetNotifyIconText();
2710 this.listCache?.PurgeCache();
2711 this.CurrentListView.Refresh();
2712 this.ListTab.Refresh();
2714 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2715 if (this.settings.Common.HotkeyEnabled)
2717 // グローバルホットキーの登録。設定で変更可能にするかも
2718 var modKey = HookGlobalHotkey.ModKeys.None;
2719 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2720 modKey |= HookGlobalHotkey.ModKeys.Alt;
2721 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2722 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2723 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2724 modKey |= HookGlobalHotkey.ModKeys.Shift;
2725 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2726 modKey |= HookGlobalHotkey.ModKeys.Win;
2728 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2731 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2734 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2742 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2744 this.TopMost = this.settings.Common.AlwaysTop;
2745 this.SaveConfigsAll(false);
2747 if (this.tw.UserId != previousUserId)
2748 await this.DoGetFollowersMenu();
2754 private void SetTabAlignment()
2756 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2757 if (this.ListTab.Alignment == newAlignment) return;
2760 var currentListViewState = this.listViewState[this.CurrentTabName];
2761 currentListViewState.Save(this.ListLockMenuItem.Checked);
2763 this.ListTab.Alignment = newAlignment;
2765 currentListViewState.Restore(forceScroll: true);
2768 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2771 if (this.listDrawer != null)
2773 this.listDrawer.IconSize = iconSz;
2774 this.listDrawer.UpdateItemHeight();
2777 this.listCache?.PurgeCache();
2780 private void ResetColumns(DetailsListView list)
2782 using (ControlTransaction.Update(list))
2783 using (ControlTransaction.Layout(list, false))
2786 list.ColumnClick -= this.MyList_ColumnClick;
2787 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2788 list.ColumnReordered -= this.MyList_ColumnReordered;
2789 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2791 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2792 list.Columns.Clear();
2793 cols.ForEach(col => col.Dispose());
2796 this.InitColumns(list, true);
2798 list.ColumnClick += this.MyList_ColumnClick;
2799 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2800 list.ColumnReordered += this.MyList_ColumnReordered;
2801 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2805 public void AddNewTabForSearch(string searchWord)
2807 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2808 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2810 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2812 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2813 this.ListTab.SelectedIndex = tabIndex;
2818 var tabName = searchWord;
2819 for (var i = 0; i <= 100; i++)
2821 if (this.statuses.ContainsTab(tabName))
2827 var tab = new PublicSearchTabModel(tabName);
2828 this.statuses.AddTab(tab);
2829 this.AddNewTab(tab, startup: false);
2831 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2833 var tabPage = this.CurrentTabPage;
2834 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2835 cmb.Items.Add(searchWord);
2836 cmb.Text = searchWord;
2837 this.SaveConfigsTabs();
2839 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2842 private async Task ShowUserTimeline()
2844 var post = this.CurrentPost;
2845 if (post == null || !this.ExistCurrentPost) return;
2846 await this.AddNewTabForUserTimeline(post.ScreenName);
2849 private async Task ShowRetweeterTimeline()
2851 var retweetedBy = this.CurrentPost?.RetweetedBy;
2852 if (retweetedBy == null || !this.ExistCurrentPost) return;
2853 await this.AddNewTabForUserTimeline(retweetedBy);
2856 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2858 if (e.KeyCode == Keys.Escape)
2860 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2861 this.SaveConfigsTabs();
2862 e.SuppressKeyPress = true;
2866 public async Task AddNewTabForUserTimeline(string user)
2868 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2869 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2871 if (tb.ScreenName == user)
2873 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2874 this.ListTab.SelectedIndex = tabIndex;
2879 var tabName = "user:" + user;
2880 while (this.statuses.ContainsTab(tabName))
2885 var tab = new UserTimelineTabModel(tabName, user);
2886 this.statuses.AddTab(tab);
2887 this.AddNewTab(tab, startup: false);
2889 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2890 this.SaveConfigsTabs();
2892 await this.RefreshTabAsync(tab);
2895 public bool AddNewTab(TabModel tab, bool startup)
2898 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2902 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2904 var tabPage = new TabPage();
2905 var listCustom = new DetailsListView();
2907 var cnt = this.statuses.Tabs.Count;
2909 // ToDo:Create and set controls follow tabtypes
2911 using (ControlTransaction.Update(listCustom))
2912 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2913 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2914 using (ControlTransaction.Layout(this.SplitContainer1, false))
2915 using (ControlTransaction.Layout(this.ListTab, false))
2916 using (ControlTransaction.Layout(this))
2917 using (ControlTransaction.Layout(tabPage, false))
2919 tabPage.Controls.Add(listCustom);
2922 var userTab = tab as UserTimelineTabModel;
2923 var listTab = tab as ListTimelineTabModel;
2924 var searchTab = tab as PublicSearchTabModel;
2926 if (userTab != null || listTab != null)
2928 var label = new Label
2930 Dock = DockStyle.Top,
2935 if (listTab != null)
2937 label.Text = listTab.ListInfo.ToString();
2939 else if (userTab != null)
2941 label.Text = userTab.ScreenName + "'s Timeline";
2943 label.TextAlign = ContentAlignment.MiddleLeft;
2944 using (var tmpComboBox = new ComboBox())
2946 label.Height = tmpComboBox.Height;
2948 tabPage.Controls.Add(label);
2951 else if (searchTab != null)
2953 var pnl = new Panel();
2955 var lbl = new Label();
2956 var cmb = new ComboBox();
2957 var btn = new Button();
2958 var cmbLang = new ComboBox();
2960 using (ControlTransaction.Layout(pnl, false))
2962 pnl.Controls.Add(cmb);
2963 pnl.Controls.Add(cmbLang);
2964 pnl.Controls.Add(btn);
2965 pnl.Controls.Add(lbl);
2966 pnl.Name = "panelSearch";
2968 pnl.Dock = DockStyle.Top;
2969 pnl.Height = cmb.Height;
2970 pnl.Enter += this.SearchControls_Enter;
2971 pnl.Leave += this.SearchControls_Leave;
2974 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2975 cmb.Dock = DockStyle.Fill;
2976 cmb.Name = "comboSearch";
2977 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2978 cmb.ImeMode = ImeMode.NoControl;
2979 cmb.TabStop = false;
2981 cmb.AutoCompleteMode = AutoCompleteMode.None;
2982 cmb.KeyDown += this.SearchComboBox_KeyDown;
2985 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2986 cmbLang.Dock = DockStyle.Right;
2988 cmbLang.Name = "comboLang";
2989 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2990 cmbLang.TabStop = false;
2991 cmbLang.TabIndex = 2;
2992 cmbLang.Items.Add("");
2993 cmbLang.Items.Add("ja");
2994 cmbLang.Items.Add("en");
2995 cmbLang.Items.Add("ar");
2996 cmbLang.Items.Add("da");
2997 cmbLang.Items.Add("nl");
2998 cmbLang.Items.Add("fa");
2999 cmbLang.Items.Add("fi");
3000 cmbLang.Items.Add("fr");
3001 cmbLang.Items.Add("de");
3002 cmbLang.Items.Add("hu");
3003 cmbLang.Items.Add("is");
3004 cmbLang.Items.Add("it");
3005 cmbLang.Items.Add("no");
3006 cmbLang.Items.Add("pl");
3007 cmbLang.Items.Add("pt");
3008 cmbLang.Items.Add("ru");
3009 cmbLang.Items.Add("es");
3010 cmbLang.Items.Add("sv");
3011 cmbLang.Items.Add("th");
3013 lbl.Text = "Search(C-S-f)";
3014 lbl.Name = "label1";
3015 lbl.Dock = DockStyle.Left;
3017 lbl.Height = cmb.Height;
3018 lbl.TextAlign = ContentAlignment.MiddleLeft;
3021 btn.Text = "Search";
3022 btn.Name = "buttonSearch";
3023 btn.UseVisualStyleBackColor = true;
3024 btn.Dock = DockStyle.Right;
3025 btn.TabStop = false;
3027 btn.Click += this.SearchButton_Click;
3029 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3031 cmb.Items.Add(searchTab.SearchWords);
3032 cmb.Text = searchTab.SearchWords;
3035 cmbLang.Text = searchTab.SearchLang;
3037 tabPage.Controls.Add(pnl);
3041 tabPage.Tag = listCustom;
3042 this.ListTab.Controls.Add(tabPage);
3044 tabPage.Location = new Point(4, 4);
3045 tabPage.Name = "CTab" + cnt;
3046 tabPage.Size = new Size(380, 260);
3047 tabPage.TabIndex = 2 + cnt;
3048 tabPage.Text = tab.TabName;
3049 tabPage.UseVisualStyleBackColor = true;
3050 tabPage.AccessibleRole = AccessibleRole.PageTab;
3052 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3053 listCustom.TabIndex = 1;
3054 listCustom.AllowColumnReorder = true;
3055 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3056 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3057 listCustom.Dock = DockStyle.Fill;
3058 listCustom.FullRowSelect = true;
3059 listCustom.HideSelection = false;
3060 listCustom.Location = new Point(0, 0);
3061 listCustom.Margin = new Padding(0);
3062 listCustom.Name = "CList" + Environment.TickCount;
3063 listCustom.ShowItemToolTips = true;
3064 listCustom.Size = new Size(380, 260);
3065 listCustom.UseCompatibleStateImageBehavior = false;
3066 listCustom.View = View.Details;
3067 listCustom.OwnerDraw = true;
3068 listCustom.VirtualMode = true;
3070 listCustom.GridLines = this.settings.Common.ShowGrid;
3071 listCustom.AllowDrop = true;
3073 this.InitColumns(listCustom, startup);
3075 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3076 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3077 listCustom.ColumnClick += this.MyList_ColumnClick;
3078 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3079 listCustom.DragDrop += this.TweenMain_DragDrop;
3080 listCustom.DragEnter += this.TweenMain_DragEnter;
3081 listCustom.DragOver += this.TweenMain_DragOver;
3082 listCustom.MouseClick += this.MyList_MouseClick;
3083 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3084 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3085 listCustom.HScrolled += this.MyList_HScrolled;
3088 var state = new TimelineListViewState(listCustom, tab);
3089 this.listViewState[tab.TabName] = state;
3094 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3096 var tabInfo = this.statuses.GetTabByName(tabName);
3097 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3102 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3103 var result = MessageBox.Show(
3105 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3106 MessageBoxButtons.OKCancel,
3107 MessageBoxIcon.Question,
3108 MessageBoxDefaultButton.Button2);
3109 if (result == DialogResult.Cancel)
3115 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3119 var tabPage = this.ListTab.TabPages[tabIndex];
3121 this.SetListProperty(); // 他のタブに列幅等を反映
3123 this.listViewState.Remove(tabName);
3126 var listCustom = (DetailsListView)tabPage.Tag;
3129 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3130 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3131 using (ControlTransaction.Layout(this.SplitContainer1, false))
3132 using (ControlTransaction.Layout(this.ListTab, false))
3133 using (ControlTransaction.Layout(this))
3134 using (ControlTransaction.Layout(tabPage, false))
3136 if (this.CurrentTabName == tabName)
3138 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3139 this.beforeSelectedTab = null;
3141 this.ListTab.Controls.Remove(tabPage);
3144 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3146 using var label = tabPage.Controls["labelUser"];
3147 tabPage.Controls.Remove(label);
3149 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3151 using var pnl = tabPage.Controls["panelSearch"];
3153 pnl.Enter -= this.SearchControls_Enter;
3154 pnl.Leave -= this.SearchControls_Leave;
3155 tabPage.Controls.Remove(pnl);
3157 foreach (Control ctrl in pnl.Controls)
3159 if (ctrl.Name == "buttonSearch")
3161 ctrl.Click -= this.SearchButton_Click;
3163 else if (ctrl.Name == "comboSearch")
3165 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3167 pnl.Controls.Remove(ctrl);
3172 tabPage.Controls.Remove(listCustom);
3174 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3175 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3176 listCustom.ColumnClick -= this.MyList_ColumnClick;
3177 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3178 listCustom.DragDrop -= this.TweenMain_DragDrop;
3179 listCustom.DragEnter -= this.TweenMain_DragEnter;
3180 listCustom.DragOver -= this.TweenMain_DragOver;
3181 listCustom.MouseClick -= this.MyList_MouseClick;
3182 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3183 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3184 listCustom.HScrolled -= this.MyList_HScrolled;
3186 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3187 listCustom.Columns.Clear();
3188 cols.ForEach(col => col.Dispose());
3191 listCustom.ContextMenuStrip = null;
3192 listCustom.ColumnHeaderContextMenuStrip = null;
3193 listCustom.Font = null;
3195 listCustom.SmallImageList = null;
3196 listCustom.ListViewItemSorter = null;
3199 this.listCache?.PurgeCache();
3203 listCustom.Dispose();
3204 this.statuses.RemoveTab(tabName);
3209 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3211 this.listCache?.PurgeCache();
3212 this.beforeSelectedTab = e.TabPage;
3215 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3219 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3222 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3223 if (!dragEnableRectangle.Contains(e.Location))
3225 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3226 tn = this.CurrentTabName;
3229 if (MyCommon.IsNullOrEmpty(tn)) return;
3231 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3234 var tabPage = this.ListTab.TabPages[tabIndex];
3235 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3240 this.tabDrag = false;
3243 var cpos = new Point(e.X, e.Y);
3244 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3246 var rect = this.ListTab.GetTabRect(index);
3247 if (rect.Contains(cpos))
3249 this.rclickTabName = tab.TabName;
3255 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3257 this.SetMainWindowTitle();
3258 this.SetStatusLabelUrl();
3259 this.SetApiStatusLabel();
3260 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3261 this.Tag = this.ListTab.Tag;
3262 this.TabMenuControl(this.CurrentTabName);
3263 this.PushSelectPostChain();
3264 this.DispSelectedPost();
3267 private void SetListProperty()
3269 if (!this.isColumnChanged) return;
3271 var currentListView = this.CurrentListView;
3273 var dispOrder = new int[currentListView.Columns.Count];
3274 for (var i = 0; i < currentListView.Columns.Count; i++)
3276 for (var j = 0; j < currentListView.Columns.Count; j++)
3278 if (currentListView.Columns[j].DisplayIndex == i)
3287 foreach (TabPage tb in this.ListTab.TabPages)
3289 if (tb.Text == this.CurrentTabName)
3292 if (tb.Tag != null && tb.Controls.Count > 0)
3294 var lst = (DetailsListView)tb.Tag;
3295 for (var i = 0; i < lst.Columns.Count; i++)
3297 lst.Columns[dispOrder[i]].DisplayIndex = i;
3298 lst.Columns[i].Width = currentListView.Columns[i].Width;
3303 this.isColumnChanged = false;
3306 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3308 if (e.KeyChar == '@')
3310 if (!this.settings.Common.UseAtIdSupplement) return;
3312 var cnt = this.AtIdSupl.ItemCount;
3313 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3314 if (cnt != this.AtIdSupl.ItemCount)
3315 this.MarkSettingAtIdModified();
3318 else if (e.KeyChar == '#')
3320 if (!this.settings.Common.UseHashSupplement) return;
3321 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3326 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3327 => this.ShowSuplDialog(owner, dialog, 0, "");
3329 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3330 => this.ShowSuplDialog(owner, dialog, offset, "");
3332 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3334 dialog.StartsWith = startswith;
3341 dialog.ShowDialog();
3343 this.TopMost = this.settings.Common.AlwaysTop;
3344 var selStart = owner.SelectionStart;
3347 if (dialog.DialogResult == DialogResult.OK)
3349 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3353 fHalf = owner.Text.Substring(0, selStart - offset);
3355 if (selStart < owner.Text.Length)
3357 eHalf = owner.Text.Substring(selStart);
3359 owner.Text = fHalf + dialog.InputText + eHalf;
3360 owner.SelectionStart = selStart + dialog.InputText.Length;
3367 fHalf = owner.Text.Substring(0, selStart);
3369 if (selStart < owner.Text.Length)
3371 eHalf = owner.Text.Substring(selStart);
3373 owner.Text = fHalf + eHalf;
3376 owner.SelectionStart = selStart;
3382 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3385 if (!e.Alt && !e.Control && !e.Shift)
3387 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3389 var isSpace = false;
3390 foreach (var c in this.StatusText.Text)
3392 if (c == ' ' || c == ' ')
3405 this.StatusText.Text = "";
3406 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3410 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3413 private void StatusText_TextChanged(object sender, EventArgs e)
3416 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3417 this.lblLen.Text = pLen.ToString();
3420 this.StatusText.ForeColor = Color.Red;
3424 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3427 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3429 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3431 this.inReplyTo = null;
3436 /// メンション以外の文字列が含まれていないテキストであるか判定します
3438 internal static bool TextContainsOnlyMentions(string text)
3440 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3443 foreach (var mention in mentions)
3445 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3447 if (!string.IsNullOrWhiteSpace(textPart))
3450 startIndex = mention.Indices[1];
3453 var textPartLast = text.Substring(startIndex);
3455 if (!string.IsNullOrWhiteSpace(textPartLast))
3462 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3464 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3466 var autoPopulatedUserIdList = new List<long>();
3468 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3469 if (replyToPost != null)
3471 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3473 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3474 autoPopulatedUserIdList.Add(replyToPost.UserId);
3476 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3478 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3480 statusText = statusText.Substring(screenName.Length + 2);
3481 autoPopulatedUserIdList.Add(userId);
3487 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3493 /// attachment_url に指定可能な URL が含まれていれば除去
3495 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3497 attachmentUrl = null;
3499 // attachment_url は media_id と同時に使用できない
3500 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3503 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3507 attachmentUrl = match.Value;
3510 statusText = statusText.Substring(0, match.Index);
3512 // テキストと URL の間にスペースが含まれていれば除去
3513 return statusText.TrimEnd(' ');
3516 private string FormatStatusTextExtended(string statusText)
3517 => this.FormatStatusTextExtended(statusText, out _, out _);
3520 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3522 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3524 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3526 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3528 return this.FormatStatusText(statusText);
3532 /// ツイート投稿前のフッター付与などの前処理を行います
3534 private string FormatStatusText(string statusText)
3536 statusText = statusText.Replace("\r\n", "\n");
3538 if (this.urlMultibyteSplit)
3541 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3544 if (this.settings.Common.WideSpaceConvert)
3546 // 文中の全角スペースを半角スペース1個にする
3547 statusText = statusText.Replace(" ", " ");
3550 // DM の場合はこれ以降の処理を行わない
3551 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3555 if (this.settings.Common.PostShiftEnter)
3557 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3561 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3562 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3564 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3567 if (statusText.Contains("RT @"))
3568 disableFooter = true;
3570 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3571 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3573 var mentionSelf = $"@{this.tw.Username} ";
3574 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3576 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3577 statusText = statusText.Substring(mentionSelf.Length);
3584 var hashtag = this.HashMgr.UseHash;
3585 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3587 if (this.HashMgr.IsHead)
3588 header = this.HashMgr.UseHash + " ";
3590 footer = " " + this.HashMgr.UseHash;
3595 if (this.settings.Local.UseRecommendStatus)
3598 footer += this.recommendedStatusFooter;
3600 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3602 // テキストボックスに入力されている文字列を使用する
3603 footer += " " + this.settings.Local.StatusText.Trim();
3607 statusText = header + statusText + footer;
3609 if (this.preventSmsCommand)
3611 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3612 // 参照: https://support.twitter.com/articles/14020
3614 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3615 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3617 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3618 statusText = '\u200b' + statusText;
3626 /// 投稿欄に表示する入力可能な文字数を計算します
3628 private int GetRestStatusCount(string statusText)
3630 var remainCount = this.tw.GetTextLengthRemain(statusText);
3632 var uploadService = this.GetSelectedImageService();
3633 if (uploadService != null)
3635 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3636 remainCount -= uploadService.GetReservedTextLength(1);
3642 private IMediaUploadService? GetSelectedImageService()
3643 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3646 /// 全てのタブの振り分けルールを反映し直します
3648 private void ApplyPostFilters()
3650 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3652 this.statuses.FilterAll();
3654 var listView = this.CurrentListView;
3655 using (ControlTransaction.Update(listView))
3657 this.listCache?.PurgeCache();
3658 this.listCache?.UpdateListSize();
3661 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3663 var tabPage = this.ListTab.TabPages[index];
3665 if (this.settings.Common.TabIconDisp)
3667 if (tab.UnreadCount > 0)
3668 tabPage.ImageIndex = 0;
3670 tabPage.ImageIndex = -1;
3674 if (!this.settings.Common.TabIconDisp)
3675 this.ListTab.Refresh();
3677 this.SetMainWindowTitle();
3678 this.SetStatusLabelUrl();
3682 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3683 => e.DrawDefault = true;
3685 private void MyList_HScrolled(object sender, EventArgs e)
3686 => ((DetailsListView)sender).Refresh();
3688 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3690 base.ScaleControl(factor, specified);
3692 ScaleChildControl(this.TabImage, factor);
3694 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3695 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3697 foreach (var listview in listviews)
3699 ScaleChildControl(listview, factor);
3703 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3705 var tab = this.CurrentTab;
3707 if (tab.AllCount == 0)
3709 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3713 var selectedIndex = tab.SelectedIndex;
3718 case SEARCHTYPE.NextSearch: // 次を検索
3719 if (selectedIndex != -1)
3720 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3724 case SEARCHTYPE.PrevSearch: // 前を検索
3725 if (selectedIndex != -1)
3726 startIndex = Math.Max(selectedIndex - 1, 0);
3728 startIndex = tab.AllCount - 1;
3730 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3732 if (selectedIndex != -1)
3733 startIndex = selectedIndex;
3739 Func<string, bool> stringComparer;
3742 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3744 catch (ArgumentException)
3746 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3750 var reverse = searchType == SEARCHTYPE.PrevSearch;
3751 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3752 .DefaultIfEmpty(-1).First();
3754 if (foundIndex == -1)
3756 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3760 var listView = this.CurrentListView;
3761 this.SelectListItem(listView, foundIndex);
3762 listView.EnsureVisible(foundIndex);
3765 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3766 => this.ShowSearchDialog(); // 検索メニュー
3768 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3770 var previousSearch = this.SearchDialog.ResultOptions;
3771 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3773 this.SearchDialog.Reset();
3774 this.ShowSearchDialog();
3780 previousSearch.Query,
3781 previousSearch.CaseSensitive,
3782 previousSearch.UseRegex,
3783 SEARCHTYPE.NextSearch);
3786 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3788 var previousSearch = this.SearchDialog.ResultOptions;
3789 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3791 this.SearchDialog.Reset();
3792 this.ShowSearchDialog();
3798 previousSearch.Query,
3799 previousSearch.CaseSensitive,
3800 previousSearch.UseRegex,
3801 SEARCHTYPE.PrevSearch);
3805 /// 検索ダイアログを表示し、検索を実行します
3807 private void ShowSearchDialog()
3809 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3811 this.TopMost = this.settings.Common.AlwaysTop;
3814 this.TopMost = this.settings.Common.AlwaysTop;
3816 var searchOptions = this.SearchDialog.ResultOptions!;
3817 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3819 if (searchOptions.NewTab)
3821 var tabName = Properties.Resources.SearchResults_TabName;
3825 tabName = this.statuses.MakeTabName(tabName);
3827 catch (TabException ex)
3829 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3832 var resultTab = new LocalSearchTabModel(tabName);
3833 this.AddNewTab(resultTab, startup: false);
3834 this.statuses.AddTab(resultTab);
3836 var targetTab = this.CurrentTab;
3838 Func<string, bool> stringComparer;
3841 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3843 catch (ArgumentException)
3845 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3849 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3850 if (foundIndices.Length == 0)
3852 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3856 var foundPosts = foundIndices.Select(x => targetTab[x]);
3857 foreach (var post in foundPosts)
3859 resultTab.AddPostQueue(post);
3862 this.statuses.DistributePosts();
3863 this.RefreshTimeline();
3865 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3866 this.ListTab.SelectedIndex = tabIndex;
3871 searchOptions.Query,
3872 searchOptions.CaseSensitive,
3873 searchOptions.UseRegex,
3874 SEARCHTYPE.DialogSearch);
3877 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3879 this.AddNewTabForSearch(searchOptions.Query);
3883 /// <summary>発言検索に使用するメソッドを生成します</summary>
3884 /// <exception cref="ArgumentException">
3885 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3887 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3891 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3892 var regex = new Regex(query, regexOption);
3894 return x => regex.IsMatch(x);
3898 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3900 return x => x.IndexOf(query, comparisonType) != -1;
3904 private void AboutMenuItem_Click(object sender, EventArgs e)
3906 using (var about = new TweenAboutBox())
3908 about.ShowDialog(this);
3910 this.TopMost = this.settings.Common.AlwaysTop;
3913 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3915 var bgnIdx = this.statuses.SelectedTabIndex;
3917 if (this.ImageSelector.Enabled)
3920 TabModel? foundTab = null;
3924 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3926 var unreadIndex = tab.NextUnreadIndex;
3927 if (unreadIndex != -1)
3929 this.ListTab.SelectedIndex = index;
3931 foundIndex = unreadIndex;
3936 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3937 if (foundTab == null && bgnIdx > 0)
3939 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3941 var unreadIndex = tab.NextUnreadIndex;
3942 if (unreadIndex != -1)
3944 this.ListTab.SelectedIndex = index;
3946 foundIndex = unreadIndex;
3952 DetailsListView lst;
3954 if (foundTab == null)
3956 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3957 this.ListTab.SelectedIndex = 0;
3958 var tabPage = this.ListTab.TabPages[0];
3959 var tab = this.statuses.Tabs[0];
3961 if (tab.AllCount == 0)
3964 if (this.statuses.SortOrder == SortOrder.Ascending)
3965 foundIndex = tab.AllCount - 1;
3969 lst = (DetailsListView)tabPage.Tag;
3973 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3974 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3977 this.SelectListItem(lst, foundIndex);
3979 if (this.statuses.SortMode == ComparerMode.Id)
3981 var rowHeight = lst.SmallImageList.ImageSize.Height;
3982 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3983 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3989 lst.EnsureVisible(foundIndex);
3994 lst.EnsureVisible(foundIndex);
4000 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4002 var tab = this.CurrentTab;
4003 var post = this.CurrentPost;
4004 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4005 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4008 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4009 => await this.CheckNewVersion(false);
4011 private void RunTweenUp()
4013 var pinfo = new ProcessStartInfo
4015 UseShellExecute = true,
4016 WorkingDirectory = this.settings.SettingsPath,
4017 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4018 Arguments = "\"" + Application.StartupPath + "\"",
4023 Process.Start(pinfo);
4027 MessageBox.Show("Failed to execute TweenUp3.exe.");
4031 public readonly record struct VersionInfo(
4038 /// OpenTween の最新バージョンの情報を取得します
4040 public async Task<VersionInfo> GetVersionInfoAsync()
4042 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4043 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4045 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4046 .ConfigureAwait(false);
4048 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4049 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4051 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4052 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4054 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4056 return new VersionInfo
4058 Version = Version.Parse(msgHeader[0]),
4059 DownloadUri = new Uri(msgHeader[1]),
4060 ReleaseNote = msgBody,
4064 private async Task CheckNewVersion(bool startup = false)
4066 if (ApplicationSettings.VersionInfoUrl == null)
4067 return; // 更新チェック無効化
4071 var versionInfo = await this.GetVersionInfoAsync();
4073 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4078 var msgtext = string.Format(
4079 Properties.Resources.CheckNewVersionText7,
4080 MyCommon.GetReadableVersion(),
4081 MyCommon.GetReadableVersion(versionInfo.Version));
4082 msgtext = MyCommon.ReplaceAppName(msgtext);
4086 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4087 MessageBoxButtons.OK,
4088 MessageBoxIcon.Information);
4093 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4096 using var dialog = new UpdateDialog();
4098 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4099 MyCommon.GetReadableVersion(versionInfo.Version));
4100 dialog.DetailsText = versionInfo.ReleaseNote;
4102 if (dialog.ShowDialog(this) == DialogResult.Yes)
4104 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4106 else if (dialog.SkipButtonPressed)
4108 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4109 this.MarkSettingCommonModified();
4114 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4118 Properties.Resources.CheckNewVersionText10,
4119 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4120 MessageBoxButtons.OK,
4121 MessageBoxIcon.Exclamation,
4122 MessageBoxDefaultButton.Button2);
4127 private void UpdateSelectedPost()
4129 // 件数関連の場合、タイトル即時書き換え
4130 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4131 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4132 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4133 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4135 this.SetMainWindowTitle();
4137 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4138 this.SetStatusLabelUrl();
4140 if (this.settings.Common.TabIconDisp)
4142 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4144 if (tab.UnreadCount == 0)
4146 var tabPage = this.ListTab.TabPages[index];
4147 if (tabPage.ImageIndex == 0)
4148 tabPage.ImageIndex = -1;
4154 this.ListTab.Refresh();
4157 this.DispSelectedPost();
4160 public string CreateDetailHtml(string orgdata)
4161 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4163 private void DispSelectedPost()
4164 => this.DispSelectedPost(false);
4166 private PostClass displayPost = new();
4169 /// サムネイル表示に使用する CancellationToken の生成元
4171 private CancellationTokenSource? thumbnailTokenSource = null;
4173 private void DispSelectedPost(bool forceupdate)
4175 var currentPost = this.CurrentPost;
4176 if (currentPost == null)
4179 var oldDisplayPost = this.displayPost;
4180 this.displayPost = currentPost;
4182 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4185 var loadTasks = new TaskCollection();
4186 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4188 if (this.settings.Common.PreviewEnable)
4190 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4191 oldTokenSource?.Cancel();
4193 var token = this.thumbnailTokenSource!.Token;
4194 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4198 this.SplitContainer3.Panel2Collapsed = true;
4201 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4203 .IgnoreException(x => x is OperationCanceledException)
4207 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4209 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4211 var timeout = Task.Delay(100);
4212 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4214 token.ThrowIfCancellationRequested();
4216 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4217 this.SplitContainer3.Panel2Collapsed = true;
4221 token.ThrowIfCancellationRequested();
4223 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4226 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4227 => await this.OpenApplicationWebsite();
4229 private async Task OpenApplicationWebsite()
4230 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4232 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4233 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4235 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4237 var tab = this.CurrentTab;
4238 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4240 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4241 if (pnl.Controls["comboSearch"].Focused ||
4242 pnl.Controls["comboLang"].Focused ||
4243 pnl.Controls["buttonSearch"].Focused) return;
4246 if (e.Control || e.Shift || e.Alt)
4249 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4252 e.SuppressKeyPress = true;
4255 if (asyncTask != null)
4259 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4261 private void InitializeShortcuts()
4263 this.shortcutCommands = new[]
4265 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4266 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4267 .FocusedOn(FocusedControl.ListTab)
4268 .Do(() => SendKeys.Send("{DOWN}")),
4270 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4271 .FocusedOn(FocusedControl.ListTab)
4272 .Do(() => SendKeys.Send("{UP}")),
4274 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4275 .FocusedOn(FocusedControl.ListTab)
4276 .Do(() => SendKeys.Send("{PGDN}")),
4278 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4279 .FocusedOn(FocusedControl.ListTab)
4280 .Do(() => SendKeys.Send("{PGUP}")),
4282 ShortcutCommand.Create(Keys.F1)
4283 .Do(() => this.OpenApplicationWebsite()),
4285 ShortcutCommand.Create(Keys.F3)
4286 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4288 ShortcutCommand.Create(Keys.F5)
4289 .Do(() => this.DoRefresh()),
4291 ShortcutCommand.Create(Keys.F6)
4292 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4294 ShortcutCommand.Create(Keys.F7)
4295 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4297 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4298 .NotFocusedOn(FocusedControl.StatusText)
4301 this.CurrentTab.ClearAnchor();
4302 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4305 ShortcutCommand.Create(Keys.G)
4306 .NotFocusedOn(FocusedControl.StatusText)
4309 this.CurrentTab.ClearAnchor();
4310 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4313 ShortcutCommand.Create(Keys.Right, Keys.N)
4314 .FocusedOn(FocusedControl.ListTab)
4315 .Do(() => this.GoRelPost(forward: true)),
4317 ShortcutCommand.Create(Keys.Left, Keys.P)
4318 .FocusedOn(FocusedControl.ListTab)
4319 .Do(() => this.GoRelPost(forward: false)),
4321 ShortcutCommand.Create(Keys.OemPeriod)
4322 .FocusedOn(FocusedControl.ListTab)
4323 .Do(() => this.GoAnchor()),
4325 ShortcutCommand.Create(Keys.I)
4326 .FocusedOn(FocusedControl.ListTab)
4327 .OnlyWhen(() => this.StatusText.Enabled)
4328 .Do(() => this.StatusText.Focus()),
4330 ShortcutCommand.Create(Keys.Enter)
4331 .FocusedOn(FocusedControl.ListTab)
4332 .Do(() => this.ListItemDoubleClickAction()),
4334 ShortcutCommand.Create(Keys.R)
4335 .FocusedOn(FocusedControl.ListTab)
4336 .Do(() => this.DoRefresh()),
4338 ShortcutCommand.Create(Keys.L)
4339 .FocusedOn(FocusedControl.ListTab)
4342 this.CurrentTab.ClearAnchor();
4343 this.GoPost(forward: true);
4346 ShortcutCommand.Create(Keys.H)
4347 .FocusedOn(FocusedControl.ListTab)
4350 this.CurrentTab.ClearAnchor();
4351 this.GoPost(forward: false);
4354 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4355 .FocusedOn(FocusedControl.ListTab)
4358 this.CurrentTab.ClearAnchor();
4362 ShortcutCommand.Create(Keys.S)
4363 .FocusedOn(FocusedControl.ListTab)
4366 this.CurrentTab.ClearAnchor();
4367 this.GoNextTab(forward: true);
4370 ShortcutCommand.Create(Keys.A)
4371 .FocusedOn(FocusedControl.ListTab)
4374 this.CurrentTab.ClearAnchor();
4375 this.GoNextTab(forward: false);
4378 // ] in_reply_to参照元へ戻る
4379 ShortcutCommand.Create(Keys.Oem4)
4380 .FocusedOn(FocusedControl.ListTab)
4383 this.CurrentTab.ClearAnchor();
4384 return this.GoInReplyToPostTree();
4387 // [ in_reply_toへジャンプ
4388 ShortcutCommand.Create(Keys.Oem6)
4389 .FocusedOn(FocusedControl.ListTab)
4392 this.CurrentTab.ClearAnchor();
4393 this.GoBackInReplyToPostTree();
4396 ShortcutCommand.Create(Keys.Escape)
4397 .FocusedOn(FocusedControl.ListTab)
4400 this.CurrentTab.ClearAnchor();
4401 var tab = this.CurrentTab;
4402 var tabtype = tab.TabType;
4403 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4405 this.RemoveSpecifiedTab(tab.TabName, false);
4406 this.SaveConfigsTabs();
4410 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4411 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4412 .FocusedOn(FocusedControl.ListTab)
4413 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4415 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4416 ShortcutCommand.Create(Keys.Up, Keys.Down)
4417 .FocusedOn(FocusedControl.PostBrowser)
4420 ShortcutCommand.Create(Keys.Control | Keys.R)
4421 .Do(() => this.MakeReplyText()),
4423 ShortcutCommand.Create(Keys.Control | Keys.D)
4424 .Do(() => this.DoStatusDelete()),
4426 ShortcutCommand.Create(Keys.Control | Keys.M)
4427 .Do(() => this.MakeDirectMessageText()),
4429 ShortcutCommand.Create(Keys.Control | Keys.S)
4430 .Do(() => this.FavoriteChange(favAdd: true)),
4432 ShortcutCommand.Create(Keys.Control | Keys.I)
4433 .Do(() => this.DoRepliedStatusOpen()),
4435 ShortcutCommand.Create(Keys.Control | Keys.Q)
4436 .Do(() => this.DoQuoteOfficial()),
4438 ShortcutCommand.Create(Keys.Control | Keys.B)
4439 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4441 ShortcutCommand.Create(Keys.Control | Keys.T)
4442 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4444 ShortcutCommand.Create(Keys.Control | Keys.L)
4445 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4447 ShortcutCommand.Create(Keys.Control | Keys.Y)
4448 .NotFocusedOn(FocusedControl.PostBrowser)
4449 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4451 ShortcutCommand.Create(Keys.Control | Keys.F)
4452 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4454 ShortcutCommand.Create(Keys.Control | Keys.U)
4455 .Do(() => this.ShowUserTimeline()),
4457 ShortcutCommand.Create(Keys.Control | Keys.H)
4458 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4460 ShortcutCommand.Create(Keys.Control | Keys.O)
4461 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4463 ShortcutCommand.Create(Keys.Control | Keys.E)
4464 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4466 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4467 .FocusedOn(FocusedControl.ListTab)
4468 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4470 ShortcutCommand.Create(Keys.Control | Keys.N)
4471 .FocusedOn(FocusedControl.ListTab)
4472 .Do(() => this.GoNextTab(forward: true)),
4474 ShortcutCommand.Create(Keys.Control | Keys.P)
4475 .FocusedOn(FocusedControl.ListTab)
4476 .Do(() => this.GoNextTab(forward: false)),
4478 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4479 .FocusedOn(FocusedControl.ListTab)
4480 .Do(() => this.CopyStot()),
4482 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4483 ShortcutCommand.Create(Keys.Control | Keys.D1)
4484 .FocusedOn(FocusedControl.ListTab)
4485 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4486 .Do(() => this.ListTab.SelectedIndex = 0),
4488 ShortcutCommand.Create(Keys.Control | Keys.D2)
4489 .FocusedOn(FocusedControl.ListTab)
4490 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4491 .Do(() => this.ListTab.SelectedIndex = 1),
4493 ShortcutCommand.Create(Keys.Control | Keys.D3)
4494 .FocusedOn(FocusedControl.ListTab)
4495 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4496 .Do(() => this.ListTab.SelectedIndex = 2),
4498 ShortcutCommand.Create(Keys.Control | Keys.D4)
4499 .FocusedOn(FocusedControl.ListTab)
4500 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4501 .Do(() => this.ListTab.SelectedIndex = 3),
4503 ShortcutCommand.Create(Keys.Control | Keys.D5)
4504 .FocusedOn(FocusedControl.ListTab)
4505 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4506 .Do(() => this.ListTab.SelectedIndex = 4),
4508 ShortcutCommand.Create(Keys.Control | Keys.D6)
4509 .FocusedOn(FocusedControl.ListTab)
4510 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4511 .Do(() => this.ListTab.SelectedIndex = 5),
4513 ShortcutCommand.Create(Keys.Control | Keys.D7)
4514 .FocusedOn(FocusedControl.ListTab)
4515 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4516 .Do(() => this.ListTab.SelectedIndex = 6),
4518 ShortcutCommand.Create(Keys.Control | Keys.D8)
4519 .FocusedOn(FocusedControl.ListTab)
4520 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4521 .Do(() => this.ListTab.SelectedIndex = 7),
4523 ShortcutCommand.Create(Keys.Control | Keys.D9)
4524 .FocusedOn(FocusedControl.ListTab)
4525 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4527 ShortcutCommand.Create(Keys.Control | Keys.A)
4528 .FocusedOn(FocusedControl.StatusText)
4529 .Do(() => this.StatusText.SelectAll()),
4531 ShortcutCommand.Create(Keys.Control | Keys.V)
4532 .FocusedOn(FocusedControl.StatusText)
4533 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4535 ShortcutCommand.Create(Keys.Control | Keys.Up)
4536 .FocusedOn(FocusedControl.StatusText)
4537 .Do(() => this.StatusTextHistoryBack()),
4539 ShortcutCommand.Create(Keys.Control | Keys.Down)
4540 .FocusedOn(FocusedControl.StatusText)
4541 .Do(() => this.StatusTextHistoryForward()),
4543 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4544 .FocusedOn(FocusedControl.StatusText)
4547 if (this.ListTab.SelectedIndex == 0)
4549 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4553 this.ListTab.SelectedIndex -= 1;
4555 this.StatusText.Focus();
4558 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4559 .FocusedOn(FocusedControl.StatusText)
4562 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4564 this.ListTab.SelectedIndex = 0;
4568 this.ListTab.SelectedIndex += 1;
4570 this.StatusText.Focus();
4573 ShortcutCommand.Create(Keys.Control | Keys.Y)
4574 .FocusedOn(FocusedControl.PostBrowser)
4577 var multiline = !this.settings.Local.StatusMultiline;
4578 this.settings.Local.StatusMultiline = multiline;
4579 this.MultiLineMenuItem.Checked = multiline;
4580 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4583 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4584 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4586 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4587 .Do(() => this.DoRefreshMore()),
4589 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4590 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4592 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4593 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4595 ShortcutCommand.Create(Keys.Shift | Keys.R)
4596 .NotFocusedOn(FocusedControl.StatusText)
4597 .Do(() => this.DoRefreshMore()),
4599 ShortcutCommand.Create(Keys.Shift | Keys.H)
4600 .FocusedOn(FocusedControl.ListTab)
4601 .Do(() => this.GoTopEnd(goTop: true)),
4603 ShortcutCommand.Create(Keys.Shift | Keys.L)
4604 .FocusedOn(FocusedControl.ListTab)
4605 .Do(() => this.GoTopEnd(goTop: false)),
4607 ShortcutCommand.Create(Keys.Shift | Keys.M)
4608 .FocusedOn(FocusedControl.ListTab)
4609 .Do(() => this.GoMiddle()),
4611 ShortcutCommand.Create(Keys.Shift | Keys.G)
4612 .FocusedOn(FocusedControl.ListTab)
4613 .Do(() => this.GoLast()),
4615 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4616 .FocusedOn(FocusedControl.ListTab)
4617 .Do(() => this.MoveMiddle()),
4619 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4620 .FocusedOn(FocusedControl.ListTab)
4621 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4623 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4624 .FocusedOn(FocusedControl.ListTab)
4625 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4627 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4628 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4629 .FocusedOn(FocusedControl.ListTab)
4630 .Do(() => this.GoFav(forward: true)),
4632 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4633 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4634 .FocusedOn(FocusedControl.ListTab)
4635 .Do(() => this.GoFav(forward: false)),
4637 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4638 .FocusedOn(FocusedControl.ListTab)
4639 .Do(() => this.GoBackSelectPostChain()),
4641 ShortcutCommand.Create(Keys.Alt | Keys.R)
4642 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4644 ShortcutCommand.Create(Keys.Alt | Keys.P)
4645 .OnlyWhen(() => this.CurrentPost != null)
4646 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4648 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4649 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4651 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4652 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4654 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4655 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4657 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4658 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4660 // 別タブの同じ書き込みへ(ALT+←/→)
4661 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4662 .FocusedOn(FocusedControl.ListTab)
4663 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4665 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4666 .FocusedOn(FocusedControl.ListTab)
4667 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4669 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4670 .Do(() => this.MakeReplyText(atAll: true)),
4672 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4673 .Do(() => this.CopyIdUri()),
4675 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4676 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4677 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4679 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4680 .Do(() => this.DoQuoteOfficial()),
4682 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4683 .Do(() => this.FavoriteChange(favAdd: false)),
4685 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4686 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4688 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4689 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4691 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4692 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4694 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4695 .Do(() => this.DoMoveToRTHome()),
4697 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4698 .FocusedOn(FocusedControl.StatusText)
4701 var tab = this.CurrentTab;
4702 var selectedIndex = tab.SelectedIndex;
4703 if (selectedIndex != -1 && selectedIndex > 0)
4705 var listView = this.CurrentListView;
4706 var idx = selectedIndex - 1;
4707 this.SelectListItem(listView, idx);
4708 listView.EnsureVisible(idx);
4712 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4713 .FocusedOn(FocusedControl.StatusText)
4716 var tab = this.CurrentTab;
4717 var selectedIndex = tab.SelectedIndex;
4718 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4720 var listView = this.CurrentListView;
4721 var idx = selectedIndex + 1;
4722 this.SelectListItem(listView, idx);
4723 listView.EnsureVisible(idx);
4727 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4728 .FocusedOn(FocusedControl.StatusText)
4731 if (this.StatusText.SelectionStart > 0)
4733 var endidx = this.StatusText.SelectionStart - 1;
4735 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4737 var c = this.StatusText.Text[i];
4738 if (char.IsLetterOrDigit(c) || c == '_')
4744 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4745 var cnt = this.AtIdSupl.ItemCount;
4746 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4747 if (this.AtIdSupl.ItemCount != cnt)
4748 this.MarkSettingAtIdModified();
4752 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4753 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4763 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4764 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4765 .FocusedOn(FocusedControl.ListTab)
4766 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4768 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4769 .FocusedOn(FocusedControl.ListTab)
4770 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4772 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4773 .FocusedOn(FocusedControl.ListTab)
4774 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4776 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4777 .FocusedOn(FocusedControl.ListTab)
4778 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4780 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4781 .FocusedOn(FocusedControl.ListTab)
4782 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4784 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4785 .FocusedOn(FocusedControl.ListTab)
4786 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4788 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4789 .FocusedOn(FocusedControl.ListTab)
4790 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4792 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4793 .FocusedOn(FocusedControl.ListTab)
4794 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4796 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4797 .FocusedOn(FocusedControl.ListTab)
4798 .Do(() => this.SetSortLastColumn()),
4800 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4801 .FocusedOn(FocusedControl.ListTab)
4802 .Do(() => this.FavoritesRetweetOfficial()),
4804 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4805 .FocusedOn(FocusedControl.ListTab)
4806 .Do(() => this.FavoritesRetweetUnofficial()),
4808 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4809 .FocusedOn(FocusedControl.ListTab)
4810 .Do(() => this.OpenUserAppointUrl()),
4812 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4813 .FocusedOn(FocusedControl.PostBrowser)
4814 .Do(() => this.DoReTweetUnofficial()),
4816 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4817 .OnlyWhen(() => this.ExistCurrentPost)
4818 .Do(() => this.tweetDetailsView.DoTranslation()),
4820 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4821 .Do(() => this.DoReTweetUnofficial()),
4823 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4824 .Do(() => this.CopyUserId()),
4826 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4827 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4829 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4830 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4832 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4833 .FocusedOn(FocusedControl.ListTab)
4834 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4835 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4839 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4841 // Task を返す非同期処理があれば asyncTask に代入する
4844 // ShortcutCommand に対応しているコマンドはここで処理される
4845 foreach (var command in this.shortcutCommands)
4847 if (command.IsMatch(keyData, focusedOn))
4849 asyncTask = command.RunCommand();
4850 return command.PreventDefault;
4857 private void GoNextTab(bool forward)
4859 var idx = this.statuses.SelectedTabIndex;
4860 var tabCount = this.statuses.Tabs.Count;
4864 if (idx > tabCount - 1) idx = 0;
4869 if (idx < 0) idx = tabCount - 1;
4871 this.ListTab.SelectedIndex = idx;
4874 private void CopyStot()
4876 var sb = new StringBuilder();
4877 var tab = this.CurrentTab;
4878 var isProtected = false;
4879 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4880 foreach (var post in tab.SelectedPosts)
4882 if (post.IsDeleted) continue;
4885 if (post.RetweetedId != null)
4886 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4888 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4892 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4897 MessageBox.Show(Properties.Resources.CopyStotText1);
4901 var clstr = sb.ToString();
4904 Clipboard.SetDataObject(clstr, false, 5, 100);
4906 catch (Exception ex)
4908 MessageBox.Show(ex.Message);
4913 private void CopyIdUri()
4915 var tab = this.CurrentTab;
4916 if (tab == null || tab is DirectMessagesTabModel)
4919 var copyUrls = new List<string>();
4920 foreach (var post in tab.SelectedPosts)
4921 copyUrls.Add(MyCommon.GetStatusUrl(post));
4923 if (copyUrls.Count == 0)
4928 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4930 catch (ExternalException ex)
4932 MessageBox.Show(ex.Message);
4936 private void GoFav(bool forward)
4938 var tab = this.CurrentTab;
4939 if (tab.AllCount == 0)
4942 var selectedIndex = tab.SelectedIndex;
4950 if (selectedIndex == -1)
4956 fIdx = selectedIndex + 1;
4957 if (fIdx > tab.AllCount - 1)
4960 toIdx = tab.AllCount;
4965 if (selectedIndex == -1)
4967 fIdx = tab.AllCount - 1;
4971 fIdx = selectedIndex - 1;
4979 for (var idx = fIdx; idx != toIdx; idx += stp)
4983 var listView = this.CurrentListView;
4984 this.SelectListItem(listView, idx);
4985 listView.EnsureVisible(idx);
4991 private void GoSamePostToAnotherTab(bool left)
4993 var tab = this.CurrentTab;
4995 // Directタブは対象外(見つかるはずがない)
4996 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4999 var selectedStatusId = tab.SelectedStatusId;
5000 if (selectedStatusId == null)
5003 int fIdx, toIdx, stp;
5008 if (this.ListTab.SelectedIndex == 0)
5014 fIdx = this.ListTab.SelectedIndex - 1;
5022 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5028 fIdx = this.ListTab.SelectedIndex + 1;
5030 toIdx = this.ListTab.TabCount;
5034 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5036 var targetTab = this.statuses.Tabs[tabidx];
5039 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5042 var foundIndex = targetTab.IndexOf(selectedStatusId);
5043 if (foundIndex != -1)
5045 this.ListTab.SelectedIndex = tabidx;
5046 var listView = this.CurrentListView;
5047 this.SelectListItem(listView, foundIndex);
5048 listView.EnsureVisible(foundIndex);
5054 private void GoPost(bool forward)
5056 var tab = this.CurrentTab;
5057 var currentPost = this.CurrentPost;
5059 if (currentPost == null)
5062 var selectedIndex = tab.SelectedIndex;
5064 int fIdx, toIdx, stp;
5068 fIdx = selectedIndex + 1;
5069 if (fIdx > tab.AllCount - 1) return;
5070 toIdx = tab.AllCount;
5075 fIdx = selectedIndex - 1;
5076 if (fIdx < 0) return;
5082 if (currentPost.RetweetedBy == null)
5084 name = currentPost.ScreenName;
5088 name = currentPost.RetweetedBy;
5090 for (var idx = fIdx; idx != toIdx; idx += stp)
5092 var post = tab[idx];
5093 if (post.RetweetedId == null)
5095 if (post.ScreenName == name)
5097 var listView = this.CurrentListView;
5098 this.SelectListItem(listView, idx);
5099 listView.EnsureVisible(idx);
5105 if (post.RetweetedBy == name)
5107 var listView = this.CurrentListView;
5108 this.SelectListItem(listView, idx);
5109 listView.EnsureVisible(idx);
5116 private void GoRelPost(bool forward)
5118 var tab = this.CurrentTab;
5119 var selectedIndex = tab.SelectedIndex;
5121 if (selectedIndex == -1)
5124 int fIdx, toIdx, stp;
5128 fIdx = selectedIndex + 1;
5129 if (fIdx > tab.AllCount - 1) return;
5130 toIdx = tab.AllCount;
5135 fIdx = selectedIndex - 1;
5136 if (fIdx < 0) return;
5141 var anchorPost = tab.AnchorPost;
5142 if (anchorPost == null)
5144 var currentPost = this.CurrentPost;
5145 if (currentPost == null)
5148 anchorPost = currentPost;
5149 tab.AnchorPost = currentPost;
5152 for (var idx = fIdx; idx != toIdx; idx += stp)
5154 var post = tab[idx];
5155 if (post.ScreenName == anchorPost.ScreenName ||
5156 post.RetweetedBy == anchorPost.ScreenName ||
5157 post.ScreenName == anchorPost.RetweetedBy ||
5158 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5159 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5160 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5161 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5162 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5164 var listView = this.CurrentListView;
5165 this.SelectListItem(listView, idx);
5166 listView.EnsureVisible(idx);
5172 private void GoAnchor()
5174 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5175 if (anchorStatusId == null)
5178 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5182 var listView = this.CurrentListView;
5183 this.SelectListItem(listView, idx);
5184 listView.EnsureVisible(idx);
5187 private void GoTopEnd(bool goTop)
5189 var listView = this.CurrentListView;
5190 if (listView.VirtualListSize == 0)
5198 item = listView.GetItemAt(0, 25);
5206 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5208 idx = listView.VirtualListSize - 1;
5212 this.SelectListItem(listView, idx);
5215 private void GoMiddle()
5217 var listView = this.CurrentListView;
5218 if (listView.VirtualListSize == 0)
5226 item = listView.GetItemAt(0, 0);
5236 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5239 idx2 = listView.VirtualListSize - 1;
5245 idx3 = (idx1 + idx2) / 2;
5247 this.SelectListItem(listView, idx3);
5250 private void GoLast()
5252 var listView = this.CurrentListView;
5253 if (listView.VirtualListSize == 0) return;
5255 if (this.statuses.SortOrder == SortOrder.Ascending)
5257 this.SelectListItem(listView, listView.VirtualListSize - 1);
5258 listView.EnsureVisible(listView.VirtualListSize - 1);
5262 this.SelectListItem(listView, 0);
5263 listView.EnsureVisible(0);
5267 private void MoveTop()
5269 var listView = this.CurrentListView;
5270 if (listView.SelectedIndices.Count == 0) return;
5271 var idx = listView.SelectedIndices[0];
5272 if (this.statuses.SortOrder == SortOrder.Ascending)
5274 listView.EnsureVisible(listView.VirtualListSize - 1);
5278 listView.EnsureVisible(0);
5280 listView.EnsureVisible(idx);
5283 private async Task GoInReplyToPostTree()
5285 var curTabClass = this.CurrentTab;
5286 var currentPost = this.CurrentPost;
5288 if (currentPost == null)
5291 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5295 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5297 currentPost = currentPost with
5299 InReplyToStatusId = post.InReplyToStatusId,
5300 InReplyToUser = post.InReplyToUser,
5301 IsReply = post.IsReply,
5303 curTabClass.ReplacePost(currentPost);
5304 this.listCache?.PurgeCache();
5306 var index = curTabClass.SelectedIndex;
5307 this.CurrentListView.RedrawItems(index, index, false);
5309 catch (WebApiException ex)
5311 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5315 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5317 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5319 this.replyChains = new Stack<ReplyChain>();
5321 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5324 string inReplyToTabName;
5325 var inReplyToId = currentPost.InReplyToStatusId;
5326 var inReplyToUser = currentPost.InReplyToUser;
5328 var inReplyToPosts = from tab in this.statuses.Tabs
5329 orderby tab != curTabClass
5330 from post in tab.Posts.Values
5331 where post.StatusId == inReplyToId
5332 let index = tab.IndexOf(post.StatusId)
5334 select new { Tab = tab, Index = index };
5336 var inReplyPost = inReplyToPosts.FirstOrDefault();
5337 if (inReplyPost == null)
5341 await Task.Run(async () =>
5343 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5344 .ConfigureAwait(false);
5347 this.statuses.AddPost(post);
5348 this.statuses.DistributePosts();
5351 catch (WebApiException ex)
5353 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5354 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5358 this.RefreshTimeline();
5360 inReplyPost = inReplyToPosts.FirstOrDefault();
5361 if (inReplyPost == null)
5363 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5367 inReplyToTabName = inReplyPost.Tab.TabName;
5368 inReplyToIndex = inReplyPost.Index;
5370 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5371 var tabPage = this.ListTab.TabPages[tabIndex];
5372 var listView = (DetailsListView)tabPage.Tag;
5374 if (this.CurrentTabName != inReplyToTabName)
5376 this.ListTab.SelectedIndex = tabIndex;
5379 this.SelectListItem(listView, inReplyToIndex);
5380 listView.EnsureVisible(inReplyToIndex);
5383 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5385 var curTabClass = this.CurrentTab;
5386 var currentPost = this.CurrentPost;
5388 if (currentPost == null)
5393 if (currentPost.InReplyToStatusId != null)
5395 var posts = from t in this.statuses.Tabs
5397 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5398 let indexOf = t.IndexOf(p.Value.StatusId)
5400 orderby isForward ? indexOf : indexOf * -1
5401 orderby t != curTabClass
5402 select new { Tab = t, Post = p.Value, Index = indexOf };
5405 var postList = posts.ToList();
5406 for (var i = postList.Count - 1; i >= 0; i--)
5409 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5411 postList.RemoveAt(index);
5414 var currentIndex = this.CurrentTab.SelectedIndex;
5415 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5416 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5417 if (post == null) post = postList.First();
5418 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5419 this.ListTab.SelectedIndex = tabIndex;
5420 var listView = this.CurrentListView;
5421 this.SelectListItem(listView, post.Index);
5422 listView.EnsureVisible(post.Index);
5424 catch (InvalidOperationException)
5432 if (this.replyChains == null || this.replyChains.Count < 1)
5434 var posts = from t in this.statuses.Tabs
5436 where p.Value.InReplyToStatusId == currentPost.StatusId
5437 let indexOf = t.IndexOf(p.Value.StatusId)
5440 orderby t != curTabClass
5441 select new { Tab = t, Index = indexOf };
5444 var post = posts.First();
5445 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5446 this.ListTab.SelectedIndex = tabIndex;
5447 var listView = this.CurrentListView;
5448 this.SelectListItem(listView, post.Index);
5449 listView.EnsureVisible(post.Index);
5451 catch (InvalidOperationException)
5458 var chainHead = this.replyChains.Pop();
5459 if (chainHead.InReplyToId == currentPost.StatusId)
5461 var tab = chainHead.OriginalTab;
5462 if (!this.statuses.Tabs.Contains(tab))
5464 this.replyChains = null;
5468 var idx = tab.IndexOf(chainHead.OriginalId);
5471 this.replyChains = null;
5475 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5478 this.ListTab.SelectedIndex = tabIndex;
5482 this.replyChains = null;
5484 var listView = this.CurrentListView;
5485 this.SelectListItem(listView, idx);
5486 listView.EnsureVisible(idx);
5492 this.replyChains = null;
5493 this.GoBackInReplyToPostTree(parallel);
5499 private void GoBackSelectPostChain()
5501 if (this.selectPostChains.Count > 1)
5504 TabModel? foundTab = null;
5510 this.selectPostChains.Pop();
5511 var (tab, post) = this.selectPostChains.Peek();
5513 if (!this.statuses.Tabs.Contains(tab))
5514 continue; // 該当タブが存在しないので無視
5518 idx = tab.IndexOf(post.StatusId);
5519 if (idx == -1) continue; // 該当ポストが存在しないので無視
5524 this.selectPostChains.Pop();
5526 catch (InvalidOperationException)
5532 while (this.selectPostChains.Count > 1);
5534 if (foundTab == null)
5537 // 履歴が残り1つであればクリアしておく
5538 if (this.selectPostChains.Count == 1)
5539 this.selectPostChains.Clear();
5543 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5544 var tabPage = this.ListTab.TabPages[tabIndex];
5545 var lst = (DetailsListView)tabPage.Tag;
5546 this.ListTab.SelectedIndex = tabIndex;
5550 this.SelectListItem(lst, idx);
5551 lst.EnsureVisible(idx);
5557 private void PushSelectPostChain()
5559 var currentTab = this.CurrentTab;
5560 var currentPost = this.CurrentPost;
5562 var count = this.selectPostChains.Count;
5565 var (tab, post) = this.selectPostChains.Peek();
5566 if (tab == currentTab)
5568 if (post == currentPost) return; // 最新の履歴と同一
5569 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5572 if (count >= 2500) this.TrimPostChain();
5573 this.selectPostChains.Push((currentTab, currentPost));
5576 private void TrimPostChain()
5578 if (this.selectPostChains.Count <= 2000) return;
5579 var p = new Stack<(TabModel, PostClass?)>(2000);
5580 for (var i = 0; i < 2000; i++)
5582 p.Push(this.selectPostChains.Pop());
5584 this.selectPostChains.Clear();
5585 for (var i = 0; i < 2000; i++)
5587 this.selectPostChains.Push(p.Pop());
5591 private bool GoStatus(PostId statusId)
5593 var tab = this.statuses.Tabs
5594 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5595 .Where(x => x.Contains(statusId))
5601 var index = tab.IndexOf(statusId);
5603 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5604 this.ListTab.SelectedIndex = tabIndex;
5606 var listView = this.CurrentListView;
5607 this.SelectListItem(listView, index);
5608 listView.EnsureVisible(index);
5613 private bool GoDirectMessage(PostId statusId)
5615 var tab = this.statuses.DirectMessageTab;
5616 var index = tab.IndexOf(statusId);
5621 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5622 this.ListTab.SelectedIndex = tabIndex;
5624 var listView = this.CurrentListView;
5625 this.SelectListItem(listView, index);
5626 listView.EnsureVisible(index);
5631 private void MyList_MouseClick(object sender, MouseEventArgs e)
5632 => this.CurrentTab.ClearAnchor();
5634 private void StatusText_Enter(object sender, EventArgs e)
5636 // フォーカスの戻り先を StatusText に設定
5637 this.Tag = this.StatusText;
5638 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5641 public Color InputBackColor
5642 => this.themeManager.ColorInputBackcolor;
5644 private void StatusText_Leave(object sender, EventArgs e)
5646 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5647 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5648 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5651 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5653 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5656 e.SuppressKeyPress = true;
5659 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5661 if (asyncTask != null)
5665 private void SaveConfigsAll(bool ifModified)
5669 this.SaveConfigsCommon();
5670 this.SaveConfigsLocal();
5671 this.SaveConfigsTabs();
5672 this.SaveConfigsAtId();
5676 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5677 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5678 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5682 private void SaveConfigsAtId()
5684 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5686 this.ModifySettingAtId = false;
5687 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5688 this.settings.SaveAtIdList();
5691 private void SaveConfigsCommon()
5693 if (this.ignoreConfigSave) return;
5695 this.ModifySettingCommon = false;
5696 lock (this.syncObject)
5698 this.settings.Common.UserName = this.tw.Username;
5699 this.settings.Common.UserId = this.tw.UserId;
5700 this.settings.Common.Token = this.tw.AccessToken;
5701 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5702 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5703 this.settings.Common.SortColumn = this.statuses.SortMode switch
5705 ComparerMode.Nickname => 1, // ニックネーム
5706 ComparerMode.Data => 2, // 本文
5707 ComparerMode.Id => 3, // 時刻=発言Id
5708 ComparerMode.Name => 4, // 名前
5709 ComparerMode.Source => 7, // Source
5710 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5712 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5713 if (this.HashMgr.IsPermanent)
5715 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5719 this.settings.Common.HashSelected = "";
5721 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5722 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5723 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5724 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5725 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5727 this.settings.SaveCommon();
5731 private void SaveConfigsLocal()
5733 if (this.ignoreConfigSave) return;
5734 lock (this.syncObject)
5736 this.ModifySettingLocal = false;
5737 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5738 this.settings.Local.FormSize = this.mySize;
5739 this.settings.Local.FormLocation = this.myLoc;
5740 this.settings.Local.SplitterDistance = this.mySpDis;
5741 this.settings.Local.PreviewDistance = this.mySpDis3;
5742 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5743 this.settings.Local.StatusTextHeight = this.mySpDis2;
5745 if (this.ignoreConfigSave) return;
5746 this.settings.SaveLocal();
5750 private void SaveConfigsTabs()
5752 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5754 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5756 foreach (var tab in tabs)
5758 if (!tab.IsPermanentTabType)
5761 var tabSetting = new SettingTabs.SettingTabItem
5763 TabName = tab.TabName,
5764 TabType = tab.TabType,
5765 UnreadManage = tab.UnreadManage,
5766 Protected = tab.Protected,
5767 Notify = tab.Notify,
5768 SoundFile = tab.SoundFile,
5773 case FilterTabModel filterTab:
5774 tabSetting.FilterArray = filterTab.FilterArray;
5776 case UserTimelineTabModel userTab:
5777 tabSetting.User = userTab.ScreenName;
5778 tabSetting.UserId = userTab.UserId;
5780 case PublicSearchTabModel searchTab:
5781 tabSetting.SearchWords = searchTab.SearchWords;
5782 tabSetting.SearchLang = searchTab.SearchLang;
5784 case ListTimelineTabModel listTab:
5785 tabSetting.ListInfo = listTab.ListInfo;
5789 tabSettingList.Add(tabSetting);
5792 this.settings.Tabs.Tabs = tabSettingList;
5793 this.settings.SaveTabs();
5796 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5798 static void ShowFormatErrorDialog(IWin32Window owner)
5802 Properties.Resources.OpenURL_InvalidFormat,
5803 Properties.Resources.OpenURL_Caption,
5804 MessageBoxButtons.OK,
5805 MessageBoxIcon.Error
5809 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5810 if (ret != DialogResult.OK)
5813 var match = Twitter.StatusUrlRegex.Match(inputText);
5816 ShowFormatErrorDialog(this);
5822 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5823 await this.OpenRelatedTab(statusId);
5825 catch (OverflowException)
5827 ShowFormatErrorDialog(this);
5829 catch (TabException ex)
5831 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5835 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5837 var tab = this.CurrentTab;
5839 var rslt = MessageBox.Show(
5840 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5841 Properties.Resources.SaveLogMenuItem_ClickText2,
5842 MessageBoxButtons.YesNoCancel,
5843 MessageBoxIcon.Question);
5844 if (rslt == DialogResult.Cancel) return;
5846 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5847 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5848 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5849 this.SaveFileDialog1.FilterIndex = 0;
5850 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5851 this.SaveFileDialog1.RestoreDirectory = true;
5853 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5855 if (!this.SaveFileDialog1.ValidateNames) return;
5856 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5857 if (rslt == DialogResult.Yes)
5860 for (var idx = 0; idx < tab.AllCount; idx++)
5862 var post = tab[idx];
5865 protect = "Protect";
5866 sw.WriteLine(post.Nickname + "\t" +
5867 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5868 post.CreatedAt.ToLocalTimeString() + "\t" +
5869 post.ScreenName + "\t" +
5870 post.StatusId.Id + "\t" +
5871 post.ImageUrl + "\t" +
5872 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5878 foreach (var post in this.CurrentTab.SelectedPosts)
5882 protect = "Protect";
5883 sw.WriteLine(post.Nickname + "\t" +
5884 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5885 post.CreatedAt.ToLocalTimeString() + "\t" +
5886 post.ScreenName + "\t" +
5887 post.StatusId.Id + "\t" +
5888 post.ImageUrl + "\t" +
5889 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5894 this.TopMost = this.settings.Common.AlwaysTop;
5897 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5901 using (var inputName = new InputTabName())
5903 inputName.TabName = origTabName;
5904 inputName.ShowDialog();
5905 if (inputName.DialogResult == DialogResult.Cancel) return false;
5906 newTabName = inputName.TabName;
5908 this.TopMost = this.settings.Common.AlwaysTop;
5909 if (!MyCommon.IsNullOrEmpty(newTabName))
5912 if (this.statuses.ContainsTab(newTabName))
5914 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5915 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5919 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5920 var tabPage = this.ListTab.TabPages[tabIndex];
5923 if (tabPage != null)
5924 tabPage.Text = newTabName;
5926 this.statuses.RenameTab(origTabName, newTabName);
5928 var state = this.listViewState[origTabName];
5929 this.listViewState.Remove(origTabName);
5930 this.listViewState[newTabName] = state;
5932 this.SaveConfigsCommon();
5933 this.SaveConfigsTabs();
5934 this.rclickTabName = newTabName;
5943 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5945 if (e.Button == MouseButtons.Middle)
5947 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5949 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5951 this.RemoveSpecifiedTab(tab.TabName, true);
5952 this.SaveConfigsTabs();
5959 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5960 => this.TabRename(this.CurrentTabName, out _);
5962 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5964 if (this.settings.Common.TabMouseLock) return;
5965 if (e.Button == MouseButtons.Left)
5967 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5969 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5971 this.tabDrag = true;
5972 this.tabMouseDownPoint = e.Location;
5979 this.tabDrag = false;
5983 private void ListTab_DragEnter(object sender, DragEventArgs e)
5985 if (e.Data.GetDataPresent(typeof(TabPage)))
5986 e.Effect = DragDropEffects.Move;
5988 e.Effect = DragDropEffects.None;
5991 private void ListTab_DragDrop(object sender, DragEventArgs e)
5993 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5995 this.tabDrag = false;
5998 var cpos = new Point(e.X, e.Y);
5999 var spos = this.ListTab.PointToClient(cpos);
6000 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6002 var rect = this.ListTab.GetTabRect(index);
6003 if (rect.Contains(spos))
6006 if (spos.X <= (rect.Left + rect.Right) / 2)
6015 // タブのないところにドロップ->最後尾へ移動
6016 if (MyCommon.IsNullOrEmpty(tn))
6018 var lastTab = this.statuses.Tabs.Last();
6019 tn = lastTab.TabName;
6023 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6024 if (tp.Text == tn) return;
6026 this.ReOrderTab(tp.Text, tn, bef);
6029 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6031 var baseIndex = this.GetTabPageIndex(baseTabText);
6032 if (baseIndex == -1)
6035 var targetIndex = this.GetTabPageIndex(targetTabText);
6036 if (targetIndex == -1)
6039 using (ControlTransaction.Layout(this.ListTab))
6041 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6042 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6043 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6044 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6046 var tab = this.statuses.Tabs[targetIndex];
6047 var tabPage = this.ListTab.TabPages[targetIndex];
6049 this.ListTab.TabPages.Remove(tabPage);
6051 if (targetIndex < baseIndex)
6054 if (!isBeforeBaseTab)
6057 this.statuses.MoveTab(baseIndex, tab);
6059 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6062 this.SaveConfigsTabs();
6065 private void MakeDirectMessageText()
6067 var selectedPosts = this.CurrentTab.SelectedPosts;
6068 if (selectedPosts.Length > 1)
6071 var post = selectedPosts.Single();
6072 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6074 this.inReplyTo = null;
6075 this.StatusText.Text = text;
6076 this.StatusText.SelectionStart = text.Length;
6077 this.StatusText.Focus();
6080 private void MakeReplyText(bool atAll = false)
6082 var selectedPosts = this.CurrentTab.SelectedPosts;
6083 if (selectedPosts.Any(x => x.IsDm))
6085 this.MakeDirectMessageText();
6089 if (selectedPosts.Length == 1)
6091 var post = selectedPosts.Single();
6092 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6093 var inReplyToScreenName = post.ScreenName;
6094 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6098 this.inReplyTo = null;
6101 var selfScreenName = this.tw.Username;
6102 var targetScreenNames = new List<string>();
6103 foreach (var post in selectedPosts)
6105 if (post.ScreenName != selfScreenName)
6106 targetScreenNames.Add(post.ScreenName);
6110 foreach (var (_, screenName) in post.ReplyToList)
6112 if (screenName != selfScreenName)
6113 targetScreenNames.Add(screenName);
6118 if (this.inReplyTo != null)
6120 var (_, screenName) = this.inReplyTo.Value;
6121 if (screenName == selfScreenName)
6122 targetScreenNames.Insert(0, screenName);
6125 var text = this.StatusText.Text;
6126 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6128 var atText = $"@{screenName} ";
6129 if (!text.Contains(atText))
6130 text = atText + text;
6133 this.StatusText.Text = text;
6134 this.StatusText.SelectionStart = text.Length;
6135 this.StatusText.Focus();
6138 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6139 => this.tabDrag = false;
6141 private int iconCnt = 0;
6142 private int blinkCnt = 0;
6143 private bool blink = false;
6145 private void RefreshTasktrayIcon()
6147 void EnableTasktrayAnimation()
6148 => this.TimerRefreshIcon.Enabled = true;
6150 void DisableTasktrayAnimation()
6151 => this.TimerRefreshIcon.Enabled = false;
6153 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6157 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6160 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6161 this.myStatusError = false;
6162 EnableTasktrayAnimation();
6166 var replyIconType = this.settings.Common.ReplyIconState;
6168 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6170 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6171 if (replyTab != null && replyTab.UnreadCount > 0)
6175 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6178 if (this.blinkCnt > 10)
6181 if (this.blinkCnt == 0)
6182 this.blink = !this.blink;
6184 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6185 EnableTasktrayAnimation();
6189 DisableTasktrayAnimation();
6195 // 優先度:リプライ→エラー→オフライン→アイドル
6196 // エラーは更新アイコンでクリアされる
6197 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6198 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6199 else if (this.myStatusError)
6200 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6201 else if (this.myStatusOnline)
6202 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6204 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6207 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6208 => this.RefreshTasktrayIcon(); // 200ms
6210 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6212 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6213 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6214 this.rclickTabName = this.CurrentTabName;
6216 if (this.statuses == null) return;
6217 if (this.statuses.Tabs == null) return;
6219 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6222 this.NotifyDispMenuItem.Checked = tb.Notify;
6223 this.NotifyTbMenuItem.Checked = tb.Notify;
6225 this.soundfileListup = true;
6226 this.SoundFileComboBox.Items.Clear();
6227 this.SoundFileTbComboBox.Items.Clear();
6228 this.SoundFileComboBox.Items.Add("");
6229 this.SoundFileTbComboBox.Items.Add("");
6230 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6231 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6233 oDir = oDir.GetDirectories("Sounds")[0];
6235 foreach (var oFile in oDir.GetFiles("*.wav"))
6237 this.SoundFileComboBox.Items.Add(oFile.Name);
6238 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6240 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6241 if (idx == -1) idx = 0;
6242 this.SoundFileComboBox.SelectedIndex = idx;
6243 this.SoundFileTbComboBox.SelectedIndex = idx;
6244 this.soundfileListup = false;
6245 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6246 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6248 this.TabMenuControl(this.rclickTabName);
6251 private void TabMenuControl(string tabName)
6253 var tabInfo = this.statuses.GetTabByName(tabName)!;
6255 this.FilterEditMenuItem.Enabled = true;
6256 this.EditRuleTbMenuItem.Enabled = true;
6258 if (tabInfo.IsDefaultTabType)
6260 this.ProtectTabMenuItem.Enabled = false;
6261 this.ProtectTbMenuItem.Enabled = false;
6265 this.ProtectTabMenuItem.Enabled = true;
6266 this.ProtectTbMenuItem.Enabled = true;
6269 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6271 this.ProtectTabMenuItem.Checked = true;
6272 this.ProtectTbMenuItem.Checked = true;
6273 this.DeleteTabMenuItem.Enabled = false;
6274 this.DeleteTbMenuItem.Enabled = false;
6278 this.ProtectTabMenuItem.Checked = false;
6279 this.ProtectTbMenuItem.Checked = false;
6280 this.DeleteTabMenuItem.Enabled = true;
6281 this.DeleteTbMenuItem.Enabled = true;
6285 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6287 var checkState = ((ToolStripMenuItem)sender).Checked;
6290 this.ProtectTbMenuItem.Checked = checkState;
6291 this.ProtectTabMenuItem.Checked = checkState;
6294 this.DeleteTabMenuItem.Enabled = !checkState;
6295 this.DeleteTbMenuItem.Enabled = !checkState;
6297 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6298 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6300 this.SaveConfigsTabs();
6303 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6305 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6306 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6308 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6309 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6311 this.SaveConfigsTabs();
6314 public void ChangeTabUnreadManage(string tabName, bool isManage)
6316 var idx = this.GetTabPageIndex(tabName);
6320 var tab = this.statuses.Tabs[tabName];
6321 tab.UnreadManage = isManage;
6323 if (this.settings.Common.TabIconDisp)
6325 var tabPage = this.ListTab.TabPages[idx];
6326 if (tab.UnreadCount > 0)
6327 tabPage.ImageIndex = 0;
6329 tabPage.ImageIndex = -1;
6332 if (this.CurrentTabName == tabName)
6334 this.listCache?.PurgeCache();
6335 this.CurrentListView.Refresh();
6338 this.SetMainWindowTitle();
6339 this.SetStatusLabelUrl();
6340 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6343 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6345 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6346 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6348 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6350 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6352 this.SaveConfigsTabs();
6355 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6357 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6359 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6361 this.SaveConfigsTabs();
6364 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6366 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6367 this.rclickTabName = this.CurrentTabName;
6369 this.RemoveSpecifiedTab(this.rclickTabName, true);
6370 this.SaveConfigsTabs();
6373 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6375 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6377 using (var fltDialog = new FilterDialog())
6379 fltDialog.Owner = this;
6380 fltDialog.SetCurrent(this.rclickTabName);
6381 fltDialog.ShowDialog(this);
6383 this.TopMost = this.settings.Common.AlwaysTop;
6385 this.ApplyPostFilters();
6386 this.SaveConfigsTabs();
6389 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6391 string? tabName = null;
6392 MyCommon.TabUsageType tabUsage;
6393 using (var inputName = new InputTabName())
6395 inputName.TabName = this.statuses.MakeTabName("MyTab");
6396 inputName.IsShowUsage = true;
6397 inputName.ShowDialog();
6398 if (inputName.DialogResult == DialogResult.Cancel) return;
6399 tabName = inputName.TabName;
6400 tabUsage = inputName.Usage;
6402 this.TopMost = this.settings.Common.AlwaysTop;
6403 if (!MyCommon.IsNullOrEmpty(tabName))
6406 ListElement? list = null;
6407 if (tabUsage == MyCommon.TabUsageType.Lists)
6409 using var listAvail = new ListAvailable();
6410 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6412 if (listAvail.SelectedList == null)
6414 list = listAvail.SelectedList;
6420 case MyCommon.TabUsageType.UserDefined:
6421 tab = new FilterTabModel(tabName);
6423 case MyCommon.TabUsageType.PublicSearch:
6424 tab = new PublicSearchTabModel(tabName);
6426 case MyCommon.TabUsageType.Lists:
6427 tab = new ListTimelineTabModel(tabName, list!);
6433 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6435 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6436 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6441 this.SaveConfigsTabs();
6443 var tabIndex = this.statuses.Tabs.Count - 1;
6445 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6447 this.ListTab.SelectedIndex = tabIndex;
6448 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6450 if (tabUsage == MyCommon.TabUsageType.Lists)
6452 this.ListTab.SelectedIndex = tabIndex;
6453 await this.RefreshTabAsync(this.CurrentTab);
6459 private void TabMenuItem_Click(object sender, EventArgs e)
6462 foreach (var post in this.CurrentTab.SelectedPosts)
6465 if (!this.SelectTab(out var tab))
6468 using (var fltDialog = new FilterDialog())
6470 fltDialog.Owner = this;
6471 fltDialog.SetCurrent(tab.TabName);
6473 if (post.RetweetedBy == null)
6475 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6479 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6481 fltDialog.ShowDialog(this);
6484 this.TopMost = this.settings.Common.AlwaysTop;
6487 this.ApplyPostFilters();
6488 this.SaveConfigsTabs();
6491 protected override bool ProcessDialogKey(Keys keyData)
6493 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6494 if ((keyData & Keys.KeyCode) == Keys.Enter)
6496 if (this.StatusText.Focused)
6498 var newLine = false;
6501 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6503 if (this.StatusText.Multiline)
6505 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6507 if ((keyData & Keys.Control) == Keys.Control) post = true;
6511 if ((keyData & Keys.Control) == Keys.Control) post = true;
6514 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6516 if (this.StatusText.Multiline)
6518 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6520 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6524 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6529 if (this.StatusText.Multiline)
6531 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6533 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6534 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6538 if (((keyData & Keys.Shift) == Keys.Shift) ||
6539 (((keyData & Keys.Control) != Keys.Control) &&
6540 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6546 var pos1 = this.StatusText.SelectionStart;
6547 if (this.StatusText.SelectionLength > 0)
6549 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6551 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6552 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6557 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6563 var tab = this.CurrentTab;
6564 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6566 var tabPage = this.CurrentTabPage;
6567 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6568 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6570 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6577 return base.ProcessDialogKey(keyData);
6580 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6581 => this.MakeReplyText(atAll: true);
6583 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6585 var tab = this.CurrentTab;
6586 var selectedPosts = tab.SelectedPosts;
6589 if (selectedPosts.Length == 0)
6592 var screenNameArray = selectedPosts
6593 .Select(x => x.RetweetedBy ?? x.ScreenName)
6596 this.AddFilterRuleByScreenName(screenNameArray);
6598 if (screenNameArray.Length != 0)
6600 var atids = new List<string>();
6601 foreach (var screenName in screenNameArray)
6603 atids.Add("@" + screenName);
6605 var cnt = this.AtIdSupl.ItemCount;
6606 this.AtIdSupl.AddRangeItem(atids.ToArray());
6607 if (this.AtIdSupl.ItemCount != cnt)
6608 this.MarkSettingAtIdModified();
6612 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6614 var tab = this.CurrentTab;
6615 var selectedPosts = tab.SelectedPosts;
6617 if (selectedPosts.Length == 0)
6620 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6622 this.AddFilterRuleBySource(sourceArray);
6625 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6628 if (!this.SelectTab(out var tab)) return;
6632 if (tab.TabType != MyCommon.TabUsageType.Mute)
6634 this.MoveOrCopy(out mv, out mk);
6638 // ミュートタブでは常に MoveMatches を true にする
6643 foreach (var screenName in screenNameArray)
6645 tab.AddFilter(new PostFilterRule
6647 FilterName = screenName,
6648 UseNameField = true,
6652 FilterByUrl = false,
6656 this.ApplyPostFilters();
6657 this.SaveConfigsTabs();
6660 public void AddFilterRuleBySource(params string[] sourceArray)
6662 // タブ選択ダイアログを表示(or追加)
6663 if (!this.SelectTab(out var filterTab))
6668 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6670 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6671 this.MoveOrCopy(out mv, out mk);
6675 // ミュートタブでは常に MoveMatches を true にする
6680 // 振り分けルールに追加するSource
6681 foreach (var source in sourceArray)
6683 filterTab.AddFilter(new PostFilterRule
6685 FilterSource = source,
6689 FilterByUrl = false,
6693 this.ApplyPostFilters();
6694 this.SaveConfigsTabs();
6697 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6704 using (var dialog = new TabsDialog(this.statuses))
6706 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6708 tab = dialog.SelectedTab;
6711 this.CurrentTabPage.Focus();
6716 using (var inputName = new InputTabName())
6718 inputName.TabName = this.statuses.MakeTabName("MyTab");
6719 inputName.ShowDialog();
6720 if (inputName.DialogResult == DialogResult.Cancel) return false;
6721 tabName = inputName.TabName;
6723 this.TopMost = this.settings.Common.AlwaysTop;
6724 if (!MyCommon.IsNullOrEmpty(tabName))
6726 var newTab = new FilterTabModel(tabName);
6727 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6729 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6730 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6749 private void MoveOrCopy(out bool move, out bool mark)
6753 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6754 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6762 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6763 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6774 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6777 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6778 => this.CopyIdUri();
6780 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6782 if (this.StatusText.Focused)
6785 this.StatusText.SelectAll();
6789 // ListView上でのCtrl+A
6790 NativeMethods.SelectAllItems(this.CurrentListView);
6794 private void MoveMiddle()
6800 var listView = this.CurrentListView;
6801 if (listView.SelectedIndices.Count == 0) return;
6803 var idx = listView.SelectedIndices[0];
6805 item = listView.GetItemAt(0, 25);
6811 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6813 idx2 = listView.VirtualListSize - 1;
6817 idx -= Math.Abs(idx1 - idx2) / 2;
6818 if (idx < 0) idx = 0;
6820 listView.EnsureVisible(listView.VirtualListSize - 1);
6821 listView.EnsureVisible(idx);
6824 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6826 var linkElements = this.tweetDetailsView.GetLinkElements();
6828 if (linkElements.Length == 0)
6831 var links = new List<OpenUrlItem>(linkElements.Length);
6833 foreach (var linkElm in linkElements)
6835 var displayUrl = linkElm.GetAttribute("title");
6836 var href = linkElm.GetAttribute("href");
6837 var linkedText = linkElm.InnerText;
6839 if (MyCommon.IsNullOrEmpty(displayUrl))
6842 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6846 bool isReverseSettings;
6848 if (links.Count == 1)
6850 // ツイートに含まれる URL が 1 つのみの場合
6851 // => OpenURL ダイアログを表示せずにリンクを開く
6852 selectedUrl = links[0].Href;
6854 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6855 isReverseSettings = false;
6859 // ツイートに含まれる URL が複数ある場合
6860 // => OpenURL を表示しユーザーが選択したリンクを開く
6861 this.urlDialog.ClearUrl();
6863 foreach (var link in links)
6864 this.urlDialog.AddUrl(link);
6866 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6869 this.TopMost = this.settings.Common.AlwaysTop;
6871 selectedUrl = this.urlDialog.SelectedUrl;
6873 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6874 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6877 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6880 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6882 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6883 this.ClearTab(this.rclickTabName, true);
6886 private void ClearTab(string tabName, bool showWarning)
6890 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6891 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6897 this.statuses.ClearTabIds(tabName);
6898 if (this.CurrentTabName == tabName)
6900 this.CurrentTab.ClearAnchor();
6901 this.listCache?.PurgeCache();
6902 this.listCache?.UpdateListSize();
6905 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6906 var tabPage = this.ListTab.TabPages[tabIndex];
6907 tabPage.ImageIndex = -1;
6909 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6911 this.SetMainWindowTitle();
6912 this.SetStatusLabelUrl();
6915 private static long followers = 0;
6917 private void SetMainWindowTitle()
6919 // メインウインドウタイトルの書き換え
6920 var ttl = new StringBuilder(256);
6923 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6924 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6925 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6926 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6928 foreach (var tab in this.statuses.Tabs)
6930 ur += tab.UnreadCount;
6935 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6936 ttl.Append(ApplicationSettings.ApplicationName);
6938 switch (this.settings.Common.DispLatestPost)
6940 case MyCommon.DispTitleEnum.Ver:
6941 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6943 case MyCommon.DispTitleEnum.Post:
6944 if (this.history != null && this.history.Count > 1)
6945 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6947 case MyCommon.DispTitleEnum.UnreadRepCount:
6948 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6950 case MyCommon.DispTitleEnum.UnreadAllCount:
6951 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6953 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6954 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6956 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6957 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6959 case MyCommon.DispTitleEnum.OwnStatus:
6960 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6961 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6967 this.Text = ttl.ToString();
6969 catch (AccessViolationException)
6971 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6975 private string GetStatusLabelText()
6978 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6979 if (this.statuses == null) return "";
6980 var tbRep = this.statuses.MentionTab;
6981 var tbDm = this.statuses.DirectMessageTab;
6982 if (tbRep == null || tbDm == null) return "";
6983 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6988 var slbl = new StringBuilder(256);
6991 foreach (var tab in this.statuses.Tabs)
6993 ur += tab.UnreadCount;
6995 if (tab.TabName == this.CurrentTabName)
6997 tur = tab.UnreadCount;
7007 this.unreadCounter = ur;
7008 this.unreadAtCounter = urat;
7010 var homeTab = this.statuses.HomeTab;
7012 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7013 if (this.settings.Common.TimelinePeriod == 0)
7015 slbl.Append(Properties.Resources.SetStatusLabelText2);
7019 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7021 return slbl.ToString();
7024 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7028 if (this.InvokeRequired && !this.IsDisposed)
7030 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7034 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7035 this.SetApiStatusLabel(endpointName);
7038 catch (ObjectDisposedException)
7042 catch (InvalidOperationException)
7048 private void SetApiStatusLabel(string? endpointName = null)
7050 var tabType = this.CurrentTab.TabType;
7052 if (endpointName == null)
7054 var authByCookie = this.tw.Api.AppToken.AuthType == APIAuthType.TwitterComCookie;
7057 endpointName = tabType switch
7059 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
7060 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7061 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7062 MyCommon.TabUsageType.Favorites => "/favorites/list",
7063 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7064 MyCommon.TabUsageType.UserTimeline =>
7065 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7066 MyCommon.TabUsageType.Lists =>
7067 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7068 MyCommon.TabUsageType.PublicSearch =>
7069 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7070 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7073 this.toolStripApiGauge.ApiEndpoint = endpointName;
7077 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7078 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7082 private void SetStatusLabelUrl()
7083 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7085 public void SetStatusLabel(string text)
7086 => this.StatusLabel.Text = text;
7088 private void SetNotifyIconText()
7090 var ur = new StringBuilder(64);
7092 // タスクトレイアイコンのツールチップテキスト書き換え
7094 ur.Remove(0, ur.Length);
7095 if (this.settings.Common.DispUsername)
7097 ur.Append(this.tw.Username);
7100 ur.Append(ApplicationSettings.ApplicationName);
7102 ur.Append("(Debug Build)");
7104 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7107 ur.Append(this.unreadCounter);
7109 ur.Append(this.unreadAtCounter);
7112 this.NotifyIcon1.Text = ur.ToString();
7115 internal void CheckReplyTo(string statusText)
7119 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7121 foreach (Match hm in m)
7123 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7125 hstr += "#" + hm.Result("$3") + " ";
7126 this.HashSupl.AddItem("#" + hm.Result("$3"));
7129 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7131 hstr += this.HashMgr.UseHash;
7133 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7135 // 本当にリプライ先指定すべきかどうかの判定
7136 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7138 if (this.settings.Common.UseAtIdSupplement)
7140 var bCnt = this.AtIdSupl.ItemCount;
7141 foreach (Match mid in m)
7143 this.AtIdSupl.AddItem(mid.Result("${id}"));
7145 if (bCnt != this.AtIdSupl.ItemCount)
7146 this.MarkSettingAtIdModified();
7149 // リプライ先ステータスIDの指定がない場合は指定しない
7150 if (this.inReplyTo == null)
7154 // 次の条件を満たす場合に in_reply_to_status_id 指定
7155 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7156 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7157 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7161 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7162 if (statusText.StartsWith("@", StringComparison.Ordinal))
7164 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7168 foreach (Match mid in m)
7170 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7175 this.inReplyTo = null;
7178 private void TweenMain_Resize(object sender, EventArgs e)
7180 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7182 this.Visible = false;
7184 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7186 // 現在の DPI と設定保存時の DPI との比を取得する
7187 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7189 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7192 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7193 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7194 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7196 this.SplitContainer1.SplitterDistance = splitterDistance;
7200 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7201 if (this.StatusText.Multiline)
7203 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7204 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7205 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7207 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7209 this.StatusText.Height = statusTextHeight;
7213 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7215 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7219 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7220 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7222 this.SplitContainer3.SplitterDistance = previewDistance;
7225 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7226 this.SplitContainer3.Panel2Collapsed = true;
7228 this.initialLayout = false;
7230 if (this.WindowState != FormWindowState.Minimized)
7232 this.formWindowState = this.WindowState;
7236 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7238 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7239 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7240 if (this.PlaySoundMenuItem.Checked)
7242 this.settings.Common.PlaySound = true;
7246 this.settings.Common.PlaySound = false;
7248 this.MarkSettingCommonModified();
7251 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7253 if (this.initialLayout)
7256 int splitterDistance;
7257 switch (this.WindowState)
7259 case FormWindowState.Normal:
7260 splitterDistance = this.SplitContainer1.SplitterDistance;
7262 case FormWindowState.Maximized:
7263 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7264 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7265 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7266 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7272 this.mySpDis = splitterDistance;
7273 this.MarkSettingLocalModified();
7276 private async Task DoRepliedStatusOpen()
7278 var currentPost = this.CurrentPost;
7279 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7281 if (MyCommon.IsKeyDown(Keys.Shift))
7283 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7286 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7288 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7292 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7294 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7295 repPost = tb.Posts[currentPost.InReplyToStatusId];
7296 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7299 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7304 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7305 => await this.DoRepliedStatusOpen();
7307 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7309 if (this.initialLayout)
7310 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7312 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7313 if (multiline != this.StatusText.Multiline)
7315 this.StatusText.Multiline = multiline;
7316 this.settings.Local.StatusMultiline = multiline;
7317 this.MarkSettingLocalModified();
7321 private void StatusText_MultilineChanged(object sender, EventArgs e)
7323 if (this.StatusText.Multiline)
7324 this.StatusText.ScrollBars = ScrollBars.Vertical;
7326 this.StatusText.ScrollBars = ScrollBars.None;
7328 if (!this.initialLayout)
7329 this.MarkSettingLocalModified();
7332 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7335 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7336 this.StatusText.Multiline = menuItemChecked;
7337 this.settings.Local.StatusMultiline = menuItemChecked;
7338 if (menuItemChecked)
7340 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7341 this.SplitContainer2.SplitterDistance = 0;
7343 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7347 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7349 this.MarkSettingLocalModified();
7352 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7354 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7356 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7357 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7358 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7360 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7365 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7366 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7367 // Appendix A. Collected ABNF for URI
7368 // http://www.ietf.org/rfc/rfc3986.txt
7370 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7373 if (this.StatusText.SelectionLength > 0)
7375 var tmp = this.StatusText.SelectedText;
7376 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7377 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7379 // 文字列が選択されている場合はその文字列について処理
7381 // nico.ms使用、nicovideoにマッチしたら変換
7382 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7384 result = Nicoms.Shorten(tmp);
7386 else if (converterType != MyCommon.UrlConverter.Nicoms)
7391 var srcUri = new Uri(tmp);
7392 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7393 result = resultUri.AbsoluteUri;
7395 catch (WebApiException e)
7397 this.StatusLabel.Text = converterType + ":" + e.Message;
7400 catch (UriFormatException e)
7402 this.StatusLabel.Text = converterType + ":" + e.Message;
7411 if (!MyCommon.IsNullOrEmpty(result))
7413 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7414 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7415 if (origUrlIndex == -1)
7418 this.StatusText.Select(origUrlIndex, tmp.Length);
7419 this.StatusText.SelectedText = result;
7422 var undo = new UrlUndo
7428 if (this.urlUndoBuffer == null)
7430 this.urlUndoBuffer = new List<UrlUndo>();
7431 this.UrlUndoToolStripMenuItem.Enabled = true;
7434 this.urlUndoBuffer.Add(undo);
7440 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7441 @"(?<url>(?<protocol>https?://)" +
7442 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7443 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7444 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7445 // 正規表現にマッチしたURL文字列をtinyurl化
7446 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7448 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7450 var tmp = mt.Result("${url}");
7451 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7452 tmp = "http://" + tmp;
7455 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7457 // nico.ms使用、nicovideoにマッチしたら変換
7458 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7460 result = Nicoms.Shorten(tmp);
7462 else if (converterType != MyCommon.UrlConverter.Nicoms)
7467 var srcUri = new Uri(tmp);
7468 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7469 result = resultUri.AbsoluteUri;
7471 catch (HttpRequestException e)
7473 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7474 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7475 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7477 this.StatusLabel.Text = converterType + ":" + message;
7480 catch (WebApiException e)
7482 this.StatusLabel.Text = converterType + ":" + e.Message;
7485 catch (UriFormatException e)
7487 this.StatusLabel.Text = converterType + ":" + e.Message;
7496 if (!MyCommon.IsNullOrEmpty(result))
7498 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7499 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7500 if (origUrlIndex == -1)
7503 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7504 this.StatusText.SelectedText = result;
7506 var undo = new UrlUndo
7508 Before = mt.Result("${url}"),
7512 if (this.urlUndoBuffer == null)
7514 this.urlUndoBuffer = new List<UrlUndo>();
7515 this.UrlUndoToolStripMenuItem.Enabled = true;
7518 this.urlUndoBuffer.Add(undo);
7526 private void DoUrlUndo()
7528 if (this.urlUndoBuffer != null)
7530 var tmp = this.StatusText.Text;
7531 foreach (var data in this.urlUndoBuffer)
7533 tmp = tmp.Replace(data.After, data.Before);
7535 this.StatusText.Text = tmp;
7536 this.urlUndoBuffer = null;
7537 this.UrlUndoToolStripMenuItem.Enabled = false;
7538 this.StatusText.SelectionStart = 0;
7539 this.StatusText.SelectionLength = 0;
7543 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7544 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7546 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7547 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7549 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7550 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7552 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7554 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7556 var rnd = new Random();
7558 MyCommon.UrlConverter svc;
7559 // 前回使用した短縮URLサービス以外を選択する
7562 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7564 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7565 await this.UrlConvertAsync(svc);
7569 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7570 => this.DoUrlUndo();
7572 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7574 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7575 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7576 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7577 this.MarkSettingCommonModified();
7580 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7582 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7583 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7584 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7585 this.MarkSettingCommonModified();
7588 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7590 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7591 this.MenuStrip1.Tag = new object();
7592 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7595 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7597 var currentTabPage = this.CurrentTabPage;
7598 if (this.Tag != null) // 設定された戻り先へ遷移
7600 if (this.Tag == currentTabPage)
7601 ((Control)currentTabPage.Tag).Select();
7603 ((Control)this.Tag).Select();
7605 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7607 this.Tag = currentTabPage.Tag;
7608 ((Control)this.Tag).Select();
7610 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7611 this.MenuStrip1.Tag = null;
7614 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7616 if (this.Use2ColumnsMode)
7622 var lst = (DetailsListView)sender;
7623 var columnsCount = lst.Columns.Count;
7625 var darr = new int[columnsCount];
7626 for (var i = 0; i < columnsCount; i++)
7627 darr[lst.Columns[i].DisplayIndex] = i;
7629 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7631 for (var i = 0; i < columnsCount; i++)
7632 this.settings.Local.ColumnsOrder[darr[i]] = i;
7634 this.MarkSettingLocalModified();
7635 this.isColumnChanged = true;
7638 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7640 var lst = (DetailsListView)sender;
7641 if (this.settings.Local == null) return;
7643 var modified = false;
7644 if (this.Use2ColumnsMode)
7646 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7648 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7651 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7653 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7659 var columnsCount = lst.Columns.Count;
7660 for (var i = 0; i < columnsCount; i++)
7662 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7665 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7671 this.MarkSettingLocalModified();
7672 this.isColumnChanged = true;
7676 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7678 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7679 this.MarkSettingLocalModified();
7682 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7684 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7686 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7688 this.SelectMedia_DragDrop(e);
7691 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7693 var (url, title) = GetUrlFromDataObject(e.Data);
7699 appendText = title + " " + url;
7701 if (this.StatusText.TextLength == 0)
7702 this.StatusText.Text = appendText;
7704 this.StatusText.Text += " " + appendText;
7706 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7708 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7710 this.StatusText.Text += text;
7712 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7714 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7715 if (data != null) this.StatusText.Text += data;
7720 /// IDataObject から URL とタイトルの対を取得します
7723 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7725 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7726 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7727 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7729 if (data.GetDataPresent("text/x-moz-url"))
7731 // Firefox, Google Chrome で利用可能
7732 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7734 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7735 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7736 if (lines.Length < 2)
7737 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7739 return (lines[0], lines[1]);
7741 else if (data.GetDataPresent("IESiteModeToUrl"))
7743 // Internet Exproler 用
7744 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7746 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7747 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7748 if (lines.Length < 2)
7749 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7751 return (lines[0], lines[1]);
7753 else if (data.GetDataPresent("UniformResourceLocatorW"))
7757 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7758 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7762 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7765 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7767 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7769 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7771 this.SelectMedia_DragEnter(e);
7775 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7777 e.Effect = DragDropEffects.Copy;
7780 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7782 e.Effect = DragDropEffects.Copy;
7785 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7787 e.Effect = DragDropEffects.Copy;
7791 e.Effect = DragDropEffects.None;
7794 private void TweenMain_DragOver(object sender, DragEventArgs e)
7798 public bool IsNetworkAvailable()
7800 var nw = MyCommon.IsNetworkAvailable();
7801 this.myStatusOnline = nw;
7805 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7807 var uriStr = uri.AbsoluteUri;
7809 // OpenTween 内部で使用する URL
7810 if (uri.Authority == "opentween")
7812 await this.OpenInternalUriAsync(uri);
7816 // ハッシュタグを含む Twitter 検索
7817 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7820 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7821 var pos = unescapedQuery.IndexOf('#');
7822 if (pos == -1) return;
7824 var hash = unescapedQuery.Substring(pos);
7825 this.HashSupl.AddItem(hash);
7826 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7827 this.AddNewTabForSearch(hash);
7832 // フラグが立っている場合は設定と逆の動作をする
7833 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7834 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7836 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7837 if (userUriMatch.Success)
7839 var screenName = userUriMatch.Groups["ScreenName"].Value;
7840 if (this.IsTwitterId(screenName))
7842 await this.AddNewTabForUserTimeline(screenName);
7849 await MyCommon.OpenInBrowserAsync(this, uriStr);
7853 /// OpenTween 内部の機能を呼び出すための URL を開きます
7855 private async Task OpenInternalUriAsync(Uri uri)
7857 // ツイートを開く (//opentween/status/:status_id)
7858 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7861 var statusId = new TwitterStatusId(match.Groups[1].Value);
7862 await this.OpenRelatedTab(statusId);
7867 private void ListTabSelect(TabPage tabPage)
7869 this.SetListProperty();
7871 var previousTabName = this.CurrentTabName;
7872 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7873 previousListViewState.Save(this.ListLockMenuItem.Checked);
7875 this.listCache?.PurgeCache();
7877 this.statuses.SelectTab(tabPage.Text);
7879 this.InitializeTimelineListView();
7881 var tab = this.CurrentTab;
7884 var listView = this.CurrentListView;
7886 var currentListViewState = this.listViewState[tab.TabName];
7887 currentListViewState.Restore(forceScroll: true);
7889 if (this.Use2ColumnsMode)
7891 listView.Columns[1].Text = this.columnText[2];
7895 for (var i = 0; i < listView.Columns.Count; i++)
7897 listView.Columns[i].Text = this.columnText[i];
7902 private void InitializeTimelineListView()
7904 var listView = this.CurrentListView;
7905 var tab = this.CurrentTab;
7907 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7908 (this.listCache, var oldCache) = (newCache, this.listCache);
7909 oldCache?.Dispose();
7911 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7912 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7913 oldDrawer?.Dispose();
7915 newDrawer.IconSize = this.settings.Common.IconSize;
7916 newDrawer.UpdateItemHeight();
7919 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7920 => this.ListTabSelect(e.TabPage);
7922 private void SelectListItem(DetailsListView lView, int index)
7925 var bnd = new Rectangle();
7927 var item = lView.FocusedItem;
7936 lView.SelectedIndices.Clear();
7938 while (lView.SelectedIndices.Count > 0);
7939 item = lView.Items[index];
7940 item.Selected = true;
7941 item.Focused = true;
7943 if (flg) lView.Invalidate(bnd);
7946 private async void TweenMain_Shown(object sender, EventArgs e)
7948 this.NotifyIcon1.Visible = true;
7951 if (this.settings.IsFirstRun)
7953 // 初回起動時だけ右下のメニューを目立たせる
7954 this.HashStripSplitButton.ShowDropDown();
7957 if (this.IsNetworkAvailable())
7959 var loadTasks = new TaskCollection();
7963 this.RefreshMuteUserIdsAsync,
7964 this.RefreshBlockIdsAsync,
7965 this.RefreshNoRetweetIdsAsync,
7966 this.RefreshTwitterConfigurationAsync,
7967 this.RefreshTabAsync<HomeTabModel>,
7968 this.RefreshTabAsync<MentionsTabModel>,
7969 this.RefreshTabAsync<DirectMessagesTabModel>,
7970 this.RefreshTabAsync<PublicSearchTabModel>,
7971 this.RefreshTabAsync<UserTimelineTabModel>,
7972 this.RefreshTabAsync<ListTimelineTabModel>,
7975 if (this.settings.Common.StartupFollowers)
7976 loadTasks.Add(this.RefreshFollowerIdsAsync);
7978 if (this.settings.Common.GetFav)
7979 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7981 var allTasks = loadTasks.RunAll();
7986 var timeout = Task.Delay(5000);
7987 if (await Task.WhenAny(allTasks, timeout) != timeout)
7991 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7993 if (MyCommon.EndingFlag)
7997 if (MyCommon.EndingFlag) return;
7999 if (ApplicationSettings.VersionInfoUrl != null)
8001 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8002 if (this.settings.Common.StartupVersion)
8003 await this.CheckNewVersion(true);
8007 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8008 this.VerUpMenuItem.Enabled = false;
8009 this.VerUpMenuItem.Available = false;
8010 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8013 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8014 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8016 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8017 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8021 var reloadTasks = new TaskCollection();
8023 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8024 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
8026 if (!this.tw.GetNoRetweetSuccess)
8027 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
8029 if (this.tw.Configuration.PhotoSizeLimit == 0)
8030 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
8032 await reloadTasks.RunAll();
8035 this.initial = false;
8038 private void StartTimers()
8040 if (!this.StopRefreshAllMenuItem.Checked)
8041 this.timelineScheduler.Enabled = true;
8043 this.selectionDebouncer.Enabled = true;
8044 this.saveConfigDebouncer.Enabled = true;
8045 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
8048 private async Task DoGetFollowersMenu()
8050 await this.RefreshFollowerIdsAsync();
8051 this.DispSelectedPost(true);
8054 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8055 => await this.DoGetFollowersMenu();
8057 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8058 => this.DoReTweetUnofficial();
8060 private async Task DoReTweetOfficial(bool isConfirm)
8063 if (this.ExistCurrentPost)
8065 var selectedPosts = this.CurrentTab.SelectedPosts;
8067 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8069 if (selectedPosts.Any(x => x.IsProtect))
8070 MessageBox.Show("Protected.");
8072 this.doFavRetweetFlags = false;
8076 if (selectedPosts.Length > 15)
8078 MessageBox.Show(Properties.Resources.RetweetLimitText);
8079 this.doFavRetweetFlags = false;
8082 else if (selectedPosts.Length > 1)
8084 var questionText = Properties.Resources.RetweetQuestion2;
8085 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8086 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8088 case DialogResult.Cancel:
8089 case DialogResult.No:
8090 this.doFavRetweetFlags = false;
8096 if (!this.settings.Common.RetweetNoConfirm)
8098 var questiontext = Properties.Resources.RetweetQuestion1;
8099 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8100 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8102 this.doFavRetweetFlags = false;
8108 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8110 await this.RetweetAsync(statusIds);
8114 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8115 => await this.DoReTweetOfficial(true);
8117 private async Task FavoritesRetweetOfficial()
8119 if (!this.ExistCurrentPost) return;
8120 this.doFavRetweetFlags = true;
8122 var tasks = new TaskCollection();
8123 tasks.Add(() => this.DoReTweetOfficial(true));
8125 if (this.doFavRetweetFlags)
8127 this.doFavRetweetFlags = false;
8128 tasks.Add(() => this.FavoriteChange(true, false));
8131 await tasks.RunAll();
8134 private async Task FavoritesRetweetUnofficial()
8136 var post = this.CurrentPost;
8137 if (this.ExistCurrentPost && post != null && !post.IsDm)
8139 this.doFavRetweetFlags = true;
8140 var favoriteTask = this.FavoriteChange(true);
8141 if (!post.IsProtect && this.doFavRetweetFlags)
8143 this.doFavRetweetFlags = false;
8144 this.DoReTweetUnofficial();
8152 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8154 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8155 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8156 /// <returns>復元されたツイート本文</returns>
8157 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8159 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8162 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8164 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8166 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8168 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8172 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8174 statusHtml = statusHtml.Replace("<br>", " ");
8176 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8177 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8178 statusHtml = statusHtml.Replace(" ", " ");
8180 return WebUtility.HtmlDecode(statusHtml);
8183 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8185 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8187 if (this.CurrentPost != null)
8188 this.DispSelectedPost(true);
8191 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8193 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8194 this.DebugModeToolStripMenuItem.Visible = true;
8196 this.DebugModeToolStripMenuItem.Visible = false;
8199 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8200 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8202 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8203 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8205 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8206 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8208 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8210 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8211 this.MarkSettingCommonModified();
8214 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8216 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8217 this.MarkSettingCommonModified();
8220 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8222 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8223 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8224 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8225 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8226 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8227 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8230 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8232 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8233 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8234 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8235 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8236 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8237 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8240 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8242 if (this.TraceOutToolStripMenuItem.Checked)
8243 MyCommon.TraceFlag = true;
8245 MyCommon.TraceFlag = false;
8248 private void TweenMain_Deactivate(object sender, EventArgs e)
8249 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8251 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8253 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8255 _ = this.TabRename(this.rclickTabName, out _);
8258 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8259 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8261 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8262 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8264 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8266 TwitterApiStatus? apiStatus;
8268 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8270 var cancellationToken = dialog.EnableCancellation();
8274 var task = this.tw.GetInfoApi();
8275 apiStatus = await dialog.WaitForAsync(this, task);
8277 catch (WebApiException)
8282 if (cancellationToken.IsCancellationRequested)
8285 if (apiStatus == null)
8287 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8292 using var apiDlg = new ApiInfoDialog();
8293 apiDlg.ShowDialog(this);
8296 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8298 var id = this.CurrentPost?.ScreenName ?? "";
8300 await this.FollowCommand(id);
8303 internal async Task FollowCommand(string id)
8305 using (var inputName = new InputTabName())
8307 inputName.FormTitle = "Follow";
8308 inputName.FormDescription = Properties.Resources.FRMessage1;
8309 inputName.TabName = id;
8311 if (inputName.ShowDialog(this) != DialogResult.OK)
8313 if (string.IsNullOrWhiteSpace(inputName.TabName))
8316 id = inputName.TabName.Trim();
8319 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8323 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8324 await dialog.WaitForAsync(this, task);
8326 catch (WebApiException ex)
8328 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8333 MessageBox.Show(Properties.Resources.FRMessage3);
8336 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8338 var id = this.CurrentPost?.ScreenName ?? "";
8340 await this.RemoveCommand(id, false);
8343 internal async Task RemoveCommand(string id, bool skipInput)
8347 using var inputName = new InputTabName();
8348 inputName.FormTitle = "Unfollow";
8349 inputName.FormDescription = Properties.Resources.FRMessage1;
8350 inputName.TabName = id;
8352 if (inputName.ShowDialog(this) != DialogResult.OK)
8354 if (string.IsNullOrWhiteSpace(inputName.TabName))
8357 id = inputName.TabName.Trim();
8360 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8364 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8365 await dialog.WaitForAsync(this, task);
8367 catch (WebApiException ex)
8369 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8374 MessageBox.Show(Properties.Resources.FRMessage3);
8377 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8379 var id = this.CurrentPost?.ScreenName ?? "";
8381 await this.ShowFriendship(id);
8384 internal async Task ShowFriendship(string id)
8386 using (var inputName = new InputTabName())
8388 inputName.FormTitle = "Show Friendships";
8389 inputName.FormDescription = Properties.Resources.FRMessage1;
8390 inputName.TabName = id;
8392 if (inputName.ShowDialog(this) != DialogResult.OK)
8394 if (string.IsNullOrWhiteSpace(inputName.TabName))
8397 id = inputName.TabName.Trim();
8400 bool isFollowing, isFollowed;
8402 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8404 var cancellationToken = dialog.EnableCancellation();
8408 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8409 var friendship = await dialog.WaitForAsync(this, task);
8411 isFollowing = friendship.Relationship.Source.Following;
8412 isFollowed = friendship.Relationship.Source.FollowedBy;
8414 catch (WebApiException ex)
8416 if (!cancellationToken.IsCancellationRequested)
8417 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8421 if (cancellationToken.IsCancellationRequested)
8428 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8432 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8436 result += Properties.Resources.GetFriendshipInfo3;
8440 result += Properties.Resources.GetFriendshipInfo4;
8442 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8443 MessageBox.Show(result);
8446 internal async Task ShowFriendship(string[] ids)
8448 foreach (var id in ids)
8450 bool isFollowing, isFollowed;
8452 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8454 var cancellationToken = dialog.EnableCancellation();
8458 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8459 var friendship = await dialog.WaitForAsync(this, task);
8461 isFollowing = friendship.Relationship.Source.Following;
8462 isFollowed = friendship.Relationship.Source.FollowedBy;
8464 catch (WebApiException ex)
8466 if (!cancellationToken.IsCancellationRequested)
8467 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8471 if (cancellationToken.IsCancellationRequested)
8481 ff += Properties.Resources.GetFriendshipInfo1;
8485 ff += Properties.Resources.GetFriendshipInfo2;
8488 ff += System.Environment.NewLine + " ";
8491 ff += Properties.Resources.GetFriendshipInfo3;
8495 ff += Properties.Resources.GetFriendshipInfo4;
8497 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8500 if (MessageBox.Show(
8501 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8502 Properties.Resources.GetFriendshipInfo8,
8503 MessageBoxButtons.YesNo,
8504 MessageBoxIcon.Question,
8505 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8507 await this.RemoveCommand(id, true);
8512 MessageBox.Show(result);
8517 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8518 => await this.DoShowUserStatus(this.tw.Username, false);
8520 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8523 public bool IsTwitterId(string name)
8525 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8526 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8528 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8531 private void DoQuoteOfficial()
8533 var post = this.CurrentPost;
8534 if (this.ExistCurrentPost && post != null)
8536 if (post.IsDm || !this.StatusText.Enabled)
8541 MessageBox.Show("Protected.");
8545 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8547 this.inReplyTo = null;
8549 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8551 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8552 this.StatusText.Focus();
8556 private void DoReTweetUnofficial()
8559 var post = this.CurrentPost;
8560 if (this.ExistCurrentPost && post != null)
8562 if (post.IsDm || !this.StatusText.Enabled)
8567 MessageBox.Show("Protected.");
8570 var rtdata = post.Text;
8571 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8573 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8575 // 投稿時に in_reply_to_status_id を付加する
8576 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8577 var inReplyToScreenName = post.ScreenName;
8578 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8580 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8582 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8583 this.StatusText.Focus();
8587 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8588 => this.DoQuoteOfficial();
8590 private async void SearchButton_Click(object sender, EventArgs e)
8593 var pnl = ((Control)sender).Parent;
8594 if (pnl == null) return;
8595 var tbName = pnl.Parent.Text;
8596 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8597 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8598 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8599 cmb.Text = cmb.Text.Trim();
8600 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8602 var buf = new StringBuilder();
8603 var c = cmb.Text.ToCharArray();
8604 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8606 if (cnt > cmb.Text.Length - 4)
8608 buf.Append(cmb.Text.Substring(cnt));
8617 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8626 cmb.Text = buf.ToString();
8628 var listView = (DetailsListView)pnl.Parent.Tag;
8630 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8632 tb.SearchWords = cmb.Text;
8633 tb.SearchLang = cmbLang.Text;
8634 if (MyCommon.IsNullOrEmpty(cmb.Text))
8637 this.SaveConfigsTabs();
8642 var idx = cmb.Items.IndexOf(tb.SearchWords);
8643 if (idx > -1) cmb.Items.RemoveAt(idx);
8644 cmb.Items.Insert(0, tb.SearchWords);
8645 cmb.Text = tb.SearchWords;
8647 this.statuses.ClearTabIds(tbName);
8648 this.listCache?.PurgeCache();
8649 this.listCache?.UpdateListSize();
8650 this.SaveConfigsTabs(); // 検索条件の保存
8654 await this.RefreshTabAsync(tb);
8657 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8658 => await this.DoRefreshMore(); // もっと前を取得
8661 /// 指定されたタブのListTabにおける位置を返します
8664 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8666 public int GetTabPageIndex(string tabName)
8667 => this.statuses.Tabs.IndexOf(tabName);
8669 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8673 var restoredTab = this.statuses.UndoRemovedTab();
8674 this.AddNewTab(restoredTab, startup: false);
8676 var tabIndex = this.statuses.Tabs.Count - 1;
8677 this.ListTab.SelectedIndex = tabIndex;
8679 this.SaveConfigsTabs();
8681 catch (TabException ex)
8683 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8687 private async Task DoMoveToRTHome()
8689 var post = this.CurrentPost;
8690 if (post != null && post.RetweetedId != null)
8691 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8694 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8695 => await this.DoMoveToRTHome();
8697 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8699 var screenName = this.CurrentPost?.ScreenName;
8700 if (screenName != null)
8701 this.ListManageUserContext(screenName);
8704 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8706 var screenName = this.CurrentPost?.RetweetedBy;
8707 if (screenName != null)
8708 this.ListManageUserContext(screenName);
8711 public void ListManageUserContext(string screenName)
8713 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8714 listSelectForm.ShowDialog(this);
8717 private void SearchControls_Enter(object sender, EventArgs e)
8719 var pnl = (Control)sender;
8720 foreach (Control ctl in pnl.Controls)
8726 private void SearchControls_Leave(object sender, EventArgs e)
8728 var pnl = (Control)sender;
8729 foreach (Control ctl in pnl.Controls)
8731 ctl.TabStop = false;
8735 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8737 var tab = this.CurrentTab;
8738 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8739 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8742 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8743 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8745 private void HashManageMenuItem_Click(object sender, EventArgs e)
8750 rslt = this.HashMgr.ShowDialog();
8756 this.TopMost = this.settings.Common.AlwaysTop;
8757 if (rslt == DialogResult.Cancel) return;
8758 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8760 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8761 this.HashTogglePullDownMenuItem.Checked = true;
8762 this.HashToggleMenuItem.Checked = true;
8766 this.HashStripSplitButton.Text = "#[-]";
8767 this.HashTogglePullDownMenuItem.Checked = false;
8768 this.HashToggleMenuItem.Checked = false;
8771 this.MarkSettingCommonModified();
8772 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8775 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8777 this.HashMgr.ToggleHash();
8778 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8780 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8781 this.HashToggleMenuItem.Checked = true;
8782 this.HashTogglePullDownMenuItem.Checked = true;
8786 this.HashStripSplitButton.Text = "#[-]";
8787 this.HashToggleMenuItem.Checked = false;
8788 this.HashTogglePullDownMenuItem.Checked = false;
8790 this.MarkSettingCommonModified();
8791 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8794 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8795 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8797 public void SetPermanentHashtag(string hashtag)
8799 this.HashMgr.SetPermanentHash("#" + hashtag);
8800 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8801 this.HashTogglePullDownMenuItem.Checked = true;
8802 this.HashToggleMenuItem.Checked = true;
8804 this.MarkSettingCommonModified();
8807 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8809 var tab = this.CurrentTab;
8810 var post = this.CurrentPost;
8811 if (!this.ExistCurrentPost)
8813 this.ReplyOpMenuItem.Enabled = false;
8814 this.ReplyAllOpMenuItem.Enabled = false;
8815 this.DmOpMenuItem.Enabled = false;
8816 this.CreateTabRuleOpMenuItem.Enabled = false;
8817 this.CreateIdRuleOpMenuItem.Enabled = false;
8818 this.CreateSourceRuleOpMenuItem.Enabled = false;
8819 this.ReadOpMenuItem.Enabled = false;
8820 this.UnreadOpMenuItem.Enabled = false;
8821 this.AuthorMenuItem.Visible = false;
8822 this.RetweetedByMenuItem.Visible = false;
8826 this.ReplyOpMenuItem.Enabled = true;
8827 this.ReplyAllOpMenuItem.Enabled = true;
8828 this.DmOpMenuItem.Enabled = true;
8829 this.CreateTabRuleOpMenuItem.Enabled = true;
8830 this.CreateIdRuleOpMenuItem.Enabled = true;
8831 this.CreateSourceRuleOpMenuItem.Enabled = true;
8832 this.ReadOpMenuItem.Enabled = true;
8833 this.UnreadOpMenuItem.Enabled = true;
8834 this.AuthorMenuItem.Visible = true;
8835 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8836 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8837 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8840 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8842 this.FavOpMenuItem.Enabled = false;
8843 this.UnFavOpMenuItem.Enabled = false;
8844 this.OpenStatusOpMenuItem.Enabled = false;
8845 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8846 this.RtOpMenuItem.Enabled = false;
8847 this.RtUnOpMenuItem.Enabled = false;
8848 this.QtOpMenuItem.Enabled = false;
8849 this.FavoriteRetweetMenuItem.Enabled = false;
8850 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8854 this.FavOpMenuItem.Enabled = true;
8855 this.UnFavOpMenuItem.Enabled = true;
8856 this.OpenStatusOpMenuItem.Enabled = true;
8857 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8859 if (!post.CanRetweetBy(this.tw.UserId))
8861 this.RtOpMenuItem.Enabled = false;
8862 this.RtUnOpMenuItem.Enabled = false;
8863 this.QtOpMenuItem.Enabled = false;
8864 this.FavoriteRetweetMenuItem.Enabled = false;
8865 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8869 this.RtOpMenuItem.Enabled = true;
8870 this.RtUnOpMenuItem.Enabled = true;
8871 this.QtOpMenuItem.Enabled = true;
8872 this.FavoriteRetweetMenuItem.Enabled = true;
8873 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8877 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8879 this.RefreshPrevOpMenuItem.Enabled = true;
8883 this.RefreshPrevOpMenuItem.Enabled = false;
8885 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8887 this.OpenRepSourceOpMenuItem.Enabled = false;
8891 this.OpenRepSourceOpMenuItem.Enabled = true;
8894 if (this.ExistCurrentPost && post != null)
8896 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8900 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8901 => this.ContextMenuTabProperty_Opening(sender, null!);
8903 public Twitter TwitterInstance
8906 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8908 if (this.initialLayout)
8911 int splitterDistance;
8912 switch (this.WindowState)
8914 case FormWindowState.Normal:
8915 splitterDistance = this.SplitContainer3.SplitterDistance;
8917 case FormWindowState.Maximized:
8918 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8919 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8920 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8921 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8927 this.mySpDis3 = splitterDistance;
8928 this.MarkSettingLocalModified();
8931 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8933 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8935 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8936 this.PublicSearchQueryMenuItem.Enabled = true;
8938 this.PublicSearchQueryMenuItem.Enabled = false;
8940 var post = this.CurrentPost;
8941 if (!this.ExistCurrentPost || post == null)
8943 this.CopySTOTMenuItem.Enabled = false;
8944 this.CopyURLMenuItem.Enabled = false;
8945 this.CopyUserIdStripMenuItem.Enabled = false;
8949 this.CopySTOTMenuItem.Enabled = true;
8950 this.CopyURLMenuItem.Enabled = true;
8951 this.CopyUserIdStripMenuItem.Enabled = true;
8953 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8954 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8958 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8959 => this.SetNotifyIconText();
8961 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8962 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8964 private async Task DoShowUserStatus(string id, bool showInputDialog)
8966 TwitterUser? user = null;
8968 if (showInputDialog)
8970 using var inputName = new InputTabName();
8971 inputName.FormTitle = "Show UserStatus";
8972 inputName.FormDescription = Properties.Resources.FRMessage1;
8973 inputName.TabName = id;
8975 if (inputName.ShowDialog(this) != DialogResult.OK)
8977 if (string.IsNullOrWhiteSpace(inputName.TabName))
8980 id = inputName.TabName.Trim();
8983 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8985 var cancellationToken = dialog.EnableCancellation();
8989 var task = this.tw.GetUserInfo(id);
8990 user = await dialog.WaitForAsync(this, task);
8992 catch (WebApiException ex)
8994 if (!cancellationToken.IsCancellationRequested)
8995 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8999 if (cancellationToken.IsCancellationRequested)
9003 await this.DoShowUserStatus(user);
9006 private async Task DoShowUserStatus(TwitterUser user)
9008 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9009 var showUserTask = userDialog.ShowUserAsync(user);
9010 userDialog.ShowDialog(this);
9013 this.BringToFront();
9015 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9019 internal Task ShowUserStatus(string id, bool showInputDialog)
9020 => this.DoShowUserStatus(id, showInputDialog);
9022 internal Task ShowUserStatus(string id)
9023 => this.DoShowUserStatus(id, true);
9025 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9027 var post = this.CurrentPost;
9030 await this.ShowUserStatus(post.ScreenName, false);
9034 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9036 var retweetedBy = this.CurrentPost?.RetweetedBy;
9037 if (retweetedBy != null)
9039 await this.ShowUserStatus(retweetedBy, false);
9043 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9045 var post = this.CurrentPost;
9046 if (!this.ExistCurrentPost || post == null)
9049 var statusId = post.RetweetedId ?? post.StatusId;
9050 TwitterStatus status;
9052 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9054 var cancellationToken = dialog.EnableCancellation();
9058 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9059 status = await dialog.WaitForAsync(this, task);
9061 catch (WebApiException ex)
9063 if (!cancellationToken.IsCancellationRequested)
9064 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9068 if (cancellationToken.IsCancellationRequested)
9072 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9075 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9077 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9080 this.Visible = false;
9082 else if (Form.ActiveForm == null)
9084 this.Visible = true;
9085 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9087 this.BringToFront();
9088 this.StatusText.Focus();
9092 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9093 => this.MultiLinePullDownMenuItem.PerformClick();
9096 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9098 if (this.ImageSelector.Visible)
9099 this.ImageSelector.EndSelection();
9101 this.ImageSelector.BeginSelection();
9104 private void SelectMedia_DragEnter(DragEventArgs e)
9106 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9108 e.Effect = DragDropEffects.Copy;
9111 e.Effect = DragDropEffects.None;
9114 private void SelectMedia_DragDrop(DragEventArgs e)
9117 this.BringToFront();
9119 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9120 this.ImageSelector.BeginSelection();
9121 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9122 this.StatusText.Focus();
9125 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9127 this.TimelinePanel.Visible = false;
9128 this.TimelinePanel.Enabled = false;
9131 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9133 this.TimelinePanel.Visible = true;
9134 this.TimelinePanel.Enabled = true;
9135 this.CurrentListView.Focus();
9138 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9139 => this.AllowDrop = false;
9141 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9142 => this.AllowDrop = true;
9144 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9146 if (this.ImageSelector.Visible)
9148 this.MarkSettingCommonModified();
9149 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9153 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9154 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9157 /// StatusTextでCtrl+Vが押下された時の処理
9159 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9163 if (Clipboard.ContainsText())
9165 // clipboardにテキストがある場合は貼り付け処理
9166 this.StatusText.Paste(Clipboard.GetText());
9168 else if (Clipboard.ContainsImage())
9171 using var image = Clipboard.GetImage();
9172 this.ImageSelector.BeginSelection();
9173 this.ImageSelector.Model.AddMediaItemFromImage(image);
9175 else if (Clipboard.ContainsFileDropList())
9177 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9178 this.ImageSelector.BeginSelection();
9179 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9182 catch (ExternalException ex)
9184 MessageBox.Show(ex.Message);
9189 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9191 using var form = new ListManage(this.tw);
9192 form.ShowDialog(this);
9195 private bool ModifySettingCommon { get; set; }
9197 private bool ModifySettingLocal { get; set; }
9199 private bool ModifySettingAtId { get; set; }
9201 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9203 var post = this.CurrentPost;
9204 if (this.ExistCurrentPost && post != null && !post.IsDm)
9205 this.RtCountMenuItem.Enabled = true;
9207 this.RtCountMenuItem.Enabled = false;
9210 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9211 => this.CopyUserId();
9213 private void CopyUserId()
9215 var post = this.CurrentPost;
9216 if (post == null) return;
9217 var clstr = post.ScreenName;
9220 Clipboard.SetDataObject(clstr, false, 5, 100);
9222 catch (Exception ex)
9224 MessageBox.Show(ex.Message);
9228 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9230 var post = this.CurrentPost;
9231 if (this.ExistCurrentPost && post != null && !post.IsDm)
9235 await this.OpenRelatedTab(post);
9237 catch (TabException ex)
9239 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9245 /// 指定されたツイートに対する関連発言タブを開きます
9247 /// <param name="statusId">表示するツイートのID</param>
9248 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9249 public async Task OpenRelatedTab(PostId statusId)
9251 var post = this.statuses[statusId];
9256 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9258 catch (WebApiException ex)
9260 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9265 await this.OpenRelatedTab(post);
9269 /// 指定されたツイートに対する関連発言タブを開きます
9271 /// <param name="post">表示する対象となるツイート</param>
9272 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9273 private async Task OpenRelatedTab(PostClass post)
9275 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9276 if (tabRelated != null)
9278 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9281 var tabName = this.statuses.MakeTabName("Related Tweets");
9283 tabRelated = new RelatedPostsTabModel(tabName, post)
9285 UnreadManage = false,
9289 this.statuses.AddTab(tabRelated);
9290 this.AddNewTab(tabRelated, startup: false);
9292 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9294 await this.RefreshTabAsync(tabRelated);
9296 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9300 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9302 var tabPage = this.ListTab.TabPages[tabIndex];
9303 var listView = (DetailsListView)tabPage.Tag;
9304 var targetPost = tabRelated.TargetPost;
9305 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9307 if (index != -1 && index < listView.Items.Count)
9309 listView.SelectedIndices.Add(index);
9310 listView.Items[index].Focused = true;
9315 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9317 var buf = new StringBuilder();
9318 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9319 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9320 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9323 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9325 MyCommon.EndingFlag = true;
9329 Application.Restart();
9333 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9337 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9338 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9340 private bool ExistCurrentPost
9344 var post = this.CurrentPost;
9345 return post != null && !post.IsDeleted;
9349 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9350 => await this.ShowUserTimeline();
9352 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9353 => await this.ShowRetweeterTimeline();
9355 private string GetUserIdFromCurPostOrInput(string caption)
9357 var id = this.CurrentPost?.ScreenName ?? "";
9359 using var inputName = new InputTabName();
9360 inputName.FormTitle = caption;
9361 inputName.FormDescription = Properties.Resources.FRMessage1;
9362 inputName.TabName = id;
9364 if (inputName.ShowDialog() == DialogResult.OK &&
9365 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9367 id = inputName.TabName.Trim();
9376 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9378 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9379 if (!MyCommon.IsNullOrEmpty(id))
9381 await this.AddNewTabForUserTimeline(id);
9385 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9387 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9388 this.timelineScheduler.SystemResumed();
9391 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9393 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9395 TimeZoneInfo.ClearCachedData();
9397 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9399 if (curTimeOffset != prevTimeOffset)
9402 this.listCache?.PurgeCache();
9403 this.CurrentListView.Refresh();
9405 this.DispSelectedPost(forceupdate: true);
9408 this.timelineScheduler.Reset();
9411 private void TimelineRefreshEnableChange(bool isEnable)
9413 this.timelineScheduler.Enabled = isEnable;
9416 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9417 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9419 private async Task OpenUserAppointUrl()
9421 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9423 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9425 var post = this.CurrentPost;
9428 var xUrl = this.settings.Common.UserAppointUrl;
9429 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9431 var statusId = post.RetweetedId ?? post.StatusId;
9432 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9434 await MyCommon.OpenInBrowserAsync(this, xUrl);
9439 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9444 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9445 => await this.OpenUserAppointUrl();
9447 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9449 if (Form.ActiveForm == null)
9451 await this.InvokeAsync(() =>
9453 this.Visible = true;
9454 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9456 this.BringToFront();
9457 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9459 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9463 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9469 private void ReplaceAppName()
9471 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9472 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9475 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9476 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9478 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9480 if (e.KeyCode == Keys.Space)
9482 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9484 e.SuppressKeyPress = true;
9488 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9490 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9491 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9492 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9493 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9494 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9496 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9499 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9500 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9502 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9503 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9505 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9506 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9508 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9509 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9511 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9512 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9514 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9516 if (this.settings.Common.IconSize == iconSize) return;
9518 var oldIconCol = this.Use2ColumnsMode;
9520 this.settings.Common.IconSize = iconSize;
9521 this.ApplyListViewIconSize(iconSize);
9523 if (this.Use2ColumnsMode != oldIconCol)
9525 foreach (TabPage tp in this.ListTab.TabPages)
9527 this.ResetColumns((DetailsListView)tp.Tag);
9531 this.CurrentListView.Refresh();
9532 this.MarkSettingCommonModified();
9535 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9537 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9538 if (this.settings.Common.SortOrderLock == state) return;
9540 this.settings.Common.SortOrderLock = state;
9541 this.MarkSettingCommonModified();
9544 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9546 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9548 this.StatusLabelUrl.Text = e.StatusText;
9552 this.SetStatusLabelUrl();