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.TwitterV2;
56 using OpenTween.Connection;
57 using OpenTween.MediaUploadServices;
58 using OpenTween.Models;
59 using OpenTween.OpenTweenCustomControl;
60 using OpenTween.Setting;
61 using OpenTween.Thumbnail;
65 public partial class TweenMain : OTBaseForm
69 /// <summary>画面サイズ</summary>
72 /// <summary>画面位置</summary>
75 /// <summary>区切り位置</summary>
78 /// <summary>発言欄区切り位置</summary>
81 /// <summary>プレビュー区切り位置</summary>
85 private bool initial; // true:起動時処理中
86 private bool initialLayout = true;
87 private bool ignoreConfigSave; // true:起動時処理中
89 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
92 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
93 private Point tabMouseDownPoint;
95 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
96 private string? rclickTabName;
98 private readonly object syncObject = new(); // ロック用
100 private const string DetailHtmlFormatHead =
101 "<head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
102 + "<style type=\"text/css\"><!-- "
103 + "body, p, pre {margin: 0;} "
104 + "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%);} "
105 + "pre {font-family: inherit;} "
106 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
107 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
108 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
109 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
110 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
114 private const string DetailHtmlFormatTemplateMono =
115 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
117 private const string DetailHtmlFormatTemplateNormal =
118 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
120 private string detailHtmlFormatPreparedTemplate = null!;
122 private bool myStatusError = false;
123 private bool myStatusOnline = false;
124 private bool soundfileListup = false;
125 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
128 private readonly SettingManager settings;
131 private readonly Twitter tw;
134 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
138 /// <summary>検索画面インスタンス</summary>
139 internal SearchWordDialog SearchDialog = new();
141 private readonly OpenURL urlDialog = new();
143 /// <summary>@id補助</summary>
144 public AtIdSupplement AtIdSupl = null!;
146 /// <summary>Hashtag補助</summary>
147 public AtIdSupplement HashSupl = null!;
149 public HashtagManage HashMgr = null!;
152 private ThemeManager themeManager;
154 /// <summary>アイコン画像リスト</summary>
155 private readonly ImageCache iconCache;
157 private readonly IconAssetsManager iconAssets;
159 private readonly ThumbnailGenerator thumbGenerator;
161 /// <summary>発言履歴</summary>
162 private readonly List<StatusTextHistory> history = new();
164 /// <summary>発言履歴カレントインデックス</summary>
167 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169 /// <summary>リプライ先のステータスID・スクリーン名</summary>
170 private (long StatusId, string ScreenName)? inReplyTo = null;
173 private readonly List<DateTimeUtc> postTimestamps = new();
174 private readonly List<DateTimeUtc> favTimestamps = new();
177 private readonly StringFormat sfTab = new();
179 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 /// <summary>発言保持クラス</summary>
182 private readonly TabInformations statuses;
184 private TimelineListViewCache? listCache;
185 private TimelineListViewDrawer? listDrawer;
186 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
188 private bool isColumnChanged = false;
190 private const int MaxWorderThreads = 20;
191 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
192 private readonly CancellationTokenSource workerCts = new();
193 private readonly IProgress<string> workerProgress = null!;
195 private int unreadCounter = -1;
196 private int unreadAtCounter = -1;
198 private readonly string[] columnOrgText = new string[9];
199 private readonly string[] columnText = new string[9];
201 private bool doFavRetweetFlags = false;
203 //////////////////////////////////////////////////////////////////////////////////////////////////////////
205 private readonly TimelineScheduler timelineScheduler = new();
206 private readonly DebounceTimer selectionDebouncer;
207 private readonly DebounceTimer saveConfigDebouncer;
209 private readonly string recommendedStatusFooter;
210 private bool urlMultibyteSplit = false;
211 private bool preventSmsCommand = true;
214 private readonly record struct UrlUndo(
219 private List<UrlUndo>? urlUndoBuffer = null;
221 private readonly record struct ReplyChain(
227 /// <summary>[, ]でのリプライ移動の履歴</summary>
228 private Stack<ReplyChain>? replyChains;
230 /// <summary>ポスト選択履歴</summary>
231 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
233 public TabModel CurrentTab
234 => this.statuses.SelectedTab;
236 public string CurrentTabName
237 => this.statuses.SelectedTabName;
239 public TabPage CurrentTabPage
240 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
242 public DetailsListView CurrentListView
243 => (DetailsListView)this.CurrentTabPage.Tag;
245 public PostClass? CurrentPost
246 => this.CurrentTab.SelectedPost;
248 public bool Use2ColumnsMode
249 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
251 /// <summary>検索処理タイプ</summary>
252 internal enum SEARCHTYPE
259 private readonly record struct StatusTextHistory(
261 (long StatusId, string ScreenName)? InReplyTo = null
264 private readonly HookGlobalHotkey hookGlobalHotkey;
266 private void TweenMain_Activated(object sender, EventArgs e)
268 // 画面がアクティブになったら、発言欄の背景色戻す
269 if (this.StatusText.Focused)
271 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
275 private bool disposed = false;
278 /// 使用中のリソースをすべてクリーンアップします。
280 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
281 protected override void Dispose(bool disposing)
283 base.Dispose(disposing);
290 this.components?.Dispose();
293 this.SearchDialog.Dispose();
294 this.urlDialog.Dispose();
295 this.themeManager.Dispose();
296 this.sfTab.Dispose();
298 this.timelineScheduler.Dispose();
299 this.workerCts.Cancel();
300 this.thumbnailTokenSource?.Dispose();
302 this.hookGlobalHotkey.Dispose();
305 // 終了時にRemoveHandlerしておかないとメモリリークする
306 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
307 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
308 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
310 this.disposed = true;
313 private void InitColumns(ListView list, bool startup)
315 this.InitColumnText();
317 ColumnHeader[]? columns = null;
320 if (this.Use2ColumnsMode)
324 new ColumnHeader(), // アイコン
325 new ColumnHeader(), // 本文
328 columns[0].Text = this.columnText[0];
329 columns[1].Text = this.columnText[2];
333 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
335 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
336 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
337 columns[0].DisplayIndex = 0;
338 columns[1].DisplayIndex = 1;
343 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
345 columns[idx].Width = curListColumn.Width;
346 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
355 new ColumnHeader(), // アイコン
356 new ColumnHeader(), // ニックネーム
357 new ColumnHeader(), // 本文
358 new ColumnHeader(), // 日付
359 new ColumnHeader(), // ユーザID
360 new ColumnHeader(), // 未読
361 new ColumnHeader(), // マーク&プロテクト
362 new ColumnHeader(), // ソース
365 foreach (var i in Enumerable.Range(0, columns.Length))
366 columns[i].Text = this.columnText[i];
370 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
372 foreach (var (column, index) in columns.WithIndex())
374 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
375 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
381 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
383 columns[idx].Width = curListColumn.Width;
384 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
390 list.Columns.AddRange(columns);
398 foreach (var column in columns)
404 private void InitColumnText()
406 this.columnText[0] = "";
407 this.columnText[1] = Properties.Resources.AddNewTabText2;
408 this.columnText[2] = Properties.Resources.AddNewTabText3;
409 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
410 this.columnText[4] = Properties.Resources.AddNewTabText5;
411 this.columnText[5] = "";
412 this.columnText[6] = "";
413 this.columnText[7] = "Source";
415 this.columnOrgText[0] = "";
416 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
417 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
418 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
419 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
420 this.columnOrgText[5] = "";
421 this.columnOrgText[6] = "";
422 this.columnOrgText[7] = "Source";
424 var c = this.statuses.SortMode switch
426 ComparerMode.Nickname => 1, // ニックネーム
427 ComparerMode.Data => 2, // 本文
428 ComparerMode.Id => 3, // 時刻=発言Id
429 ComparerMode.Name => 4, // 名前
430 ComparerMode.Source => 7, // Source
434 if (this.Use2ColumnsMode)
436 if (this.statuses.SortOrder == SortOrder.Descending)
438 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
439 this.columnText[2] = this.columnOrgText[2] + "▾";
443 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
444 this.columnText[2] = this.columnOrgText[2] + "▴";
449 if (this.statuses.SortOrder == SortOrder.Descending)
451 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
452 this.columnText[c] = this.columnOrgText[c] + "▾";
456 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
457 this.columnText[c] = this.columnOrgText[c] + "▴";
463 SettingManager settingManager,
464 TabInformations tabInfo,
466 ImageCache imageCache,
467 IconAssetsManager iconAssets,
468 ThumbnailGenerator thumbGenerator
471 this.settings = settingManager;
472 this.statuses = tabInfo;
474 this.iconCache = imageCache;
475 this.iconAssets = iconAssets;
476 this.thumbGenerator = thumbGenerator;
478 this.InitializeComponent();
480 if (!this.DesignMode)
482 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
483 this.StatusText.Dock = DockStyle.Fill;
486 this.hookGlobalHotkey = new HookGlobalHotkey(this);
488 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
489 this.gh.NotifyClicked += this.GrowlHelper_Callback;
491 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
492 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
494 this.ImageSelector.Visible = false;
495 this.ImageSelector.Enabled = false;
496 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
498 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
500 this.ReplaceAppName();
501 this.InitializeShortcuts();
503 this.ignoreConfigSave = true;
504 this.Visible = false;
506 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
508 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
510 Regex.CacheSize = 100;
513 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
514 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
515 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
517 // <<<<<<<<<設定関連>>>>>>>>>
521 // 現在の DPI と設定保存時の DPI との比を取得する
522 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
525 var account = this.settings.Common.SelectedAccount;
527 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
529 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
533 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
534 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
536 // アクセストークンが有効であるか確認する
537 // ここが Twitter API への最初のアクセスになるようにすること
540 this.tw.VerifyCredentials();
542 catch (WebApiException ex)
546 string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
547 ApplicationSettings.ApplicationName,
548 MessageBoxButtons.OK,
549 MessageBoxIcon.Warning);
553 // プロキシ設定等の通信まわりの初期化が済んでから処理する
554 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
555 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
556 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
557 imgazyobizinet.AutoUpdate = true;
559 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
562 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
563 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
565 this.tweetThumbnail1.Initialize(this.thumbGenerator);
568 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
569 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
570 this.HashMgr = new HashtagManage(this.HashSupl,
571 this.settings.Common.HashTags.ToArray(),
572 this.settings.Common.HashSelected,
573 this.settings.Common.HashIsPermanent,
574 this.settings.Common.HashIsHead,
575 this.settings.Common.HashIsNotAddToAtReply);
576 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
579 this.themeManager = new(this.settings.Local);
580 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
582 // StringFormatオブジェクトへの事前設定
583 this.sfTab.Alignment = StringAlignment.Center;
584 this.sfTab.LineAlignment = StringAlignment.Center;
586 this.InitDetailHtmlFormat();
587 this.tweetDetailsView.ClearPostBrowser();
589 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
591 this.history.Add(new StatusTextHistory(""));
593 this.inReplyTo = null;
596 this.SearchDialog.Owner = this;
597 this.urlDialog.Owner = this;
600 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
601 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
603 // 新着取得時のリストスクロールをするか。trueならスクロールしない
604 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
605 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
607 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
608 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
611 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
612 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
613 this.myLoc = this.settings.Local.FormLocation;
615 if (this.WindowState != FormWindowState.Minimized)
617 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
618 var outOfScreen = true;
619 if (Screen.AllScreens.Length == 1) // ハングするとの報告
621 foreach (var scr in Screen.AllScreens)
623 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
631 this.myLoc = new Point(0, 0);
633 this.DesktopLocation = this.myLoc;
635 this.TopMost = this.settings.Common.AlwaysTop;
636 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
637 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
638 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
640 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
641 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
643 this.StatusText.Font = this.themeManager.FontInputFont;
644 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
646 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
647 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
648 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
650 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
651 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
653 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
654 if (this.settings.Common.UnreadManage == false)
656 this.ReadedStripMenuItem.Enabled = false;
657 this.UnreadStripMenuItem.Enabled = false;
660 // リンク先URL表示部の初期化(画面左下)
661 this.StatusLabelUrl.Text = "";
663 this.StatusLabel.Text = "";
664 this.StatusLabel.AutoToolTip = false;
665 this.StatusLabel.ToolTipText = "";
667 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
669 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
670 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
671 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
672 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
674 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
675 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
676 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
677 this.SplitContainer2.Panel2.AccessibleName = "";
679 ////////////////////////////////////////////////////////////////////////////////
680 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
681 var mode = this.settings.Common.SortColumn switch
683 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
684 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
685 1 => ComparerMode.Nickname, // ニックネーム
686 2 => ComparerMode.Data, // 本文
687 3 => ComparerMode.Id, // 時刻=発言Id
688 4 => ComparerMode.Name, // 名前
689 7 => ComparerMode.Source, // Source
690 _ => ComparerMode.Id,
692 this.statuses.SetSortMode(mode, sortOrder);
693 ////////////////////////////////////////////////////////////////////////////////
695 this.ApplyListViewIconSize(this.settings.Common.IconSize);
697 // <<<<<<<<タブ関連>>>>>>>
698 foreach (var tab in this.statuses.Tabs)
700 if (!this.AddNewTab(tab, startup: true))
701 throw new TabException(Properties.Resources.TweenMain_LoadText1);
704 this.ListTabSelect(this.ListTab.SelectedTab);
707 this.SetTabAlignment();
709 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
710 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
712 if (this.settings.Common.TabIconDisp)
714 this.ListTab.DrawMode = TabDrawMode.Normal;
718 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
719 this.ListTab.DrawItem += this.ListTab_DrawItem;
720 this.ListTab.ImageList = null;
723 if (this.settings.Common.HotkeyEnabled)
726 var modKey = HookGlobalHotkey.ModKeys.None;
727 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
728 modKey |= HookGlobalHotkey.ModKeys.Alt;
729 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
730 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
731 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
732 modKey |= HookGlobalHotkey.ModKeys.Shift;
733 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
734 modKey |= HookGlobalHotkey.ModKeys.Win;
736 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
739 if (this.settings.Common.IsUseNotifyGrowl)
740 this.gh.RegisterGrowl();
742 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
744 this.SetMainWindowTitle();
745 this.SetNotifyIconText();
747 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
754 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
755 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
756 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
757 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
758 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
759 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
760 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
762 this.DoGetFollowersMenu(),
763 this.RefreshBlockIdsAsync(),
764 this.RefreshMuteUserIdsAsync(),
765 this.RefreshNoRetweetIdsAsync(),
766 this.RefreshTwitterConfigurationAsync(),
768 this.RefreshTimelineScheduler();
770 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
771 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
774 this.TimerRefreshIcon.Interval = 200;
775 this.TimerRefreshIcon.Enabled = false;
777 this.ignoreConfigSave = false;
778 this.TweenMain_Resize(this, EventArgs.Empty);
780 if (this.settings.IsFirstRun)
782 // 初回起動時だけ右下のメニューを目立たせる
783 this.HashStripSplitButton.ShowDropDown();
787 private void InitDetailHtmlFormat()
789 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
791 static string ColorToRGBString(Color color)
792 => $"{color.R},{color.G},{color.B}";
794 this.detailHtmlFormatPreparedTemplate = htmlTemplate
795 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
796 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
797 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
798 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
799 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
800 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
803 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
808 txt = this.statuses.Tabs[e.Index].TabName;
815 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
816 if (e.State == DrawItemState.Selected)
818 e.DrawFocusRectangle();
823 if (this.statuses.Tabs[txt].UnreadCount > 0)
826 fore = System.Drawing.SystemBrushes.ControlText;
830 fore = System.Drawing.SystemBrushes.ControlText;
832 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
835 private void LoadConfig()
837 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
838 this.statuses.AddDefaultTabs();
841 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
843 this.RefreshTimelineScheduler();
846 private void RefreshTimelineScheduler()
848 static TimeSpan IntervalSecondsOrDisabled(int seconds)
849 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
851 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
852 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
853 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
854 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
855 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
856 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
857 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
858 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
860 this.timelineScheduler.RefreshSchedule();
863 private void MarkSettingCommonModified()
865 if (this.saveConfigDebouncer == null)
868 this.ModifySettingCommon = true;
869 _ = this.saveConfigDebouncer.Call();
872 private void MarkSettingLocalModified()
874 if (this.saveConfigDebouncer == null)
877 this.ModifySettingLocal = true;
878 _ = this.saveConfigDebouncer.Call();
881 internal void MarkSettingAtIdModified()
883 if (this.saveConfigDebouncer == null)
886 this.ModifySettingAtId = true;
887 _ = this.saveConfigDebouncer.Call();
890 private void RefreshTimeline()
892 var curListView = this.CurrentListView;
894 // 現在表示中のタブのスクロール位置を退避
895 var currentListViewState = this.listViewState[this.CurrentTabName];
896 currentListViewState.Save(this.ListLockMenuItem.Checked);
900 addCount = this.statuses.SubmitUpdate(
903 out var newMentionOrDm,
906 if (MyCommon.EndingFlag) return;
909 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
911 using (ControlTransaction.Update(curListView))
913 this.listCache.PurgeCache();
914 this.listCache.UpdateListSize();
917 currentListViewState.RestoreSelection();
923 if (this.settings.Common.TabIconDisp)
925 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
927 var tabPage = this.ListTab.TabPages[index];
928 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
929 tabPage.ImageIndex = 0; // 未読アイコン
934 this.ListTab.Refresh();
939 currentListViewState.RestoreScroll();
942 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
944 this.SetMainWindowTitle();
945 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
947 this.HashSupl.AddRangeItem(this.tw.GetHashList());
950 private bool BalloonRequired()
955 if (NativeMethods.IsScreenSaverRunning())
959 if (!this.NewPostPopMenuItem.Checked)
962 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
963 if (this.settings.Common.LimitBalloon)
965 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
972 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
974 if (this.settings.Common.ReadOwnPost)
976 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
981 if (this.BalloonRequired())
983 if (notifyPosts != null && notifyPosts.Length > 0)
985 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
986 if (this.settings.Common.IsUseNotifyGrowl)
988 var sb = new StringBuilder();
992 foreach (var post in notifyPosts)
994 if (!(notifyPosts.Length > 3))
1000 if (post.IsReply && !post.IsExcludeReply) reply = true;
1001 if (post.IsDm) dm = true;
1002 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1003 switch (this.settings.Common.NameBalloon)
1005 case MyCommon.NameBalloonEnum.UserID:
1006 sb.Append(post.ScreenName).Append(" : ");
1008 case MyCommon.NameBalloonEnum.NickName:
1009 sb.Append(post.Nickname).Append(" : ");
1012 sb.Append(post.TextFromApi);
1013 if (notifyPosts.Length > 3)
1015 if (notifyPosts.Last() != post) continue;
1018 var title = new StringBuilder();
1019 GrowlHelper.NotifyType nt;
1020 if (this.settings.Common.DispUsername)
1022 title.Append(this.tw.Username);
1023 title.Append(" - ");
1028 title.Append(ApplicationSettings.ApplicationName);
1029 title.Append(" [DM] ");
1030 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1031 nt = GrowlHelper.NotifyType.DirectMessage;
1035 title.Append(ApplicationSettings.ApplicationName);
1036 title.Append(" [Reply!] ");
1037 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1038 nt = GrowlHelper.NotifyType.Reply;
1042 title.Append(ApplicationSettings.ApplicationName);
1044 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1045 nt = GrowlHelper.NotifyType.Notify;
1047 var bText = sb.ToString();
1048 if (MyCommon.IsNullOrEmpty(bText)) return;
1050 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1051 this.gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1056 var sb = new StringBuilder();
1059 foreach (var post in notifyPosts)
1061 if (post.IsReply && !post.IsExcludeReply) reply = true;
1062 if (post.IsDm) dm = true;
1063 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1064 switch (this.settings.Common.NameBalloon)
1066 case MyCommon.NameBalloonEnum.UserID:
1067 sb.Append(post.ScreenName).Append(" : ");
1069 case MyCommon.NameBalloonEnum.NickName:
1070 sb.Append(post.Nickname).Append(" : ");
1073 sb.Append(post.TextFromApi);
1076 var title = new StringBuilder();
1078 if (this.settings.Common.DispUsername)
1080 title.Append(this.tw.Username);
1081 title.Append(" - ");
1086 ntIcon = ToolTipIcon.Warning;
1087 title.Append(ApplicationSettings.ApplicationName);
1088 title.Append(" [DM] ");
1089 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1093 ntIcon = ToolTipIcon.Warning;
1094 title.Append(ApplicationSettings.ApplicationName);
1095 title.Append(" [Reply!] ");
1096 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1100 ntIcon = ToolTipIcon.Info;
1101 title.Append(ApplicationSettings.ApplicationName);
1103 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1105 var bText = sb.ToString();
1106 if (MyCommon.IsNullOrEmpty(bText)) return;
1108 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1109 this.NotifyIcon1.BalloonTipText = bText;
1110 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1111 this.NotifyIcon1.ShowBalloonTip(500);
1117 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1121 var dir = Application.StartupPath;
1122 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1124 dir = Path.Combine(dir, "Sounds");
1126 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1134 // mentions新着時に画面ブリンク
1135 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1137 NativeMethods.FlashMyWindow(this.Handle, 3);
1141 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1143 var listView = this.CurrentListView;
1144 if (listView != sender)
1147 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1148 this.CurrentTab.SelectPosts(indices);
1150 if (indices.Length != 1)
1153 var index = indices[0];
1154 if (index > listView.VirtualListSize - 1) return;
1156 this.PushSelectPostChain();
1158 var post = this.CurrentPost!;
1159 this.statuses.SetReadAllTab(post.StatusId, read: true);
1161 this.listCache?.RefreshStyle();
1162 await this.selectionDebouncer.Call();
1165 private void StatusTextHistoryBack()
1167 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1168 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1171 if (this.hisIdx < 0)
1174 var historyItem = this.history[this.hisIdx];
1175 this.inReplyTo = historyItem.InReplyTo;
1176 this.StatusText.Text = historyItem.Status;
1177 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1180 private void StatusTextHistoryForward()
1182 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1183 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1186 if (this.hisIdx > this.history.Count - 1)
1187 this.hisIdx = this.history.Count - 1;
1189 var historyItem = this.history[this.hisIdx];
1190 this.inReplyTo = historyItem.InReplyTo;
1191 this.StatusText.Text = historyItem.Status;
1192 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1195 private async void PostButton_Click(object sender, EventArgs e)
1197 if (this.StatusText.Text.Trim().Length == 0)
1199 if (!this.ImageSelector.Enabled)
1201 await this.DoRefresh();
1206 var currentPost = this.CurrentPost;
1207 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1209 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1211 MessageBoxButtons.YesNoCancel,
1212 MessageBoxIcon.Question);
1215 case DialogResult.Yes:
1216 this.StatusText.Text = "";
1217 await this.DoReTweetOfficial(false);
1219 case DialogResult.Cancel:
1224 if (TextContainsOnlyMentions(this.StatusText.Text))
1226 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1227 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1229 if (ret != DialogResult.OK)
1233 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1235 if (this.settings.Common.Nicoms)
1237 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1238 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1241 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1242 this.CheckReplyTo(this.StatusText.Text);
1244 var status = new PostStatusParams();
1246 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1247 if (this.GetRestStatusCount(statusTextCompat) >= 0)
1249 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1250 // 収まる場合はこれらのオプションを使用せずに投稿する
1251 status.Text = statusTextCompat;
1252 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1256 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1257 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1259 status.AttachmentUrl = attachmentUrl;
1261 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1263 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1264 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1266 status.AutoPopulateReplyMetadata = true;
1268 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1269 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1274 if (this.GetRestStatusCount(status.Text) < 0)
1276 // 文字数制限を超えているが強制的に投稿するか
1277 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1278 if (ret != DialogResult.OK)
1282 IMediaUploadService? uploadService = null;
1283 IMediaItem[]? uploadItems = null;
1284 if (this.ImageSelector.Visible)
1287 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1290 this.ImageSelector.EndSelection();
1291 uploadService = this.ImageSelector.Model.GetService(serviceName);
1294 this.inReplyTo = null;
1295 this.StatusText.Text = "";
1296 this.history.Add(new StatusTextHistory(""));
1297 this.hisIdx = this.history.Count - 1;
1298 if (!this.settings.Common.FocusLockToStatusText)
1299 this.CurrentListView.Focus();
1300 this.urlUndoBuffer = null;
1301 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1304 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1306 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1307 await MyCommon.OpenInBrowserAsync(this, tmp);
1310 await this.PostMessageAsync(status, uploadService, uploadItems);
1313 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1315 MyCommon.EndingFlag = true;
1319 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1321 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1323 // _endingFlag=false:フォームの×ボタン
1325 this.Visible = false;
1329 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1330 this.ignoreConfigSave = true;
1331 MyCommon.EndingFlag = true;
1332 this.timelineScheduler.Enabled = false;
1333 this.TimerRefreshIcon.Enabled = false;
1337 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1339 this.Visible = true;
1340 if (this.WindowState == FormWindowState.Minimized)
1342 this.WindowState = FormWindowState.Normal;
1345 this.BringToFront();
1348 private static int errorCount = 0;
1350 private static bool CheckAccountValid()
1352 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1358 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1367 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1368 private Task RefreshTabAsync<T>()
1370 => this.RefreshTabAsync<T>(backward: false);
1372 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1373 private Task RefreshTabAsync<T>(bool backward)
1377 from tab in this.statuses.GetTabsByType<T>()
1378 select this.RefreshTabAsync(tab, backward);
1380 return Task.WhenAll(loadTasks);
1383 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1384 private Task RefreshTabAsync(TabModel tab)
1385 => this.RefreshTabAsync(tab, backward: false);
1387 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1388 private async Task RefreshTabAsync(TabModel tab, bool backward)
1390 await this.workerSemaphore.WaitAsync();
1394 this.RefreshTasktrayIcon();
1395 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1397 catch (WebApiException ex)
1399 this.myStatusError = true;
1400 var tabType = tab switch
1402 HomeTabModel => "GetTimeline",
1403 MentionsTabModel => "GetTimeline",
1404 DirectMessagesTabModel => "GetDirectMessage",
1405 FavoritesTabModel => "GetFavorites",
1406 PublicSearchTabModel => "GetSearch",
1407 UserTimelineTabModel => "GetUserTimeline",
1408 ListTimelineTabModel => "GetListStatus",
1409 RelatedPostsTabModel => "GetRelatedTweets",
1410 _ => tab.GetType().Name.Replace("Model", ""),
1412 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1416 this.RefreshTimeline();
1417 this.workerSemaphore.Release();
1421 private async Task FavAddAsync(long statusId, TabModel tab)
1423 await this.workerSemaphore.WaitAsync();
1427 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1429 this.RefreshTasktrayIcon();
1430 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1432 catch (WebApiException ex)
1434 this.myStatusError = true;
1435 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1439 this.workerSemaphore.Release();
1443 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
1445 if (ct.IsCancellationRequested)
1448 if (!CheckAccountValid())
1449 throw new WebApiException("Auth error. Check your account");
1451 if (!tab.Posts.TryGetValue(statusId, out var post))
1457 await Task.Run(async () =>
1459 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1465 await this.tw.Api.FavoritesCreate(post.RetweetedId ?? post.StatusId)
1467 .ConfigureAwait(false);
1469 catch (TwitterApiException ex)
1470 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1472 // エラーコード 139 のみの場合は成功と見なす
1475 if (this.settings.Common.RestrictFavCheck)
1477 var status = await this.tw.Api.StatusesShow(post.RetweetedId ?? post.StatusId)
1478 .ConfigureAwait(false);
1480 if (status.Favorited != true)
1481 throw new WebApiException("NG(Restricted?)");
1484 this.favTimestamps.Add(DateTimeUtc.Now);
1487 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1489 postTl.IsFav = true;
1491 var favTab = this.statuses.FavoriteTab;
1492 favTab.AddPostQueue(postTl);
1495 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1496 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1498 if (tb.Contains(statusId))
1499 tb.Posts[statusId].IsFav = true;
1502 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1504 catch (WebApiException)
1506 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1511 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1512 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1514 if (this.favTimestamps[i] < oneHour)
1515 this.favTimestamps.RemoveAt(i);
1518 this.statuses.DistributePosts();
1521 if (ct.IsCancellationRequested)
1524 this.RefreshTimeline();
1526 if (this.CurrentTabName == tab.TabName)
1528 using (ControlTransaction.Update(this.CurrentListView))
1530 var idx = tab.IndexOf(statusId);
1532 this.listCache?.RefreshStyle(idx);
1535 var currentPost = this.CurrentPost;
1536 if (currentPost != null && statusId == currentPost.StatusId)
1537 this.DispSelectedPost(true); // 選択アイテム再表示
1541 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
1543 await this.workerSemaphore.WaitAsync();
1547 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1549 this.RefreshTasktrayIcon();
1550 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1552 catch (WebApiException ex)
1554 this.myStatusError = true;
1555 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1559 this.workerSemaphore.Release();
1563 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
1565 if (ct.IsCancellationRequested)
1568 if (!CheckAccountValid())
1569 throw new WebApiException("Auth error. Check your account");
1571 var successIds = new List<long>();
1573 await Task.Run(async () =>
1577 var failedCount = 0;
1578 foreach (var statusId in statusIds)
1582 var post = tab.Posts[statusId];
1584 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1591 await this.tw.Api.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
1593 .ConfigureAwait(false);
1595 catch (WebApiException)
1601 successIds.Add(statusId);
1602 post.IsFav = false; // リスト再描画必要
1604 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1605 tabinfoPost.IsFav = false;
1607 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1608 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1610 if (tb.Contains(statusId))
1611 tb.Posts[statusId].IsFav = false;
1616 if (ct.IsCancellationRequested)
1619 var favTab = this.statuses.FavoriteTab;
1620 foreach (var statusId in successIds)
1622 // ツイートが削除された訳ではないので IsDeleted はセットしない
1623 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1626 this.RefreshTimeline();
1628 if (this.CurrentTabName == tab.TabName)
1630 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1636 using (ControlTransaction.Update(this.CurrentListView))
1638 foreach (var statusId in successIds)
1640 var idx = tab.IndexOf(statusId);
1642 this.listCache?.RefreshStyle(idx);
1646 var currentPost = this.CurrentPost;
1647 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1648 this.DispSelectedPost(true); // 選択アイテム再表示
1653 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1655 await this.workerSemaphore.WaitAsync();
1659 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1661 this.RefreshTasktrayIcon();
1662 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1664 catch (WebApiException ex)
1666 this.myStatusError = true;
1667 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1671 this.workerSemaphore.Release();
1675 private async Task PostMessageAsyncInternal(
1676 IProgress<string> p,
1677 CancellationToken ct,
1678 PostStatusParams postParams,
1679 IMediaUploadService? uploadService,
1680 IMediaItem[]? uploadItems)
1682 if (ct.IsCancellationRequested)
1685 if (!CheckAccountValid())
1686 throw new WebApiException("Auth error. Check your account");
1688 p.Report("Posting...");
1690 PostClass? post = null;
1695 await Task.Run(async () =>
1697 var postParamsWithMedia = postParams;
1699 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1701 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1702 .ConfigureAwait(false);
1705 post = await this.tw.PostStatus(postParamsWithMedia)
1706 .ConfigureAwait(false);
1709 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1711 catch (WebApiException ex)
1713 // 処理は中断せずエラーの表示のみ行う
1714 errMsg = $"Err:{ex.Message}(PostMessage)";
1716 this.myStatusError = true;
1718 catch (UnauthorizedAccessException ex)
1720 // アップロード対象のファイルが開けなかった場合など
1721 errMsg = $"Err:{ex.Message}(PostMessage)";
1723 this.myStatusError = true;
1727 // 使い終わった MediaItem は破棄する
1728 if (uploadItems != null)
1730 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1732 disposableItem.Dispose();
1737 if (ct.IsCancellationRequested)
1740 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1741 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1742 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1744 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1746 var ret = MessageBox.Show(
1748 "Failed to update status",
1749 MessageBoxButtons.RetryCancel,
1750 MessageBoxIcon.Question);
1752 if (ret == DialogResult.Retry)
1754 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1758 this.StatusTextHistoryBack();
1759 this.StatusText.Focus();
1761 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1762 if (this.settings.Common.FocusLockToStatusText)
1763 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1768 this.postTimestamps.Add(DateTimeUtc.Now);
1770 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1771 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1773 if (this.postTimestamps[i] < oneHour)
1774 this.postTimestamps.RemoveAt(i);
1777 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1779 this.HashMgr.ClearHashtag();
1780 this.HashStripSplitButton.Text = "#[-]";
1781 this.HashTogglePullDownMenuItem.Checked = false;
1782 this.HashToggleMenuItem.Checked = false;
1785 this.SetMainWindowTitle();
1790 this.statuses.AddPost(post);
1791 this.statuses.DistributePosts();
1792 this.RefreshTimeline();
1795 if (this.settings.Common.PostAndGet)
1796 await this.RefreshTabAsync<HomeTabModel>();
1799 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
1801 await this.workerSemaphore.WaitAsync();
1805 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1807 this.RefreshTasktrayIcon();
1808 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1810 catch (WebApiException ex)
1812 this.myStatusError = true;
1813 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1817 this.workerSemaphore.Release();
1821 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
1823 if (ct.IsCancellationRequested)
1826 if (!CheckAccountValid())
1827 throw new WebApiException("Auth error. Check your account");
1830 if (!this.settings.Common.UnreadManage)
1833 read = this.initial && this.settings.Common.Read;
1835 p.Report("Posting...");
1837 var posts = new List<PostClass>();
1839 await Task.Run(async () =>
1841 foreach (var statusId in statusIds)
1843 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1844 if (post != null) posts.Add(post);
1848 if (ct.IsCancellationRequested)
1851 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1853 this.postTimestamps.Add(DateTimeUtc.Now);
1855 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1856 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1858 if (this.postTimestamps[i] < oneHour)
1859 this.postTimestamps.RemoveAt(i);
1862 // 自分のRTはTLの更新では取得できない場合があるので、
1863 // 投稿時取得の有無に関わらず追加しておく
1864 posts.ForEach(post => this.statuses.AddPost(post));
1866 if (this.settings.Common.PostAndGet)
1868 await this.RefreshTabAsync<HomeTabModel>();
1872 this.statuses.DistributePosts();
1873 this.RefreshTimeline();
1877 private async Task RefreshFollowerIdsAsync()
1879 await this.workerSemaphore.WaitAsync();
1883 this.RefreshTasktrayIcon();
1884 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1886 await this.tw.RefreshFollowerIds();
1888 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1890 this.RefreshTimeline();
1891 this.listCache?.PurgeCache();
1892 this.CurrentListView.Refresh();
1894 catch (WebApiException ex)
1896 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1900 this.workerSemaphore.Release();
1904 private async Task RefreshNoRetweetIdsAsync()
1906 await this.workerSemaphore.WaitAsync();
1910 this.RefreshTasktrayIcon();
1911 await this.tw.RefreshNoRetweetIds();
1913 this.StatusLabel.Text = "NoRetweetIds refreshed";
1915 catch (WebApiException ex)
1917 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1921 this.workerSemaphore.Release();
1925 private async Task RefreshBlockIdsAsync()
1927 await this.workerSemaphore.WaitAsync();
1931 this.RefreshTasktrayIcon();
1932 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1934 await this.tw.RefreshBlockIds();
1936 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1938 catch (WebApiException ex)
1940 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1944 this.workerSemaphore.Release();
1948 private async Task RefreshTwitterConfigurationAsync()
1950 await this.workerSemaphore.WaitAsync();
1954 this.RefreshTasktrayIcon();
1955 await this.tw.RefreshConfiguration();
1957 if (this.tw.Configuration.PhotoSizeLimit != 0)
1959 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1961 service.UpdateTwitterConfiguration(this.tw.Configuration);
1965 this.listCache?.PurgeCache();
1966 this.CurrentListView.Refresh();
1968 catch (WebApiException ex)
1970 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1974 this.workerSemaphore.Release();
1978 private async Task RefreshMuteUserIdsAsync()
1980 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1984 await this.tw.RefreshMuteUserIdsAsync();
1986 catch (WebApiException ex)
1988 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1992 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1995 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1997 if (e.Button == MouseButtons.Left)
1999 this.Visible = true;
2000 if (this.WindowState == FormWindowState.Minimized)
2002 this.WindowState = this.formWindowState;
2005 this.BringToFront();
2009 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2010 => await this.ListItemDoubleClickAction();
2012 private async Task ListItemDoubleClickAction()
2014 switch (this.settings.Common.ListDoubleClickAction)
2016 case MyCommon.ListItemDoubleClickActionType.Reply:
2017 this.MakeReplyText();
2019 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2020 this.MakeReplyText(atAll: true);
2022 case MyCommon.ListItemDoubleClickActionType.Favorite:
2023 await this.FavoriteChange(true);
2025 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2026 var post = this.CurrentPost;
2028 await this.ShowUserStatus(post.ScreenName, false);
2030 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2031 await this.ShowUserTimeline();
2033 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2034 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2036 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2037 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2039 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2040 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2042 case MyCommon.ListItemDoubleClickActionType.None:
2049 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2050 => await this.FavoriteChange(true);
2052 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2053 => await this.FavoriteChange(false);
2055 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2056 => await this.FavoritesRetweetOfficial();
2058 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2059 => await this.FavoritesRetweetUnofficial();
2061 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2063 var tab = this.CurrentTab;
2064 var posts = tab.SelectedPosts;
2066 // trueでFavAdd,falseでFavRemove
2067 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2068 || !this.ExistCurrentPost) return;
2070 if (posts.Length > 1)
2075 // https://support.twitter.com/articles/76915#favoriting
2076 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2077 this.doFavRetweetFlags = false;
2082 if (multiFavoriteChangeDialogEnable)
2084 var confirm = MessageBox.Show(
2085 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2086 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2087 MessageBoxButtons.OKCancel,
2088 MessageBoxIcon.Question);
2090 if (confirm == DialogResult.Cancel)
2098 var selectedPost = posts.Single();
2099 if (selectedPost.IsFav)
2101 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2105 await this.FavAddAsync(selectedPost.StatusId, tab);
2109 var selectedPosts = posts.Where(x => x.IsFav);
2110 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2111 if (statusIds.Length == 0)
2113 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2117 await this.FavRemoveAsync(statusIds, tab);
2121 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2123 var post = this.CurrentPost;
2125 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2127 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2130 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2132 if ((!this.initialLayout) && this.Visible)
2134 if (this.WindowState == FormWindowState.Normal)
2136 this.mySize = this.ClientSize;
2137 this.mySpDis = this.SplitContainer1.SplitterDistance;
2138 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2139 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2140 this.MarkSettingLocalModified();
2145 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2147 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2148 if (comparerMode == null)
2151 this.SetSortColumn(comparerMode.Value);
2155 /// 列インデックスからソートを行う ComparerMode を求める
2157 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2158 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2159 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2161 if (this.Use2ColumnsMode)
2162 return ComparerMode.Id;
2164 return columnIndex switch
2166 1 => ComparerMode.Nickname, // ニックネーム
2167 2 => ComparerMode.Data, // 本文
2168 3 => ComparerMode.Id, // 時刻=発言Id
2169 4 => ComparerMode.Name, // 名前
2170 7 => ComparerMode.Source, // Source
2171 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2176 /// 発言一覧の指定した位置の列でソートする
2178 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2179 private void SetSortColumnByDisplayIndex(int columnIndex)
2181 // 表示上の列の位置から ColumnHeader を求める
2182 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2183 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2188 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2189 if (comparerMode == null)
2192 this.SetSortColumn(comparerMode.Value);
2196 /// 発言一覧の最後列の項目でソートする
2198 private void SetSortLastColumn()
2200 // 表示上の最後列にある ColumnHeader を求める
2201 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2202 .OrderByDescending(x => x.DisplayIndex)
2205 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2206 if (comparerMode == null)
2209 this.SetSortColumn(comparerMode.Value);
2213 /// 発言一覧を指定された ComparerMode に基づいてソートする
2215 private void SetSortColumn(ComparerMode sortColumn)
2217 if (this.settings.Common.SortOrderLock)
2220 this.statuses.ToggleSortOrder(sortColumn);
2221 this.InitColumnText();
2223 var list = this.CurrentListView;
2224 if (this.Use2ColumnsMode)
2226 list.Columns[0].Text = this.columnText[0];
2227 list.Columns[1].Text = this.columnText[2];
2231 for (var i = 0; i <= 7; i++)
2233 list.Columns[i].Text = this.columnText[i];
2237 this.listCache?.PurgeCache();
2239 var tab = this.CurrentTab;
2240 var post = this.CurrentPost;
2241 if (tab.AllCount > 0 && post != null)
2243 var idx = tab.IndexOf(post.StatusId);
2246 this.SelectListItem(list, idx);
2247 list.EnsureVisible(idx);
2252 this.MarkSettingCommonModified();
2255 private void TweenMain_LocationChanged(object sender, EventArgs e)
2257 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2259 this.myLoc = this.DesktopLocation;
2260 this.MarkSettingLocalModified();
2264 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2266 var post = this.CurrentPost;
2267 if (!this.ExistCurrentPost)
2269 this.ReplyStripMenuItem.Enabled = false;
2270 this.ReplyAllStripMenuItem.Enabled = false;
2271 this.DMStripMenuItem.Enabled = false;
2272 this.TabMenuItem.Enabled = false;
2273 this.IDRuleMenuItem.Enabled = false;
2274 this.SourceRuleMenuItem.Enabled = false;
2275 this.ReadedStripMenuItem.Enabled = false;
2276 this.UnreadStripMenuItem.Enabled = false;
2277 this.AuthorContextMenuItem.Visible = false;
2278 this.RetweetedByContextMenuItem.Visible = false;
2282 this.ReplyStripMenuItem.Enabled = true;
2283 this.ReplyAllStripMenuItem.Enabled = true;
2284 this.DMStripMenuItem.Enabled = true;
2285 this.TabMenuItem.Enabled = true;
2286 this.IDRuleMenuItem.Enabled = true;
2287 this.SourceRuleMenuItem.Enabled = true;
2288 this.ReadedStripMenuItem.Enabled = true;
2289 this.UnreadStripMenuItem.Enabled = true;
2290 this.AuthorContextMenuItem.Visible = true;
2291 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2292 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2293 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2295 var tab = this.CurrentTab;
2296 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2298 this.FavAddToolStripMenuItem.Enabled = false;
2299 this.FavRemoveToolStripMenuItem.Enabled = false;
2300 this.StatusOpenMenuItem.Enabled = false;
2301 this.ShowRelatedStatusesMenuItem.Enabled = false;
2303 this.ReTweetStripMenuItem.Enabled = false;
2304 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2305 this.QuoteStripMenuItem.Enabled = false;
2306 this.FavoriteRetweetContextMenu.Enabled = false;
2307 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2311 this.FavAddToolStripMenuItem.Enabled = true;
2312 this.FavRemoveToolStripMenuItem.Enabled = true;
2313 this.StatusOpenMenuItem.Enabled = true;
2314 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2316 if (!post.CanRetweetBy(this.tw.UserId))
2318 this.ReTweetStripMenuItem.Enabled = false;
2319 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2320 this.QuoteStripMenuItem.Enabled = false;
2321 this.FavoriteRetweetContextMenu.Enabled = false;
2322 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2326 this.ReTweetStripMenuItem.Enabled = true;
2327 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2328 this.QuoteStripMenuItem.Enabled = true;
2329 this.FavoriteRetweetContextMenu.Enabled = true;
2330 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2334 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2336 this.RepliedStatusOpenMenuItem.Enabled = false;
2340 this.RepliedStatusOpenMenuItem.Enabled = true;
2343 if (this.ExistCurrentPost && post != null)
2345 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2346 if (post.RetweetedByUserId == this.tw.UserId)
2347 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2349 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2353 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2354 => this.MakeReplyText();
2356 private void DMStripMenuItem_Click(object sender, EventArgs e)
2357 => this.MakeDirectMessageText();
2359 private async Task DoStatusDelete()
2361 var posts = this.CurrentTab.SelectedPosts;
2362 if (posts.Length == 0)
2365 // 選択されたツイートの中に削除可能なものが一つでもあるか
2366 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2369 var ret = MessageBox.Show(
2371 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2372 Properties.Resources.DeleteStripMenuItem_ClickText2,
2373 MessageBoxButtons.OKCancel,
2374 MessageBoxIcon.Question);
2376 if (ret != DialogResult.OK)
2379 var currentListView = this.CurrentListView;
2380 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2382 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2384 Exception? lastException = null;
2385 foreach (var post in posts)
2387 if (!post.CanDeleteBy(this.tw.UserId))
2394 await this.tw.Api.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
2398 if (post.RetweetedByUserId == this.tw.UserId)
2400 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2402 await this.tw.Api.StatusesDestroy(post.StatusId)
2407 if (post.UserId == this.tw.UserId)
2409 if (post.RetweetedId != null)
2411 // 他人に RT された自分のツイート
2412 // => RT 元の自分のツイートを削除
2413 await this.tw.Api.StatusesDestroy(post.RetweetedId.Value)
2420 await this.tw.Api.StatusesDestroy(post.StatusId)
2427 catch (WebApiException ex)
2433 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2436 if (lastException == null)
2437 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2439 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2441 using (ControlTransaction.Update(currentListView))
2443 this.listCache?.PurgeCache();
2444 this.listCache?.UpdateListSize();
2446 currentListView.SelectedIndices.Clear();
2448 var currentTab = this.CurrentTab;
2449 if (currentTab.AllCount != 0)
2452 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2453 selectedIndex = focusedIndex;
2455 selectedIndex = currentTab.AllCount - 1;
2457 currentListView.SelectedIndices.Add(selectedIndex);
2458 currentListView.EnsureVisible(selectedIndex);
2459 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2463 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2465 var tabPage = this.ListTab.TabPages[index];
2466 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2468 if (tabPage.ImageIndex == 0)
2469 tabPage.ImageIndex = -1; // タブアイコン
2473 if (!this.settings.Common.TabIconDisp)
2474 this.ListTab.Refresh();
2478 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2479 => await this.DoStatusDelete();
2481 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2483 using (ControlTransaction.Update(this.CurrentListView))
2485 var tab = this.CurrentTab;
2486 foreach (var statusId in tab.SelectedStatusIds)
2488 this.statuses.SetReadAllTab(statusId, read: true);
2489 var idx = tab.IndexOf(statusId);
2490 this.listCache?.RefreshStyle(idx);
2493 if (this.settings.Common.TabIconDisp)
2495 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2497 if (tab.UnreadCount == 0)
2499 var tabPage = this.ListTab.TabPages[index];
2500 if (tabPage.ImageIndex == 0)
2501 tabPage.ImageIndex = -1; // タブアイコン
2505 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2508 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2510 using (ControlTransaction.Update(this.CurrentListView))
2512 var tab = this.CurrentTab;
2513 foreach (var statusId in tab.SelectedStatusIds)
2515 this.statuses.SetReadAllTab(statusId, read: false);
2516 var idx = tab.IndexOf(statusId);
2517 this.listCache?.RefreshStyle(idx);
2520 if (this.settings.Common.TabIconDisp)
2522 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2524 if (tab.UnreadCount > 0)
2526 var tabPage = this.ListTab.TabPages[index];
2527 if (tabPage.ImageIndex == -1)
2528 tabPage.ImageIndex = 0; // タブアイコン
2532 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2535 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2536 => await this.DoRefresh();
2538 private async Task DoRefresh()
2539 => await this.RefreshTabAsync(this.CurrentTab);
2541 private async Task DoRefreshMore()
2542 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2544 private DialogResult ShowSettingDialog()
2546 using var settingDialog = new AppendSettingDialog();
2547 settingDialog.Icon = this.iconAssets.IconMain;
2548 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2550 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2552 DialogResult result;
2555 result = settingDialog.ShowDialog(this);
2559 return DialogResult.Abort;
2562 if (result == DialogResult.OK)
2564 lock (this.syncObject)
2566 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2573 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2576 var previousUserId = this.settings.Common.UserId;
2577 var oldIconCol = this.Use2ColumnsMode;
2579 if (this.ShowSettingDialog() == DialogResult.OK)
2581 lock (this.syncObject)
2583 this.settings.ApplySettings();
2585 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2586 this.tw.ClearAuthInfo();
2588 var account = this.settings.Common.SelectedAccount;
2589 if (account != null)
2590 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
2592 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
2594 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2595 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2597 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2601 if (this.settings.Common.TabIconDisp)
2603 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2604 this.ListTab.DrawMode = TabDrawMode.Normal;
2605 this.ListTab.ImageList = this.TabImage;
2609 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2610 this.ListTab.DrawItem += this.ListTab_DrawItem;
2611 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2612 this.ListTab.ImageList = null;
2615 catch (Exception ex)
2617 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2618 ex.Data["IsTerminatePermission"] = false;
2624 if (!this.settings.Common.UnreadManage)
2626 this.ReadedStripMenuItem.Enabled = false;
2627 this.UnreadStripMenuItem.Enabled = false;
2628 if (this.settings.Common.TabIconDisp)
2630 foreach (TabPage myTab in this.ListTab.TabPages)
2632 myTab.ImageIndex = -1;
2638 this.ReadedStripMenuItem.Enabled = true;
2639 this.UnreadStripMenuItem.Enabled = true;
2642 catch (Exception ex)
2644 ex.Data["Instance"] = "ListTab(UnreadManage)";
2645 ex.Data["IsTerminatePermission"] = false;
2650 this.SetTabAlignment();
2652 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2654 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2655 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2656 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2658 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2659 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2660 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2661 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2663 var newTheme = new ThemeManager(this.settings.Local);
2664 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2665 this.tweetDetailsView.Theme = this.themeManager;
2666 if (this.listDrawer != null)
2667 this.listDrawer.Theme = this.themeManager;
2672 if (this.StatusText.Focused)
2673 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2675 this.StatusText.Font = this.themeManager.FontInputFont;
2676 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2678 catch (Exception ex)
2680 MessageBox.Show(ex.Message);
2685 this.InitDetailHtmlFormat();
2687 catch (Exception ex)
2689 ex.Data["Instance"] = "Font";
2690 ex.Data["IsTerminatePermission"] = false;
2696 if (this.settings.Common.TabIconDisp)
2698 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2700 var tabPage = this.ListTab.TabPages[index];
2701 if (tab.UnreadCount == 0)
2702 tabPage.ImageIndex = -1;
2704 tabPage.ImageIndex = 0;
2708 catch (Exception ex)
2710 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2711 ex.Data["IsTerminatePermission"] = false;
2717 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2719 foreach (TabPage tp in this.ListTab.TabPages)
2721 var lst = (DetailsListView)tp.Tag;
2723 using (ControlTransaction.Update(lst))
2725 lst.GridLines = this.settings.Common.ShowGrid;
2727 if (this.Use2ColumnsMode != oldIconCol)
2728 this.ResetColumns(lst);
2732 catch (Exception ex)
2734 ex.Data["Instance"] = "ListView(IconSize)";
2735 ex.Data["IsTerminatePermission"] = false;
2739 this.SetMainWindowTitle();
2740 this.SetNotifyIconText();
2742 this.listCache?.PurgeCache();
2743 this.CurrentListView.Refresh();
2744 this.ListTab.Refresh();
2746 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2747 if (this.settings.Common.HotkeyEnabled)
2749 // グローバルホットキーの登録。設定で変更可能にするかも
2750 var modKey = HookGlobalHotkey.ModKeys.None;
2751 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2752 modKey |= HookGlobalHotkey.ModKeys.Alt;
2753 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2754 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2755 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2756 modKey |= HookGlobalHotkey.ModKeys.Shift;
2757 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2758 modKey |= HookGlobalHotkey.ModKeys.Win;
2760 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2763 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2766 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2774 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2776 this.TopMost = this.settings.Common.AlwaysTop;
2777 this.SaveConfigsAll(false);
2779 if (this.tw.UserId != previousUserId)
2780 await this.DoGetFollowersMenu();
2786 private void SetTabAlignment()
2788 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2789 if (this.ListTab.Alignment == newAlignment) return;
2792 var currentListViewState = this.listViewState[this.CurrentTabName];
2793 currentListViewState.Save(this.ListLockMenuItem.Checked);
2795 this.ListTab.Alignment = newAlignment;
2797 currentListViewState.Restore(forceScroll: true);
2800 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2803 if (this.listDrawer != null)
2805 this.listDrawer.IconSize = iconSz;
2806 this.listDrawer.UpdateItemHeight();
2809 this.listCache?.PurgeCache();
2812 private void ResetColumns(DetailsListView list)
2814 using (ControlTransaction.Update(list))
2815 using (ControlTransaction.Layout(list, false))
2818 list.ColumnClick -= this.MyList_ColumnClick;
2819 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2820 list.ColumnReordered -= this.MyList_ColumnReordered;
2821 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2823 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2824 list.Columns.Clear();
2825 cols.ForEach(col => col.Dispose());
2828 this.InitColumns(list, true);
2830 list.ColumnClick += this.MyList_ColumnClick;
2831 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2832 list.ColumnReordered += this.MyList_ColumnReordered;
2833 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2837 public void AddNewTabForSearch(string searchWord)
2839 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2840 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2842 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2844 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2845 this.ListTab.SelectedIndex = tabIndex;
2850 var tabName = searchWord;
2851 for (var i = 0; i <= 100; i++)
2853 if (this.statuses.ContainsTab(tabName))
2859 var tab = new PublicSearchTabModel(tabName);
2860 this.statuses.AddTab(tab);
2861 this.AddNewTab(tab, startup: false);
2863 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2865 var tabPage = this.CurrentTabPage;
2866 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2867 cmb.Items.Add(searchWord);
2868 cmb.Text = searchWord;
2869 this.SaveConfigsTabs();
2871 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2874 private async Task ShowUserTimeline()
2876 var post = this.CurrentPost;
2877 if (post == null || !this.ExistCurrentPost) return;
2878 await this.AddNewTabForUserTimeline(post.ScreenName);
2881 private async Task ShowRetweeterTimeline()
2883 var retweetedBy = this.CurrentPost?.RetweetedBy;
2884 if (retweetedBy == null || !this.ExistCurrentPost) return;
2885 await this.AddNewTabForUserTimeline(retweetedBy);
2888 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2890 if (e.KeyCode == Keys.Escape)
2892 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2893 this.SaveConfigsTabs();
2894 e.SuppressKeyPress = true;
2898 public async Task AddNewTabForUserTimeline(string user)
2900 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2901 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2903 if (tb.ScreenName == user)
2905 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2906 this.ListTab.SelectedIndex = tabIndex;
2911 var tabName = "user:" + user;
2912 while (this.statuses.ContainsTab(tabName))
2917 var tab = new UserTimelineTabModel(tabName, user);
2918 this.statuses.AddTab(tab);
2919 this.AddNewTab(tab, startup: false);
2921 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2922 this.SaveConfigsTabs();
2924 await this.RefreshTabAsync(tab);
2927 public bool AddNewTab(TabModel tab, bool startup)
2930 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2934 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2936 var tabPage = new TabPage();
2937 var listCustom = new DetailsListView();
2939 var cnt = this.statuses.Tabs.Count;
2941 // ToDo:Create and set controls follow tabtypes
2943 using (ControlTransaction.Update(listCustom))
2944 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2945 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2946 using (ControlTransaction.Layout(this.SplitContainer1, false))
2947 using (ControlTransaction.Layout(this.ListTab, false))
2948 using (ControlTransaction.Layout(this))
2949 using (ControlTransaction.Layout(tabPage, false))
2951 tabPage.Controls.Add(listCustom);
2954 var userTab = tab as UserTimelineTabModel;
2955 var listTab = tab as ListTimelineTabModel;
2956 var searchTab = tab as PublicSearchTabModel;
2958 if (userTab != null || listTab != null)
2960 var label = new Label
2962 Dock = DockStyle.Top,
2967 if (listTab != null)
2969 label.Text = listTab.ListInfo.ToString();
2971 else if (userTab != null)
2973 label.Text = userTab.ScreenName + "'s Timeline";
2975 label.TextAlign = ContentAlignment.MiddleLeft;
2976 using (var tmpComboBox = new ComboBox())
2978 label.Height = tmpComboBox.Height;
2980 tabPage.Controls.Add(label);
2983 else if (searchTab != null)
2985 var pnl = new Panel();
2987 var lbl = new Label();
2988 var cmb = new ComboBox();
2989 var btn = new Button();
2990 var cmbLang = new ComboBox();
2992 using (ControlTransaction.Layout(pnl, false))
2994 pnl.Controls.Add(cmb);
2995 pnl.Controls.Add(cmbLang);
2996 pnl.Controls.Add(btn);
2997 pnl.Controls.Add(lbl);
2998 pnl.Name = "panelSearch";
3000 pnl.Dock = DockStyle.Top;
3001 pnl.Height = cmb.Height;
3002 pnl.Enter += this.SearchControls_Enter;
3003 pnl.Leave += this.SearchControls_Leave;
3006 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3007 cmb.Dock = DockStyle.Fill;
3008 cmb.Name = "comboSearch";
3009 cmb.DropDownStyle = ComboBoxStyle.DropDown;
3010 cmb.ImeMode = ImeMode.NoControl;
3011 cmb.TabStop = false;
3013 cmb.AutoCompleteMode = AutoCompleteMode.None;
3014 cmb.KeyDown += this.SearchComboBox_KeyDown;
3017 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3018 cmbLang.Dock = DockStyle.Right;
3020 cmbLang.Name = "comboLang";
3021 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3022 cmbLang.TabStop = false;
3023 cmbLang.TabIndex = 2;
3024 cmbLang.Items.Add("");
3025 cmbLang.Items.Add("ja");
3026 cmbLang.Items.Add("en");
3027 cmbLang.Items.Add("ar");
3028 cmbLang.Items.Add("da");
3029 cmbLang.Items.Add("nl");
3030 cmbLang.Items.Add("fa");
3031 cmbLang.Items.Add("fi");
3032 cmbLang.Items.Add("fr");
3033 cmbLang.Items.Add("de");
3034 cmbLang.Items.Add("hu");
3035 cmbLang.Items.Add("is");
3036 cmbLang.Items.Add("it");
3037 cmbLang.Items.Add("no");
3038 cmbLang.Items.Add("pl");
3039 cmbLang.Items.Add("pt");
3040 cmbLang.Items.Add("ru");
3041 cmbLang.Items.Add("es");
3042 cmbLang.Items.Add("sv");
3043 cmbLang.Items.Add("th");
3045 lbl.Text = "Search(C-S-f)";
3046 lbl.Name = "label1";
3047 lbl.Dock = DockStyle.Left;
3049 lbl.Height = cmb.Height;
3050 lbl.TextAlign = ContentAlignment.MiddleLeft;
3053 btn.Text = "Search";
3054 btn.Name = "buttonSearch";
3055 btn.UseVisualStyleBackColor = true;
3056 btn.Dock = DockStyle.Right;
3057 btn.TabStop = false;
3059 btn.Click += this.SearchButton_Click;
3061 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3063 cmb.Items.Add(searchTab.SearchWords);
3064 cmb.Text = searchTab.SearchWords;
3067 cmbLang.Text = searchTab.SearchLang;
3069 tabPage.Controls.Add(pnl);
3073 tabPage.Tag = listCustom;
3074 this.ListTab.Controls.Add(tabPage);
3076 tabPage.Location = new Point(4, 4);
3077 tabPage.Name = "CTab" + cnt;
3078 tabPage.Size = new Size(380, 260);
3079 tabPage.TabIndex = 2 + cnt;
3080 tabPage.Text = tab.TabName;
3081 tabPage.UseVisualStyleBackColor = true;
3082 tabPage.AccessibleRole = AccessibleRole.PageTab;
3084 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3085 listCustom.TabIndex = 1;
3086 listCustom.AllowColumnReorder = true;
3087 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3088 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3089 listCustom.Dock = DockStyle.Fill;
3090 listCustom.FullRowSelect = true;
3091 listCustom.HideSelection = false;
3092 listCustom.Location = new Point(0, 0);
3093 listCustom.Margin = new Padding(0);
3094 listCustom.Name = "CList" + Environment.TickCount;
3095 listCustom.ShowItemToolTips = true;
3096 listCustom.Size = new Size(380, 260);
3097 listCustom.UseCompatibleStateImageBehavior = false;
3098 listCustom.View = View.Details;
3099 listCustom.OwnerDraw = true;
3100 listCustom.VirtualMode = true;
3102 listCustom.GridLines = this.settings.Common.ShowGrid;
3103 listCustom.AllowDrop = true;
3105 this.InitColumns(listCustom, startup);
3107 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3108 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3109 listCustom.ColumnClick += this.MyList_ColumnClick;
3110 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3111 listCustom.DragDrop += this.TweenMain_DragDrop;
3112 listCustom.DragEnter += this.TweenMain_DragEnter;
3113 listCustom.DragOver += this.TweenMain_DragOver;
3114 listCustom.MouseClick += this.MyList_MouseClick;
3115 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3116 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3117 listCustom.HScrolled += this.MyList_HScrolled;
3120 var state = new TimelineListViewState(listCustom, tab);
3121 this.listViewState[tab.TabName] = state;
3126 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3128 var tabInfo = this.statuses.GetTabByName(tabName);
3129 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3134 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3135 var result = MessageBox.Show(
3137 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3138 MessageBoxButtons.OKCancel,
3139 MessageBoxIcon.Question,
3140 MessageBoxDefaultButton.Button2);
3141 if (result == DialogResult.Cancel)
3147 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3151 var tabPage = this.ListTab.TabPages[tabIndex];
3153 this.SetListProperty(); // 他のタブに列幅等を反映
3155 this.listViewState.Remove(tabName);
3158 var listCustom = (DetailsListView)tabPage.Tag;
3161 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3162 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3163 using (ControlTransaction.Layout(this.SplitContainer1, false))
3164 using (ControlTransaction.Layout(this.ListTab, false))
3165 using (ControlTransaction.Layout(this))
3166 using (ControlTransaction.Layout(tabPage, false))
3168 if (this.CurrentTabName == tabName)
3170 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3171 this.beforeSelectedTab = null;
3173 this.ListTab.Controls.Remove(tabPage);
3176 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3178 using var label = tabPage.Controls["labelUser"];
3179 tabPage.Controls.Remove(label);
3181 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3183 using var pnl = tabPage.Controls["panelSearch"];
3185 pnl.Enter -= this.SearchControls_Enter;
3186 pnl.Leave -= this.SearchControls_Leave;
3187 tabPage.Controls.Remove(pnl);
3189 foreach (Control ctrl in pnl.Controls)
3191 if (ctrl.Name == "buttonSearch")
3193 ctrl.Click -= this.SearchButton_Click;
3195 else if (ctrl.Name == "comboSearch")
3197 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3199 pnl.Controls.Remove(ctrl);
3204 tabPage.Controls.Remove(listCustom);
3206 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3207 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3208 listCustom.ColumnClick -= this.MyList_ColumnClick;
3209 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3210 listCustom.DragDrop -= this.TweenMain_DragDrop;
3211 listCustom.DragEnter -= this.TweenMain_DragEnter;
3212 listCustom.DragOver -= this.TweenMain_DragOver;
3213 listCustom.MouseClick -= this.MyList_MouseClick;
3214 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3215 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3216 listCustom.HScrolled -= this.MyList_HScrolled;
3218 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3219 listCustom.Columns.Clear();
3220 cols.ForEach(col => col.Dispose());
3223 listCustom.ContextMenuStrip = null;
3224 listCustom.ColumnHeaderContextMenuStrip = null;
3225 listCustom.Font = null;
3227 listCustom.SmallImageList = null;
3228 listCustom.ListViewItemSorter = null;
3231 this.listCache?.PurgeCache();
3235 listCustom.Dispose();
3236 this.statuses.RemoveTab(tabName);
3241 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3243 this.listCache?.PurgeCache();
3244 this.beforeSelectedTab = e.TabPage;
3247 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3251 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3254 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3255 if (!dragEnableRectangle.Contains(e.Location))
3257 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3258 tn = this.CurrentTabName;
3261 if (MyCommon.IsNullOrEmpty(tn)) return;
3263 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3266 var tabPage = this.ListTab.TabPages[tabIndex];
3267 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3272 this.tabDrag = false;
3275 var cpos = new Point(e.X, e.Y);
3276 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3278 var rect = this.ListTab.GetTabRect(index);
3279 if (rect.Contains(cpos))
3281 this.rclickTabName = tab.TabName;
3287 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3289 this.SetMainWindowTitle();
3290 this.SetStatusLabelUrl();
3291 this.SetApiStatusLabel();
3292 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3293 this.Tag = this.ListTab.Tag;
3294 this.TabMenuControl(this.CurrentTabName);
3295 this.PushSelectPostChain();
3296 this.DispSelectedPost();
3299 private void SetListProperty()
3301 if (!this.isColumnChanged) return;
3303 var currentListView = this.CurrentListView;
3305 var dispOrder = new int[currentListView.Columns.Count];
3306 for (var i = 0; i < currentListView.Columns.Count; i++)
3308 for (var j = 0; j < currentListView.Columns.Count; j++)
3310 if (currentListView.Columns[j].DisplayIndex == i)
3319 foreach (TabPage tb in this.ListTab.TabPages)
3321 if (tb.Text == this.CurrentTabName)
3324 if (tb.Tag != null && tb.Controls.Count > 0)
3326 var lst = (DetailsListView)tb.Tag;
3327 for (var i = 0; i < lst.Columns.Count; i++)
3329 lst.Columns[dispOrder[i]].DisplayIndex = i;
3330 lst.Columns[i].Width = currentListView.Columns[i].Width;
3335 this.isColumnChanged = false;
3338 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3340 if (e.KeyChar == '@')
3342 if (!this.settings.Common.UseAtIdSupplement) return;
3344 var cnt = this.AtIdSupl.ItemCount;
3345 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3346 if (cnt != this.AtIdSupl.ItemCount)
3347 this.MarkSettingAtIdModified();
3350 else if (e.KeyChar == '#')
3352 if (!this.settings.Common.UseHashSupplement) return;
3353 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3358 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3359 => this.ShowSuplDialog(owner, dialog, 0, "");
3361 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3362 => this.ShowSuplDialog(owner, dialog, offset, "");
3364 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3366 dialog.StartsWith = startswith;
3373 dialog.ShowDialog();
3375 this.TopMost = this.settings.Common.AlwaysTop;
3376 var selStart = owner.SelectionStart;
3379 if (dialog.DialogResult == DialogResult.OK)
3381 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3385 fHalf = owner.Text.Substring(0, selStart - offset);
3387 if (selStart < owner.Text.Length)
3389 eHalf = owner.Text.Substring(selStart);
3391 owner.Text = fHalf + dialog.InputText + eHalf;
3392 owner.SelectionStart = selStart + dialog.InputText.Length;
3399 fHalf = owner.Text.Substring(0, selStart);
3401 if (selStart < owner.Text.Length)
3403 eHalf = owner.Text.Substring(selStart);
3405 owner.Text = fHalf + eHalf;
3408 owner.SelectionStart = selStart;
3414 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3417 if (!e.Alt && !e.Control && !e.Shift)
3419 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3421 var isSpace = false;
3422 foreach (var c in this.StatusText.Text)
3424 if (c == ' ' || c == ' ')
3437 this.StatusText.Text = "";
3438 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3442 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3445 private void StatusText_TextChanged(object sender, EventArgs e)
3448 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3449 this.lblLen.Text = pLen.ToString();
3452 this.StatusText.ForeColor = Color.Red;
3456 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3459 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3461 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3463 this.inReplyTo = null;
3468 /// メンション以外の文字列が含まれていないテキストであるか判定します
3470 internal static bool TextContainsOnlyMentions(string text)
3472 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3475 foreach (var mention in mentions)
3477 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3479 if (!string.IsNullOrWhiteSpace(textPart))
3482 startIndex = mention.Indices[1];
3485 var textPartLast = text.Substring(startIndex);
3487 if (!string.IsNullOrWhiteSpace(textPartLast))
3494 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3496 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3498 var autoPopulatedUserIdList = new List<long>();
3500 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3501 if (replyToPost != null)
3503 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3505 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3506 autoPopulatedUserIdList.Add(replyToPost.UserId);
3508 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3510 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3512 statusText = statusText.Substring(screenName.Length + 2);
3513 autoPopulatedUserIdList.Add(userId);
3519 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3525 /// attachment_url に指定可能な URL が含まれていれば除去
3527 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3529 attachmentUrl = null;
3531 // attachment_url は media_id と同時に使用できない
3532 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3535 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3539 attachmentUrl = match.Value;
3542 statusText = statusText.Substring(0, match.Index);
3544 // テキストと URL の間にスペースが含まれていれば除去
3545 return statusText.TrimEnd(' ');
3548 private string FormatStatusTextExtended(string statusText)
3549 => this.FormatStatusTextExtended(statusText, out _, out _);
3552 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3554 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3556 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3558 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3560 return this.FormatStatusText(statusText);
3564 /// ツイート投稿前のフッター付与などの前処理を行います
3566 private string FormatStatusText(string statusText)
3568 statusText = statusText.Replace("\r\n", "\n");
3570 if (this.urlMultibyteSplit)
3573 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3576 if (this.settings.Common.WideSpaceConvert)
3578 // 文中の全角スペースを半角スペース1個にする
3579 statusText = statusText.Replace(" ", " ");
3582 // DM の場合はこれ以降の処理を行わない
3583 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3587 if (this.settings.Common.PostShiftEnter)
3589 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3593 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3594 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3596 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3599 if (statusText.Contains("RT @"))
3600 disableFooter = true;
3602 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3603 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3605 var mentionSelf = $"@{this.tw.Username} ";
3606 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3608 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3609 statusText = statusText.Substring(mentionSelf.Length);
3616 var hashtag = this.HashMgr.UseHash;
3617 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3619 if (this.HashMgr.IsHead)
3620 header = this.HashMgr.UseHash + " ";
3622 footer = " " + this.HashMgr.UseHash;
3627 if (this.settings.Local.UseRecommendStatus)
3630 footer += this.recommendedStatusFooter;
3632 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3634 // テキストボックスに入力されている文字列を使用する
3635 footer += " " + this.settings.Local.StatusText.Trim();
3639 statusText = header + statusText + footer;
3641 if (this.preventSmsCommand)
3643 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3644 // 参照: https://support.twitter.com/articles/14020
3646 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3647 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3649 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3650 statusText = '\u200b' + statusText;
3658 /// 投稿欄に表示する入力可能な文字数を計算します
3660 private int GetRestStatusCount(string statusText)
3662 var remainCount = this.tw.GetTextLengthRemain(statusText);
3664 var uploadService = this.GetSelectedImageService();
3665 if (uploadService != null)
3667 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3668 remainCount -= uploadService.GetReservedTextLength(1);
3674 private IMediaUploadService? GetSelectedImageService()
3675 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3678 /// 全てのタブの振り分けルールを反映し直します
3680 private void ApplyPostFilters()
3682 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3684 this.statuses.FilterAll();
3686 var listView = this.CurrentListView;
3687 using (ControlTransaction.Update(listView))
3689 this.listCache?.PurgeCache();
3690 this.listCache?.UpdateListSize();
3693 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3695 var tabPage = this.ListTab.TabPages[index];
3697 if (this.settings.Common.TabIconDisp)
3699 if (tab.UnreadCount > 0)
3700 tabPage.ImageIndex = 0;
3702 tabPage.ImageIndex = -1;
3706 if (!this.settings.Common.TabIconDisp)
3707 this.ListTab.Refresh();
3709 this.SetMainWindowTitle();
3710 this.SetStatusLabelUrl();
3714 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3715 => e.DrawDefault = true;
3717 private void MyList_HScrolled(object sender, EventArgs e)
3718 => ((DetailsListView)sender).Refresh();
3720 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3722 base.ScaleControl(factor, specified);
3724 ScaleChildControl(this.TabImage, factor);
3726 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3727 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3729 foreach (var listview in listviews)
3731 ScaleChildControl(listview, factor);
3735 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3737 var tab = this.CurrentTab;
3739 if (tab.AllCount == 0)
3741 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3745 var selectedIndex = tab.SelectedIndex;
3750 case SEARCHTYPE.NextSearch: // 次を検索
3751 if (selectedIndex != -1)
3752 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3756 case SEARCHTYPE.PrevSearch: // 前を検索
3757 if (selectedIndex != -1)
3758 startIndex = Math.Max(selectedIndex - 1, 0);
3760 startIndex = tab.AllCount - 1;
3762 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3764 if (selectedIndex != -1)
3765 startIndex = selectedIndex;
3771 Func<string, bool> stringComparer;
3774 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3776 catch (ArgumentException)
3778 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3782 var reverse = searchType == SEARCHTYPE.PrevSearch;
3783 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3784 .DefaultIfEmpty(-1).First();
3786 if (foundIndex == -1)
3788 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3792 var listView = this.CurrentListView;
3793 this.SelectListItem(listView, foundIndex);
3794 listView.EnsureVisible(foundIndex);
3797 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3798 => this.ShowSearchDialog(); // 検索メニュー
3800 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3802 var previousSearch = this.SearchDialog.ResultOptions;
3803 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3805 this.SearchDialog.Reset();
3806 this.ShowSearchDialog();
3812 previousSearch.Query,
3813 previousSearch.CaseSensitive,
3814 previousSearch.UseRegex,
3815 SEARCHTYPE.NextSearch);
3818 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3820 var previousSearch = this.SearchDialog.ResultOptions;
3821 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3823 this.SearchDialog.Reset();
3824 this.ShowSearchDialog();
3830 previousSearch.Query,
3831 previousSearch.CaseSensitive,
3832 previousSearch.UseRegex,
3833 SEARCHTYPE.PrevSearch);
3837 /// 検索ダイアログを表示し、検索を実行します
3839 private void ShowSearchDialog()
3841 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3843 this.TopMost = this.settings.Common.AlwaysTop;
3846 this.TopMost = this.settings.Common.AlwaysTop;
3848 var searchOptions = this.SearchDialog.ResultOptions!;
3849 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3851 if (searchOptions.NewTab)
3853 var tabName = Properties.Resources.SearchResults_TabName;
3857 tabName = this.statuses.MakeTabName(tabName);
3859 catch (TabException ex)
3861 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3864 var resultTab = new LocalSearchTabModel(tabName);
3865 this.AddNewTab(resultTab, startup: false);
3866 this.statuses.AddTab(resultTab);
3868 var targetTab = this.CurrentTab;
3870 Func<string, bool> stringComparer;
3873 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3875 catch (ArgumentException)
3877 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3881 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3882 if (foundIndices.Length == 0)
3884 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3888 var foundPosts = foundIndices.Select(x => targetTab[x]);
3889 foreach (var post in foundPosts)
3891 resultTab.AddPostQueue(post);
3894 this.statuses.DistributePosts();
3895 this.RefreshTimeline();
3897 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3898 this.ListTab.SelectedIndex = tabIndex;
3903 searchOptions.Query,
3904 searchOptions.CaseSensitive,
3905 searchOptions.UseRegex,
3906 SEARCHTYPE.DialogSearch);
3909 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3911 this.AddNewTabForSearch(searchOptions.Query);
3915 /// <summary>発言検索に使用するメソッドを生成します</summary>
3916 /// <exception cref="ArgumentException">
3917 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3919 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3923 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3924 var regex = new Regex(query, regexOption);
3926 return x => regex.IsMatch(x);
3930 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3932 return x => x.IndexOf(query, comparisonType) != -1;
3936 private void AboutMenuItem_Click(object sender, EventArgs e)
3938 using (var about = new TweenAboutBox())
3940 about.ShowDialog(this);
3942 this.TopMost = this.settings.Common.AlwaysTop;
3945 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3947 var bgnIdx = this.statuses.SelectedTabIndex;
3949 if (this.ImageSelector.Enabled)
3952 TabModel? foundTab = null;
3956 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3958 var unreadIndex = tab.NextUnreadIndex;
3959 if (unreadIndex != -1)
3961 this.ListTab.SelectedIndex = index;
3963 foundIndex = unreadIndex;
3968 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3969 if (foundTab == null && bgnIdx > 0)
3971 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3973 var unreadIndex = tab.NextUnreadIndex;
3974 if (unreadIndex != -1)
3976 this.ListTab.SelectedIndex = index;
3978 foundIndex = unreadIndex;
3984 DetailsListView lst;
3986 if (foundTab == null)
3988 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3989 this.ListTab.SelectedIndex = 0;
3990 var tabPage = this.ListTab.TabPages[0];
3991 var tab = this.statuses.Tabs[0];
3993 if (tab.AllCount == 0)
3996 if (this.statuses.SortOrder == SortOrder.Ascending)
3997 foundIndex = tab.AllCount - 1;
4001 lst = (DetailsListView)tabPage.Tag;
4005 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
4006 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
4009 this.SelectListItem(lst, foundIndex);
4011 if (this.statuses.SortMode == ComparerMode.Id)
4013 var rowHeight = lst.SmallImageList.ImageSize.Height;
4014 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4015 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4021 lst.EnsureVisible(foundIndex);
4026 lst.EnsureVisible(foundIndex);
4032 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4034 var tab = this.CurrentTab;
4035 var post = this.CurrentPost;
4036 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4037 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4040 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4041 => await this.CheckNewVersion(false);
4043 private void RunTweenUp()
4045 var pinfo = new ProcessStartInfo
4047 UseShellExecute = true,
4048 WorkingDirectory = this.settings.SettingsPath,
4049 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4050 Arguments = "\"" + Application.StartupPath + "\"",
4055 Process.Start(pinfo);
4059 MessageBox.Show("Failed to execute TweenUp3.exe.");
4063 public readonly record struct VersionInfo(
4070 /// OpenTween の最新バージョンの情報を取得します
4072 public async Task<VersionInfo> GetVersionInfoAsync()
4074 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4075 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4077 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4078 .ConfigureAwait(false);
4080 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4081 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4083 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4084 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4086 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4088 return new VersionInfo
4090 Version = Version.Parse(msgHeader[0]),
4091 DownloadUri = new Uri(msgHeader[1]),
4092 ReleaseNote = msgBody,
4096 private async Task CheckNewVersion(bool startup = false)
4098 if (ApplicationSettings.VersionInfoUrl == null)
4099 return; // 更新チェック無効化
4103 var versionInfo = await this.GetVersionInfoAsync();
4105 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4110 var msgtext = string.Format(
4111 Properties.Resources.CheckNewVersionText7,
4112 MyCommon.GetReadableVersion(),
4113 MyCommon.GetReadableVersion(versionInfo.Version));
4114 msgtext = MyCommon.ReplaceAppName(msgtext);
4118 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4119 MessageBoxButtons.OK,
4120 MessageBoxIcon.Information);
4125 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4128 using var dialog = new UpdateDialog();
4130 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4131 MyCommon.GetReadableVersion(versionInfo.Version));
4132 dialog.DetailsText = versionInfo.ReleaseNote;
4134 if (dialog.ShowDialog(this) == DialogResult.Yes)
4136 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4138 else if (dialog.SkipButtonPressed)
4140 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4141 this.MarkSettingCommonModified();
4146 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4150 Properties.Resources.CheckNewVersionText10,
4151 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4152 MessageBoxButtons.OK,
4153 MessageBoxIcon.Exclamation,
4154 MessageBoxDefaultButton.Button2);
4159 private void UpdateSelectedPost()
4161 // 件数関連の場合、タイトル即時書き換え
4162 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4163 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4164 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4165 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4167 this.SetMainWindowTitle();
4169 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4170 this.SetStatusLabelUrl();
4172 if (this.settings.Common.TabIconDisp)
4174 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4176 if (tab.UnreadCount == 0)
4178 var tabPage = this.ListTab.TabPages[index];
4179 if (tabPage.ImageIndex == 0)
4180 tabPage.ImageIndex = -1;
4186 this.ListTab.Refresh();
4189 this.DispSelectedPost();
4192 public string CreateDetailHtml(string orgdata)
4193 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4195 private void DispSelectedPost()
4196 => this.DispSelectedPost(false);
4198 private PostClass displayPost = new();
4201 /// サムネイル表示に使用する CancellationToken の生成元
4203 private CancellationTokenSource? thumbnailTokenSource = null;
4205 private void DispSelectedPost(bool forceupdate)
4207 var currentPost = this.CurrentPost;
4208 if (currentPost == null)
4211 var oldDisplayPost = this.displayPost;
4212 this.displayPost = currentPost;
4214 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4217 var loadTasks = new List<Task>
4219 this.tweetDetailsView.ShowPostDetails(currentPost),
4222 this.SplitContainer3.Panel2Collapsed = true;
4224 if (this.settings.Common.PreviewEnable)
4226 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4227 oldTokenSource?.Cancel();
4229 var token = this.thumbnailTokenSource!.Token;
4230 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
4233 async Task DelayedTasks()
4237 await Task.WhenAll(loadTasks);
4239 catch (OperationCanceledException)
4244 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4248 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4249 => await this.OpenApplicationWebsite();
4251 private async Task OpenApplicationWebsite()
4252 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4254 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4255 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4257 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4259 var tab = this.CurrentTab;
4260 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4262 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4263 if (pnl.Controls["comboSearch"].Focused ||
4264 pnl.Controls["comboLang"].Focused ||
4265 pnl.Controls["buttonSearch"].Focused) return;
4268 if (e.Control || e.Shift || e.Alt)
4271 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4274 e.SuppressKeyPress = true;
4277 if (asyncTask != null)
4281 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4283 private void InitializeShortcuts()
4285 this.shortcutCommands = new[]
4287 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4288 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4289 .FocusedOn(FocusedControl.ListTab)
4290 .Do(() => SendKeys.Send("{DOWN}")),
4292 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4293 .FocusedOn(FocusedControl.ListTab)
4294 .Do(() => SendKeys.Send("{UP}")),
4296 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4297 .FocusedOn(FocusedControl.ListTab)
4298 .Do(() => SendKeys.Send("{PGDN}")),
4300 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4301 .FocusedOn(FocusedControl.ListTab)
4302 .Do(() => SendKeys.Send("{PGUP}")),
4304 ShortcutCommand.Create(Keys.F1)
4305 .Do(() => this.OpenApplicationWebsite()),
4307 ShortcutCommand.Create(Keys.F3)
4308 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4310 ShortcutCommand.Create(Keys.F5)
4311 .Do(() => this.DoRefresh()),
4313 ShortcutCommand.Create(Keys.F6)
4314 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4316 ShortcutCommand.Create(Keys.F7)
4317 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4319 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4320 .NotFocusedOn(FocusedControl.StatusText)
4323 this.CurrentTab.ClearAnchor();
4324 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4327 ShortcutCommand.Create(Keys.G)
4328 .NotFocusedOn(FocusedControl.StatusText)
4331 this.CurrentTab.ClearAnchor();
4332 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4335 ShortcutCommand.Create(Keys.Right, Keys.N)
4336 .FocusedOn(FocusedControl.ListTab)
4337 .Do(() => this.GoRelPost(forward: true)),
4339 ShortcutCommand.Create(Keys.Left, Keys.P)
4340 .FocusedOn(FocusedControl.ListTab)
4341 .Do(() => this.GoRelPost(forward: false)),
4343 ShortcutCommand.Create(Keys.OemPeriod)
4344 .FocusedOn(FocusedControl.ListTab)
4345 .Do(() => this.GoAnchor()),
4347 ShortcutCommand.Create(Keys.I)
4348 .FocusedOn(FocusedControl.ListTab)
4349 .OnlyWhen(() => this.StatusText.Enabled)
4350 .Do(() => this.StatusText.Focus()),
4352 ShortcutCommand.Create(Keys.Enter)
4353 .FocusedOn(FocusedControl.ListTab)
4354 .Do(() => this.ListItemDoubleClickAction()),
4356 ShortcutCommand.Create(Keys.R)
4357 .FocusedOn(FocusedControl.ListTab)
4358 .Do(() => this.DoRefresh()),
4360 ShortcutCommand.Create(Keys.L)
4361 .FocusedOn(FocusedControl.ListTab)
4364 this.CurrentTab.ClearAnchor();
4365 this.GoPost(forward: true);
4368 ShortcutCommand.Create(Keys.H)
4369 .FocusedOn(FocusedControl.ListTab)
4372 this.CurrentTab.ClearAnchor();
4373 this.GoPost(forward: false);
4376 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4377 .FocusedOn(FocusedControl.ListTab)
4380 this.CurrentTab.ClearAnchor();
4384 ShortcutCommand.Create(Keys.S)
4385 .FocusedOn(FocusedControl.ListTab)
4388 this.CurrentTab.ClearAnchor();
4389 this.GoNextTab(forward: true);
4392 ShortcutCommand.Create(Keys.A)
4393 .FocusedOn(FocusedControl.ListTab)
4396 this.CurrentTab.ClearAnchor();
4397 this.GoNextTab(forward: false);
4400 // ] in_reply_to参照元へ戻る
4401 ShortcutCommand.Create(Keys.Oem4)
4402 .FocusedOn(FocusedControl.ListTab)
4405 this.CurrentTab.ClearAnchor();
4406 return this.GoInReplyToPostTree();
4409 // [ in_reply_toへジャンプ
4410 ShortcutCommand.Create(Keys.Oem6)
4411 .FocusedOn(FocusedControl.ListTab)
4414 this.CurrentTab.ClearAnchor();
4415 this.GoBackInReplyToPostTree();
4418 ShortcutCommand.Create(Keys.Escape)
4419 .FocusedOn(FocusedControl.ListTab)
4422 this.CurrentTab.ClearAnchor();
4423 var tab = this.CurrentTab;
4424 var tabtype = tab.TabType;
4425 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4427 this.RemoveSpecifiedTab(tab.TabName, false);
4428 this.SaveConfigsTabs();
4432 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4433 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4434 .FocusedOn(FocusedControl.ListTab)
4435 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4437 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4438 ShortcutCommand.Create(Keys.Up, Keys.Down)
4439 .FocusedOn(FocusedControl.PostBrowser)
4442 ShortcutCommand.Create(Keys.Control | Keys.R)
4443 .Do(() => this.MakeReplyText()),
4445 ShortcutCommand.Create(Keys.Control | Keys.D)
4446 .Do(() => this.DoStatusDelete()),
4448 ShortcutCommand.Create(Keys.Control | Keys.M)
4449 .Do(() => this.MakeDirectMessageText()),
4451 ShortcutCommand.Create(Keys.Control | Keys.S)
4452 .Do(() => this.FavoriteChange(favAdd: true)),
4454 ShortcutCommand.Create(Keys.Control | Keys.I)
4455 .Do(() => this.DoRepliedStatusOpen()),
4457 ShortcutCommand.Create(Keys.Control | Keys.Q)
4458 .Do(() => this.DoQuoteOfficial()),
4460 ShortcutCommand.Create(Keys.Control | Keys.B)
4461 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4463 ShortcutCommand.Create(Keys.Control | Keys.T)
4464 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4466 ShortcutCommand.Create(Keys.Control | Keys.L)
4467 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4469 ShortcutCommand.Create(Keys.Control | Keys.Y)
4470 .NotFocusedOn(FocusedControl.PostBrowser)
4471 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4473 ShortcutCommand.Create(Keys.Control | Keys.F)
4474 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4476 ShortcutCommand.Create(Keys.Control | Keys.U)
4477 .Do(() => this.ShowUserTimeline()),
4479 ShortcutCommand.Create(Keys.Control | Keys.H)
4480 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4482 ShortcutCommand.Create(Keys.Control | Keys.O)
4483 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4485 ShortcutCommand.Create(Keys.Control | Keys.E)
4486 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4488 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4489 .FocusedOn(FocusedControl.ListTab)
4490 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4492 ShortcutCommand.Create(Keys.Control | Keys.N)
4493 .FocusedOn(FocusedControl.ListTab)
4494 .Do(() => this.GoNextTab(forward: true)),
4496 ShortcutCommand.Create(Keys.Control | Keys.P)
4497 .FocusedOn(FocusedControl.ListTab)
4498 .Do(() => this.GoNextTab(forward: false)),
4500 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4501 .FocusedOn(FocusedControl.ListTab)
4502 .Do(() => this.CopyStot()),
4504 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4505 ShortcutCommand.Create(Keys.Control | Keys.D1)
4506 .FocusedOn(FocusedControl.ListTab)
4507 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4508 .Do(() => this.ListTab.SelectedIndex = 0),
4510 ShortcutCommand.Create(Keys.Control | Keys.D2)
4511 .FocusedOn(FocusedControl.ListTab)
4512 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4513 .Do(() => this.ListTab.SelectedIndex = 1),
4515 ShortcutCommand.Create(Keys.Control | Keys.D3)
4516 .FocusedOn(FocusedControl.ListTab)
4517 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4518 .Do(() => this.ListTab.SelectedIndex = 2),
4520 ShortcutCommand.Create(Keys.Control | Keys.D4)
4521 .FocusedOn(FocusedControl.ListTab)
4522 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4523 .Do(() => this.ListTab.SelectedIndex = 3),
4525 ShortcutCommand.Create(Keys.Control | Keys.D5)
4526 .FocusedOn(FocusedControl.ListTab)
4527 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4528 .Do(() => this.ListTab.SelectedIndex = 4),
4530 ShortcutCommand.Create(Keys.Control | Keys.D6)
4531 .FocusedOn(FocusedControl.ListTab)
4532 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4533 .Do(() => this.ListTab.SelectedIndex = 5),
4535 ShortcutCommand.Create(Keys.Control | Keys.D7)
4536 .FocusedOn(FocusedControl.ListTab)
4537 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4538 .Do(() => this.ListTab.SelectedIndex = 6),
4540 ShortcutCommand.Create(Keys.Control | Keys.D8)
4541 .FocusedOn(FocusedControl.ListTab)
4542 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4543 .Do(() => this.ListTab.SelectedIndex = 7),
4545 ShortcutCommand.Create(Keys.Control | Keys.D9)
4546 .FocusedOn(FocusedControl.ListTab)
4547 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4549 ShortcutCommand.Create(Keys.Control | Keys.A)
4550 .FocusedOn(FocusedControl.StatusText)
4551 .Do(() => this.StatusText.SelectAll()),
4553 ShortcutCommand.Create(Keys.Control | Keys.V)
4554 .FocusedOn(FocusedControl.StatusText)
4555 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4557 ShortcutCommand.Create(Keys.Control | Keys.Up)
4558 .FocusedOn(FocusedControl.StatusText)
4559 .Do(() => this.StatusTextHistoryBack()),
4561 ShortcutCommand.Create(Keys.Control | Keys.Down)
4562 .FocusedOn(FocusedControl.StatusText)
4563 .Do(() => this.StatusTextHistoryForward()),
4565 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4566 .FocusedOn(FocusedControl.StatusText)
4569 if (this.ListTab.SelectedIndex == 0)
4571 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4575 this.ListTab.SelectedIndex -= 1;
4577 this.StatusText.Focus();
4580 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4581 .FocusedOn(FocusedControl.StatusText)
4584 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4586 this.ListTab.SelectedIndex = 0;
4590 this.ListTab.SelectedIndex += 1;
4592 this.StatusText.Focus();
4595 ShortcutCommand.Create(Keys.Control | Keys.Y)
4596 .FocusedOn(FocusedControl.PostBrowser)
4599 var multiline = !this.settings.Local.StatusMultiline;
4600 this.settings.Local.StatusMultiline = multiline;
4601 this.MultiLineMenuItem.Checked = multiline;
4602 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4605 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4606 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4608 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4609 .Do(() => this.DoRefreshMore()),
4611 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4612 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4614 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4615 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4617 ShortcutCommand.Create(Keys.Shift | Keys.R)
4618 .NotFocusedOn(FocusedControl.StatusText)
4619 .Do(() => this.DoRefreshMore()),
4621 ShortcutCommand.Create(Keys.Shift | Keys.H)
4622 .FocusedOn(FocusedControl.ListTab)
4623 .Do(() => this.GoTopEnd(goTop: true)),
4625 ShortcutCommand.Create(Keys.Shift | Keys.L)
4626 .FocusedOn(FocusedControl.ListTab)
4627 .Do(() => this.GoTopEnd(goTop: false)),
4629 ShortcutCommand.Create(Keys.Shift | Keys.M)
4630 .FocusedOn(FocusedControl.ListTab)
4631 .Do(() => this.GoMiddle()),
4633 ShortcutCommand.Create(Keys.Shift | Keys.G)
4634 .FocusedOn(FocusedControl.ListTab)
4635 .Do(() => this.GoLast()),
4637 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4638 .FocusedOn(FocusedControl.ListTab)
4639 .Do(() => this.MoveMiddle()),
4641 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4642 .FocusedOn(FocusedControl.ListTab)
4643 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4645 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4646 .FocusedOn(FocusedControl.ListTab)
4647 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4649 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4650 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4651 .FocusedOn(FocusedControl.ListTab)
4652 .Do(() => this.GoFav(forward: true)),
4654 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4655 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4656 .FocusedOn(FocusedControl.ListTab)
4657 .Do(() => this.GoFav(forward: false)),
4659 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4660 .FocusedOn(FocusedControl.ListTab)
4661 .Do(() => this.GoBackSelectPostChain()),
4663 ShortcutCommand.Create(Keys.Alt | Keys.R)
4664 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4666 ShortcutCommand.Create(Keys.Alt | Keys.P)
4667 .OnlyWhen(() => this.CurrentPost != null)
4668 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4670 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4671 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4673 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4674 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4676 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4677 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4679 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4680 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4682 // 別タブの同じ書き込みへ(ALT+←/→)
4683 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4684 .FocusedOn(FocusedControl.ListTab)
4685 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4687 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4688 .FocusedOn(FocusedControl.ListTab)
4689 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4691 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4692 .Do(() => this.MakeReplyText(atAll: true)),
4694 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4695 .Do(() => this.CopyIdUri()),
4697 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4698 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4699 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4701 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4702 .Do(() => this.DoQuoteOfficial()),
4704 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4705 .Do(() => this.FavoriteChange(favAdd: false)),
4707 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4708 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4710 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4711 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4713 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4714 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4716 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4717 .Do(() => this.DoMoveToRTHome()),
4719 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4720 .FocusedOn(FocusedControl.StatusText)
4723 var tab = this.CurrentTab;
4724 var selectedIndex = tab.SelectedIndex;
4725 if (selectedIndex != -1 && selectedIndex > 0)
4727 var listView = this.CurrentListView;
4728 var idx = selectedIndex - 1;
4729 this.SelectListItem(listView, idx);
4730 listView.EnsureVisible(idx);
4734 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4735 .FocusedOn(FocusedControl.StatusText)
4738 var tab = this.CurrentTab;
4739 var selectedIndex = tab.SelectedIndex;
4740 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4742 var listView = this.CurrentListView;
4743 var idx = selectedIndex + 1;
4744 this.SelectListItem(listView, idx);
4745 listView.EnsureVisible(idx);
4749 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4750 .FocusedOn(FocusedControl.StatusText)
4753 if (this.StatusText.SelectionStart > 0)
4755 var endidx = this.StatusText.SelectionStart - 1;
4757 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4759 var c = this.StatusText.Text[i];
4760 if (char.IsLetterOrDigit(c) || c == '_')
4766 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4767 var cnt = this.AtIdSupl.ItemCount;
4768 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4769 if (this.AtIdSupl.ItemCount != cnt)
4770 this.MarkSettingAtIdModified();
4774 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4775 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4785 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4786 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4787 .FocusedOn(FocusedControl.ListTab)
4788 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4790 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4791 .FocusedOn(FocusedControl.ListTab)
4792 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4794 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4795 .FocusedOn(FocusedControl.ListTab)
4796 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4798 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4799 .FocusedOn(FocusedControl.ListTab)
4800 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4802 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4803 .FocusedOn(FocusedControl.ListTab)
4804 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4806 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4807 .FocusedOn(FocusedControl.ListTab)
4808 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4810 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4811 .FocusedOn(FocusedControl.ListTab)
4812 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4814 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4815 .FocusedOn(FocusedControl.ListTab)
4816 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4818 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4819 .FocusedOn(FocusedControl.ListTab)
4820 .Do(() => this.SetSortLastColumn()),
4822 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4823 .FocusedOn(FocusedControl.ListTab)
4824 .Do(() => this.FavoritesRetweetOfficial()),
4826 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4827 .FocusedOn(FocusedControl.ListTab)
4828 .Do(() => this.FavoritesRetweetUnofficial()),
4830 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4831 .FocusedOn(FocusedControl.ListTab)
4832 .Do(() => this.OpenUserAppointUrl()),
4834 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4835 .FocusedOn(FocusedControl.PostBrowser)
4836 .Do(() => this.DoReTweetUnofficial()),
4838 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4839 .OnlyWhen(() => this.ExistCurrentPost)
4840 .Do(() => this.tweetDetailsView.DoTranslation()),
4842 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4843 .Do(() => this.DoReTweetUnofficial()),
4845 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4846 .Do(() => this.CopyUserId()),
4848 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4849 .Do(() => this.tweetThumbnail1.ScrollUp()),
4851 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4852 .Do(() => this.tweetThumbnail1.ScrollDown()),
4854 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4855 .FocusedOn(FocusedControl.ListTab)
4856 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4857 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
4861 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4863 // Task を返す非同期処理があれば asyncTask に代入する
4866 // ShortcutCommand に対応しているコマンドはここで処理される
4867 foreach (var command in this.shortcutCommands)
4869 if (command.IsMatch(keyData, focusedOn))
4871 asyncTask = command.RunCommand();
4872 return command.PreventDefault;
4879 private void GoNextTab(bool forward)
4881 var idx = this.statuses.SelectedTabIndex;
4882 var tabCount = this.statuses.Tabs.Count;
4886 if (idx > tabCount - 1) idx = 0;
4891 if (idx < 0) idx = tabCount - 1;
4893 this.ListTab.SelectedIndex = idx;
4896 private void CopyStot()
4898 var sb = new StringBuilder();
4899 var tab = this.CurrentTab;
4900 var isProtected = false;
4901 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4902 foreach (var post in tab.SelectedPosts)
4904 if (post.IsDeleted) continue;
4907 if (post.RetweetedId != null)
4908 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4910 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4914 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4919 MessageBox.Show(Properties.Resources.CopyStotText1);
4923 var clstr = sb.ToString();
4926 Clipboard.SetDataObject(clstr, false, 5, 100);
4928 catch (Exception ex)
4930 MessageBox.Show(ex.Message);
4935 private void CopyIdUri()
4937 var tab = this.CurrentTab;
4938 if (tab == null || tab is DirectMessagesTabModel)
4941 var copyUrls = new List<string>();
4942 foreach (var post in tab.SelectedPosts)
4943 copyUrls.Add(MyCommon.GetStatusUrl(post));
4945 if (copyUrls.Count == 0)
4950 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4952 catch (ExternalException ex)
4954 MessageBox.Show(ex.Message);
4958 private void GoFav(bool forward)
4960 var tab = this.CurrentTab;
4961 if (tab.AllCount == 0)
4964 var selectedIndex = tab.SelectedIndex;
4972 if (selectedIndex == -1)
4978 fIdx = selectedIndex + 1;
4979 if (fIdx > tab.AllCount - 1)
4982 toIdx = tab.AllCount;
4987 if (selectedIndex == -1)
4989 fIdx = tab.AllCount - 1;
4993 fIdx = selectedIndex - 1;
5001 for (var idx = fIdx; idx != toIdx; idx += stp)
5005 var listView = this.CurrentListView;
5006 this.SelectListItem(listView, idx);
5007 listView.EnsureVisible(idx);
5013 private void GoSamePostToAnotherTab(bool left)
5015 var tab = this.CurrentTab;
5017 // Directタブは対象外(見つかるはずがない)
5018 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5021 var selectedStatusId = tab.SelectedStatusId;
5022 if (selectedStatusId == -1)
5025 int fIdx, toIdx, stp;
5030 if (this.ListTab.SelectedIndex == 0)
5036 fIdx = this.ListTab.SelectedIndex - 1;
5044 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5050 fIdx = this.ListTab.SelectedIndex + 1;
5052 toIdx = this.ListTab.TabCount;
5056 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5058 var targetTab = this.statuses.Tabs[tabidx];
5061 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5064 var foundIndex = targetTab.IndexOf(selectedStatusId);
5065 if (foundIndex != -1)
5067 this.ListTab.SelectedIndex = tabidx;
5068 var listView = this.CurrentListView;
5069 this.SelectListItem(listView, foundIndex);
5070 listView.EnsureVisible(foundIndex);
5076 private void GoPost(bool forward)
5078 var tab = this.CurrentTab;
5079 var currentPost = this.CurrentPost;
5081 if (currentPost == null)
5084 var selectedIndex = tab.SelectedIndex;
5086 int fIdx, toIdx, stp;
5090 fIdx = selectedIndex + 1;
5091 if (fIdx > tab.AllCount - 1) return;
5092 toIdx = tab.AllCount;
5097 fIdx = selectedIndex - 1;
5098 if (fIdx < 0) return;
5104 if (currentPost.RetweetedBy == null)
5106 name = currentPost.ScreenName;
5110 name = currentPost.RetweetedBy;
5112 for (var idx = fIdx; idx != toIdx; idx += stp)
5114 var post = tab[idx];
5115 if (post.RetweetedId == null)
5117 if (post.ScreenName == name)
5119 var listView = this.CurrentListView;
5120 this.SelectListItem(listView, idx);
5121 listView.EnsureVisible(idx);
5127 if (post.RetweetedBy == name)
5129 var listView = this.CurrentListView;
5130 this.SelectListItem(listView, idx);
5131 listView.EnsureVisible(idx);
5138 private void GoRelPost(bool forward)
5140 var tab = this.CurrentTab;
5141 var selectedIndex = tab.SelectedIndex;
5143 if (selectedIndex == -1)
5146 int fIdx, toIdx, stp;
5150 fIdx = selectedIndex + 1;
5151 if (fIdx > tab.AllCount - 1) return;
5152 toIdx = tab.AllCount;
5157 fIdx = selectedIndex - 1;
5158 if (fIdx < 0) return;
5163 var anchorPost = tab.AnchorPost;
5164 if (anchorPost == null)
5166 var currentPost = this.CurrentPost;
5167 if (currentPost == null)
5170 anchorPost = currentPost;
5171 tab.AnchorPost = currentPost;
5174 for (var idx = fIdx; idx != toIdx; idx += stp)
5176 var post = tab[idx];
5177 if (post.ScreenName == anchorPost.ScreenName ||
5178 post.RetweetedBy == anchorPost.ScreenName ||
5179 post.ScreenName == anchorPost.RetweetedBy ||
5180 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5181 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5182 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5183 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5184 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5186 var listView = this.CurrentListView;
5187 this.SelectListItem(listView, idx);
5188 listView.EnsureVisible(idx);
5194 private void GoAnchor()
5196 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5197 if (anchorStatusId == null)
5200 var idx = this.CurrentTab.IndexOf(anchorStatusId.Value);
5204 var listView = this.CurrentListView;
5205 this.SelectListItem(listView, idx);
5206 listView.EnsureVisible(idx);
5209 private void GoTopEnd(bool goTop)
5211 var listView = this.CurrentListView;
5212 if (listView.VirtualListSize == 0)
5220 item = listView.GetItemAt(0, 25);
5228 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5230 idx = listView.VirtualListSize - 1;
5234 this.SelectListItem(listView, idx);
5237 private void GoMiddle()
5239 var listView = this.CurrentListView;
5240 if (listView.VirtualListSize == 0)
5248 item = listView.GetItemAt(0, 0);
5258 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5261 idx2 = listView.VirtualListSize - 1;
5267 idx3 = (idx1 + idx2) / 2;
5269 this.SelectListItem(listView, idx3);
5272 private void GoLast()
5274 var listView = this.CurrentListView;
5275 if (listView.VirtualListSize == 0) return;
5277 if (this.statuses.SortOrder == SortOrder.Ascending)
5279 this.SelectListItem(listView, listView.VirtualListSize - 1);
5280 listView.EnsureVisible(listView.VirtualListSize - 1);
5284 this.SelectListItem(listView, 0);
5285 listView.EnsureVisible(0);
5289 private void MoveTop()
5291 var listView = this.CurrentListView;
5292 if (listView.SelectedIndices.Count == 0) return;
5293 var idx = listView.SelectedIndices[0];
5294 if (this.statuses.SortOrder == SortOrder.Ascending)
5296 listView.EnsureVisible(listView.VirtualListSize - 1);
5300 listView.EnsureVisible(0);
5302 listView.EnsureVisible(idx);
5305 private async Task GoInReplyToPostTree()
5307 var curTabClass = this.CurrentTab;
5308 var currentPost = this.CurrentPost;
5310 if (currentPost == null)
5313 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5317 var post = await this.tw.GetStatusApi(false, currentPost.StatusId);
5319 currentPost.InReplyToStatusId = post.InReplyToStatusId;
5320 currentPost.InReplyToUser = post.InReplyToUser;
5321 currentPost.IsReply = post.IsReply;
5322 this.listCache?.PurgeCache();
5324 var index = curTabClass.SelectedIndex;
5325 this.CurrentListView.RedrawItems(index, index, false);
5327 catch (WebApiException ex)
5329 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5333 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5335 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5337 this.replyChains = new Stack<ReplyChain>();
5339 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
5342 string inReplyToTabName;
5343 var inReplyToId = currentPost.InReplyToStatusId.Value;
5344 var inReplyToUser = currentPost.InReplyToUser;
5346 var inReplyToPosts = from tab in this.statuses.Tabs
5347 orderby tab != curTabClass
5348 from post in tab.Posts.Values
5349 where post.StatusId == inReplyToId
5350 let index = tab.IndexOf(post.StatusId)
5352 select new { Tab = tab, Index = index };
5354 var inReplyPost = inReplyToPosts.FirstOrDefault();
5355 if (inReplyPost == null)
5359 await Task.Run(async () =>
5361 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
5362 .ConfigureAwait(false);
5365 this.statuses.AddPost(post);
5366 this.statuses.DistributePosts();
5369 catch (WebApiException ex)
5371 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5372 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5376 this.RefreshTimeline();
5378 inReplyPost = inReplyToPosts.FirstOrDefault();
5379 if (inReplyPost == null)
5381 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5385 inReplyToTabName = inReplyPost.Tab.TabName;
5386 inReplyToIndex = inReplyPost.Index;
5388 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5389 var tabPage = this.ListTab.TabPages[tabIndex];
5390 var listView = (DetailsListView)tabPage.Tag;
5392 if (this.CurrentTabName != inReplyToTabName)
5394 this.ListTab.SelectedIndex = tabIndex;
5397 this.SelectListItem(listView, inReplyToIndex);
5398 listView.EnsureVisible(inReplyToIndex);
5401 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5403 var curTabClass = this.CurrentTab;
5404 var currentPost = this.CurrentPost;
5406 if (currentPost == null)
5411 if (currentPost.InReplyToStatusId != null)
5413 var posts = from t in this.statuses.Tabs
5415 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5416 let indexOf = t.IndexOf(p.Value.StatusId)
5418 orderby isForward ? indexOf : indexOf * -1
5419 orderby t != curTabClass
5420 select new { Tab = t, Post = p.Value, Index = indexOf };
5423 var postList = posts.ToList();
5424 for (var i = postList.Count - 1; i >= 0; i--)
5427 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5429 postList.RemoveAt(index);
5432 var currentIndex = this.CurrentTab.SelectedIndex;
5433 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5434 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5435 if (post == null) post = postList.First();
5436 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5437 this.ListTab.SelectedIndex = tabIndex;
5438 var listView = this.CurrentListView;
5439 this.SelectListItem(listView, post.Index);
5440 listView.EnsureVisible(post.Index);
5442 catch (InvalidOperationException)
5450 if (this.replyChains == null || this.replyChains.Count < 1)
5452 var posts = from t in this.statuses.Tabs
5454 where p.Value.InReplyToStatusId == currentPost.StatusId
5455 let indexOf = t.IndexOf(p.Value.StatusId)
5458 orderby t != curTabClass
5459 select new { Tab = t, Index = indexOf };
5462 var post = posts.First();
5463 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5464 this.ListTab.SelectedIndex = tabIndex;
5465 var listView = this.CurrentListView;
5466 this.SelectListItem(listView, post.Index);
5467 listView.EnsureVisible(post.Index);
5469 catch (InvalidOperationException)
5476 var chainHead = this.replyChains.Pop();
5477 if (chainHead.InReplyToId == currentPost.StatusId)
5479 var tab = chainHead.OriginalTab;
5480 if (!this.statuses.Tabs.Contains(tab))
5482 this.replyChains = null;
5486 var idx = tab.IndexOf(chainHead.OriginalId);
5489 this.replyChains = null;
5493 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5496 this.ListTab.SelectedIndex = tabIndex;
5500 this.replyChains = null;
5502 var listView = this.CurrentListView;
5503 this.SelectListItem(listView, idx);
5504 listView.EnsureVisible(idx);
5510 this.replyChains = null;
5511 this.GoBackInReplyToPostTree(parallel);
5517 private void GoBackSelectPostChain()
5519 if (this.selectPostChains.Count > 1)
5522 TabModel? foundTab = null;
5528 this.selectPostChains.Pop();
5529 var (tab, post) = this.selectPostChains.Peek();
5531 if (!this.statuses.Tabs.Contains(tab))
5532 continue; // 該当タブが存在しないので無視
5536 idx = tab.IndexOf(post.StatusId);
5537 if (idx == -1) continue; // 該当ポストが存在しないので無視
5542 this.selectPostChains.Pop();
5544 catch (InvalidOperationException)
5550 while (this.selectPostChains.Count > 1);
5552 if (foundTab == null)
5555 // 履歴が残り1つであればクリアしておく
5556 if (this.selectPostChains.Count == 1)
5557 this.selectPostChains.Clear();
5561 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5562 var tabPage = this.ListTab.TabPages[tabIndex];
5563 var lst = (DetailsListView)tabPage.Tag;
5564 this.ListTab.SelectedIndex = tabIndex;
5568 this.SelectListItem(lst, idx);
5569 lst.EnsureVisible(idx);
5575 private void PushSelectPostChain()
5577 var currentTab = this.CurrentTab;
5578 var currentPost = this.CurrentPost;
5580 var count = this.selectPostChains.Count;
5583 var (tab, post) = this.selectPostChains.Peek();
5584 if (tab == currentTab)
5586 if (post == currentPost) return; // 最新の履歴と同一
5587 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5590 if (count >= 2500) this.TrimPostChain();
5591 this.selectPostChains.Push((currentTab, currentPost));
5594 private void TrimPostChain()
5596 if (this.selectPostChains.Count <= 2000) return;
5597 var p = new Stack<(TabModel, PostClass?)>(2000);
5598 for (var i = 0; i < 2000; i++)
5600 p.Push(this.selectPostChains.Pop());
5602 this.selectPostChains.Clear();
5603 for (var i = 0; i < 2000; i++)
5605 this.selectPostChains.Push(p.Pop());
5609 private bool GoStatus(long statusId)
5611 if (statusId == 0) return false;
5613 var tab = this.statuses.Tabs
5614 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5615 .Where(x => x.Contains(statusId))
5621 var index = tab.IndexOf(statusId);
5623 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5624 this.ListTab.SelectedIndex = tabIndex;
5626 var listView = this.CurrentListView;
5627 this.SelectListItem(listView, index);
5628 listView.EnsureVisible(index);
5633 private bool GoDirectMessage(long statusId)
5635 if (statusId == 0) return false;
5637 var tab = this.statuses.DirectMessageTab;
5638 var index = tab.IndexOf(statusId);
5643 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5644 this.ListTab.SelectedIndex = tabIndex;
5646 var listView = this.CurrentListView;
5647 this.SelectListItem(listView, index);
5648 listView.EnsureVisible(index);
5653 private void MyList_MouseClick(object sender, MouseEventArgs e)
5654 => this.CurrentTab.ClearAnchor();
5656 private void StatusText_Enter(object sender, EventArgs e)
5658 // フォーカスの戻り先を StatusText に設定
5659 this.Tag = this.StatusText;
5660 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5663 public Color InputBackColor
5664 => this.themeManager.ColorInputBackcolor;
5666 private void StatusText_Leave(object sender, EventArgs e)
5668 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5669 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5670 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5673 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5675 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5678 e.SuppressKeyPress = true;
5681 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5683 if (asyncTask != null)
5687 private void SaveConfigsAll(bool ifModified)
5691 this.SaveConfigsCommon();
5692 this.SaveConfigsLocal();
5693 this.SaveConfigsTabs();
5694 this.SaveConfigsAtId();
5698 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5699 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5700 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5704 private void SaveConfigsAtId()
5706 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5708 this.ModifySettingAtId = false;
5709 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5710 this.settings.SaveAtIdList();
5713 private void SaveConfigsCommon()
5715 if (this.ignoreConfigSave) return;
5717 this.ModifySettingCommon = false;
5718 lock (this.syncObject)
5720 this.settings.Common.UserName = this.tw.Username;
5721 this.settings.Common.UserId = this.tw.UserId;
5722 this.settings.Common.Token = this.tw.AccessToken;
5723 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5724 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5725 this.settings.Common.SortColumn = this.statuses.SortMode switch
5727 ComparerMode.Nickname => 1, // ニックネーム
5728 ComparerMode.Data => 2, // 本文
5729 ComparerMode.Id => 3, // 時刻=発言Id
5730 ComparerMode.Name => 4, // 名前
5731 ComparerMode.Source => 7, // Source
5732 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5734 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5735 if (this.HashMgr.IsPermanent)
5737 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5741 this.settings.Common.HashSelected = "";
5743 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5744 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5745 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5746 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5747 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5749 this.settings.SaveCommon();
5753 private void SaveConfigsLocal()
5755 if (this.ignoreConfigSave) return;
5756 lock (this.syncObject)
5758 this.ModifySettingLocal = false;
5759 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5760 this.settings.Local.FormSize = this.mySize;
5761 this.settings.Local.FormLocation = this.myLoc;
5762 this.settings.Local.SplitterDistance = this.mySpDis;
5763 this.settings.Local.PreviewDistance = this.mySpDis3;
5764 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5765 this.settings.Local.StatusTextHeight = this.mySpDis2;
5767 if (this.ignoreConfigSave) return;
5768 this.settings.SaveLocal();
5772 private void SaveConfigsTabs()
5774 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5776 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5778 foreach (var tab in tabs)
5780 if (!tab.IsPermanentTabType)
5783 var tabSetting = new SettingTabs.SettingTabItem
5785 TabName = tab.TabName,
5786 TabType = tab.TabType,
5787 UnreadManage = tab.UnreadManage,
5788 Protected = tab.Protected,
5789 Notify = tab.Notify,
5790 SoundFile = tab.SoundFile,
5795 case FilterTabModel filterTab:
5796 tabSetting.FilterArray = filterTab.FilterArray;
5798 case UserTimelineTabModel userTab:
5799 tabSetting.User = userTab.ScreenName;
5801 case PublicSearchTabModel searchTab:
5802 tabSetting.SearchWords = searchTab.SearchWords;
5803 tabSetting.SearchLang = searchTab.SearchLang;
5805 case ListTimelineTabModel listTab:
5806 tabSetting.ListInfo = listTab.ListInfo;
5810 tabSettingList.Add(tabSetting);
5813 this.settings.Tabs.Tabs = tabSettingList;
5814 this.settings.SaveTabs();
5817 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5819 static void ShowFormatErrorDialog(IWin32Window owner)
5823 Properties.Resources.OpenURL_InvalidFormat,
5824 Properties.Resources.OpenURL_Caption,
5825 MessageBoxButtons.OK,
5826 MessageBoxIcon.Error
5830 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5831 if (ret != DialogResult.OK)
5834 var match = Twitter.StatusUrlRegex.Match(inputText);
5837 ShowFormatErrorDialog(this);
5843 var statusId = long.Parse(match.Groups["StatusId"].Value);
5844 await this.OpenRelatedTab(statusId);
5846 catch (OverflowException)
5848 ShowFormatErrorDialog(this);
5850 catch (TabException ex)
5852 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5856 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5858 var tab = this.CurrentTab;
5860 var rslt = MessageBox.Show(
5861 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5862 Properties.Resources.SaveLogMenuItem_ClickText2,
5863 MessageBoxButtons.YesNoCancel,
5864 MessageBoxIcon.Question);
5865 if (rslt == DialogResult.Cancel) return;
5867 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5868 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5869 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5870 this.SaveFileDialog1.FilterIndex = 0;
5871 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5872 this.SaveFileDialog1.RestoreDirectory = true;
5874 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5876 if (!this.SaveFileDialog1.ValidateNames) return;
5877 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5878 if (rslt == DialogResult.Yes)
5881 for (var idx = 0; idx < tab.AllCount; idx++)
5883 var post = tab[idx];
5886 protect = "Protect";
5887 sw.WriteLine(post.Nickname + "\t" +
5888 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5889 post.CreatedAt.ToLocalTimeString() + "\t" +
5890 post.ScreenName + "\t" +
5891 post.StatusId + "\t" +
5892 post.ImageUrl + "\t" +
5893 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5899 foreach (var post in this.CurrentTab.SelectedPosts)
5903 protect = "Protect";
5904 sw.WriteLine(post.Nickname + "\t" +
5905 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5906 post.CreatedAt.ToLocalTimeString() + "\t" +
5907 post.ScreenName + "\t" +
5908 post.StatusId + "\t" +
5909 post.ImageUrl + "\t" +
5910 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5915 this.TopMost = this.settings.Common.AlwaysTop;
5918 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5922 using (var inputName = new InputTabName())
5924 inputName.TabName = origTabName;
5925 inputName.ShowDialog();
5926 if (inputName.DialogResult == DialogResult.Cancel) return false;
5927 newTabName = inputName.TabName;
5929 this.TopMost = this.settings.Common.AlwaysTop;
5930 if (!MyCommon.IsNullOrEmpty(newTabName))
5933 if (this.statuses.ContainsTab(newTabName))
5935 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5936 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5940 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5941 var tabPage = this.ListTab.TabPages[tabIndex];
5944 if (tabPage != null)
5945 tabPage.Text = newTabName;
5947 this.statuses.RenameTab(origTabName, newTabName);
5949 var state = this.listViewState[origTabName];
5950 this.listViewState.Remove(origTabName);
5951 this.listViewState[newTabName] = state;
5953 this.SaveConfigsCommon();
5954 this.SaveConfigsTabs();
5955 this.rclickTabName = newTabName;
5964 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5966 if (e.Button == MouseButtons.Middle)
5968 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5970 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5972 this.RemoveSpecifiedTab(tab.TabName, true);
5973 this.SaveConfigsTabs();
5980 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5981 => this.TabRename(this.CurrentTabName, out _);
5983 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5985 if (this.settings.Common.TabMouseLock) return;
5986 if (e.Button == MouseButtons.Left)
5988 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5990 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5992 this.tabDrag = true;
5993 this.tabMouseDownPoint = e.Location;
6000 this.tabDrag = false;
6004 private void ListTab_DragEnter(object sender, DragEventArgs e)
6006 if (e.Data.GetDataPresent(typeof(TabPage)))
6007 e.Effect = DragDropEffects.Move;
6009 e.Effect = DragDropEffects.None;
6012 private void ListTab_DragDrop(object sender, DragEventArgs e)
6014 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
6016 this.tabDrag = false;
6019 var cpos = new Point(e.X, e.Y);
6020 var spos = this.ListTab.PointToClient(cpos);
6021 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6023 var rect = this.ListTab.GetTabRect(index);
6024 if (rect.Contains(spos))
6027 if (spos.X <= (rect.Left + rect.Right) / 2)
6036 // タブのないところにドロップ->最後尾へ移動
6037 if (MyCommon.IsNullOrEmpty(tn))
6039 var lastTab = this.statuses.Tabs.Last();
6040 tn = lastTab.TabName;
6044 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6045 if (tp.Text == tn) return;
6047 this.ReOrderTab(tp.Text, tn, bef);
6050 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6052 var baseIndex = this.GetTabPageIndex(baseTabText);
6053 if (baseIndex == -1)
6056 var targetIndex = this.GetTabPageIndex(targetTabText);
6057 if (targetIndex == -1)
6060 using (ControlTransaction.Layout(this.ListTab))
6062 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6063 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6064 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6065 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6067 var tab = this.statuses.Tabs[targetIndex];
6068 var tabPage = this.ListTab.TabPages[targetIndex];
6070 this.ListTab.TabPages.Remove(tabPage);
6072 if (targetIndex < baseIndex)
6075 if (!isBeforeBaseTab)
6078 this.statuses.MoveTab(baseIndex, tab);
6080 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6083 this.SaveConfigsTabs();
6086 private void MakeDirectMessageText()
6088 var selectedPosts = this.CurrentTab.SelectedPosts;
6089 if (selectedPosts.Length > 1)
6092 var post = selectedPosts.Single();
6093 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6095 this.inReplyTo = null;
6096 this.StatusText.Text = text;
6097 this.StatusText.SelectionStart = text.Length;
6098 this.StatusText.Focus();
6101 private void MakeReplyText(bool atAll = false)
6103 var selectedPosts = this.CurrentTab.SelectedPosts;
6104 if (selectedPosts.Any(x => x.IsDm))
6106 this.MakeDirectMessageText();
6110 if (selectedPosts.Length == 1)
6112 var post = selectedPosts.Single();
6113 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6114 var inReplyToScreenName = post.ScreenName;
6115 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6119 this.inReplyTo = null;
6122 var selfScreenName = this.tw.Username;
6123 var targetScreenNames = new List<string>();
6124 foreach (var post in selectedPosts)
6126 if (post.ScreenName != selfScreenName)
6127 targetScreenNames.Add(post.ScreenName);
6131 foreach (var (_, screenName) in post.ReplyToList)
6133 if (screenName != selfScreenName)
6134 targetScreenNames.Add(screenName);
6139 if (this.inReplyTo != null)
6141 var (_, screenName) = this.inReplyTo.Value;
6142 if (screenName == selfScreenName)
6143 targetScreenNames.Insert(0, screenName);
6146 var text = this.StatusText.Text;
6147 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6149 var atText = $"@{screenName} ";
6150 if (!text.Contains(atText))
6151 text = atText + text;
6154 this.StatusText.Text = text;
6155 this.StatusText.SelectionStart = text.Length;
6156 this.StatusText.Focus();
6159 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6160 => this.tabDrag = false;
6162 private int iconCnt = 0;
6163 private int blinkCnt = 0;
6164 private bool blink = false;
6166 private void RefreshTasktrayIcon()
6168 void EnableTasktrayAnimation()
6169 => this.TimerRefreshIcon.Enabled = true;
6171 void DisableTasktrayAnimation()
6172 => this.TimerRefreshIcon.Enabled = false;
6174 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6178 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6181 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6182 this.myStatusError = false;
6183 EnableTasktrayAnimation();
6187 var replyIconType = this.settings.Common.ReplyIconState;
6189 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6191 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6192 if (replyTab != null && replyTab.UnreadCount > 0)
6196 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6199 if (this.blinkCnt > 10)
6202 if (this.blinkCnt == 0)
6203 this.blink = !this.blink;
6205 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6206 EnableTasktrayAnimation();
6210 DisableTasktrayAnimation();
6216 // 優先度:リプライ→エラー→オフライン→アイドル
6217 // エラーは更新アイコンでクリアされる
6218 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6219 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6220 else if (this.myStatusError)
6221 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6222 else if (this.myStatusOnline)
6223 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6225 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6228 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6229 => this.RefreshTasktrayIcon(); // 200ms
6231 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6233 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6234 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6235 this.rclickTabName = this.CurrentTabName;
6237 if (this.statuses == null) return;
6238 if (this.statuses.Tabs == null) return;
6240 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6243 this.NotifyDispMenuItem.Checked = tb.Notify;
6244 this.NotifyTbMenuItem.Checked = tb.Notify;
6246 this.soundfileListup = true;
6247 this.SoundFileComboBox.Items.Clear();
6248 this.SoundFileTbComboBox.Items.Clear();
6249 this.SoundFileComboBox.Items.Add("");
6250 this.SoundFileTbComboBox.Items.Add("");
6251 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6252 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6254 oDir = oDir.GetDirectories("Sounds")[0];
6256 foreach (var oFile in oDir.GetFiles("*.wav"))
6258 this.SoundFileComboBox.Items.Add(oFile.Name);
6259 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6261 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6262 if (idx == -1) idx = 0;
6263 this.SoundFileComboBox.SelectedIndex = idx;
6264 this.SoundFileTbComboBox.SelectedIndex = idx;
6265 this.soundfileListup = false;
6266 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6267 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6269 this.TabMenuControl(this.rclickTabName);
6272 private void TabMenuControl(string tabName)
6274 var tabInfo = this.statuses.GetTabByName(tabName)!;
6276 this.FilterEditMenuItem.Enabled = true;
6277 this.EditRuleTbMenuItem.Enabled = true;
6279 if (tabInfo.IsDefaultTabType)
6281 this.ProtectTabMenuItem.Enabled = false;
6282 this.ProtectTbMenuItem.Enabled = false;
6286 this.ProtectTabMenuItem.Enabled = true;
6287 this.ProtectTbMenuItem.Enabled = true;
6290 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6292 this.ProtectTabMenuItem.Checked = true;
6293 this.ProtectTbMenuItem.Checked = true;
6294 this.DeleteTabMenuItem.Enabled = false;
6295 this.DeleteTbMenuItem.Enabled = false;
6299 this.ProtectTabMenuItem.Checked = false;
6300 this.ProtectTbMenuItem.Checked = false;
6301 this.DeleteTabMenuItem.Enabled = true;
6302 this.DeleteTbMenuItem.Enabled = true;
6306 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6308 var checkState = ((ToolStripMenuItem)sender).Checked;
6311 this.ProtectTbMenuItem.Checked = checkState;
6312 this.ProtectTabMenuItem.Checked = checkState;
6315 this.DeleteTabMenuItem.Enabled = !checkState;
6316 this.DeleteTbMenuItem.Enabled = !checkState;
6318 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6319 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6321 this.SaveConfigsTabs();
6324 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6326 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6327 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6329 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6330 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6332 this.SaveConfigsTabs();
6335 public void ChangeTabUnreadManage(string tabName, bool isManage)
6337 var idx = this.GetTabPageIndex(tabName);
6341 var tab = this.statuses.Tabs[tabName];
6342 tab.UnreadManage = isManage;
6344 if (this.settings.Common.TabIconDisp)
6346 var tabPage = this.ListTab.TabPages[idx];
6347 if (tab.UnreadCount > 0)
6348 tabPage.ImageIndex = 0;
6350 tabPage.ImageIndex = -1;
6353 if (this.CurrentTabName == tabName)
6355 this.listCache?.PurgeCache();
6356 this.CurrentListView.Refresh();
6359 this.SetMainWindowTitle();
6360 this.SetStatusLabelUrl();
6361 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6364 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6366 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6367 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6369 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6371 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6373 this.SaveConfigsTabs();
6376 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6378 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6380 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6382 this.SaveConfigsTabs();
6385 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6387 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6388 this.rclickTabName = this.CurrentTabName;
6390 this.RemoveSpecifiedTab(this.rclickTabName, true);
6391 this.SaveConfigsTabs();
6394 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6396 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6398 using (var fltDialog = new FilterDialog())
6400 fltDialog.Owner = this;
6401 fltDialog.SetCurrent(this.rclickTabName);
6402 fltDialog.ShowDialog(this);
6404 this.TopMost = this.settings.Common.AlwaysTop;
6406 this.ApplyPostFilters();
6407 this.SaveConfigsTabs();
6410 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6412 string? tabName = null;
6413 MyCommon.TabUsageType tabUsage;
6414 using (var inputName = new InputTabName())
6416 inputName.TabName = this.statuses.MakeTabName("MyTab");
6417 inputName.IsShowUsage = true;
6418 inputName.ShowDialog();
6419 if (inputName.DialogResult == DialogResult.Cancel) return;
6420 tabName = inputName.TabName;
6421 tabUsage = inputName.Usage;
6423 this.TopMost = this.settings.Common.AlwaysTop;
6424 if (!MyCommon.IsNullOrEmpty(tabName))
6427 ListElement? list = null;
6428 if (tabUsage == MyCommon.TabUsageType.Lists)
6430 using var listAvail = new ListAvailable();
6431 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6433 if (listAvail.SelectedList == null)
6435 list = listAvail.SelectedList;
6441 case MyCommon.TabUsageType.UserDefined:
6442 tab = new FilterTabModel(tabName);
6444 case MyCommon.TabUsageType.PublicSearch:
6445 tab = new PublicSearchTabModel(tabName);
6447 case MyCommon.TabUsageType.Lists:
6448 tab = new ListTimelineTabModel(tabName, list!);
6454 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6456 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6457 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6462 this.SaveConfigsTabs();
6464 var tabIndex = this.statuses.Tabs.Count - 1;
6466 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6468 this.ListTab.SelectedIndex = tabIndex;
6469 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6471 if (tabUsage == MyCommon.TabUsageType.Lists)
6473 this.ListTab.SelectedIndex = tabIndex;
6474 await this.RefreshTabAsync(this.CurrentTab);
6480 private void TabMenuItem_Click(object sender, EventArgs e)
6483 foreach (var post in this.CurrentTab.SelectedPosts)
6486 if (!this.SelectTab(out var tab))
6489 using (var fltDialog = new FilterDialog())
6491 fltDialog.Owner = this;
6492 fltDialog.SetCurrent(tab.TabName);
6494 if (post.RetweetedBy == null)
6496 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6500 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6502 fltDialog.ShowDialog(this);
6505 this.TopMost = this.settings.Common.AlwaysTop;
6508 this.ApplyPostFilters();
6509 this.SaveConfigsTabs();
6512 protected override bool ProcessDialogKey(Keys keyData)
6514 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6515 if ((keyData & Keys.KeyCode) == Keys.Enter)
6517 if (this.StatusText.Focused)
6519 var newLine = false;
6522 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6524 if (this.StatusText.Multiline)
6526 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6528 if ((keyData & Keys.Control) == Keys.Control) post = true;
6532 if ((keyData & Keys.Control) == Keys.Control) post = true;
6535 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6537 if (this.StatusText.Multiline)
6539 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6541 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6545 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6550 if (this.StatusText.Multiline)
6552 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6554 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6555 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6559 if (((keyData & Keys.Shift) == Keys.Shift) ||
6560 (((keyData & Keys.Control) != Keys.Control) &&
6561 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6567 var pos1 = this.StatusText.SelectionStart;
6568 if (this.StatusText.SelectionLength > 0)
6570 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6572 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6573 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6578 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6584 var tab = this.CurrentTab;
6585 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6587 var tabPage = this.CurrentTabPage;
6588 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6589 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6591 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6598 return base.ProcessDialogKey(keyData);
6601 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6602 => this.MakeReplyText(atAll: true);
6604 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6606 var tab = this.CurrentTab;
6607 var selectedPosts = tab.SelectedPosts;
6610 if (selectedPosts.Length == 0)
6613 var screenNameArray = selectedPosts
6614 .Select(x => x.RetweetedBy ?? x.ScreenName)
6617 this.AddFilterRuleByScreenName(screenNameArray);
6619 if (screenNameArray.Length != 0)
6621 var atids = new List<string>();
6622 foreach (var screenName in screenNameArray)
6624 atids.Add("@" + screenName);
6626 var cnt = this.AtIdSupl.ItemCount;
6627 this.AtIdSupl.AddRangeItem(atids.ToArray());
6628 if (this.AtIdSupl.ItemCount != cnt)
6629 this.MarkSettingAtIdModified();
6633 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6635 var tab = this.CurrentTab;
6636 var selectedPosts = tab.SelectedPosts;
6638 if (selectedPosts.Length == 0)
6641 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6643 this.AddFilterRuleBySource(sourceArray);
6646 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6649 if (!this.SelectTab(out var tab)) return;
6653 if (tab.TabType != MyCommon.TabUsageType.Mute)
6655 this.MoveOrCopy(out mv, out mk);
6659 // ミュートタブでは常に MoveMatches を true にする
6664 foreach (var screenName in screenNameArray)
6666 tab.AddFilter(new PostFilterRule
6668 FilterName = screenName,
6669 UseNameField = true,
6673 FilterByUrl = false,
6677 this.ApplyPostFilters();
6678 this.SaveConfigsTabs();
6681 public void AddFilterRuleBySource(params string[] sourceArray)
6683 // タブ選択ダイアログを表示(or追加)
6684 if (!this.SelectTab(out var filterTab))
6689 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6691 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6692 this.MoveOrCopy(out mv, out mk);
6696 // ミュートタブでは常に MoveMatches を true にする
6701 // 振り分けルールに追加するSource
6702 foreach (var source in sourceArray)
6704 filterTab.AddFilter(new PostFilterRule
6706 FilterSource = source,
6710 FilterByUrl = false,
6714 this.ApplyPostFilters();
6715 this.SaveConfigsTabs();
6718 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6725 using (var dialog = new TabsDialog(this.statuses))
6727 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6729 tab = dialog.SelectedTab;
6732 this.CurrentTabPage.Focus();
6737 using (var inputName = new InputTabName())
6739 inputName.TabName = this.statuses.MakeTabName("MyTab");
6740 inputName.ShowDialog();
6741 if (inputName.DialogResult == DialogResult.Cancel) return false;
6742 tabName = inputName.TabName;
6744 this.TopMost = this.settings.Common.AlwaysTop;
6745 if (!MyCommon.IsNullOrEmpty(tabName))
6747 var newTab = new FilterTabModel(tabName);
6748 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6750 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6751 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6770 private void MoveOrCopy(out bool move, out bool mark)
6774 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6775 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6783 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6784 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6795 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6798 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6799 => this.CopyIdUri();
6801 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6803 if (this.StatusText.Focused)
6806 this.StatusText.SelectAll();
6810 // ListView上でのCtrl+A
6811 NativeMethods.SelectAllItems(this.CurrentListView);
6815 private void MoveMiddle()
6821 var listView = this.CurrentListView;
6822 if (listView.SelectedIndices.Count == 0) return;
6824 var idx = listView.SelectedIndices[0];
6826 item = listView.GetItemAt(0, 25);
6832 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6834 idx2 = listView.VirtualListSize - 1;
6838 idx -= Math.Abs(idx1 - idx2) / 2;
6839 if (idx < 0) idx = 0;
6841 listView.EnsureVisible(listView.VirtualListSize - 1);
6842 listView.EnsureVisible(idx);
6845 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6847 var linkElements = this.tweetDetailsView.GetLinkElements();
6849 if (linkElements.Length == 0)
6852 var links = new List<OpenUrlItem>(linkElements.Length);
6854 foreach (var linkElm in linkElements)
6856 var displayUrl = linkElm.GetAttribute("title");
6857 var href = linkElm.GetAttribute("href");
6858 var linkedText = linkElm.InnerText;
6860 if (MyCommon.IsNullOrEmpty(displayUrl))
6863 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6867 bool isReverseSettings;
6869 if (links.Count == 1)
6871 // ツイートに含まれる URL が 1 つのみの場合
6872 // => OpenURL ダイアログを表示せずにリンクを開く
6873 selectedUrl = links[0].Href;
6875 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6876 isReverseSettings = false;
6880 // ツイートに含まれる URL が複数ある場合
6881 // => OpenURL を表示しユーザーが選択したリンクを開く
6882 this.urlDialog.ClearUrl();
6884 foreach (var link in links)
6885 this.urlDialog.AddUrl(link);
6887 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6890 this.TopMost = this.settings.Common.AlwaysTop;
6892 selectedUrl = this.urlDialog.SelectedUrl;
6894 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6895 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6898 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6901 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6903 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6904 this.ClearTab(this.rclickTabName, true);
6907 private void ClearTab(string tabName, bool showWarning)
6911 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6912 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6918 this.statuses.ClearTabIds(tabName);
6919 if (this.CurrentTabName == tabName)
6921 this.CurrentTab.ClearAnchor();
6922 this.listCache?.PurgeCache();
6923 this.listCache?.UpdateListSize();
6926 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6927 var tabPage = this.ListTab.TabPages[tabIndex];
6928 tabPage.ImageIndex = -1;
6930 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6932 this.SetMainWindowTitle();
6933 this.SetStatusLabelUrl();
6936 private static long followers = 0;
6938 private void SetMainWindowTitle()
6940 // メインウインドウタイトルの書き換え
6941 var ttl = new StringBuilder(256);
6944 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6945 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6946 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6947 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6949 foreach (var tab in this.statuses.Tabs)
6951 ur += tab.UnreadCount;
6956 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6957 ttl.Append(ApplicationSettings.ApplicationName);
6959 switch (this.settings.Common.DispLatestPost)
6961 case MyCommon.DispTitleEnum.Ver:
6962 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6964 case MyCommon.DispTitleEnum.Post:
6965 if (this.history != null && this.history.Count > 1)
6966 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6968 case MyCommon.DispTitleEnum.UnreadRepCount:
6969 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6971 case MyCommon.DispTitleEnum.UnreadAllCount:
6972 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6974 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6975 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6977 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6978 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6980 case MyCommon.DispTitleEnum.OwnStatus:
6981 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6982 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6988 this.Text = ttl.ToString();
6990 catch (AccessViolationException)
6992 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6996 private string GetStatusLabelText()
6999 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
7000 if (this.statuses == null) return "";
7001 var tbRep = this.statuses.MentionTab;
7002 var tbDm = this.statuses.DirectMessageTab;
7003 if (tbRep == null || tbDm == null) return "";
7004 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
7009 var slbl = new StringBuilder(256);
7012 foreach (var tab in this.statuses.Tabs)
7014 ur += tab.UnreadCount;
7016 if (tab.TabName == this.CurrentTabName)
7018 tur = tab.UnreadCount;
7028 this.unreadCounter = ur;
7029 this.unreadAtCounter = urat;
7031 var homeTab = this.statuses.HomeTab;
7033 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7034 if (this.settings.Common.TimelinePeriod == 0)
7036 slbl.Append(Properties.Resources.SetStatusLabelText2);
7040 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7042 return slbl.ToString();
7045 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7049 if (this.InvokeRequired && !this.IsDisposed)
7051 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7055 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7056 this.SetApiStatusLabel(endpointName);
7059 catch (ObjectDisposedException)
7063 catch (InvalidOperationException)
7069 private void SetApiStatusLabel(string? endpointName = null)
7071 var tabType = this.CurrentTab.TabType;
7073 if (endpointName == null)
7076 endpointName = tabType switch
7078 MyCommon.TabUsageType.Home => GetTimelineRequest.EndpointName,
7079 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7080 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7081 MyCommon.TabUsageType.Favorites => "/favorites/list",
7082 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7083 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7084 MyCommon.TabUsageType.Lists => "/lists/statuses",
7085 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7086 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7089 this.toolStripApiGauge.ApiEndpoint = endpointName;
7093 // 表示中のタブに関連する endpoint であれば更新
7095 if (endpointName == GetTimelineRequest.EndpointName)
7097 update = tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined;
7101 update = endpointName switch
7103 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7104 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7105 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7106 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7107 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7108 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7109 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7116 this.toolStripApiGauge.ApiEndpoint = endpointName;
7121 private void SetStatusLabelUrl()
7122 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7124 public void SetStatusLabel(string text)
7125 => this.StatusLabel.Text = text;
7127 private void SetNotifyIconText()
7129 var ur = new StringBuilder(64);
7131 // タスクトレイアイコンのツールチップテキスト書き換え
7133 ur.Remove(0, ur.Length);
7134 if (this.settings.Common.DispUsername)
7136 ur.Append(this.tw.Username);
7139 ur.Append(ApplicationSettings.ApplicationName);
7141 ur.Append("(Debug Build)");
7143 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7146 ur.Append(this.unreadCounter);
7148 ur.Append(this.unreadAtCounter);
7151 this.NotifyIcon1.Text = ur.ToString();
7154 internal void CheckReplyTo(string statusText)
7158 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7160 foreach (Match hm in m)
7162 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7164 hstr += "#" + hm.Result("$3") + " ";
7165 this.HashSupl.AddItem("#" + hm.Result("$3"));
7168 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7170 hstr += this.HashMgr.UseHash;
7172 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7174 // 本当にリプライ先指定すべきかどうかの判定
7175 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7177 if (this.settings.Common.UseAtIdSupplement)
7179 var bCnt = this.AtIdSupl.ItemCount;
7180 foreach (Match mid in m)
7182 this.AtIdSupl.AddItem(mid.Result("${id}"));
7184 if (bCnt != this.AtIdSupl.ItemCount)
7185 this.MarkSettingAtIdModified();
7188 // リプライ先ステータスIDの指定がない場合は指定しない
7189 if (this.inReplyTo == null)
7193 // 次の条件を満たす場合に in_reply_to_status_id 指定
7194 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7195 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7196 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7200 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7201 if (statusText.StartsWith("@", StringComparison.Ordinal))
7203 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7207 foreach (Match mid in m)
7209 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7214 this.inReplyTo = null;
7217 private void TweenMain_Resize(object sender, EventArgs e)
7219 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7221 this.Visible = false;
7223 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7225 // 現在の DPI と設定保存時の DPI との比を取得する
7226 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7228 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7231 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7232 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7233 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7235 this.SplitContainer1.SplitterDistance = splitterDistance;
7239 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7240 if (this.StatusText.Multiline)
7242 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7243 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7244 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7246 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7248 this.StatusText.Height = statusTextHeight;
7252 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7254 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7258 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7259 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7261 this.SplitContainer3.SplitterDistance = previewDistance;
7264 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7265 this.SplitContainer3.Panel2Collapsed = true;
7267 this.initialLayout = false;
7269 if (this.WindowState != FormWindowState.Minimized)
7271 this.formWindowState = this.WindowState;
7275 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7277 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7278 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7279 if (this.PlaySoundMenuItem.Checked)
7281 this.settings.Common.PlaySound = true;
7285 this.settings.Common.PlaySound = false;
7287 this.MarkSettingCommonModified();
7290 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7292 if (this.initialLayout)
7295 int splitterDistance;
7296 switch (this.WindowState)
7298 case FormWindowState.Normal:
7299 splitterDistance = this.SplitContainer1.SplitterDistance;
7301 case FormWindowState.Maximized:
7302 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7303 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7304 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7305 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7311 this.mySpDis = splitterDistance;
7312 this.MarkSettingLocalModified();
7315 private async Task DoRepliedStatusOpen()
7317 var currentPost = this.CurrentPost;
7318 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7320 if (MyCommon.IsKeyDown(Keys.Shift))
7322 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7325 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
7327 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7331 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7333 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
7334 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
7335 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7338 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7343 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7344 => await this.DoRepliedStatusOpen();
7346 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7348 if (this.initialLayout)
7349 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7351 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7352 if (multiline != this.StatusText.Multiline)
7354 this.StatusText.Multiline = multiline;
7355 this.settings.Local.StatusMultiline = multiline;
7356 this.MarkSettingLocalModified();
7360 private void StatusText_MultilineChanged(object sender, EventArgs e)
7362 if (this.StatusText.Multiline)
7363 this.StatusText.ScrollBars = ScrollBars.Vertical;
7365 this.StatusText.ScrollBars = ScrollBars.None;
7367 if (!this.initialLayout)
7368 this.MarkSettingLocalModified();
7371 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7374 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7375 this.StatusText.Multiline = menuItemChecked;
7376 this.settings.Local.StatusMultiline = menuItemChecked;
7377 if (menuItemChecked)
7379 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7380 this.SplitContainer2.SplitterDistance = 0;
7382 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7386 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7388 this.MarkSettingLocalModified();
7391 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7393 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7395 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7396 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7397 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7399 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7404 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7405 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7406 // Appendix A. Collected ABNF for URI
7407 // http://www.ietf.org/rfc/rfc3986.txt
7409 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7412 if (this.StatusText.SelectionLength > 0)
7414 var tmp = this.StatusText.SelectedText;
7415 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7416 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7418 // 文字列が選択されている場合はその文字列について処理
7420 // nico.ms使用、nicovideoにマッチしたら変換
7421 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7423 result = Nicoms.Shorten(tmp);
7425 else if (converterType != MyCommon.UrlConverter.Nicoms)
7430 var srcUri = new Uri(tmp);
7431 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7432 result = resultUri.AbsoluteUri;
7434 catch (WebApiException e)
7436 this.StatusLabel.Text = converterType + ":" + e.Message;
7439 catch (UriFormatException e)
7441 this.StatusLabel.Text = converterType + ":" + e.Message;
7450 if (!MyCommon.IsNullOrEmpty(result))
7452 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7453 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7454 if (origUrlIndex == -1)
7457 this.StatusText.Select(origUrlIndex, tmp.Length);
7458 this.StatusText.SelectedText = result;
7461 var undo = new UrlUndo
7467 if (this.urlUndoBuffer == null)
7469 this.urlUndoBuffer = new List<UrlUndo>();
7470 this.UrlUndoToolStripMenuItem.Enabled = true;
7473 this.urlUndoBuffer.Add(undo);
7479 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7480 @"(?<url>(?<protocol>https?://)" +
7481 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7482 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7483 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7484 // 正規表現にマッチしたURL文字列をtinyurl化
7485 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7487 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7489 var tmp = mt.Result("${url}");
7490 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7491 tmp = "http://" + tmp;
7494 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7496 // nico.ms使用、nicovideoにマッチしたら変換
7497 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7499 result = Nicoms.Shorten(tmp);
7501 else if (converterType != MyCommon.UrlConverter.Nicoms)
7506 var srcUri = new Uri(tmp);
7507 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7508 result = resultUri.AbsoluteUri;
7510 catch (HttpRequestException e)
7512 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7513 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7514 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7516 this.StatusLabel.Text = converterType + ":" + message;
7519 catch (WebApiException e)
7521 this.StatusLabel.Text = converterType + ":" + e.Message;
7524 catch (UriFormatException e)
7526 this.StatusLabel.Text = converterType + ":" + e.Message;
7535 if (!MyCommon.IsNullOrEmpty(result))
7537 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7538 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7539 if (origUrlIndex == -1)
7542 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7543 this.StatusText.SelectedText = result;
7545 var undo = new UrlUndo
7547 Before = mt.Result("${url}"),
7551 if (this.urlUndoBuffer == null)
7553 this.urlUndoBuffer = new List<UrlUndo>();
7554 this.UrlUndoToolStripMenuItem.Enabled = true;
7557 this.urlUndoBuffer.Add(undo);
7565 private void DoUrlUndo()
7567 if (this.urlUndoBuffer != null)
7569 var tmp = this.StatusText.Text;
7570 foreach (var data in this.urlUndoBuffer)
7572 tmp = tmp.Replace(data.After, data.Before);
7574 this.StatusText.Text = tmp;
7575 this.urlUndoBuffer = null;
7576 this.UrlUndoToolStripMenuItem.Enabled = false;
7577 this.StatusText.SelectionStart = 0;
7578 this.StatusText.SelectionLength = 0;
7582 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7583 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7585 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7586 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7588 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7589 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7591 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7593 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7595 var rnd = new Random();
7597 MyCommon.UrlConverter svc;
7598 // 前回使用した短縮URLサービス以外を選択する
7601 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7603 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7604 await this.UrlConvertAsync(svc);
7608 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7609 => this.DoUrlUndo();
7611 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7613 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7614 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7615 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7616 this.MarkSettingCommonModified();
7619 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7621 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7622 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7623 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7624 this.MarkSettingCommonModified();
7627 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7629 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7630 this.MenuStrip1.Tag = new object();
7631 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7634 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7636 var currentTabPage = this.CurrentTabPage;
7637 if (this.Tag != null) // 設定された戻り先へ遷移
7639 if (this.Tag == currentTabPage)
7640 ((Control)currentTabPage.Tag).Select();
7642 ((Control)this.Tag).Select();
7644 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7646 this.Tag = currentTabPage.Tag;
7647 ((Control)this.Tag).Select();
7649 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7650 this.MenuStrip1.Tag = null;
7653 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7655 if (this.Use2ColumnsMode)
7661 var lst = (DetailsListView)sender;
7662 var columnsCount = lst.Columns.Count;
7664 var darr = new int[columnsCount];
7665 for (var i = 0; i < columnsCount; i++)
7666 darr[lst.Columns[i].DisplayIndex] = i;
7668 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7670 for (var i = 0; i < columnsCount; i++)
7671 this.settings.Local.ColumnsOrder[darr[i]] = i;
7673 this.MarkSettingLocalModified();
7674 this.isColumnChanged = true;
7677 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7679 var lst = (DetailsListView)sender;
7680 if (this.settings.Local == null) return;
7682 var modified = false;
7683 if (this.Use2ColumnsMode)
7685 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7687 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7690 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7692 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7698 var columnsCount = lst.Columns.Count;
7699 for (var i = 0; i < columnsCount; i++)
7701 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7704 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7710 this.MarkSettingLocalModified();
7711 this.isColumnChanged = true;
7715 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7717 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7718 this.MarkSettingLocalModified();
7721 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7723 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7725 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7727 this.SelectMedia_DragDrop(e);
7730 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7732 var (url, title) = GetUrlFromDataObject(e.Data);
7738 appendText = title + " " + url;
7740 if (this.StatusText.TextLength == 0)
7741 this.StatusText.Text = appendText;
7743 this.StatusText.Text += " " + appendText;
7745 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7747 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7749 this.StatusText.Text += text;
7751 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7753 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7754 if (data != null) this.StatusText.Text += data;
7759 /// IDataObject から URL とタイトルの対を取得します
7762 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7764 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7765 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7766 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7768 if (data.GetDataPresent("text/x-moz-url"))
7770 // Firefox, Google Chrome で利用可能
7771 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7773 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7774 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7775 if (lines.Length < 2)
7776 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7778 return (lines[0], lines[1]);
7780 else if (data.GetDataPresent("IESiteModeToUrl"))
7782 // Internet Exproler 用
7783 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7785 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7786 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7787 if (lines.Length < 2)
7788 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7790 return (lines[0], lines[1]);
7792 else if (data.GetDataPresent("UniformResourceLocatorW"))
7796 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7797 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7801 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7804 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7806 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7808 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7810 this.SelectMedia_DragEnter(e);
7814 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7816 e.Effect = DragDropEffects.Copy;
7819 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7821 e.Effect = DragDropEffects.Copy;
7824 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7826 e.Effect = DragDropEffects.Copy;
7830 e.Effect = DragDropEffects.None;
7833 private void TweenMain_DragOver(object sender, DragEventArgs e)
7837 public bool IsNetworkAvailable()
7839 var nw = MyCommon.IsNetworkAvailable();
7840 this.myStatusOnline = nw;
7844 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7846 var uriStr = uri.AbsoluteUri;
7848 // OpenTween 内部で使用する URL
7849 if (uri.Authority == "opentween")
7851 await this.OpenInternalUriAsync(uri);
7855 // ハッシュタグを含む Twitter 検索
7856 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7859 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7860 var pos = unescapedQuery.IndexOf('#');
7861 if (pos == -1) return;
7863 var hash = unescapedQuery.Substring(pos);
7864 this.HashSupl.AddItem(hash);
7865 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7866 this.AddNewTabForSearch(hash);
7871 // フラグが立っている場合は設定と逆の動作をする
7872 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7873 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7875 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7876 if (userUriMatch.Success)
7878 var screenName = userUriMatch.Groups["ScreenName"].Value;
7879 if (this.IsTwitterId(screenName))
7881 await this.AddNewTabForUserTimeline(screenName);
7888 await MyCommon.OpenInBrowserAsync(this, uriStr);
7892 /// OpenTween 内部の機能を呼び出すための URL を開きます
7894 private async Task OpenInternalUriAsync(Uri uri)
7896 // ツイートを開く (//opentween/status/:status_id)
7897 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7900 var statusId = long.Parse(match.Groups[1].Value);
7901 await this.OpenRelatedTab(statusId);
7906 private void ListTabSelect(TabPage tabPage)
7908 this.SetListProperty();
7910 var previousTabName = this.CurrentTabName;
7911 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7912 previousListViewState.Save(this.ListLockMenuItem.Checked);
7914 this.listCache?.PurgeCache();
7916 this.statuses.SelectTab(tabPage.Text);
7918 this.InitializeTimelineListView();
7920 var tab = this.CurrentTab;
7923 var listView = this.CurrentListView;
7925 var currentListViewState = this.listViewState[tab.TabName];
7926 currentListViewState.Restore(forceScroll: true);
7928 if (this.Use2ColumnsMode)
7930 listView.Columns[1].Text = this.columnText[2];
7934 for (var i = 0; i < listView.Columns.Count; i++)
7936 listView.Columns[i].Text = this.columnText[i];
7941 private void InitializeTimelineListView()
7943 var listView = this.CurrentListView;
7944 var tab = this.CurrentTab;
7946 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7947 (this.listCache, var oldCache) = (newCache, this.listCache);
7948 oldCache?.Dispose();
7950 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7951 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7952 oldDrawer?.Dispose();
7954 newDrawer.IconSize = this.settings.Common.IconSize;
7955 newDrawer.UpdateItemHeight();
7958 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7959 => this.ListTabSelect(e.TabPage);
7961 private void SelectListItem(DetailsListView lView, int index)
7964 var bnd = new Rectangle();
7966 var item = lView.FocusedItem;
7975 lView.SelectedIndices.Clear();
7977 while (lView.SelectedIndices.Count > 0);
7978 item = lView.Items[index];
7979 item.Selected = true;
7980 item.Focused = true;
7982 if (flg) lView.Invalidate(bnd);
7985 private async void TweenMain_Shown(object sender, EventArgs e)
7987 this.NotifyIcon1.Visible = true;
7989 if (this.IsNetworkAvailable())
7991 var loadTasks = new List<Task>
7993 this.RefreshMuteUserIdsAsync(),
7994 this.RefreshBlockIdsAsync(),
7995 this.RefreshNoRetweetIdsAsync(),
7996 this.RefreshTwitterConfigurationAsync(),
7997 this.RefreshTabAsync<HomeTabModel>(),
7998 this.RefreshTabAsync<MentionsTabModel>(),
7999 this.RefreshTabAsync<DirectMessagesTabModel>(),
8000 this.RefreshTabAsync<PublicSearchTabModel>(),
8001 this.RefreshTabAsync<UserTimelineTabModel>(),
8002 this.RefreshTabAsync<ListTimelineTabModel>(),
8005 if (this.settings.Common.StartupFollowers)
8006 loadTasks.Add(this.RefreshFollowerIdsAsync());
8008 if (this.settings.Common.GetFav)
8009 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
8011 var allTasks = Task.WhenAll(loadTasks);
8016 var timeout = Task.Delay(5000);
8017 if (await Task.WhenAny(allTasks, timeout) != timeout)
8021 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
8023 if (MyCommon.EndingFlag)
8027 if (MyCommon.EndingFlag) return;
8029 if (ApplicationSettings.VersionInfoUrl != null)
8031 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8032 if (this.settings.Common.StartupVersion)
8033 await this.CheckNewVersion(true);
8037 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8038 this.VerUpMenuItem.Enabled = false;
8039 this.VerUpMenuItem.Available = false;
8040 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8043 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8044 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8046 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8047 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8051 var reloadTasks = new List<Task>();
8053 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8054 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8056 if (!this.tw.GetNoRetweetSuccess)
8057 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8059 if (this.tw.Configuration.PhotoSizeLimit == 0)
8060 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8062 await Task.WhenAll(reloadTasks);
8065 this.initial = false;
8067 this.timelineScheduler.Enabled = true;
8070 private async Task DoGetFollowersMenu()
8072 await this.RefreshFollowerIdsAsync();
8073 this.DispSelectedPost(true);
8076 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8077 => await this.DoGetFollowersMenu();
8079 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8080 => this.DoReTweetUnofficial();
8082 private async Task DoReTweetOfficial(bool isConfirm)
8085 if (this.ExistCurrentPost)
8087 var selectedPosts = this.CurrentTab.SelectedPosts;
8089 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8091 if (selectedPosts.Any(x => x.IsProtect))
8092 MessageBox.Show("Protected.");
8094 this.doFavRetweetFlags = false;
8098 if (selectedPosts.Length > 15)
8100 MessageBox.Show(Properties.Resources.RetweetLimitText);
8101 this.doFavRetweetFlags = false;
8104 else if (selectedPosts.Length > 1)
8106 var questionText = Properties.Resources.RetweetQuestion2;
8107 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8108 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8110 case DialogResult.Cancel:
8111 case DialogResult.No:
8112 this.doFavRetweetFlags = false;
8118 if (!this.settings.Common.RetweetNoConfirm)
8120 var questiontext = Properties.Resources.RetweetQuestion1;
8121 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8122 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8124 this.doFavRetweetFlags = false;
8130 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8132 await this.RetweetAsync(statusIds);
8136 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8137 => await this.DoReTweetOfficial(true);
8139 private async Task FavoritesRetweetOfficial()
8141 if (!this.ExistCurrentPost) return;
8142 this.doFavRetweetFlags = true;
8143 var retweetTask = this.DoReTweetOfficial(true);
8144 if (this.doFavRetweetFlags)
8146 this.doFavRetweetFlags = false;
8147 var favoriteTask = this.FavoriteChange(true, false);
8149 await Task.WhenAll(retweetTask, favoriteTask);
8157 private async Task FavoritesRetweetUnofficial()
8159 var post = this.CurrentPost;
8160 if (this.ExistCurrentPost && post != null && !post.IsDm)
8162 this.doFavRetweetFlags = true;
8163 var favoriteTask = this.FavoriteChange(true);
8164 if (!post.IsProtect && this.doFavRetweetFlags)
8166 this.doFavRetweetFlags = false;
8167 this.DoReTweetUnofficial();
8175 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8177 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8178 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8179 /// <returns>復元されたツイート本文</returns>
8180 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8182 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8185 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
8187 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8189 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8191 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
8195 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8197 statusHtml = statusHtml.Replace("<br>", " ");
8199 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8200 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8201 statusHtml = statusHtml.Replace(" ", " ");
8203 return WebUtility.HtmlDecode(statusHtml);
8206 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8208 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8210 if (this.CurrentPost != null)
8211 this.DispSelectedPost(true);
8214 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8216 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8217 this.DebugModeToolStripMenuItem.Visible = true;
8219 this.DebugModeToolStripMenuItem.Visible = false;
8222 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8223 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8225 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8226 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8228 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8229 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8231 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8233 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8234 this.MarkSettingCommonModified();
8237 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8239 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8240 this.MarkSettingCommonModified();
8243 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8245 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8246 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8247 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8248 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8249 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8250 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8253 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8255 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8256 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8257 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8258 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8259 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8260 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8263 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8265 if (this.TraceOutToolStripMenuItem.Checked)
8266 MyCommon.TraceFlag = true;
8268 MyCommon.TraceFlag = false;
8271 private void TweenMain_Deactivate(object sender, EventArgs e)
8272 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8274 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8276 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8278 _ = this.TabRename(this.rclickTabName, out _);
8281 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8282 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8284 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8285 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8287 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8289 TwitterApiStatus? apiStatus;
8291 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8293 var cancellationToken = dialog.EnableCancellation();
8297 var task = this.tw.GetInfoApi();
8298 apiStatus = await dialog.WaitForAsync(this, task);
8300 catch (WebApiException)
8305 if (cancellationToken.IsCancellationRequested)
8308 if (apiStatus == null)
8310 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8315 using var apiDlg = new ApiInfoDialog();
8316 apiDlg.ShowDialog(this);
8319 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8321 var id = this.CurrentPost?.ScreenName ?? "";
8323 await this.FollowCommand(id);
8326 internal async Task FollowCommand(string id)
8328 using (var inputName = new InputTabName())
8330 inputName.FormTitle = "Follow";
8331 inputName.FormDescription = Properties.Resources.FRMessage1;
8332 inputName.TabName = id;
8334 if (inputName.ShowDialog(this) != DialogResult.OK)
8336 if (string.IsNullOrWhiteSpace(inputName.TabName))
8339 id = inputName.TabName.Trim();
8342 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8346 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8347 await dialog.WaitForAsync(this, task);
8349 catch (WebApiException ex)
8351 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8356 MessageBox.Show(Properties.Resources.FRMessage3);
8359 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8361 var id = this.CurrentPost?.ScreenName ?? "";
8363 await this.RemoveCommand(id, false);
8366 internal async Task RemoveCommand(string id, bool skipInput)
8370 using var inputName = new InputTabName();
8371 inputName.FormTitle = "Unfollow";
8372 inputName.FormDescription = Properties.Resources.FRMessage1;
8373 inputName.TabName = id;
8375 if (inputName.ShowDialog(this) != DialogResult.OK)
8377 if (string.IsNullOrWhiteSpace(inputName.TabName))
8380 id = inputName.TabName.Trim();
8383 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8387 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8388 await dialog.WaitForAsync(this, task);
8390 catch (WebApiException ex)
8392 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8397 MessageBox.Show(Properties.Resources.FRMessage3);
8400 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8402 var id = this.CurrentPost?.ScreenName ?? "";
8404 await this.ShowFriendship(id);
8407 internal async Task ShowFriendship(string id)
8409 using (var inputName = new InputTabName())
8411 inputName.FormTitle = "Show Friendships";
8412 inputName.FormDescription = Properties.Resources.FRMessage1;
8413 inputName.TabName = id;
8415 if (inputName.ShowDialog(this) != DialogResult.OK)
8417 if (string.IsNullOrWhiteSpace(inputName.TabName))
8420 id = inputName.TabName.Trim();
8423 bool isFollowing, isFollowed;
8425 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8427 var cancellationToken = dialog.EnableCancellation();
8431 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8432 var friendship = await dialog.WaitForAsync(this, task);
8434 isFollowing = friendship.Relationship.Source.Following;
8435 isFollowed = friendship.Relationship.Source.FollowedBy;
8437 catch (WebApiException ex)
8439 if (!cancellationToken.IsCancellationRequested)
8440 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8444 if (cancellationToken.IsCancellationRequested)
8451 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8455 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8459 result += Properties.Resources.GetFriendshipInfo3;
8463 result += Properties.Resources.GetFriendshipInfo4;
8465 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8466 MessageBox.Show(result);
8469 internal async Task ShowFriendship(string[] ids)
8471 foreach (var id in ids)
8473 bool isFollowing, isFollowed;
8475 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8477 var cancellationToken = dialog.EnableCancellation();
8481 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8482 var friendship = await dialog.WaitForAsync(this, task);
8484 isFollowing = friendship.Relationship.Source.Following;
8485 isFollowed = friendship.Relationship.Source.FollowedBy;
8487 catch (WebApiException ex)
8489 if (!cancellationToken.IsCancellationRequested)
8490 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8494 if (cancellationToken.IsCancellationRequested)
8504 ff += Properties.Resources.GetFriendshipInfo1;
8508 ff += Properties.Resources.GetFriendshipInfo2;
8511 ff += System.Environment.NewLine + " ";
8514 ff += Properties.Resources.GetFriendshipInfo3;
8518 ff += Properties.Resources.GetFriendshipInfo4;
8520 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8523 if (MessageBox.Show(
8524 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8525 Properties.Resources.GetFriendshipInfo8,
8526 MessageBoxButtons.YesNo,
8527 MessageBoxIcon.Question,
8528 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8530 await this.RemoveCommand(id, true);
8535 MessageBox.Show(result);
8540 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8541 => await this.DoShowUserStatus(this.tw.Username, false);
8543 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8546 public bool IsTwitterId(string name)
8548 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8549 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8551 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8554 private void DoQuoteOfficial()
8556 var post = this.CurrentPost;
8557 if (this.ExistCurrentPost && post != null)
8559 if (post.IsDm || !this.StatusText.Enabled)
8564 MessageBox.Show("Protected.");
8568 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8570 this.inReplyTo = null;
8572 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8574 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8575 this.StatusText.Focus();
8579 private void DoReTweetUnofficial()
8582 var post = this.CurrentPost;
8583 if (this.ExistCurrentPost && post != null)
8585 if (post.IsDm || !this.StatusText.Enabled)
8590 MessageBox.Show("Protected.");
8593 var rtdata = post.Text;
8594 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8596 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8598 // 投稿時に in_reply_to_status_id を付加する
8599 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8600 var inReplyToScreenName = post.ScreenName;
8601 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8603 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8605 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8606 this.StatusText.Focus();
8610 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8611 => this.DoQuoteOfficial();
8613 private async void SearchButton_Click(object sender, EventArgs e)
8616 var pnl = ((Control)sender).Parent;
8617 if (pnl == null) return;
8618 var tbName = pnl.Parent.Text;
8619 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8620 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8621 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8622 cmb.Text = cmb.Text.Trim();
8623 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8625 var buf = new StringBuilder();
8626 var c = cmb.Text.ToCharArray();
8627 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8629 if (cnt > cmb.Text.Length - 4)
8631 buf.Append(cmb.Text.Substring(cnt));
8640 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8649 cmb.Text = buf.ToString();
8651 var listView = (DetailsListView)pnl.Parent.Tag;
8653 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8655 tb.SearchWords = cmb.Text;
8656 tb.SearchLang = cmbLang.Text;
8657 if (MyCommon.IsNullOrEmpty(cmb.Text))
8660 this.SaveConfigsTabs();
8665 var idx = cmb.Items.IndexOf(tb.SearchWords);
8666 if (idx > -1) cmb.Items.RemoveAt(idx);
8667 cmb.Items.Insert(0, tb.SearchWords);
8668 cmb.Text = tb.SearchWords;
8670 this.statuses.ClearTabIds(tbName);
8671 this.listCache?.PurgeCache();
8672 this.listCache?.UpdateListSize();
8673 this.SaveConfigsTabs(); // 検索条件の保存
8677 await this.RefreshTabAsync(tb);
8680 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8681 => await this.DoRefreshMore(); // もっと前を取得
8684 /// 指定されたタブのListTabにおける位置を返します
8687 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8689 public int GetTabPageIndex(string tabName)
8690 => this.statuses.Tabs.IndexOf(tabName);
8692 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8694 if (this.statuses.RemovedTab.Count == 0)
8696 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
8701 var tb = this.statuses.RemovedTab.Pop();
8702 if (tb.TabType == MyCommon.TabUsageType.Related)
8704 var relatedTab = this.statuses.GetTabByType(MyCommon.TabUsageType.Related);
8705 if (relatedTab != null)
8707 // 関連発言なら既存のタブを置き換える
8708 tb.TabName = relatedTab.TabName;
8709 this.ClearTab(tb.TabName, false);
8711 this.statuses.ReplaceTab(tb);
8713 var tabIndex = this.statuses.Tabs.IndexOf(tb);
8714 this.ListTab.SelectedIndex = tabIndex;
8718 const string TabName = "Related Tweets";
8719 var renamed = TabName;
8720 for (var i = 2; i <= 100; i++)
8722 if (!this.statuses.ContainsTab(renamed))
8724 renamed = TabName + i;
8726 tb.TabName = renamed;
8728 this.statuses.AddTab(tb);
8729 this.AddNewTab(tb, startup: false);
8731 var tabIndex = this.statuses.Tabs.Count - 1;
8732 this.ListTab.SelectedIndex = tabIndex;
8737 var renamed = tb.TabName;
8738 for (var i = 1; i < int.MaxValue; i++)
8740 if (!this.statuses.ContainsTab(renamed))
8742 renamed = tb.TabName + "(" + i + ")";
8744 tb.TabName = renamed;
8746 this.statuses.AddTab(tb);
8747 this.AddNewTab(tb, startup: false);
8749 var tabIndex = this.statuses.Tabs.Count - 1;
8750 this.ListTab.SelectedIndex = tabIndex;
8752 this.SaveConfigsTabs();
8756 private async Task DoMoveToRTHome()
8758 var post = this.CurrentPost;
8759 if (post != null && post.RetweetedId != null)
8760 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8763 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8764 => await this.DoMoveToRTHome();
8766 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8768 var screenName = this.CurrentPost?.ScreenName;
8769 if (screenName != null)
8770 this.ListManageUserContext(screenName);
8773 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8775 var screenName = this.CurrentPost?.RetweetedBy;
8776 if (screenName != null)
8777 this.ListManageUserContext(screenName);
8780 public void ListManageUserContext(string screenName)
8782 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8783 listSelectForm.ShowDialog(this);
8786 private void SearchControls_Enter(object sender, EventArgs e)
8788 var pnl = (Control)sender;
8789 foreach (Control ctl in pnl.Controls)
8795 private void SearchControls_Leave(object sender, EventArgs e)
8797 var pnl = (Control)sender;
8798 foreach (Control ctl in pnl.Controls)
8800 ctl.TabStop = false;
8804 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8806 var tab = this.CurrentTab;
8807 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8808 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8811 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8812 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8814 private void HashManageMenuItem_Click(object sender, EventArgs e)
8819 rslt = this.HashMgr.ShowDialog();
8825 this.TopMost = this.settings.Common.AlwaysTop;
8826 if (rslt == DialogResult.Cancel) return;
8827 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8829 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8830 this.HashTogglePullDownMenuItem.Checked = true;
8831 this.HashToggleMenuItem.Checked = true;
8835 this.HashStripSplitButton.Text = "#[-]";
8836 this.HashTogglePullDownMenuItem.Checked = false;
8837 this.HashToggleMenuItem.Checked = false;
8840 this.MarkSettingCommonModified();
8841 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8844 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8846 this.HashMgr.ToggleHash();
8847 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8849 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8850 this.HashToggleMenuItem.Checked = true;
8851 this.HashTogglePullDownMenuItem.Checked = true;
8855 this.HashStripSplitButton.Text = "#[-]";
8856 this.HashToggleMenuItem.Checked = false;
8857 this.HashTogglePullDownMenuItem.Checked = false;
8859 this.MarkSettingCommonModified();
8860 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8863 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8864 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8866 public void SetPermanentHashtag(string hashtag)
8868 this.HashMgr.SetPermanentHash("#" + hashtag);
8869 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8870 this.HashTogglePullDownMenuItem.Checked = true;
8871 this.HashToggleMenuItem.Checked = true;
8873 this.MarkSettingCommonModified();
8876 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8878 var tab = this.CurrentTab;
8879 var post = this.CurrentPost;
8880 if (!this.ExistCurrentPost)
8882 this.ReplyOpMenuItem.Enabled = false;
8883 this.ReplyAllOpMenuItem.Enabled = false;
8884 this.DmOpMenuItem.Enabled = false;
8885 this.CreateTabRuleOpMenuItem.Enabled = false;
8886 this.CreateIdRuleOpMenuItem.Enabled = false;
8887 this.CreateSourceRuleOpMenuItem.Enabled = false;
8888 this.ReadOpMenuItem.Enabled = false;
8889 this.UnreadOpMenuItem.Enabled = false;
8890 this.AuthorMenuItem.Visible = false;
8891 this.RetweetedByMenuItem.Visible = false;
8895 this.ReplyOpMenuItem.Enabled = true;
8896 this.ReplyAllOpMenuItem.Enabled = true;
8897 this.DmOpMenuItem.Enabled = true;
8898 this.CreateTabRuleOpMenuItem.Enabled = true;
8899 this.CreateIdRuleOpMenuItem.Enabled = true;
8900 this.CreateSourceRuleOpMenuItem.Enabled = true;
8901 this.ReadOpMenuItem.Enabled = true;
8902 this.UnreadOpMenuItem.Enabled = true;
8903 this.AuthorMenuItem.Visible = true;
8904 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8905 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8906 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8909 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8911 this.FavOpMenuItem.Enabled = false;
8912 this.UnFavOpMenuItem.Enabled = false;
8913 this.OpenStatusOpMenuItem.Enabled = false;
8914 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8915 this.RtOpMenuItem.Enabled = false;
8916 this.RtUnOpMenuItem.Enabled = false;
8917 this.QtOpMenuItem.Enabled = false;
8918 this.FavoriteRetweetMenuItem.Enabled = false;
8919 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8923 this.FavOpMenuItem.Enabled = true;
8924 this.UnFavOpMenuItem.Enabled = true;
8925 this.OpenStatusOpMenuItem.Enabled = true;
8926 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8928 if (!post.CanRetweetBy(this.tw.UserId))
8930 this.RtOpMenuItem.Enabled = false;
8931 this.RtUnOpMenuItem.Enabled = false;
8932 this.QtOpMenuItem.Enabled = false;
8933 this.FavoriteRetweetMenuItem.Enabled = false;
8934 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8938 this.RtOpMenuItem.Enabled = true;
8939 this.RtUnOpMenuItem.Enabled = true;
8940 this.QtOpMenuItem.Enabled = true;
8941 this.FavoriteRetweetMenuItem.Enabled = true;
8942 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8946 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8948 this.RefreshPrevOpMenuItem.Enabled = true;
8952 this.RefreshPrevOpMenuItem.Enabled = false;
8954 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8956 this.OpenRepSourceOpMenuItem.Enabled = false;
8960 this.OpenRepSourceOpMenuItem.Enabled = true;
8963 if (this.ExistCurrentPost && post != null)
8965 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8969 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8970 => this.ContextMenuTabProperty_Opening(sender, null!);
8972 public Twitter TwitterInstance
8975 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8977 if (this.initialLayout)
8980 int splitterDistance;
8981 switch (this.WindowState)
8983 case FormWindowState.Normal:
8984 splitterDistance = this.SplitContainer3.SplitterDistance;
8986 case FormWindowState.Maximized:
8987 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8988 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8989 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8990 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8996 this.mySpDis3 = splitterDistance;
8997 this.MarkSettingLocalModified();
9000 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
9002 if (this.statuses.RemovedTab.Count == 0)
9004 this.UndoRemoveTabMenuItem.Enabled = false;
9008 this.UndoRemoveTabMenuItem.Enabled = true;
9011 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
9012 this.PublicSearchQueryMenuItem.Enabled = true;
9014 this.PublicSearchQueryMenuItem.Enabled = false;
9016 var post = this.CurrentPost;
9017 if (!this.ExistCurrentPost || post == null)
9019 this.CopySTOTMenuItem.Enabled = false;
9020 this.CopyURLMenuItem.Enabled = false;
9021 this.CopyUserIdStripMenuItem.Enabled = false;
9025 this.CopySTOTMenuItem.Enabled = true;
9026 this.CopyURLMenuItem.Enabled = true;
9027 this.CopyUserIdStripMenuItem.Enabled = true;
9029 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
9030 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
9034 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
9035 => this.SetNotifyIconText();
9037 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
9038 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
9040 private async Task DoShowUserStatus(string id, bool showInputDialog)
9042 TwitterUser? user = null;
9044 if (showInputDialog)
9046 using var inputName = new InputTabName();
9047 inputName.FormTitle = "Show UserStatus";
9048 inputName.FormDescription = Properties.Resources.FRMessage1;
9049 inputName.TabName = id;
9051 if (inputName.ShowDialog(this) != DialogResult.OK)
9053 if (string.IsNullOrWhiteSpace(inputName.TabName))
9056 id = inputName.TabName.Trim();
9059 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9061 var cancellationToken = dialog.EnableCancellation();
9065 var task = this.tw.Api.UsersShow(id);
9066 user = await dialog.WaitForAsync(this, task);
9068 catch (WebApiException ex)
9070 if (!cancellationToken.IsCancellationRequested)
9071 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9075 if (cancellationToken.IsCancellationRequested)
9079 await this.DoShowUserStatus(user);
9082 private async Task DoShowUserStatus(TwitterUser user)
9084 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9085 var showUserTask = userDialog.ShowUserAsync(user);
9086 userDialog.ShowDialog(this);
9089 this.BringToFront();
9091 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9095 internal Task ShowUserStatus(string id, bool showInputDialog)
9096 => this.DoShowUserStatus(id, showInputDialog);
9098 internal Task ShowUserStatus(string id)
9099 => this.DoShowUserStatus(id, true);
9101 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9103 var post = this.CurrentPost;
9106 await this.ShowUserStatus(post.ScreenName, false);
9110 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9112 var retweetedBy = this.CurrentPost?.RetweetedBy;
9113 if (retweetedBy != null)
9115 await this.ShowUserStatus(retweetedBy, false);
9119 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9121 var post = this.CurrentPost;
9122 if (!this.ExistCurrentPost || post == null)
9125 var statusId = post.RetweetedId ?? post.StatusId;
9126 TwitterStatus status;
9128 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9130 var cancellationToken = dialog.EnableCancellation();
9134 var task = this.tw.Api.StatusesShow(statusId);
9135 status = await dialog.WaitForAsync(this, task);
9137 catch (WebApiException ex)
9139 if (!cancellationToken.IsCancellationRequested)
9140 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9144 if (cancellationToken.IsCancellationRequested)
9148 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9151 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9153 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9156 this.Visible = false;
9158 else if (Form.ActiveForm == null)
9160 this.Visible = true;
9161 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9163 this.BringToFront();
9164 this.StatusText.Focus();
9168 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9169 => this.MultiLinePullDownMenuItem.PerformClick();
9172 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9174 if (this.ImageSelector.Visible)
9175 this.ImageSelector.EndSelection();
9177 this.ImageSelector.BeginSelection();
9180 private void SelectMedia_DragEnter(DragEventArgs e)
9182 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9184 e.Effect = DragDropEffects.Copy;
9187 e.Effect = DragDropEffects.None;
9190 private void SelectMedia_DragDrop(DragEventArgs e)
9193 this.BringToFront();
9195 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9196 this.ImageSelector.BeginSelection();
9197 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9198 this.StatusText.Focus();
9201 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9203 this.TimelinePanel.Visible = false;
9204 this.TimelinePanel.Enabled = false;
9207 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9209 this.TimelinePanel.Visible = true;
9210 this.TimelinePanel.Enabled = true;
9211 this.CurrentListView.Focus();
9214 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9215 => this.AllowDrop = false;
9217 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9218 => this.AllowDrop = true;
9220 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9222 if (this.ImageSelector.Visible)
9224 this.MarkSettingCommonModified();
9225 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9229 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9230 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9233 /// StatusTextでCtrl+Vが押下された時の処理
9235 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9239 if (Clipboard.ContainsText())
9241 // clipboardにテキストがある場合は貼り付け処理
9242 this.StatusText.Paste(Clipboard.GetText());
9244 else if (Clipboard.ContainsImage())
9247 using var image = Clipboard.GetImage();
9248 this.ImageSelector.BeginSelection();
9249 this.ImageSelector.Model.AddMediaItemFromImage(image);
9251 else if (Clipboard.ContainsFileDropList())
9253 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9254 this.ImageSelector.BeginSelection();
9255 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9258 catch (ExternalException ex)
9260 MessageBox.Show(ex.Message);
9265 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9267 using var form = new ListManage(this.tw);
9268 form.ShowDialog(this);
9271 private bool ModifySettingCommon { get; set; }
9273 private bool ModifySettingLocal { get; set; }
9275 private bool ModifySettingAtId { get; set; }
9277 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9279 var post = this.CurrentPost;
9280 if (this.ExistCurrentPost && post != null && !post.IsDm)
9281 this.RtCountMenuItem.Enabled = true;
9283 this.RtCountMenuItem.Enabled = false;
9286 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9287 => this.CopyUserId();
9289 private void CopyUserId()
9291 var post = this.CurrentPost;
9292 if (post == null) return;
9293 var clstr = post.ScreenName;
9296 Clipboard.SetDataObject(clstr, false, 5, 100);
9298 catch (Exception ex)
9300 MessageBox.Show(ex.Message);
9304 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9306 var post = this.CurrentPost;
9307 if (this.ExistCurrentPost && post != null && !post.IsDm)
9311 await this.OpenRelatedTab(post);
9313 catch (TabException ex)
9315 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9321 /// 指定されたツイートに対する関連発言タブを開きます
9323 /// <param name="statusId">表示するツイートのID</param>
9324 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9325 public async Task OpenRelatedTab(long statusId)
9327 var post = this.statuses[statusId];
9332 post = await this.tw.GetStatusApi(false, statusId);
9334 catch (WebApiException ex)
9336 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9341 await this.OpenRelatedTab(post);
9345 /// 指定されたツイートに対する関連発言タブを開きます
9347 /// <param name="post">表示する対象となるツイート</param>
9348 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9349 private async Task OpenRelatedTab(PostClass post)
9351 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9352 if (tabRelated != null)
9354 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9357 var tabName = this.statuses.MakeTabName("Related Tweets");
9359 tabRelated = new RelatedPostsTabModel(tabName, post)
9361 UnreadManage = false,
9365 this.statuses.AddTab(tabRelated);
9366 this.AddNewTab(tabRelated, startup: false);
9368 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9370 await this.RefreshTabAsync(tabRelated);
9372 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9376 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9378 var tabPage = this.ListTab.TabPages[tabIndex];
9379 var listView = (DetailsListView)tabPage.Tag;
9380 var targetPost = tabRelated.TargetPost;
9381 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9383 if (index != -1 && index < listView.Items.Count)
9385 listView.SelectedIndices.Add(index);
9386 listView.Items[index].Focused = true;
9391 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9393 var buf = new StringBuilder();
9394 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9395 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9396 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9399 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9401 MyCommon.EndingFlag = true;
9405 Application.Restart();
9409 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9413 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9414 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9416 private bool ExistCurrentPost
9420 var post = this.CurrentPost;
9421 return post != null && !post.IsDeleted;
9425 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9426 => await this.ShowUserTimeline();
9428 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9429 => await this.ShowRetweeterTimeline();
9431 private string GetUserIdFromCurPostOrInput(string caption)
9433 var id = this.CurrentPost?.ScreenName ?? "";
9435 using var inputName = new InputTabName();
9436 inputName.FormTitle = caption;
9437 inputName.FormDescription = Properties.Resources.FRMessage1;
9438 inputName.TabName = id;
9440 if (inputName.ShowDialog() == DialogResult.OK &&
9441 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9443 id = inputName.TabName.Trim();
9452 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9454 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9455 if (!MyCommon.IsNullOrEmpty(id))
9457 await this.AddNewTabForUserTimeline(id);
9461 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9463 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9464 this.timelineScheduler.SystemResumed();
9467 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9469 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9471 TimeZoneInfo.ClearCachedData();
9473 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9475 if (curTimeOffset != prevTimeOffset)
9478 this.listCache?.PurgeCache();
9479 this.CurrentListView.Refresh();
9481 this.DispSelectedPost(forceupdate: true);
9484 this.timelineScheduler.Reset();
9487 private void TimelineRefreshEnableChange(bool isEnable)
9489 this.timelineScheduler.Enabled = isEnable;
9492 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9493 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9495 private async Task OpenUserAppointUrl()
9497 if (this.settings.Common.UserAppointUrl != null)
9499 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9501 var post = this.CurrentPost;
9504 var xUrl = this.settings.Common.UserAppointUrl;
9505 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9507 var statusId = post.RetweetedId ?? post.StatusId;
9508 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
9510 await MyCommon.OpenInBrowserAsync(this, xUrl);
9515 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9520 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9521 => await this.OpenUserAppointUrl();
9523 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9525 if (Form.ActiveForm == null)
9527 await this.InvokeAsync(() =>
9529 this.Visible = true;
9530 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9532 this.BringToFront();
9533 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9535 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
9539 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
9545 private void ReplaceAppName()
9547 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9548 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9551 private void TweetThumbnail_ThumbnailLoading(object sender, EventArgs e)
9552 => this.SplitContainer3.Panel2Collapsed = false;
9554 private async void TweetThumbnail_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
9555 => await this.OpenThumbnailPicture(e.Thumbnail);
9557 private async void TweetThumbnail_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
9558 => await MyCommon.OpenInBrowserAsync(this, e.ImageUrl);
9560 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
9562 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
9564 await MyCommon.OpenInBrowserAsync(this, url);
9567 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9568 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9570 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9572 if (e.KeyCode == Keys.Space)
9574 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9576 e.SuppressKeyPress = true;
9580 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9582 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9583 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9584 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9585 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9586 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9588 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9591 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9592 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9594 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9595 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9597 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9598 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9600 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9601 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9603 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9604 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9606 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9608 if (this.settings.Common.IconSize == iconSize) return;
9610 var oldIconCol = this.Use2ColumnsMode;
9612 this.settings.Common.IconSize = iconSize;
9613 this.ApplyListViewIconSize(iconSize);
9615 if (this.Use2ColumnsMode != oldIconCol)
9617 foreach (TabPage tp in this.ListTab.TabPages)
9619 this.ResetColumns((DetailsListView)tp.Tag);
9623 this.CurrentListView.Refresh();
9624 this.MarkSettingCommonModified();
9627 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9629 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9630 if (this.settings.Common.SortOrderLock == state) return;
9632 this.settings.Common.SortOrderLock = state;
9633 this.MarkSettingCommonModified();
9636 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9638 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9640 this.StatusLabelUrl.Text = e.StatusText;
9644 this.SetStatusLabelUrl();