1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.Thumbnail;
66 public partial class TweenMain : OTBaseForm
70 /// <summary>画面サイズ</summary>
73 /// <summary>画面位置</summary>
76 /// <summary>区切り位置</summary>
79 /// <summary>発言欄区切り位置</summary>
82 /// <summary>プレビュー区切り位置</summary>
86 private bool initial; // true:起動時処理中
87 private bool initialLayout = true;
88 private bool ignoreConfigSave; // true:起動時処理中
90 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
93 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
94 private Point tabMouseDownPoint;
96 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
97 private string? rclickTabName;
99 private readonly object syncObject = new(); // ロック用
101 private const string DetailHtmlFormatHead =
102 """<head><meta http-equiv="X-UA-Compatible" content="IE=8">"""
103 + """<style type="text/css"><!-- """
104 + "body, p, pre {margin: 0;} "
105 + """body {font-family: "%FONT_FAMILY%", "Segoe UI Emoji", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} """
106 + "pre {font-family: inherit;} "
107 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
108 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
109 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
110 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
111 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
115 private const string DetailHtmlFormatTemplateMono =
116 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
118 private const string DetailHtmlFormatTemplateNormal =
119 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
121 private string detailHtmlFormatPreparedTemplate = null!;
123 private bool myStatusError = false;
124 private bool myStatusOnline = false;
125 private bool soundfileListup = false;
126 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
129 private readonly SettingManager settings;
132 private readonly Twitter tw;
135 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
139 /// <summary>検索画面インスタンス</summary>
140 internal SearchWordDialog SearchDialog = new();
142 private readonly OpenURL urlDialog = new();
144 /// <summary>@id補助</summary>
145 public AtIdSupplement AtIdSupl = null!;
147 /// <summary>Hashtag補助</summary>
148 public AtIdSupplement HashSupl = null!;
150 public HashtagManage HashMgr = null!;
153 private ThemeManager themeManager;
155 /// <summary>アイコン画像リスト</summary>
156 private readonly ImageCache iconCache;
158 private readonly IconAssetsManager iconAssets;
160 private readonly ThumbnailGenerator thumbGenerator;
162 /// <summary>発言履歴</summary>
163 private readonly List<StatusTextHistory> history = new();
165 /// <summary>発言履歴カレントインデックス</summary>
168 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
170 /// <summary>リプライ先のステータスID・スクリーン名</summary>
171 private (PostId StatusId, string ScreenName)? inReplyTo = null;
174 private readonly List<DateTimeUtc> postTimestamps = new();
175 private readonly List<DateTimeUtc> favTimestamps = new();
178 private readonly StringFormat sfTab = new();
180 //////////////////////////////////////////////////////////////////////////////////////////////////////////
182 /// <summary>発言保持クラス</summary>
183 private readonly TabInformations statuses;
185 private TimelineListViewCache? listCache;
186 private TimelineListViewDrawer? listDrawer;
187 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
189 private bool isColumnChanged = false;
191 private const int MaxWorderThreads = 20;
192 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
193 private readonly CancellationTokenSource workerCts = new();
194 private readonly IProgress<string> workerProgress = null!;
196 private int unreadCounter = -1;
197 private int unreadAtCounter = -1;
199 private readonly string[] columnOrgText = new string[9];
200 private readonly string[] columnText = new string[9];
202 private bool doFavRetweetFlags = false;
204 //////////////////////////////////////////////////////////////////////////////////////////////////////////
206 private readonly TimelineScheduler timelineScheduler = new();
207 private readonly DebounceTimer selectionDebouncer;
208 private readonly DebounceTimer saveConfigDebouncer;
210 private readonly string recommendedStatusFooter;
212 internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
214 private bool preventSmsCommand = true;
217 private readonly record struct UrlUndo(
222 private List<UrlUndo>? urlUndoBuffer = null;
224 private readonly record struct ReplyChain(
230 /// <summary>[, ]でのリプライ移動の履歴</summary>
231 private Stack<ReplyChain>? replyChains;
233 /// <summary>ポスト選択履歴</summary>
234 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
236 public TabModel CurrentTab
237 => this.statuses.SelectedTab;
239 public string CurrentTabName
240 => this.statuses.SelectedTabName;
242 public TabPage CurrentTabPage
243 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
245 public DetailsListView CurrentListView
246 => (DetailsListView)this.CurrentTabPage.Tag;
248 public PostClass? CurrentPost
249 => this.CurrentTab.SelectedPost;
251 public bool Use2ColumnsMode
252 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
254 /// <summary>検索処理タイプ</summary>
255 internal enum SEARCHTYPE
262 private readonly record struct StatusTextHistory(
264 (PostId StatusId, string ScreenName)? InReplyTo = null
267 private readonly HookGlobalHotkey hookGlobalHotkey;
270 SettingManager settingManager,
271 TabInformations tabInfo,
273 ImageCache imageCache,
274 IconAssetsManager iconAssets,
275 ThumbnailGenerator thumbGenerator
278 this.settings = settingManager;
279 this.statuses = tabInfo;
281 this.iconCache = imageCache;
282 this.iconAssets = iconAssets;
283 this.thumbGenerator = thumbGenerator;
285 this.InitializeComponent();
287 if (!this.DesignMode)
289 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
290 this.StatusText.Dock = DockStyle.Fill;
293 this.hookGlobalHotkey = new HookGlobalHotkey(this);
295 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
296 this.gh.NotifyClicked += this.GrowlHelper_Callback;
298 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
299 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
301 this.ImageSelector.Visible = false;
302 this.ImageSelector.Enabled = false;
303 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
305 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
307 this.ReplaceAppName();
308 this.InitializeShortcuts();
310 this.ignoreConfigSave = true;
312 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
314 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
316 Regex.CacheSize = 100;
319 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
320 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
321 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
323 // <<<<<<<<<設定関連>>>>>>>>>
327 // 現在の DPI と設定保存時の DPI との比を取得する
328 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
333 // プロキシ設定等の通信まわりの初期化が済んでから処理する
334 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
335 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
336 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
338 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
341 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
342 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
344 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
347 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
348 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
349 this.HashMgr = new HashtagManage(this.HashSupl,
350 this.settings.Common.HashTags.ToArray(),
351 this.settings.Common.HashSelected,
352 this.settings.Common.HashIsPermanent,
353 this.settings.Common.HashIsHead,
354 this.settings.Common.HashIsNotAddToAtReply);
355 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
358 this.themeManager = new(this.settings.Local);
359 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
361 // StringFormatオブジェクトへの事前設定
362 this.sfTab.Alignment = StringAlignment.Center;
363 this.sfTab.LineAlignment = StringAlignment.Center;
365 this.InitDetailHtmlFormat();
366 this.tweetDetailsView.ClearPostBrowser();
368 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
370 this.history.Add(new StatusTextHistory(""));
372 this.inReplyTo = null;
375 this.SearchDialog.Owner = this;
376 this.urlDialog.Owner = this;
379 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
380 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
382 // 新着取得時のリストスクロールをするか。trueならスクロールしない
383 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
384 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
386 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
387 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
390 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
391 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
392 this.myLoc = this.settings.Local.FormLocation;
394 if (this.WindowState != FormWindowState.Minimized)
396 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
397 var outOfScreen = true;
398 if (Screen.AllScreens.Length == 1) // ハングするとの報告
400 foreach (var scr in Screen.AllScreens)
402 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
410 this.myLoc = new Point(0, 0);
412 this.DesktopLocation = this.myLoc;
414 this.TopMost = this.settings.Common.AlwaysTop;
415 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
416 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
417 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
419 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
420 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
422 this.StatusText.Font = this.themeManager.FontInputFont;
423 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
425 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
426 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
427 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
429 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
430 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
432 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
433 if (this.settings.Common.UnreadManage == false)
435 this.ReadedStripMenuItem.Enabled = false;
436 this.UnreadStripMenuItem.Enabled = false;
439 // リンク先URL表示部の初期化(画面左下)
440 this.StatusLabelUrl.Text = "";
442 this.StatusLabel.Text = "";
443 this.StatusLabel.AutoToolTip = false;
444 this.StatusLabel.ToolTipText = "";
446 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
448 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
449 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
450 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
451 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
453 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
454 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
455 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
456 this.SplitContainer2.Panel2.AccessibleName = "";
458 ////////////////////////////////////////////////////////////////////////////////
459 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
460 var mode = this.settings.Common.SortColumn switch
462 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
463 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
464 1 => ComparerMode.Nickname, // ニックネーム
465 2 => ComparerMode.Data, // 本文
466 3 => ComparerMode.Id, // 時刻=発言Id
467 4 => ComparerMode.Name, // 名前
468 7 => ComparerMode.Source, // Source
469 _ => ComparerMode.Id,
471 this.statuses.SetSortMode(mode, sortOrder);
472 ////////////////////////////////////////////////////////////////////////////////
474 this.ApplyListViewIconSize(this.settings.Common.IconSize);
476 // <<<<<<<<タブ関連>>>>>>>
477 foreach (var tab in this.statuses.Tabs)
479 if (!this.AddNewTab(tab, startup: true))
480 throw new TabException(Properties.Resources.TweenMain_LoadText1);
483 this.ListTabSelect(this.ListTab.SelectedTab);
486 this.SetTabAlignment();
488 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
489 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
491 if (this.settings.Common.TabIconDisp)
493 this.ListTab.DrawMode = TabDrawMode.Normal;
497 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
498 this.ListTab.DrawItem += this.ListTab_DrawItem;
499 this.ListTab.ImageList = null;
502 if (this.settings.Common.HotkeyEnabled)
505 var modKey = HookGlobalHotkey.ModKeys.None;
506 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
507 modKey |= HookGlobalHotkey.ModKeys.Alt;
508 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
509 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
510 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
511 modKey |= HookGlobalHotkey.ModKeys.Shift;
512 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
513 modKey |= HookGlobalHotkey.ModKeys.Win;
515 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
518 if (this.settings.Common.IsUseNotifyGrowl)
519 this.gh.RegisterGrowl();
521 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
523 this.SetMainWindowTitle();
524 this.SetNotifyIconText();
526 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
528 this.Visible = false;
533 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
534 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
535 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
536 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
537 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
538 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
539 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
541 this.DoGetFollowersMenu(),
542 this.RefreshBlockIdsAsync(),
543 this.RefreshMuteUserIdsAsync(),
544 this.RefreshNoRetweetIdsAsync(),
545 this.RefreshTwitterConfigurationAsync(),
547 this.RefreshTimelineScheduler();
549 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
550 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
553 this.TimerRefreshIcon.Interval = 200;
554 this.TimerRefreshIcon.Enabled = false;
556 this.ignoreConfigSave = false;
557 this.ApplyLayoutFromSettings();
560 private void TweenMain_Activated(object sender, EventArgs e)
562 // 画面がアクティブになったら、発言欄の背景色戻す
563 if (this.StatusText.Focused)
565 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
569 private bool disposed = false;
572 /// 使用中のリソースをすべてクリーンアップします。
574 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
575 protected override void Dispose(bool disposing)
577 base.Dispose(disposing);
584 this.components?.Dispose();
587 this.SearchDialog.Dispose();
588 this.urlDialog.Dispose();
589 this.themeManager.Dispose();
590 this.sfTab.Dispose();
592 this.timelineScheduler.Dispose();
593 this.workerCts.Cancel();
594 this.thumbnailTokenSource?.Dispose();
596 this.hookGlobalHotkey.Dispose();
599 // 終了時にRemoveHandlerしておかないとメモリリークする
600 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
601 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
602 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
603 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
605 this.disposed = true;
608 private void InitColumns(ListView list, bool startup)
610 this.InitColumnText();
612 ColumnHeader[]? columns = null;
615 if (this.Use2ColumnsMode)
619 new ColumnHeader(), // アイコン
620 new ColumnHeader(), // 本文
623 columns[0].Text = this.columnText[0];
624 columns[1].Text = this.columnText[2];
628 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
630 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
631 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
632 columns[0].DisplayIndex = 0;
633 columns[1].DisplayIndex = 1;
638 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
640 columns[idx].Width = curListColumn.Width;
641 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
650 new ColumnHeader(), // アイコン
651 new ColumnHeader(), // ニックネーム
652 new ColumnHeader(), // 本文
653 new ColumnHeader(), // 日付
654 new ColumnHeader(), // ユーザID
655 new ColumnHeader(), // 未読
656 new ColumnHeader(), // マーク&プロテクト
657 new ColumnHeader(), // ソース
660 foreach (var i in Enumerable.Range(0, columns.Length))
661 columns[i].Text = this.columnText[i];
665 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
667 foreach (var (column, index) in columns.WithIndex())
669 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
670 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
676 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
678 columns[idx].Width = curListColumn.Width;
679 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
685 list.Columns.AddRange(columns);
693 foreach (var column in columns)
699 private void InitColumnText()
701 this.columnText[0] = "";
702 this.columnText[1] = Properties.Resources.AddNewTabText2;
703 this.columnText[2] = Properties.Resources.AddNewTabText3;
704 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
705 this.columnText[4] = Properties.Resources.AddNewTabText5;
706 this.columnText[5] = "";
707 this.columnText[6] = "";
708 this.columnText[7] = "Source";
710 this.columnOrgText[0] = "";
711 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
712 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
713 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
714 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
715 this.columnOrgText[5] = "";
716 this.columnOrgText[6] = "";
717 this.columnOrgText[7] = "Source";
719 var c = this.statuses.SortMode switch
721 ComparerMode.Nickname => 1, // ニックネーム
722 ComparerMode.Data => 2, // 本文
723 ComparerMode.Id => 3, // 時刻=発言Id
724 ComparerMode.Name => 4, // 名前
725 ComparerMode.Source => 7, // Source
729 if (this.Use2ColumnsMode)
731 if (this.statuses.SortOrder == SortOrder.Descending)
733 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
734 this.columnText[2] = this.columnOrgText[2] + "▾";
738 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
739 this.columnText[2] = this.columnOrgText[2] + "▴";
744 if (this.statuses.SortOrder == SortOrder.Descending)
746 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
747 this.columnText[c] = this.columnOrgText[c] + "▾";
751 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
752 this.columnText[c] = this.columnOrgText[c] + "▴";
757 private void InitDetailHtmlFormat()
759 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
761 static string ColorToRGBString(Color color)
762 => $"{color.R},{color.G},{color.B}";
764 this.detailHtmlFormatPreparedTemplate = htmlTemplate
765 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
766 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
767 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
768 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
769 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
770 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
773 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
778 txt = this.statuses.Tabs[e.Index].TabName;
785 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
786 if (e.State == DrawItemState.Selected)
788 e.DrawFocusRectangle();
793 if (this.statuses.Tabs[txt].UnreadCount > 0)
796 fore = System.Drawing.SystemBrushes.ControlText;
800 fore = System.Drawing.SystemBrushes.ControlText;
802 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
805 private void LoadConfig()
807 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
808 this.statuses.AddDefaultTabs();
811 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
813 this.RefreshTimelineScheduler();
816 private void RefreshTimelineScheduler()
818 static TimeSpan IntervalSecondsOrDisabled(int seconds)
819 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
821 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
822 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
823 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
824 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
825 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
826 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
827 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
828 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
830 this.timelineScheduler.RefreshSchedule();
833 private void MarkSettingCommonModified()
835 if (this.saveConfigDebouncer == null)
838 this.ModifySettingCommon = true;
839 _ = this.saveConfigDebouncer.Call();
842 private void MarkSettingLocalModified()
844 if (this.saveConfigDebouncer == null)
847 this.ModifySettingLocal = true;
848 _ = this.saveConfigDebouncer.Call();
851 internal void MarkSettingAtIdModified()
853 if (this.saveConfigDebouncer == null)
856 this.ModifySettingAtId = true;
857 _ = this.saveConfigDebouncer.Call();
860 private void RefreshTimeline()
862 var curListView = this.CurrentListView;
864 // 現在表示中のタブのスクロール位置を退避
865 var currentListViewState = this.listViewState[this.CurrentTabName];
866 currentListViewState.Save(this.ListLockMenuItem.Checked);
870 addCount = this.statuses.SubmitUpdate(
873 out var newMentionOrDm,
876 if (MyCommon.EndingFlag) return;
879 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
881 using (ControlTransaction.Update(curListView))
883 this.listCache.PurgeCache();
884 this.listCache.UpdateListSize();
887 currentListViewState.RestoreSelection();
893 if (this.settings.Common.TabIconDisp)
895 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
897 var tabPage = this.ListTab.TabPages[index];
898 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
899 tabPage.ImageIndex = 0; // 未読アイコン
904 this.ListTab.Refresh();
909 currentListViewState.RestoreScroll();
912 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
914 this.SetMainWindowTitle();
915 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
917 this.HashSupl.AddRangeItem(this.tw.GetHashList());
920 private bool BalloonRequired()
925 if (NativeMethods.IsScreenSaverRunning())
929 if (!this.NewPostPopMenuItem.Checked)
932 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
933 if (this.settings.Common.LimitBalloon)
935 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
942 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
944 if (this.settings.Common.ReadOwnPost)
946 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
951 if (this.BalloonRequired())
953 if (notifyPosts != null && notifyPosts.Length > 0)
955 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
956 if (this.settings.Common.IsUseNotifyGrowl)
958 var sb = new StringBuilder();
962 foreach (var post in notifyPosts)
964 if (!(notifyPosts.Length > 3))
970 if (post.IsReply && !post.IsExcludeReply) reply = true;
971 if (post.IsDm) dm = true;
972 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
973 switch (this.settings.Common.NameBalloon)
975 case MyCommon.NameBalloonEnum.UserID:
976 sb.Append(post.ScreenName).Append(" : ");
978 case MyCommon.NameBalloonEnum.NickName:
979 sb.Append(post.Nickname).Append(" : ");
982 sb.Append(post.TextFromApi);
983 if (notifyPosts.Length > 3)
985 if (notifyPosts.Last() != post) continue;
988 var title = new StringBuilder();
989 GrowlHelper.NotifyType nt;
990 if (this.settings.Common.DispUsername)
992 title.Append(this.tw.Username);
998 title.Append(ApplicationSettings.ApplicationName);
999 title.Append(" [DM] ");
1000 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1001 nt = GrowlHelper.NotifyType.DirectMessage;
1005 title.Append(ApplicationSettings.ApplicationName);
1006 title.Append(" [Reply!] ");
1007 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1008 nt = GrowlHelper.NotifyType.Reply;
1012 title.Append(ApplicationSettings.ApplicationName);
1014 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1015 nt = GrowlHelper.NotifyType.Notify;
1017 var bText = sb.ToString();
1018 if (MyCommon.IsNullOrEmpty(bText)) return;
1020 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1021 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
1026 var sb = new StringBuilder();
1029 foreach (var post in notifyPosts)
1031 if (post.IsReply && !post.IsExcludeReply) reply = true;
1032 if (post.IsDm) dm = true;
1033 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1034 switch (this.settings.Common.NameBalloon)
1036 case MyCommon.NameBalloonEnum.UserID:
1037 sb.Append(post.ScreenName).Append(" : ");
1039 case MyCommon.NameBalloonEnum.NickName:
1040 sb.Append(post.Nickname).Append(" : ");
1043 sb.Append(post.TextFromApi);
1046 var title = new StringBuilder();
1048 if (this.settings.Common.DispUsername)
1050 title.Append(this.tw.Username);
1051 title.Append(" - ");
1056 ntIcon = ToolTipIcon.Warning;
1057 title.Append(ApplicationSettings.ApplicationName);
1058 title.Append(" [DM] ");
1059 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1063 ntIcon = ToolTipIcon.Warning;
1064 title.Append(ApplicationSettings.ApplicationName);
1065 title.Append(" [Reply!] ");
1066 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1070 ntIcon = ToolTipIcon.Info;
1071 title.Append(ApplicationSettings.ApplicationName);
1073 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1075 var bText = sb.ToString();
1076 if (MyCommon.IsNullOrEmpty(bText)) return;
1078 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1079 this.NotifyIcon1.BalloonTipText = bText;
1080 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1081 this.NotifyIcon1.ShowBalloonTip(500);
1087 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1091 var dir = Application.StartupPath;
1092 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1094 dir = Path.Combine(dir, "Sounds");
1096 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1104 // mentions新着時に画面ブリンク
1105 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1107 NativeMethods.FlashMyWindow(this.Handle, 3);
1111 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1113 var listView = this.CurrentListView;
1114 if (listView != sender)
1117 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1118 this.CurrentTab.SelectPosts(indices);
1120 if (indices.Length != 1)
1123 var index = indices[0];
1124 if (index > listView.VirtualListSize - 1) return;
1126 this.PushSelectPostChain();
1128 var post = this.CurrentPost!;
1129 this.statuses.SetReadAllTab(post.StatusId, read: true);
1131 this.listCache?.RefreshStyle();
1132 await this.selectionDebouncer.Call();
1135 private void StatusTextHistoryBack()
1137 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1138 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1141 if (this.hisIdx < 0)
1144 var historyItem = this.history[this.hisIdx];
1145 this.inReplyTo = historyItem.InReplyTo;
1146 this.StatusText.Text = historyItem.Status;
1147 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1150 private void StatusTextHistoryForward()
1152 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1153 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1156 if (this.hisIdx > this.history.Count - 1)
1157 this.hisIdx = this.history.Count - 1;
1159 var historyItem = this.history[this.hisIdx];
1160 this.inReplyTo = historyItem.InReplyTo;
1161 this.StatusText.Text = historyItem.Status;
1162 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1165 private async void PostButton_Click(object sender, EventArgs e)
1167 if (this.StatusText.Text.Trim().Length == 0)
1169 if (!this.ImageSelector.Enabled)
1171 await this.DoRefresh();
1176 var currentPost = this.CurrentPost;
1177 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1179 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1181 MessageBoxButtons.YesNoCancel,
1182 MessageBoxIcon.Question);
1185 case DialogResult.Yes:
1186 this.StatusText.Text = "";
1187 await this.DoReTweetOfficial(false);
1189 case DialogResult.Cancel:
1194 if (TextContainsOnlyMentions(this.StatusText.Text))
1196 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1197 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1199 if (ret != DialogResult.OK)
1203 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1205 if (this.settings.Common.Nicoms)
1207 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1208 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1211 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1212 this.CheckReplyTo(this.StatusText.Text);
1214 var status = new PostStatusParams();
1216 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1217 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1219 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1220 // 収まる場合はこれらのオプションを使用せずに投稿する
1221 status.Text = statusTextCompat;
1222 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1226 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1227 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1229 status.AttachmentUrl = attachmentUrl;
1231 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1233 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1234 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1236 status.AutoPopulateReplyMetadata = true;
1238 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1239 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1244 if (this.GetRestStatusCount(status.Text) < 0)
1246 // 文字数制限を超えているが強制的に投稿するか
1247 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1248 if (ret != DialogResult.OK)
1252 IMediaUploadService? uploadService = null;
1253 IMediaItem[]? uploadItems = null;
1254 if (this.ImageSelector.Visible)
1257 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1260 this.ImageSelector.EndSelection();
1261 uploadService = this.ImageSelector.Model.GetService(serviceName);
1264 this.inReplyTo = null;
1265 this.StatusText.Text = "";
1266 this.history.Add(new StatusTextHistory(""));
1267 this.hisIdx = this.history.Count - 1;
1268 if (!this.settings.Common.FocusLockToStatusText)
1269 this.CurrentListView.Focus();
1270 this.urlUndoBuffer = null;
1271 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1274 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1276 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1277 await MyCommon.OpenInBrowserAsync(this, tmp);
1280 await this.PostMessageAsync(status, uploadService, uploadItems);
1283 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1285 MyCommon.EndingFlag = true;
1289 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1291 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1293 // _endingFlag=false:フォームの×ボタン
1295 this.Visible = false;
1299 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1300 this.ignoreConfigSave = true;
1301 MyCommon.EndingFlag = true;
1302 this.timelineScheduler.Enabled = false;
1303 this.TimerRefreshIcon.Enabled = false;
1307 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1309 this.Visible = true;
1310 if (this.WindowState == FormWindowState.Minimized)
1312 this.WindowState = FormWindowState.Normal;
1315 this.BringToFront();
1318 private static int errorCount = 0;
1320 private static bool CheckAccountValid()
1322 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1328 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1337 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1338 private Task RefreshTabAsync<T>()
1340 => this.RefreshTabAsync<T>(backward: false);
1342 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1343 private Task RefreshTabAsync<T>(bool backward)
1347 from tab in this.statuses.GetTabsByType<T>()
1348 select this.RefreshTabAsync(tab, backward);
1350 return Task.WhenAll(loadTasks);
1353 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1354 private Task RefreshTabAsync(TabModel tab)
1355 => this.RefreshTabAsync(tab, backward: false);
1357 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1358 private async Task RefreshTabAsync(TabModel tab, bool backward)
1360 await this.workerSemaphore.WaitAsync();
1364 this.RefreshTasktrayIcon();
1365 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1367 catch (WebApiException ex)
1369 this.myStatusError = true;
1370 var tabType = tab switch
1372 HomeTabModel => "GetTimeline",
1373 MentionsTabModel => "GetTimeline",
1374 DirectMessagesTabModel => "GetDirectMessage",
1375 FavoritesTabModel => "GetFavorites",
1376 PublicSearchTabModel => "GetSearch",
1377 UserTimelineTabModel => "GetUserTimeline",
1378 ListTimelineTabModel => "GetListStatus",
1379 RelatedPostsTabModel => "GetRelatedTweets",
1380 _ => tab.GetType().Name.Replace("Model", ""),
1382 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1386 this.RefreshTimeline();
1387 this.workerSemaphore.Release();
1391 private async Task FavAddAsync(PostId statusId, TabModel tab)
1393 await this.workerSemaphore.WaitAsync();
1397 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1399 this.RefreshTasktrayIcon();
1400 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1402 catch (WebApiException ex)
1404 this.myStatusError = true;
1405 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1409 this.workerSemaphore.Release();
1413 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1415 if (ct.IsCancellationRequested)
1418 if (!CheckAccountValid())
1419 throw new WebApiException("Auth error. Check your account");
1421 if (!tab.Posts.TryGetValue(statusId, out var post))
1427 await Task.Run(async () =>
1429 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1433 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1436 await this.tw.Api.FavoritesCreate(twitterStatusId)
1438 .ConfigureAwait(false);
1440 catch (TwitterApiException ex)
1441 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1443 // エラーコード 139 のみの場合は成功と見なす
1446 if (this.settings.Common.RestrictFavCheck)
1448 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1449 .ConfigureAwait(false);
1451 if (status.Favorited != true)
1452 throw new WebApiException("NG(Restricted?)");
1455 this.favTimestamps.Add(DateTimeUtc.Now);
1458 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1460 postTl.IsFav = true;
1462 var favTab = this.statuses.FavoriteTab;
1463 favTab.AddPostQueue(postTl);
1466 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1467 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1469 if (tb.Contains(statusId))
1470 tb.Posts[statusId].IsFav = true;
1473 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1475 catch (WebApiException)
1477 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1482 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1483 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1485 if (this.favTimestamps[i] < oneHour)
1486 this.favTimestamps.RemoveAt(i);
1489 this.statuses.DistributePosts();
1492 if (ct.IsCancellationRequested)
1495 this.RefreshTimeline();
1497 if (this.CurrentTabName == tab.TabName)
1499 using (ControlTransaction.Update(this.CurrentListView))
1501 var idx = tab.IndexOf(statusId);
1503 this.listCache?.RefreshStyle(idx);
1506 var currentPost = this.CurrentPost;
1507 if (currentPost != null && statusId == currentPost.StatusId)
1508 this.DispSelectedPost(true); // 選択アイテム再表示
1512 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1514 await this.workerSemaphore.WaitAsync();
1518 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1520 this.RefreshTasktrayIcon();
1521 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1523 catch (WebApiException ex)
1525 this.myStatusError = true;
1526 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1530 this.workerSemaphore.Release();
1534 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1536 if (ct.IsCancellationRequested)
1539 if (!CheckAccountValid())
1540 throw new WebApiException("Auth error. Check your account");
1542 var successIds = new List<PostId>();
1544 await Task.Run(async () =>
1548 var failedCount = 0;
1549 foreach (var statusId in statusIds)
1553 var post = tab.Posts[statusId];
1555 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1560 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1564 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1566 .ConfigureAwait(false);
1568 catch (WebApiException)
1574 successIds.Add(statusId);
1575 post.IsFav = false; // リスト再描画必要
1577 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1578 tabinfoPost.IsFav = false;
1580 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1581 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1583 if (tb.Contains(statusId))
1584 tb.Posts[statusId].IsFav = false;
1589 if (ct.IsCancellationRequested)
1592 var favTab = this.statuses.FavoriteTab;
1593 foreach (var statusId in successIds)
1595 // ツイートが削除された訳ではないので IsDeleted はセットしない
1596 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1599 this.RefreshTimeline();
1601 if (this.CurrentTabName == tab.TabName)
1603 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1609 using (ControlTransaction.Update(this.CurrentListView))
1611 foreach (var statusId in successIds)
1613 var idx = tab.IndexOf(statusId);
1615 this.listCache?.RefreshStyle(idx);
1619 var currentPost = this.CurrentPost;
1620 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1621 this.DispSelectedPost(true); // 選択アイテム再表示
1626 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1628 await this.workerSemaphore.WaitAsync();
1632 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1634 this.RefreshTasktrayIcon();
1635 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1637 catch (WebApiException ex)
1639 this.myStatusError = true;
1640 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1644 this.workerSemaphore.Release();
1648 private async Task PostMessageAsyncInternal(
1649 IProgress<string> p,
1650 CancellationToken ct,
1651 PostStatusParams postParams,
1652 IMediaUploadService? uploadService,
1653 IMediaItem[]? uploadItems)
1655 if (ct.IsCancellationRequested)
1658 if (!CheckAccountValid())
1659 throw new WebApiException("Auth error. Check your account");
1661 p.Report("Posting...");
1663 PostClass? post = null;
1668 await Task.Run(async () =>
1670 var postParamsWithMedia = postParams;
1672 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1674 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1675 .ConfigureAwait(false);
1678 post = await this.tw.PostStatus(postParamsWithMedia)
1679 .ConfigureAwait(false);
1682 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1684 catch (WebApiException ex)
1686 // 処理は中断せずエラーの表示のみ行う
1687 errMsg = $"Err:{ex.Message}(PostMessage)";
1689 this.myStatusError = true;
1691 catch (UnauthorizedAccessException ex)
1693 // アップロード対象のファイルが開けなかった場合など
1694 errMsg = $"Err:{ex.Message}(PostMessage)";
1696 this.myStatusError = true;
1700 // 使い終わった MediaItem は破棄する
1701 if (uploadItems != null)
1703 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1705 disposableItem.Dispose();
1710 if (ct.IsCancellationRequested)
1713 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1714 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1715 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1717 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1719 var ret = MessageBox.Show(
1721 "Failed to update status",
1722 MessageBoxButtons.RetryCancel,
1723 MessageBoxIcon.Question);
1725 if (ret == DialogResult.Retry)
1727 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1731 this.StatusTextHistoryBack();
1732 this.StatusText.Focus();
1734 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1735 if (this.settings.Common.FocusLockToStatusText)
1736 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1741 this.postTimestamps.Add(DateTimeUtc.Now);
1743 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1744 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1746 if (this.postTimestamps[i] < oneHour)
1747 this.postTimestamps.RemoveAt(i);
1750 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1752 this.HashMgr.ClearHashtag();
1753 this.HashStripSplitButton.Text = "#[-]";
1754 this.HashTogglePullDownMenuItem.Checked = false;
1755 this.HashToggleMenuItem.Checked = false;
1758 this.SetMainWindowTitle();
1763 this.statuses.AddPost(post);
1764 this.statuses.DistributePosts();
1765 this.RefreshTimeline();
1768 if (this.settings.Common.PostAndGet)
1769 await this.RefreshTabAsync<HomeTabModel>();
1772 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1774 await this.workerSemaphore.WaitAsync();
1778 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1780 this.RefreshTasktrayIcon();
1781 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1783 catch (WebApiException ex)
1785 this.myStatusError = true;
1786 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1790 this.workerSemaphore.Release();
1794 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1796 if (ct.IsCancellationRequested)
1799 if (!CheckAccountValid())
1800 throw new WebApiException("Auth error. Check your account");
1803 if (!this.settings.Common.UnreadManage)
1806 read = this.initial && this.settings.Common.Read;
1808 p.Report("Posting...");
1810 var posts = new List<PostClass>();
1812 await Task.Run(async () =>
1814 foreach (var statusId in statusIds)
1816 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1817 if (post != null) posts.Add(post);
1821 if (ct.IsCancellationRequested)
1824 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1826 this.postTimestamps.Add(DateTimeUtc.Now);
1828 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1829 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1831 if (this.postTimestamps[i] < oneHour)
1832 this.postTimestamps.RemoveAt(i);
1835 // 自分のRTはTLの更新では取得できない場合があるので、
1836 // 投稿時取得の有無に関わらず追加しておく
1837 posts.ForEach(post => this.statuses.AddPost(post));
1839 if (this.settings.Common.PostAndGet)
1841 await this.RefreshTabAsync<HomeTabModel>();
1845 this.statuses.DistributePosts();
1846 this.RefreshTimeline();
1850 private async Task RefreshFollowerIdsAsync()
1852 await this.workerSemaphore.WaitAsync();
1856 this.RefreshTasktrayIcon();
1857 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1859 await this.tw.RefreshFollowerIds();
1861 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1863 this.RefreshTimeline();
1864 this.listCache?.PurgeCache();
1865 this.CurrentListView.Refresh();
1867 catch (WebApiException ex)
1869 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1873 this.workerSemaphore.Release();
1877 private async Task RefreshNoRetweetIdsAsync()
1879 await this.workerSemaphore.WaitAsync();
1883 this.RefreshTasktrayIcon();
1884 await this.tw.RefreshNoRetweetIds();
1886 this.StatusLabel.Text = "NoRetweetIds refreshed";
1888 catch (WebApiException ex)
1890 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1894 this.workerSemaphore.Release();
1898 private async Task RefreshBlockIdsAsync()
1900 await this.workerSemaphore.WaitAsync();
1904 this.RefreshTasktrayIcon();
1905 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1907 await this.tw.RefreshBlockIds();
1909 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1911 catch (WebApiException ex)
1913 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1917 this.workerSemaphore.Release();
1921 private async Task RefreshTwitterConfigurationAsync()
1923 await this.workerSemaphore.WaitAsync();
1927 this.RefreshTasktrayIcon();
1928 await this.tw.RefreshConfiguration();
1930 if (this.tw.Configuration.PhotoSizeLimit != 0)
1932 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1934 service.UpdateTwitterConfiguration(this.tw.Configuration);
1938 this.listCache?.PurgeCache();
1939 this.CurrentListView.Refresh();
1941 catch (WebApiException ex)
1943 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1947 this.workerSemaphore.Release();
1951 private async Task RefreshMuteUserIdsAsync()
1953 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1957 await this.tw.RefreshMuteUserIdsAsync();
1959 catch (WebApiException ex)
1961 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1965 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1968 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1970 if (e.Button == MouseButtons.Left)
1972 this.Visible = true;
1973 if (this.WindowState == FormWindowState.Minimized)
1975 this.WindowState = this.formWindowState;
1978 this.BringToFront();
1982 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1983 => await this.ListItemDoubleClickAction();
1985 private async Task ListItemDoubleClickAction()
1987 switch (this.settings.Common.ListDoubleClickAction)
1989 case MyCommon.ListItemDoubleClickActionType.Reply:
1990 this.MakeReplyText();
1992 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1993 this.MakeReplyText(atAll: true);
1995 case MyCommon.ListItemDoubleClickActionType.Favorite:
1996 await this.FavoriteChange(true);
1998 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1999 var post = this.CurrentPost;
2001 await this.ShowUserStatus(post.ScreenName, false);
2003 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2004 await this.ShowUserTimeline();
2006 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2007 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2009 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2010 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2012 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2013 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2015 case MyCommon.ListItemDoubleClickActionType.None:
2022 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2023 => await this.FavoriteChange(true);
2025 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2026 => await this.FavoriteChange(false);
2028 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2029 => await this.FavoritesRetweetOfficial();
2031 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2032 => await this.FavoritesRetweetUnofficial();
2034 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2036 var tab = this.CurrentTab;
2037 var posts = tab.SelectedPosts;
2039 // trueでFavAdd,falseでFavRemove
2040 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2041 || !this.ExistCurrentPost) return;
2043 if (posts.Length > 1)
2048 // https://support.twitter.com/articles/76915#favoriting
2049 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2050 this.doFavRetweetFlags = false;
2055 if (multiFavoriteChangeDialogEnable)
2057 var confirm = MessageBox.Show(
2058 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2059 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2060 MessageBoxButtons.OKCancel,
2061 MessageBoxIcon.Question);
2063 if (confirm == DialogResult.Cancel)
2071 var selectedPost = posts.Single();
2072 if (selectedPost.IsFav)
2074 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2078 await this.FavAddAsync(selectedPost.StatusId, tab);
2082 var selectedPosts = posts.Where(x => x.IsFav);
2083 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2084 if (statusIds.Length == 0)
2086 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2090 await this.FavRemoveAsync(statusIds, tab);
2094 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2096 var post = this.CurrentPost;
2098 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2100 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2103 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2105 if ((!this.initialLayout) && this.Visible)
2107 if (this.WindowState == FormWindowState.Normal)
2109 this.mySize = this.ClientSize;
2110 this.mySpDis = this.SplitContainer1.SplitterDistance;
2111 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2112 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2113 this.MarkSettingLocalModified();
2118 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2120 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2121 if (comparerMode == null)
2124 this.SetSortColumn(comparerMode.Value);
2128 /// 列インデックスからソートを行う ComparerMode を求める
2130 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2131 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2132 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2134 if (this.Use2ColumnsMode)
2135 return ComparerMode.Id;
2137 return columnIndex switch
2139 1 => ComparerMode.Nickname, // ニックネーム
2140 2 => ComparerMode.Data, // 本文
2141 3 => ComparerMode.Id, // 時刻=発言Id
2142 4 => ComparerMode.Name, // 名前
2143 7 => ComparerMode.Source, // Source
2144 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2149 /// 発言一覧の指定した位置の列でソートする
2151 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2152 private void SetSortColumnByDisplayIndex(int columnIndex)
2154 // 表示上の列の位置から ColumnHeader を求める
2155 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2156 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2161 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2162 if (comparerMode == null)
2165 this.SetSortColumn(comparerMode.Value);
2169 /// 発言一覧の最後列の項目でソートする
2171 private void SetSortLastColumn()
2173 // 表示上の最後列にある ColumnHeader を求める
2174 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2175 .OrderByDescending(x => x.DisplayIndex)
2178 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2179 if (comparerMode == null)
2182 this.SetSortColumn(comparerMode.Value);
2186 /// 発言一覧を指定された ComparerMode に基づいてソートする
2188 private void SetSortColumn(ComparerMode sortColumn)
2190 if (this.settings.Common.SortOrderLock)
2193 this.statuses.ToggleSortOrder(sortColumn);
2194 this.InitColumnText();
2196 var list = this.CurrentListView;
2197 if (this.Use2ColumnsMode)
2199 list.Columns[0].Text = this.columnText[0];
2200 list.Columns[1].Text = this.columnText[2];
2204 for (var i = 0; i <= 7; i++)
2206 list.Columns[i].Text = this.columnText[i];
2210 this.listCache?.PurgeCache();
2212 var tab = this.CurrentTab;
2213 var post = this.CurrentPost;
2214 if (tab.AllCount > 0 && post != null)
2216 var idx = tab.IndexOf(post.StatusId);
2219 this.SelectListItem(list, idx);
2220 list.EnsureVisible(idx);
2225 this.MarkSettingCommonModified();
2228 private void TweenMain_LocationChanged(object sender, EventArgs e)
2230 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2232 this.myLoc = this.DesktopLocation;
2233 this.MarkSettingLocalModified();
2237 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2239 var post = this.CurrentPost;
2240 if (!this.ExistCurrentPost)
2242 this.ReplyStripMenuItem.Enabled = false;
2243 this.ReplyAllStripMenuItem.Enabled = false;
2244 this.DMStripMenuItem.Enabled = false;
2245 this.TabMenuItem.Enabled = false;
2246 this.IDRuleMenuItem.Enabled = false;
2247 this.SourceRuleMenuItem.Enabled = false;
2248 this.ReadedStripMenuItem.Enabled = false;
2249 this.UnreadStripMenuItem.Enabled = false;
2250 this.AuthorContextMenuItem.Visible = false;
2251 this.RetweetedByContextMenuItem.Visible = false;
2255 this.ReplyStripMenuItem.Enabled = true;
2256 this.ReplyAllStripMenuItem.Enabled = true;
2257 this.DMStripMenuItem.Enabled = true;
2258 this.TabMenuItem.Enabled = true;
2259 this.IDRuleMenuItem.Enabled = true;
2260 this.SourceRuleMenuItem.Enabled = true;
2261 this.ReadedStripMenuItem.Enabled = true;
2262 this.UnreadStripMenuItem.Enabled = true;
2263 this.AuthorContextMenuItem.Visible = true;
2264 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2265 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2266 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2268 var tab = this.CurrentTab;
2269 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2271 this.FavAddToolStripMenuItem.Enabled = false;
2272 this.FavRemoveToolStripMenuItem.Enabled = false;
2273 this.StatusOpenMenuItem.Enabled = false;
2274 this.ShowRelatedStatusesMenuItem.Enabled = false;
2276 this.ReTweetStripMenuItem.Enabled = false;
2277 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2278 this.QuoteStripMenuItem.Enabled = false;
2279 this.FavoriteRetweetContextMenu.Enabled = false;
2280 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2284 this.FavAddToolStripMenuItem.Enabled = true;
2285 this.FavRemoveToolStripMenuItem.Enabled = true;
2286 this.StatusOpenMenuItem.Enabled = true;
2287 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2289 if (!post.CanRetweetBy(this.tw.UserId))
2291 this.ReTweetStripMenuItem.Enabled = false;
2292 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2293 this.QuoteStripMenuItem.Enabled = false;
2294 this.FavoriteRetweetContextMenu.Enabled = false;
2295 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2299 this.ReTweetStripMenuItem.Enabled = true;
2300 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2301 this.QuoteStripMenuItem.Enabled = true;
2302 this.FavoriteRetweetContextMenu.Enabled = true;
2303 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2307 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2309 this.RepliedStatusOpenMenuItem.Enabled = false;
2313 this.RepliedStatusOpenMenuItem.Enabled = true;
2316 if (this.ExistCurrentPost && post != null)
2318 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2319 if (post.RetweetedByUserId == this.tw.UserId)
2320 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2322 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2326 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2327 => this.MakeReplyText();
2329 private void DMStripMenuItem_Click(object sender, EventArgs e)
2330 => this.MakeDirectMessageText();
2332 private async Task DoStatusDelete()
2334 var posts = this.CurrentTab.SelectedPosts;
2335 if (posts.Length == 0)
2338 // 選択されたツイートの中に削除可能なものが一つでもあるか
2339 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2342 var ret = MessageBox.Show(
2344 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2345 Properties.Resources.DeleteStripMenuItem_ClickText2,
2346 MessageBoxButtons.OKCancel,
2347 MessageBoxIcon.Question);
2349 if (ret != DialogResult.OK)
2352 var currentListView = this.CurrentListView;
2353 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2355 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2357 Exception? lastException = null;
2358 foreach (var post in posts)
2360 if (!post.CanDeleteBy(this.tw.UserId))
2365 if (post.StatusId is TwitterDirectMessageId dmId)
2367 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2371 if (post.RetweetedByUserId == this.tw.UserId)
2373 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2375 await this.tw.DeleteRetweet(post);
2379 if (post.UserId == this.tw.UserId)
2381 if (post.RetweetedId != null)
2383 // 他人に RT された自分のツイート
2384 // => RT 元の自分のツイートを削除
2385 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2391 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2397 catch (WebApiException ex)
2403 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2406 if (lastException == null)
2407 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2409 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2411 using (ControlTransaction.Update(currentListView))
2413 this.listCache?.PurgeCache();
2414 this.listCache?.UpdateListSize();
2416 currentListView.SelectedIndices.Clear();
2418 var currentTab = this.CurrentTab;
2419 if (currentTab.AllCount != 0)
2422 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2423 selectedIndex = focusedIndex;
2425 selectedIndex = currentTab.AllCount - 1;
2427 currentListView.SelectedIndices.Add(selectedIndex);
2428 currentListView.EnsureVisible(selectedIndex);
2429 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2433 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2435 var tabPage = this.ListTab.TabPages[index];
2436 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2438 if (tabPage.ImageIndex == 0)
2439 tabPage.ImageIndex = -1; // タブアイコン
2443 if (!this.settings.Common.TabIconDisp)
2444 this.ListTab.Refresh();
2448 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2449 => await this.DoStatusDelete();
2451 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2453 using (ControlTransaction.Update(this.CurrentListView))
2455 var tab = this.CurrentTab;
2456 foreach (var statusId in tab.SelectedStatusIds)
2458 this.statuses.SetReadAllTab(statusId, read: true);
2459 var idx = tab.IndexOf(statusId);
2460 this.listCache?.RefreshStyle(idx);
2463 if (this.settings.Common.TabIconDisp)
2465 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2467 if (tab.UnreadCount == 0)
2469 var tabPage = this.ListTab.TabPages[index];
2470 if (tabPage.ImageIndex == 0)
2471 tabPage.ImageIndex = -1; // タブアイコン
2475 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2478 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2480 using (ControlTransaction.Update(this.CurrentListView))
2482 var tab = this.CurrentTab;
2483 foreach (var statusId in tab.SelectedStatusIds)
2485 this.statuses.SetReadAllTab(statusId, read: false);
2486 var idx = tab.IndexOf(statusId);
2487 this.listCache?.RefreshStyle(idx);
2490 if (this.settings.Common.TabIconDisp)
2492 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2494 if (tab.UnreadCount > 0)
2496 var tabPage = this.ListTab.TabPages[index];
2497 if (tabPage.ImageIndex == -1)
2498 tabPage.ImageIndex = 0; // タブアイコン
2502 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2505 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2506 => await this.DoRefresh();
2508 private async Task DoRefresh()
2509 => await this.RefreshTabAsync(this.CurrentTab);
2511 private async Task DoRefreshMore()
2512 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2514 private DialogResult ShowSettingDialog()
2516 using var settingDialog = new AppendSettingDialog();
2517 settingDialog.Icon = this.iconAssets.IconMain;
2518 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2520 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2522 DialogResult result;
2525 result = settingDialog.ShowDialog(this);
2529 return DialogResult.Abort;
2532 if (result == DialogResult.OK)
2534 lock (this.syncObject)
2536 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2543 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2546 var previousUserId = this.settings.Common.UserId;
2547 var oldIconCol = this.Use2ColumnsMode;
2549 if (this.ShowSettingDialog() == DialogResult.OK)
2551 lock (this.syncObject)
2553 this.settings.ApplySettings();
2555 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2556 this.tw.ClearAuthInfo();
2558 var account = this.settings.Common.SelectedAccount;
2559 if (account != null)
2560 this.tw.Initialize(account.GetTwitterCredential(), account.Username, account.UserId);
2562 this.tw.Initialize(new TwitterCredentialNone(), "", 0L);
2564 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2565 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2567 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2571 if (this.settings.Common.TabIconDisp)
2573 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2574 this.ListTab.DrawMode = TabDrawMode.Normal;
2575 this.ListTab.ImageList = this.TabImage;
2579 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2580 this.ListTab.DrawItem += this.ListTab_DrawItem;
2581 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2582 this.ListTab.ImageList = null;
2585 catch (Exception ex)
2587 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2588 ex.Data["IsTerminatePermission"] = false;
2594 if (!this.settings.Common.UnreadManage)
2596 this.ReadedStripMenuItem.Enabled = false;
2597 this.UnreadStripMenuItem.Enabled = false;
2598 if (this.settings.Common.TabIconDisp)
2600 foreach (TabPage myTab in this.ListTab.TabPages)
2602 myTab.ImageIndex = -1;
2608 this.ReadedStripMenuItem.Enabled = true;
2609 this.UnreadStripMenuItem.Enabled = true;
2612 catch (Exception ex)
2614 ex.Data["Instance"] = "ListTab(UnreadManage)";
2615 ex.Data["IsTerminatePermission"] = false;
2620 this.SetTabAlignment();
2622 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2624 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2625 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2626 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2628 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2629 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2630 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2631 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2633 var newTheme = new ThemeManager(this.settings.Local);
2634 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2635 this.tweetDetailsView.Theme = this.themeManager;
2636 if (this.listDrawer != null)
2637 this.listDrawer.Theme = this.themeManager;
2642 if (this.StatusText.Focused)
2643 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2645 this.StatusText.Font = this.themeManager.FontInputFont;
2646 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2648 catch (Exception ex)
2650 MessageBox.Show(ex.Message);
2655 this.InitDetailHtmlFormat();
2657 catch (Exception ex)
2659 ex.Data["Instance"] = "Font";
2660 ex.Data["IsTerminatePermission"] = false;
2666 if (this.settings.Common.TabIconDisp)
2668 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2670 var tabPage = this.ListTab.TabPages[index];
2671 if (tab.UnreadCount == 0)
2672 tabPage.ImageIndex = -1;
2674 tabPage.ImageIndex = 0;
2678 catch (Exception ex)
2680 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2681 ex.Data["IsTerminatePermission"] = false;
2687 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2689 foreach (TabPage tp in this.ListTab.TabPages)
2691 var lst = (DetailsListView)tp.Tag;
2693 using (ControlTransaction.Update(lst))
2695 lst.GridLines = this.settings.Common.ShowGrid;
2697 if (this.Use2ColumnsMode != oldIconCol)
2698 this.ResetColumns(lst);
2702 catch (Exception ex)
2704 ex.Data["Instance"] = "ListView(IconSize)";
2705 ex.Data["IsTerminatePermission"] = false;
2709 this.SetMainWindowTitle();
2710 this.SetNotifyIconText();
2712 this.listCache?.PurgeCache();
2713 this.CurrentListView.Refresh();
2714 this.ListTab.Refresh();
2716 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2717 if (this.settings.Common.HotkeyEnabled)
2719 // グローバルホットキーの登録。設定で変更可能にするかも
2720 var modKey = HookGlobalHotkey.ModKeys.None;
2721 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2722 modKey |= HookGlobalHotkey.ModKeys.Alt;
2723 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2724 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2725 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2726 modKey |= HookGlobalHotkey.ModKeys.Shift;
2727 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2728 modKey |= HookGlobalHotkey.ModKeys.Win;
2730 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2733 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2736 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2744 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2746 this.TopMost = this.settings.Common.AlwaysTop;
2747 this.SaveConfigsAll(false);
2749 if (this.tw.UserId != previousUserId)
2750 await this.DoGetFollowersMenu();
2756 private void SetTabAlignment()
2758 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2759 if (this.ListTab.Alignment == newAlignment) return;
2762 var currentListViewState = this.listViewState[this.CurrentTabName];
2763 currentListViewState.Save(this.ListLockMenuItem.Checked);
2765 this.ListTab.Alignment = newAlignment;
2767 currentListViewState.Restore(forceScroll: true);
2770 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2773 if (this.listDrawer != null)
2775 this.listDrawer.IconSize = iconSz;
2776 this.listDrawer.UpdateItemHeight();
2779 this.listCache?.PurgeCache();
2782 private void ResetColumns(DetailsListView list)
2784 using (ControlTransaction.Update(list))
2785 using (ControlTransaction.Layout(list, false))
2788 list.ColumnClick -= this.MyList_ColumnClick;
2789 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2790 list.ColumnReordered -= this.MyList_ColumnReordered;
2791 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2793 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2794 list.Columns.Clear();
2795 cols.ForEach(col => col.Dispose());
2798 this.InitColumns(list, true);
2800 list.ColumnClick += this.MyList_ColumnClick;
2801 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2802 list.ColumnReordered += this.MyList_ColumnReordered;
2803 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2807 public void AddNewTabForSearch(string searchWord)
2809 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2810 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2812 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2814 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2815 this.ListTab.SelectedIndex = tabIndex;
2820 var tabName = searchWord;
2821 for (var i = 0; i <= 100; i++)
2823 if (this.statuses.ContainsTab(tabName))
2829 var tab = new PublicSearchTabModel(tabName);
2830 this.statuses.AddTab(tab);
2831 this.AddNewTab(tab, startup: false);
2833 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2835 var tabPage = this.CurrentTabPage;
2836 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2837 cmb.Items.Add(searchWord);
2838 cmb.Text = searchWord;
2839 this.SaveConfigsTabs();
2841 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2844 private async Task ShowUserTimeline()
2846 var post = this.CurrentPost;
2847 if (post == null || !this.ExistCurrentPost) return;
2848 await this.AddNewTabForUserTimeline(post.ScreenName);
2851 private async Task ShowRetweeterTimeline()
2853 var retweetedBy = this.CurrentPost?.RetweetedBy;
2854 if (retweetedBy == null || !this.ExistCurrentPost) return;
2855 await this.AddNewTabForUserTimeline(retweetedBy);
2858 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2860 if (e.KeyCode == Keys.Escape)
2862 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2863 this.SaveConfigsTabs();
2864 e.SuppressKeyPress = true;
2868 public async Task AddNewTabForUserTimeline(string user)
2870 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2871 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2873 if (tb.ScreenName == user)
2875 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2876 this.ListTab.SelectedIndex = tabIndex;
2881 var tabName = "user:" + user;
2882 while (this.statuses.ContainsTab(tabName))
2887 var tab = new UserTimelineTabModel(tabName, user);
2888 this.statuses.AddTab(tab);
2889 this.AddNewTab(tab, startup: false);
2891 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2892 this.SaveConfigsTabs();
2894 await this.RefreshTabAsync(tab);
2897 public bool AddNewTab(TabModel tab, bool startup)
2900 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2904 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2906 var tabPage = new TabPage();
2907 var listCustom = new DetailsListView();
2909 var cnt = this.statuses.Tabs.Count;
2911 // ToDo:Create and set controls follow tabtypes
2913 using (ControlTransaction.Update(listCustom))
2914 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2915 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2916 using (ControlTransaction.Layout(this.SplitContainer1, false))
2917 using (ControlTransaction.Layout(this.ListTab, false))
2918 using (ControlTransaction.Layout(this))
2919 using (ControlTransaction.Layout(tabPage, false))
2921 tabPage.Controls.Add(listCustom);
2924 var userTab = tab as UserTimelineTabModel;
2925 var listTab = tab as ListTimelineTabModel;
2926 var searchTab = tab as PublicSearchTabModel;
2928 if (userTab != null || listTab != null)
2930 var label = new Label
2932 Dock = DockStyle.Top,
2937 if (listTab != null)
2939 label.Text = listTab.ListInfo.ToString();
2941 else if (userTab != null)
2943 label.Text = userTab.ScreenName + "'s Timeline";
2945 label.TextAlign = ContentAlignment.MiddleLeft;
2946 using (var tmpComboBox = new ComboBox())
2948 label.Height = tmpComboBox.Height;
2950 tabPage.Controls.Add(label);
2953 else if (searchTab != null)
2955 var pnl = new Panel();
2957 var lbl = new Label();
2958 var cmb = new ComboBox();
2959 var btn = new Button();
2960 var cmbLang = new ComboBox();
2962 using (ControlTransaction.Layout(pnl, false))
2964 pnl.Controls.Add(cmb);
2965 pnl.Controls.Add(cmbLang);
2966 pnl.Controls.Add(btn);
2967 pnl.Controls.Add(lbl);
2968 pnl.Name = "panelSearch";
2970 pnl.Dock = DockStyle.Top;
2971 pnl.Height = cmb.Height;
2972 pnl.Enter += this.SearchControls_Enter;
2973 pnl.Leave += this.SearchControls_Leave;
2976 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2977 cmb.Dock = DockStyle.Fill;
2978 cmb.Name = "comboSearch";
2979 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2980 cmb.ImeMode = ImeMode.NoControl;
2981 cmb.TabStop = false;
2983 cmb.AutoCompleteMode = AutoCompleteMode.None;
2984 cmb.KeyDown += this.SearchComboBox_KeyDown;
2987 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2988 cmbLang.Dock = DockStyle.Right;
2990 cmbLang.Name = "comboLang";
2991 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2992 cmbLang.TabStop = false;
2993 cmbLang.TabIndex = 2;
2994 cmbLang.Items.Add("");
2995 cmbLang.Items.Add("ja");
2996 cmbLang.Items.Add("en");
2997 cmbLang.Items.Add("ar");
2998 cmbLang.Items.Add("da");
2999 cmbLang.Items.Add("nl");
3000 cmbLang.Items.Add("fa");
3001 cmbLang.Items.Add("fi");
3002 cmbLang.Items.Add("fr");
3003 cmbLang.Items.Add("de");
3004 cmbLang.Items.Add("hu");
3005 cmbLang.Items.Add("is");
3006 cmbLang.Items.Add("it");
3007 cmbLang.Items.Add("no");
3008 cmbLang.Items.Add("pl");
3009 cmbLang.Items.Add("pt");
3010 cmbLang.Items.Add("ru");
3011 cmbLang.Items.Add("es");
3012 cmbLang.Items.Add("sv");
3013 cmbLang.Items.Add("th");
3015 lbl.Text = "Search(C-S-f)";
3016 lbl.Name = "label1";
3017 lbl.Dock = DockStyle.Left;
3019 lbl.Height = cmb.Height;
3020 lbl.TextAlign = ContentAlignment.MiddleLeft;
3023 btn.Text = "Search";
3024 btn.Name = "buttonSearch";
3025 btn.UseVisualStyleBackColor = true;
3026 btn.Dock = DockStyle.Right;
3027 btn.TabStop = false;
3029 btn.Click += this.SearchButton_Click;
3031 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3033 cmb.Items.Add(searchTab.SearchWords);
3034 cmb.Text = searchTab.SearchWords;
3037 cmbLang.Text = searchTab.SearchLang;
3039 tabPage.Controls.Add(pnl);
3043 tabPage.Tag = listCustom;
3044 this.ListTab.Controls.Add(tabPage);
3046 tabPage.Location = new Point(4, 4);
3047 tabPage.Name = "CTab" + cnt;
3048 tabPage.Size = new Size(380, 260);
3049 tabPage.TabIndex = 2 + cnt;
3050 tabPage.Text = tab.TabName;
3051 tabPage.UseVisualStyleBackColor = true;
3052 tabPage.AccessibleRole = AccessibleRole.PageTab;
3054 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3055 listCustom.TabIndex = 1;
3056 listCustom.AllowColumnReorder = true;
3057 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3058 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3059 listCustom.Dock = DockStyle.Fill;
3060 listCustom.FullRowSelect = true;
3061 listCustom.HideSelection = false;
3062 listCustom.Location = new Point(0, 0);
3063 listCustom.Margin = new Padding(0);
3064 listCustom.Name = "CList" + Environment.TickCount;
3065 listCustom.ShowItemToolTips = true;
3066 listCustom.Size = new Size(380, 260);
3067 listCustom.UseCompatibleStateImageBehavior = false;
3068 listCustom.View = View.Details;
3069 listCustom.OwnerDraw = true;
3070 listCustom.VirtualMode = true;
3072 listCustom.GridLines = this.settings.Common.ShowGrid;
3073 listCustom.AllowDrop = true;
3075 this.InitColumns(listCustom, startup);
3077 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3078 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3079 listCustom.ColumnClick += this.MyList_ColumnClick;
3080 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3081 listCustom.DragDrop += this.TweenMain_DragDrop;
3082 listCustom.DragEnter += this.TweenMain_DragEnter;
3083 listCustom.DragOver += this.TweenMain_DragOver;
3084 listCustom.MouseClick += this.MyList_MouseClick;
3085 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3086 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3087 listCustom.HScrolled += this.MyList_HScrolled;
3090 var state = new TimelineListViewState(listCustom, tab);
3091 this.listViewState[tab.TabName] = state;
3096 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3098 var tabInfo = this.statuses.GetTabByName(tabName);
3099 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3104 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3105 var result = MessageBox.Show(
3107 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3108 MessageBoxButtons.OKCancel,
3109 MessageBoxIcon.Question,
3110 MessageBoxDefaultButton.Button2);
3111 if (result == DialogResult.Cancel)
3117 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3121 var tabPage = this.ListTab.TabPages[tabIndex];
3123 this.SetListProperty(); // 他のタブに列幅等を反映
3125 this.listViewState.Remove(tabName);
3128 var listCustom = (DetailsListView)tabPage.Tag;
3131 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3132 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3133 using (ControlTransaction.Layout(this.SplitContainer1, false))
3134 using (ControlTransaction.Layout(this.ListTab, false))
3135 using (ControlTransaction.Layout(this))
3136 using (ControlTransaction.Layout(tabPage, false))
3138 if (this.CurrentTabName == tabName)
3140 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3141 this.beforeSelectedTab = null;
3143 this.ListTab.Controls.Remove(tabPage);
3146 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3148 using var label = tabPage.Controls["labelUser"];
3149 tabPage.Controls.Remove(label);
3151 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3153 using var pnl = tabPage.Controls["panelSearch"];
3155 pnl.Enter -= this.SearchControls_Enter;
3156 pnl.Leave -= this.SearchControls_Leave;
3157 tabPage.Controls.Remove(pnl);
3159 foreach (Control ctrl in pnl.Controls)
3161 if (ctrl.Name == "buttonSearch")
3163 ctrl.Click -= this.SearchButton_Click;
3165 else if (ctrl.Name == "comboSearch")
3167 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3169 pnl.Controls.Remove(ctrl);
3174 tabPage.Controls.Remove(listCustom);
3176 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3177 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3178 listCustom.ColumnClick -= this.MyList_ColumnClick;
3179 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3180 listCustom.DragDrop -= this.TweenMain_DragDrop;
3181 listCustom.DragEnter -= this.TweenMain_DragEnter;
3182 listCustom.DragOver -= this.TweenMain_DragOver;
3183 listCustom.MouseClick -= this.MyList_MouseClick;
3184 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3185 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3186 listCustom.HScrolled -= this.MyList_HScrolled;
3188 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3189 listCustom.Columns.Clear();
3190 cols.ForEach(col => col.Dispose());
3193 listCustom.ContextMenuStrip = null;
3194 listCustom.ColumnHeaderContextMenuStrip = null;
3195 listCustom.Font = null;
3197 listCustom.SmallImageList = null;
3198 listCustom.ListViewItemSorter = null;
3201 this.listCache?.PurgeCache();
3205 listCustom.Dispose();
3206 this.statuses.RemoveTab(tabName);
3211 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3213 this.listCache?.PurgeCache();
3214 this.beforeSelectedTab = e.TabPage;
3217 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3221 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3224 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3225 if (!dragEnableRectangle.Contains(e.Location))
3227 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3228 tn = this.CurrentTabName;
3231 if (MyCommon.IsNullOrEmpty(tn)) return;
3233 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3236 var tabPage = this.ListTab.TabPages[tabIndex];
3237 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3242 this.tabDrag = false;
3245 var cpos = new Point(e.X, e.Y);
3246 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3248 var rect = this.ListTab.GetTabRect(index);
3249 if (rect.Contains(cpos))
3251 this.rclickTabName = tab.TabName;
3257 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3259 this.SetMainWindowTitle();
3260 this.SetStatusLabelUrl();
3261 this.SetApiStatusLabel();
3262 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3263 this.Tag = this.ListTab.Tag;
3264 this.TabMenuControl(this.CurrentTabName);
3265 this.PushSelectPostChain();
3266 this.DispSelectedPost();
3269 private void SetListProperty()
3271 if (!this.isColumnChanged) return;
3273 var currentListView = this.CurrentListView;
3275 var dispOrder = new int[currentListView.Columns.Count];
3276 for (var i = 0; i < currentListView.Columns.Count; i++)
3278 for (var j = 0; j < currentListView.Columns.Count; j++)
3280 if (currentListView.Columns[j].DisplayIndex == i)
3289 foreach (TabPage tb in this.ListTab.TabPages)
3291 if (tb.Text == this.CurrentTabName)
3294 if (tb.Tag != null && tb.Controls.Count > 0)
3296 var lst = (DetailsListView)tb.Tag;
3297 for (var i = 0; i < lst.Columns.Count; i++)
3299 lst.Columns[dispOrder[i]].DisplayIndex = i;
3300 lst.Columns[i].Width = currentListView.Columns[i].Width;
3305 this.isColumnChanged = false;
3308 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3310 if (e.KeyChar == '@')
3312 if (!this.settings.Common.UseAtIdSupplement) return;
3314 var cnt = this.AtIdSupl.ItemCount;
3315 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3316 if (cnt != this.AtIdSupl.ItemCount)
3317 this.MarkSettingAtIdModified();
3320 else if (e.KeyChar == '#')
3322 if (!this.settings.Common.UseHashSupplement) return;
3323 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3328 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3329 => this.ShowSuplDialog(owner, dialog, 0, "");
3331 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3332 => this.ShowSuplDialog(owner, dialog, offset, "");
3334 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3336 dialog.StartsWith = startswith;
3343 dialog.ShowDialog();
3345 this.TopMost = this.settings.Common.AlwaysTop;
3346 var selStart = owner.SelectionStart;
3349 if (dialog.DialogResult == DialogResult.OK)
3351 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3355 fHalf = owner.Text.Substring(0, selStart - offset);
3357 if (selStart < owner.Text.Length)
3359 eHalf = owner.Text.Substring(selStart);
3361 owner.Text = fHalf + dialog.InputText + eHalf;
3362 owner.SelectionStart = selStart + dialog.InputText.Length;
3369 fHalf = owner.Text.Substring(0, selStart);
3371 if (selStart < owner.Text.Length)
3373 eHalf = owner.Text.Substring(selStart);
3375 owner.Text = fHalf + eHalf;
3378 owner.SelectionStart = selStart;
3384 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3387 if (!e.Alt && !e.Control && !e.Shift)
3389 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3391 var isSpace = false;
3392 foreach (var c in this.StatusText.Text)
3394 if (c == ' ' || c == ' ')
3407 this.StatusText.Text = "";
3408 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3412 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3415 private void StatusText_TextChanged(object sender, EventArgs e)
3418 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3419 this.lblLen.Text = pLen.ToString();
3422 this.StatusText.ForeColor = Color.Red;
3426 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3429 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3431 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3433 this.inReplyTo = null;
3438 /// メンション以外の文字列が含まれていないテキストであるか判定します
3440 internal static bool TextContainsOnlyMentions(string text)
3442 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3445 foreach (var mention in mentions)
3447 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3449 if (!string.IsNullOrWhiteSpace(textPart))
3452 startIndex = mention.Indices[1];
3455 var textPartLast = text.Substring(startIndex);
3457 if (!string.IsNullOrWhiteSpace(textPartLast))
3464 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3466 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3468 var autoPopulatedUserIdList = new List<long>();
3470 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3471 if (replyToPost != null)
3473 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3475 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3476 autoPopulatedUserIdList.Add(replyToPost.UserId);
3478 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3480 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3482 statusText = statusText.Substring(screenName.Length + 2);
3483 autoPopulatedUserIdList.Add(userId);
3489 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3495 /// attachment_url に指定可能な URL が含まれていれば除去
3497 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3499 attachmentUrl = null;
3501 // attachment_url は media_id と同時に使用できない
3502 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3505 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3509 attachmentUrl = match.Value;
3512 statusText = statusText.Substring(0, match.Index);
3514 // テキストと URL の間にスペースが含まれていれば除去
3515 return statusText.TrimEnd(' ');
3518 private string FormatStatusTextExtended(string statusText)
3519 => this.FormatStatusTextExtended(statusText, out _, out _);
3522 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3524 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3526 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3528 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3530 return this.FormatStatusText(statusText);
3533 internal string FormatStatusText(string statusText)
3534 => this.FormatStatusText(statusText, Control.ModifierKeys);
3537 /// ツイート投稿前のフッター付与などの前処理を行います
3539 internal string FormatStatusText(string statusText, Keys modifierKeys)
3541 statusText = statusText.Replace("\r\n", "\n");
3543 if (this.SeparateUrlAndFullwidthCharacter)
3546 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3549 if (this.settings.Common.WideSpaceConvert)
3551 // 文中の全角スペースを半角スペース1個にする
3552 statusText = statusText.Replace(" ", " ");
3555 // DM の場合はこれ以降の処理を行わない
3556 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3560 if (this.settings.Common.PostShiftEnter)
3562 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3566 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3567 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3569 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3572 if (statusText.Contains("RT @"))
3573 disableFooter = true;
3575 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3576 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3578 var mentionSelf = $"@{this.tw.Username} ";
3579 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3581 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3582 statusText = statusText.Substring(mentionSelf.Length);
3589 var hashtag = this.HashMgr.UseHash;
3590 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3592 if (this.HashMgr.IsHead)
3593 header = this.HashMgr.UseHash + " ";
3595 footer = " " + this.HashMgr.UseHash;
3600 if (this.settings.Local.UseRecommendStatus)
3603 footer += this.recommendedStatusFooter;
3605 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3607 // テキストボックスに入力されている文字列を使用する
3608 footer += " " + this.settings.Local.StatusText.Trim();
3612 statusText = header + statusText + footer;
3614 if (this.preventSmsCommand)
3616 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3617 // 参照: https://support.twitter.com/articles/14020
3619 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3620 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3622 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3623 statusText = '\u200b' + statusText;
3631 /// 投稿欄に表示する入力可能な文字数を計算します
3633 private int GetRestStatusCount(string statusText)
3635 var remainCount = this.tw.GetTextLengthRemain(statusText);
3637 var uploadService = this.GetSelectedImageService();
3638 if (uploadService != null)
3640 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3641 remainCount -= uploadService.GetReservedTextLength(1);
3647 private IMediaUploadService? GetSelectedImageService()
3648 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3651 /// 全てのタブの振り分けルールを反映し直します
3653 private void ApplyPostFilters()
3655 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3657 this.statuses.FilterAll();
3659 var listView = this.CurrentListView;
3660 using (ControlTransaction.Update(listView))
3662 this.listCache?.PurgeCache();
3663 this.listCache?.UpdateListSize();
3666 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3668 var tabPage = this.ListTab.TabPages[index];
3670 if (this.settings.Common.TabIconDisp)
3672 if (tab.UnreadCount > 0)
3673 tabPage.ImageIndex = 0;
3675 tabPage.ImageIndex = -1;
3679 if (!this.settings.Common.TabIconDisp)
3680 this.ListTab.Refresh();
3682 this.SetMainWindowTitle();
3683 this.SetStatusLabelUrl();
3687 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3688 => e.DrawDefault = true;
3690 private void MyList_HScrolled(object sender, EventArgs e)
3691 => ((DetailsListView)sender).Refresh();
3693 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3695 base.ScaleControl(factor, specified);
3697 ScaleChildControl(this.TabImage, factor);
3699 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3700 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3702 foreach (var listview in listviews)
3704 ScaleChildControl(listview, factor);
3708 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3710 var tab = this.CurrentTab;
3712 if (tab.AllCount == 0)
3714 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3718 var selectedIndex = tab.SelectedIndex;
3723 case SEARCHTYPE.NextSearch: // 次を検索
3724 if (selectedIndex != -1)
3725 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3729 case SEARCHTYPE.PrevSearch: // 前を検索
3730 if (selectedIndex != -1)
3731 startIndex = Math.Max(selectedIndex - 1, 0);
3733 startIndex = tab.AllCount - 1;
3735 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3737 if (selectedIndex != -1)
3738 startIndex = selectedIndex;
3744 Func<string, bool> stringComparer;
3747 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3749 catch (ArgumentException)
3751 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3755 var reverse = searchType == SEARCHTYPE.PrevSearch;
3756 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3757 .DefaultIfEmpty(-1).First();
3759 if (foundIndex == -1)
3761 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3765 var listView = this.CurrentListView;
3766 this.SelectListItem(listView, foundIndex);
3767 listView.EnsureVisible(foundIndex);
3770 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3771 => this.ShowSearchDialog(); // 検索メニュー
3773 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3775 var previousSearch = this.SearchDialog.ResultOptions;
3776 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3778 this.SearchDialog.Reset();
3779 this.ShowSearchDialog();
3785 previousSearch.Query,
3786 previousSearch.CaseSensitive,
3787 previousSearch.UseRegex,
3788 SEARCHTYPE.NextSearch);
3791 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3793 var previousSearch = this.SearchDialog.ResultOptions;
3794 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3796 this.SearchDialog.Reset();
3797 this.ShowSearchDialog();
3803 previousSearch.Query,
3804 previousSearch.CaseSensitive,
3805 previousSearch.UseRegex,
3806 SEARCHTYPE.PrevSearch);
3810 /// 検索ダイアログを表示し、検索を実行します
3812 private void ShowSearchDialog()
3814 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3816 this.TopMost = this.settings.Common.AlwaysTop;
3819 this.TopMost = this.settings.Common.AlwaysTop;
3821 var searchOptions = this.SearchDialog.ResultOptions!;
3822 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3824 if (searchOptions.NewTab)
3826 var tabName = Properties.Resources.SearchResults_TabName;
3830 tabName = this.statuses.MakeTabName(tabName);
3832 catch (TabException ex)
3834 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3837 var resultTab = new LocalSearchTabModel(tabName);
3838 this.AddNewTab(resultTab, startup: false);
3839 this.statuses.AddTab(resultTab);
3841 var targetTab = this.CurrentTab;
3843 Func<string, bool> stringComparer;
3846 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3848 catch (ArgumentException)
3850 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3854 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3855 if (foundIndices.Length == 0)
3857 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3861 var foundPosts = foundIndices.Select(x => targetTab[x]);
3862 foreach (var post in foundPosts)
3864 resultTab.AddPostQueue(post);
3867 this.statuses.DistributePosts();
3868 this.RefreshTimeline();
3870 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3871 this.ListTab.SelectedIndex = tabIndex;
3876 searchOptions.Query,
3877 searchOptions.CaseSensitive,
3878 searchOptions.UseRegex,
3879 SEARCHTYPE.DialogSearch);
3882 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3884 this.AddNewTabForSearch(searchOptions.Query);
3888 /// <summary>発言検索に使用するメソッドを生成します</summary>
3889 /// <exception cref="ArgumentException">
3890 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3892 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3896 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3897 var regex = new Regex(query, regexOption);
3899 return x => regex.IsMatch(x);
3903 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3905 return x => x.IndexOf(query, comparisonType) != -1;
3909 private void AboutMenuItem_Click(object sender, EventArgs e)
3911 using (var about = new TweenAboutBox())
3913 about.ShowDialog(this);
3915 this.TopMost = this.settings.Common.AlwaysTop;
3918 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3920 var bgnIdx = this.statuses.SelectedTabIndex;
3922 if (this.ImageSelector.Enabled)
3925 TabModel? foundTab = null;
3929 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3931 var unreadIndex = tab.NextUnreadIndex;
3932 if (unreadIndex != -1)
3934 this.ListTab.SelectedIndex = index;
3936 foundIndex = unreadIndex;
3941 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3942 if (foundTab == null && bgnIdx > 0)
3944 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3946 var unreadIndex = tab.NextUnreadIndex;
3947 if (unreadIndex != -1)
3949 this.ListTab.SelectedIndex = index;
3951 foundIndex = unreadIndex;
3957 DetailsListView lst;
3959 if (foundTab == null)
3961 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3962 this.ListTab.SelectedIndex = 0;
3963 var tabPage = this.ListTab.TabPages[0];
3964 var tab = this.statuses.Tabs[0];
3966 if (tab.AllCount == 0)
3969 if (this.statuses.SortOrder == SortOrder.Ascending)
3970 foundIndex = tab.AllCount - 1;
3974 lst = (DetailsListView)tabPage.Tag;
3978 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3979 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3982 this.SelectListItem(lst, foundIndex);
3984 if (this.statuses.SortMode == ComparerMode.Id)
3986 var rowHeight = lst.SmallImageList.ImageSize.Height;
3987 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3988 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3994 lst.EnsureVisible(foundIndex);
3999 lst.EnsureVisible(foundIndex);
4005 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4007 var tab = this.CurrentTab;
4008 var post = this.CurrentPost;
4009 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4010 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4013 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4014 => await this.CheckNewVersion(false);
4016 private void RunTweenUp()
4018 var pinfo = new ProcessStartInfo
4020 UseShellExecute = true,
4021 WorkingDirectory = this.settings.SettingsPath,
4022 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4023 Arguments = "\"" + Application.StartupPath + "\"",
4028 Process.Start(pinfo);
4032 MessageBox.Show("Failed to execute TweenUp3.exe.");
4036 public readonly record struct VersionInfo(
4043 /// OpenTween の最新バージョンの情報を取得します
4045 public async Task<VersionInfo> GetVersionInfoAsync()
4047 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4048 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4050 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4051 .ConfigureAwait(false);
4053 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4054 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4056 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4057 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4059 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4061 return new VersionInfo
4063 Version = Version.Parse(msgHeader[0]),
4064 DownloadUri = new Uri(msgHeader[1]),
4065 ReleaseNote = msgBody,
4069 private async Task CheckNewVersion(bool startup = false)
4071 if (ApplicationSettings.VersionInfoUrl == null)
4072 return; // 更新チェック無効化
4076 var versionInfo = await this.GetVersionInfoAsync();
4078 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4083 var msgtext = string.Format(
4084 Properties.Resources.CheckNewVersionText7,
4085 MyCommon.GetReadableVersion(),
4086 MyCommon.GetReadableVersion(versionInfo.Version));
4087 msgtext = MyCommon.ReplaceAppName(msgtext);
4091 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4092 MessageBoxButtons.OK,
4093 MessageBoxIcon.Information);
4098 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4101 using var dialog = new UpdateDialog();
4103 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4104 MyCommon.GetReadableVersion(versionInfo.Version));
4105 dialog.DetailsText = versionInfo.ReleaseNote;
4107 if (dialog.ShowDialog(this) == DialogResult.Yes)
4109 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4111 else if (dialog.SkipButtonPressed)
4113 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4114 this.MarkSettingCommonModified();
4119 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4123 Properties.Resources.CheckNewVersionText10,
4124 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4125 MessageBoxButtons.OK,
4126 MessageBoxIcon.Exclamation,
4127 MessageBoxDefaultButton.Button2);
4132 private void UpdateSelectedPost()
4134 // 件数関連の場合、タイトル即時書き換え
4135 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4136 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4137 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4138 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4140 this.SetMainWindowTitle();
4142 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4143 this.SetStatusLabelUrl();
4145 if (this.settings.Common.TabIconDisp)
4147 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4149 if (tab.UnreadCount == 0)
4151 var tabPage = this.ListTab.TabPages[index];
4152 if (tabPage.ImageIndex == 0)
4153 tabPage.ImageIndex = -1;
4159 this.ListTab.Refresh();
4162 this.DispSelectedPost();
4165 public string CreateDetailHtml(string orgdata)
4166 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4168 private void DispSelectedPost()
4169 => this.DispSelectedPost(false);
4171 private PostClass displayPost = new();
4174 /// サムネイル表示に使用する CancellationToken の生成元
4176 private CancellationTokenSource? thumbnailTokenSource = null;
4178 private void DispSelectedPost(bool forceupdate)
4180 var currentPost = this.CurrentPost;
4181 if (currentPost == null)
4184 var oldDisplayPost = this.displayPost;
4185 this.displayPost = currentPost;
4187 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4190 var loadTasks = new TaskCollection();
4191 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4193 if (this.settings.Common.PreviewEnable)
4195 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4196 oldTokenSource?.Cancel();
4198 var token = this.thumbnailTokenSource!.Token;
4199 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4203 this.SplitContainer3.Panel2Collapsed = true;
4206 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4208 .IgnoreException(x => x is OperationCanceledException)
4212 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4214 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4216 var timeout = Task.Delay(100);
4217 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4219 token.ThrowIfCancellationRequested();
4221 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4222 this.SplitContainer3.Panel2Collapsed = true;
4226 token.ThrowIfCancellationRequested();
4228 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4231 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4232 => await this.OpenApplicationWebsite();
4234 private async Task OpenApplicationWebsite()
4235 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4237 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4238 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4240 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4242 var tab = this.CurrentTab;
4243 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4245 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4246 if (pnl.Controls["comboSearch"].Focused ||
4247 pnl.Controls["comboLang"].Focused ||
4248 pnl.Controls["buttonSearch"].Focused) return;
4251 if (e.Control || e.Shift || e.Alt)
4254 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4257 e.SuppressKeyPress = true;
4260 if (asyncTask != null)
4264 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4266 private void InitializeShortcuts()
4268 this.shortcutCommands = new[]
4270 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4271 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4272 .FocusedOn(FocusedControl.ListTab)
4273 .Do(() => SendKeys.Send("{DOWN}")),
4275 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4276 .FocusedOn(FocusedControl.ListTab)
4277 .Do(() => SendKeys.Send("{UP}")),
4279 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4280 .FocusedOn(FocusedControl.ListTab)
4281 .Do(() => SendKeys.Send("{PGDN}")),
4283 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4284 .FocusedOn(FocusedControl.ListTab)
4285 .Do(() => SendKeys.Send("{PGUP}")),
4287 ShortcutCommand.Create(Keys.F1)
4288 .Do(() => this.OpenApplicationWebsite()),
4290 ShortcutCommand.Create(Keys.F3)
4291 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4293 ShortcutCommand.Create(Keys.F5)
4294 .Do(() => this.DoRefresh()),
4296 ShortcutCommand.Create(Keys.F6)
4297 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4299 ShortcutCommand.Create(Keys.F7)
4300 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4302 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4303 .NotFocusedOn(FocusedControl.StatusText)
4306 this.CurrentTab.ClearAnchor();
4307 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4310 ShortcutCommand.Create(Keys.G)
4311 .NotFocusedOn(FocusedControl.StatusText)
4314 this.CurrentTab.ClearAnchor();
4315 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4318 ShortcutCommand.Create(Keys.Right, Keys.N)
4319 .FocusedOn(FocusedControl.ListTab)
4320 .Do(() => this.GoRelPost(forward: true)),
4322 ShortcutCommand.Create(Keys.Left, Keys.P)
4323 .FocusedOn(FocusedControl.ListTab)
4324 .Do(() => this.GoRelPost(forward: false)),
4326 ShortcutCommand.Create(Keys.OemPeriod)
4327 .FocusedOn(FocusedControl.ListTab)
4328 .Do(() => this.GoAnchor()),
4330 ShortcutCommand.Create(Keys.I)
4331 .FocusedOn(FocusedControl.ListTab)
4332 .OnlyWhen(() => this.StatusText.Enabled)
4333 .Do(() => this.StatusText.Focus()),
4335 ShortcutCommand.Create(Keys.Enter)
4336 .FocusedOn(FocusedControl.ListTab)
4337 .Do(() => this.ListItemDoubleClickAction()),
4339 ShortcutCommand.Create(Keys.R)
4340 .FocusedOn(FocusedControl.ListTab)
4341 .Do(() => this.DoRefresh()),
4343 ShortcutCommand.Create(Keys.L)
4344 .FocusedOn(FocusedControl.ListTab)
4347 this.CurrentTab.ClearAnchor();
4348 this.GoPost(forward: true);
4351 ShortcutCommand.Create(Keys.H)
4352 .FocusedOn(FocusedControl.ListTab)
4355 this.CurrentTab.ClearAnchor();
4356 this.GoPost(forward: false);
4359 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4360 .FocusedOn(FocusedControl.ListTab)
4363 this.CurrentTab.ClearAnchor();
4367 ShortcutCommand.Create(Keys.S)
4368 .FocusedOn(FocusedControl.ListTab)
4371 this.CurrentTab.ClearAnchor();
4372 this.GoNextTab(forward: true);
4375 ShortcutCommand.Create(Keys.A)
4376 .FocusedOn(FocusedControl.ListTab)
4379 this.CurrentTab.ClearAnchor();
4380 this.GoNextTab(forward: false);
4383 // ] in_reply_to参照元へ戻る
4384 ShortcutCommand.Create(Keys.Oem4)
4385 .FocusedOn(FocusedControl.ListTab)
4388 this.CurrentTab.ClearAnchor();
4389 return this.GoInReplyToPostTree();
4392 // [ in_reply_toへジャンプ
4393 ShortcutCommand.Create(Keys.Oem6)
4394 .FocusedOn(FocusedControl.ListTab)
4397 this.CurrentTab.ClearAnchor();
4398 this.GoBackInReplyToPostTree();
4401 ShortcutCommand.Create(Keys.Escape)
4402 .FocusedOn(FocusedControl.ListTab)
4405 this.CurrentTab.ClearAnchor();
4406 var tab = this.CurrentTab;
4407 var tabtype = tab.TabType;
4408 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4410 this.RemoveSpecifiedTab(tab.TabName, false);
4411 this.SaveConfigsTabs();
4415 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4416 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4417 .FocusedOn(FocusedControl.ListTab)
4418 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4420 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4421 ShortcutCommand.Create(Keys.Up, Keys.Down)
4422 .FocusedOn(FocusedControl.PostBrowser)
4425 ShortcutCommand.Create(Keys.Control | Keys.R)
4426 .Do(() => this.MakeReplyText()),
4428 ShortcutCommand.Create(Keys.Control | Keys.D)
4429 .Do(() => this.DoStatusDelete()),
4431 ShortcutCommand.Create(Keys.Control | Keys.M)
4432 .Do(() => this.MakeDirectMessageText()),
4434 ShortcutCommand.Create(Keys.Control | Keys.S)
4435 .Do(() => this.FavoriteChange(favAdd: true)),
4437 ShortcutCommand.Create(Keys.Control | Keys.I)
4438 .Do(() => this.DoRepliedStatusOpen()),
4440 ShortcutCommand.Create(Keys.Control | Keys.Q)
4441 .Do(() => this.DoQuoteOfficial()),
4443 ShortcutCommand.Create(Keys.Control | Keys.B)
4444 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4446 ShortcutCommand.Create(Keys.Control | Keys.T)
4447 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4449 ShortcutCommand.Create(Keys.Control | Keys.L)
4450 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4452 ShortcutCommand.Create(Keys.Control | Keys.Y)
4453 .NotFocusedOn(FocusedControl.PostBrowser)
4454 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4456 ShortcutCommand.Create(Keys.Control | Keys.F)
4457 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4459 ShortcutCommand.Create(Keys.Control | Keys.U)
4460 .Do(() => this.ShowUserTimeline()),
4462 ShortcutCommand.Create(Keys.Control | Keys.H)
4463 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4465 ShortcutCommand.Create(Keys.Control | Keys.O)
4466 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4468 ShortcutCommand.Create(Keys.Control | Keys.E)
4469 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4471 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4472 .FocusedOn(FocusedControl.ListTab)
4473 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4475 ShortcutCommand.Create(Keys.Control | Keys.N)
4476 .FocusedOn(FocusedControl.ListTab)
4477 .Do(() => this.GoNextTab(forward: true)),
4479 ShortcutCommand.Create(Keys.Control | Keys.P)
4480 .FocusedOn(FocusedControl.ListTab)
4481 .Do(() => this.GoNextTab(forward: false)),
4483 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4484 .FocusedOn(FocusedControl.ListTab)
4485 .Do(() => this.CopyStot()),
4487 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4488 ShortcutCommand.Create(Keys.Control | Keys.D1)
4489 .FocusedOn(FocusedControl.ListTab)
4490 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4491 .Do(() => this.ListTab.SelectedIndex = 0),
4493 ShortcutCommand.Create(Keys.Control | Keys.D2)
4494 .FocusedOn(FocusedControl.ListTab)
4495 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4496 .Do(() => this.ListTab.SelectedIndex = 1),
4498 ShortcutCommand.Create(Keys.Control | Keys.D3)
4499 .FocusedOn(FocusedControl.ListTab)
4500 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4501 .Do(() => this.ListTab.SelectedIndex = 2),
4503 ShortcutCommand.Create(Keys.Control | Keys.D4)
4504 .FocusedOn(FocusedControl.ListTab)
4505 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4506 .Do(() => this.ListTab.SelectedIndex = 3),
4508 ShortcutCommand.Create(Keys.Control | Keys.D5)
4509 .FocusedOn(FocusedControl.ListTab)
4510 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4511 .Do(() => this.ListTab.SelectedIndex = 4),
4513 ShortcutCommand.Create(Keys.Control | Keys.D6)
4514 .FocusedOn(FocusedControl.ListTab)
4515 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4516 .Do(() => this.ListTab.SelectedIndex = 5),
4518 ShortcutCommand.Create(Keys.Control | Keys.D7)
4519 .FocusedOn(FocusedControl.ListTab)
4520 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4521 .Do(() => this.ListTab.SelectedIndex = 6),
4523 ShortcutCommand.Create(Keys.Control | Keys.D8)
4524 .FocusedOn(FocusedControl.ListTab)
4525 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4526 .Do(() => this.ListTab.SelectedIndex = 7),
4528 ShortcutCommand.Create(Keys.Control | Keys.D9)
4529 .FocusedOn(FocusedControl.ListTab)
4530 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4532 ShortcutCommand.Create(Keys.Control | Keys.A)
4533 .FocusedOn(FocusedControl.StatusText)
4534 .Do(() => this.StatusText.SelectAll()),
4536 ShortcutCommand.Create(Keys.Control | Keys.V)
4537 .FocusedOn(FocusedControl.StatusText)
4538 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4540 ShortcutCommand.Create(Keys.Control | Keys.Up)
4541 .FocusedOn(FocusedControl.StatusText)
4542 .Do(() => this.StatusTextHistoryBack()),
4544 ShortcutCommand.Create(Keys.Control | Keys.Down)
4545 .FocusedOn(FocusedControl.StatusText)
4546 .Do(() => this.StatusTextHistoryForward()),
4548 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4549 .FocusedOn(FocusedControl.StatusText)
4552 if (this.ListTab.SelectedIndex == 0)
4554 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4558 this.ListTab.SelectedIndex -= 1;
4560 this.StatusText.Focus();
4563 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4564 .FocusedOn(FocusedControl.StatusText)
4567 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4569 this.ListTab.SelectedIndex = 0;
4573 this.ListTab.SelectedIndex += 1;
4575 this.StatusText.Focus();
4578 ShortcutCommand.Create(Keys.Control | Keys.Y)
4579 .FocusedOn(FocusedControl.PostBrowser)
4582 var multiline = !this.settings.Local.StatusMultiline;
4583 this.settings.Local.StatusMultiline = multiline;
4584 this.MultiLineMenuItem.Checked = multiline;
4585 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4588 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4589 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4591 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4592 .Do(() => this.DoRefreshMore()),
4594 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4595 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4597 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4598 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4600 ShortcutCommand.Create(Keys.Shift | Keys.R)
4601 .NotFocusedOn(FocusedControl.StatusText)
4602 .Do(() => this.DoRefreshMore()),
4604 ShortcutCommand.Create(Keys.Shift | Keys.H)
4605 .FocusedOn(FocusedControl.ListTab)
4606 .Do(() => this.GoTopEnd(goTop: true)),
4608 ShortcutCommand.Create(Keys.Shift | Keys.L)
4609 .FocusedOn(FocusedControl.ListTab)
4610 .Do(() => this.GoTopEnd(goTop: false)),
4612 ShortcutCommand.Create(Keys.Shift | Keys.M)
4613 .FocusedOn(FocusedControl.ListTab)
4614 .Do(() => this.GoMiddle()),
4616 ShortcutCommand.Create(Keys.Shift | Keys.G)
4617 .FocusedOn(FocusedControl.ListTab)
4618 .Do(() => this.GoLast()),
4620 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4621 .FocusedOn(FocusedControl.ListTab)
4622 .Do(() => this.MoveMiddle()),
4624 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4625 .FocusedOn(FocusedControl.ListTab)
4626 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4628 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4629 .FocusedOn(FocusedControl.ListTab)
4630 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4632 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4633 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4634 .FocusedOn(FocusedControl.ListTab)
4635 .Do(() => this.GoFav(forward: true)),
4637 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4638 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4639 .FocusedOn(FocusedControl.ListTab)
4640 .Do(() => this.GoFav(forward: false)),
4642 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4643 .FocusedOn(FocusedControl.ListTab)
4644 .Do(() => this.GoBackSelectPostChain()),
4646 ShortcutCommand.Create(Keys.Alt | Keys.R)
4647 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4649 ShortcutCommand.Create(Keys.Alt | Keys.P)
4650 .OnlyWhen(() => this.CurrentPost != null)
4651 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4653 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4654 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4656 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4657 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4659 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4660 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4662 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4663 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4665 // 別タブの同じ書き込みへ(ALT+←/→)
4666 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4667 .FocusedOn(FocusedControl.ListTab)
4668 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4670 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4671 .FocusedOn(FocusedControl.ListTab)
4672 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4674 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4675 .Do(() => this.MakeReplyText(atAll: true)),
4677 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4678 .Do(() => this.CopyIdUri()),
4680 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4681 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4682 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4684 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4685 .Do(() => this.DoQuoteOfficial()),
4687 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4688 .Do(() => this.FavoriteChange(favAdd: false)),
4690 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4691 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4693 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4694 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4696 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4697 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4699 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4700 .Do(() => this.DoMoveToRTHome()),
4702 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4703 .FocusedOn(FocusedControl.StatusText)
4706 var tab = this.CurrentTab;
4707 var selectedIndex = tab.SelectedIndex;
4708 if (selectedIndex != -1 && selectedIndex > 0)
4710 var listView = this.CurrentListView;
4711 var idx = selectedIndex - 1;
4712 this.SelectListItem(listView, idx);
4713 listView.EnsureVisible(idx);
4717 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4718 .FocusedOn(FocusedControl.StatusText)
4721 var tab = this.CurrentTab;
4722 var selectedIndex = tab.SelectedIndex;
4723 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4725 var listView = this.CurrentListView;
4726 var idx = selectedIndex + 1;
4727 this.SelectListItem(listView, idx);
4728 listView.EnsureVisible(idx);
4732 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4733 .FocusedOn(FocusedControl.StatusText)
4736 if (this.StatusText.SelectionStart > 0)
4738 var endidx = this.StatusText.SelectionStart - 1;
4740 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4742 var c = this.StatusText.Text[i];
4743 if (char.IsLetterOrDigit(c) || c == '_')
4749 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4750 var cnt = this.AtIdSupl.ItemCount;
4751 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4752 if (this.AtIdSupl.ItemCount != cnt)
4753 this.MarkSettingAtIdModified();
4757 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4758 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4768 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4769 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4770 .FocusedOn(FocusedControl.ListTab)
4771 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4773 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4774 .FocusedOn(FocusedControl.ListTab)
4775 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4777 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4778 .FocusedOn(FocusedControl.ListTab)
4779 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4781 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4782 .FocusedOn(FocusedControl.ListTab)
4783 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4785 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4786 .FocusedOn(FocusedControl.ListTab)
4787 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4789 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4790 .FocusedOn(FocusedControl.ListTab)
4791 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4793 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4794 .FocusedOn(FocusedControl.ListTab)
4795 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4797 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4798 .FocusedOn(FocusedControl.ListTab)
4799 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4801 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4802 .FocusedOn(FocusedControl.ListTab)
4803 .Do(() => this.SetSortLastColumn()),
4805 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4806 .FocusedOn(FocusedControl.ListTab)
4807 .Do(() => this.FavoritesRetweetOfficial()),
4809 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4810 .FocusedOn(FocusedControl.ListTab)
4811 .Do(() => this.FavoritesRetweetUnofficial()),
4813 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4814 .FocusedOn(FocusedControl.ListTab)
4815 .Do(() => this.OpenUserAppointUrl()),
4817 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4818 .FocusedOn(FocusedControl.PostBrowser)
4819 .Do(() => this.DoReTweetUnofficial()),
4821 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4822 .OnlyWhen(() => this.ExistCurrentPost)
4823 .Do(() => this.tweetDetailsView.DoTranslation()),
4825 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4826 .Do(() => this.DoReTweetUnofficial()),
4828 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4829 .Do(() => this.CopyUserId()),
4831 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4832 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4834 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4835 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4837 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4838 .FocusedOn(FocusedControl.ListTab)
4839 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4840 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4844 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4846 // Task を返す非同期処理があれば asyncTask に代入する
4849 // ShortcutCommand に対応しているコマンドはここで処理される
4850 foreach (var command in this.shortcutCommands)
4852 if (command.IsMatch(keyData, focusedOn))
4854 asyncTask = command.RunCommand();
4855 return command.PreventDefault;
4862 private void GoNextTab(bool forward)
4864 var idx = this.statuses.SelectedTabIndex;
4865 var tabCount = this.statuses.Tabs.Count;
4869 if (idx > tabCount - 1) idx = 0;
4874 if (idx < 0) idx = tabCount - 1;
4876 this.ListTab.SelectedIndex = idx;
4879 private void CopyStot()
4881 var sb = new StringBuilder();
4882 var tab = this.CurrentTab;
4883 var isProtected = false;
4884 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4885 foreach (var post in tab.SelectedPosts)
4887 if (post.IsDeleted) continue;
4890 if (post.RetweetedId != null)
4891 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4893 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4897 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4902 MessageBox.Show(Properties.Resources.CopyStotText1);
4906 var clstr = sb.ToString();
4909 Clipboard.SetDataObject(clstr, false, 5, 100);
4911 catch (Exception ex)
4913 MessageBox.Show(ex.Message);
4918 private void CopyIdUri()
4920 var tab = this.CurrentTab;
4921 if (tab == null || tab is DirectMessagesTabModel)
4924 var copyUrls = new List<string>();
4925 foreach (var post in tab.SelectedPosts)
4926 copyUrls.Add(MyCommon.GetStatusUrl(post));
4928 if (copyUrls.Count == 0)
4933 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4935 catch (ExternalException ex)
4937 MessageBox.Show(ex.Message);
4941 private void GoFav(bool forward)
4943 var tab = this.CurrentTab;
4944 if (tab.AllCount == 0)
4947 var selectedIndex = tab.SelectedIndex;
4955 if (selectedIndex == -1)
4961 fIdx = selectedIndex + 1;
4962 if (fIdx > tab.AllCount - 1)
4965 toIdx = tab.AllCount;
4970 if (selectedIndex == -1)
4972 fIdx = tab.AllCount - 1;
4976 fIdx = selectedIndex - 1;
4984 for (var idx = fIdx; idx != toIdx; idx += stp)
4988 var listView = this.CurrentListView;
4989 this.SelectListItem(listView, idx);
4990 listView.EnsureVisible(idx);
4996 private void GoSamePostToAnotherTab(bool left)
4998 var tab = this.CurrentTab;
5000 // Directタブは対象外(見つかるはずがない)
5001 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5004 var selectedStatusId = tab.SelectedStatusId;
5005 if (selectedStatusId == null)
5008 int fIdx, toIdx, stp;
5013 if (this.ListTab.SelectedIndex == 0)
5019 fIdx = this.ListTab.SelectedIndex - 1;
5027 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5033 fIdx = this.ListTab.SelectedIndex + 1;
5035 toIdx = this.ListTab.TabCount;
5039 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5041 var targetTab = this.statuses.Tabs[tabidx];
5044 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5047 var foundIndex = targetTab.IndexOf(selectedStatusId);
5048 if (foundIndex != -1)
5050 this.ListTab.SelectedIndex = tabidx;
5051 var listView = this.CurrentListView;
5052 this.SelectListItem(listView, foundIndex);
5053 listView.EnsureVisible(foundIndex);
5059 private void GoPost(bool forward)
5061 var tab = this.CurrentTab;
5062 var currentPost = this.CurrentPost;
5064 if (currentPost == null)
5067 var selectedIndex = tab.SelectedIndex;
5069 int fIdx, toIdx, stp;
5073 fIdx = selectedIndex + 1;
5074 if (fIdx > tab.AllCount - 1) return;
5075 toIdx = tab.AllCount;
5080 fIdx = selectedIndex - 1;
5081 if (fIdx < 0) return;
5087 if (currentPost.RetweetedBy == null)
5089 name = currentPost.ScreenName;
5093 name = currentPost.RetweetedBy;
5095 for (var idx = fIdx; idx != toIdx; idx += stp)
5097 var post = tab[idx];
5098 if (post.RetweetedId == null)
5100 if (post.ScreenName == name)
5102 var listView = this.CurrentListView;
5103 this.SelectListItem(listView, idx);
5104 listView.EnsureVisible(idx);
5110 if (post.RetweetedBy == name)
5112 var listView = this.CurrentListView;
5113 this.SelectListItem(listView, idx);
5114 listView.EnsureVisible(idx);
5121 private void GoRelPost(bool forward)
5123 var tab = this.CurrentTab;
5124 var selectedIndex = tab.SelectedIndex;
5126 if (selectedIndex == -1)
5129 int fIdx, toIdx, stp;
5133 fIdx = selectedIndex + 1;
5134 if (fIdx > tab.AllCount - 1) return;
5135 toIdx = tab.AllCount;
5140 fIdx = selectedIndex - 1;
5141 if (fIdx < 0) return;
5146 var anchorPost = tab.AnchorPost;
5147 if (anchorPost == null)
5149 var currentPost = this.CurrentPost;
5150 if (currentPost == null)
5153 anchorPost = currentPost;
5154 tab.AnchorPost = currentPost;
5157 for (var idx = fIdx; idx != toIdx; idx += stp)
5159 var post = tab[idx];
5160 if (post.ScreenName == anchorPost.ScreenName ||
5161 post.RetweetedBy == anchorPost.ScreenName ||
5162 post.ScreenName == anchorPost.RetweetedBy ||
5163 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5164 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5165 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5166 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5167 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5169 var listView = this.CurrentListView;
5170 this.SelectListItem(listView, idx);
5171 listView.EnsureVisible(idx);
5177 private void GoAnchor()
5179 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5180 if (anchorStatusId == null)
5183 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5187 var listView = this.CurrentListView;
5188 this.SelectListItem(listView, idx);
5189 listView.EnsureVisible(idx);
5192 private void GoTopEnd(bool goTop)
5194 var listView = this.CurrentListView;
5195 if (listView.VirtualListSize == 0)
5203 item = listView.GetItemAt(0, 25);
5211 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5213 idx = listView.VirtualListSize - 1;
5217 this.SelectListItem(listView, idx);
5220 private void GoMiddle()
5222 var listView = this.CurrentListView;
5223 if (listView.VirtualListSize == 0)
5231 item = listView.GetItemAt(0, 0);
5241 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5244 idx2 = listView.VirtualListSize - 1;
5250 idx3 = (idx1 + idx2) / 2;
5252 this.SelectListItem(listView, idx3);
5255 private void GoLast()
5257 var listView = this.CurrentListView;
5258 if (listView.VirtualListSize == 0) return;
5260 if (this.statuses.SortOrder == SortOrder.Ascending)
5262 this.SelectListItem(listView, listView.VirtualListSize - 1);
5263 listView.EnsureVisible(listView.VirtualListSize - 1);
5267 this.SelectListItem(listView, 0);
5268 listView.EnsureVisible(0);
5272 private void MoveTop()
5274 var listView = this.CurrentListView;
5275 if (listView.SelectedIndices.Count == 0) return;
5276 var idx = listView.SelectedIndices[0];
5277 if (this.statuses.SortOrder == SortOrder.Ascending)
5279 listView.EnsureVisible(listView.VirtualListSize - 1);
5283 listView.EnsureVisible(0);
5285 listView.EnsureVisible(idx);
5288 private async Task GoInReplyToPostTree()
5290 var curTabClass = this.CurrentTab;
5291 var currentPost = this.CurrentPost;
5293 if (currentPost == null)
5296 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5300 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5302 currentPost = currentPost with
5304 InReplyToStatusId = post.InReplyToStatusId,
5305 InReplyToUser = post.InReplyToUser,
5306 IsReply = post.IsReply,
5308 curTabClass.ReplacePost(currentPost);
5309 this.listCache?.PurgeCache();
5311 var index = curTabClass.SelectedIndex;
5312 this.CurrentListView.RedrawItems(index, index, false);
5314 catch (WebApiException ex)
5316 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5320 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5322 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5324 this.replyChains = new Stack<ReplyChain>();
5326 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5329 string inReplyToTabName;
5330 var inReplyToId = currentPost.InReplyToStatusId;
5331 var inReplyToUser = currentPost.InReplyToUser;
5333 var inReplyToPosts = from tab in this.statuses.Tabs
5334 orderby tab != curTabClass
5335 from post in tab.Posts.Values
5336 where post.StatusId == inReplyToId
5337 let index = tab.IndexOf(post.StatusId)
5339 select new { Tab = tab, Index = index };
5341 var inReplyPost = inReplyToPosts.FirstOrDefault();
5342 if (inReplyPost == null)
5346 await Task.Run(async () =>
5348 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5349 .ConfigureAwait(false);
5352 this.statuses.AddPost(post);
5353 this.statuses.DistributePosts();
5356 catch (WebApiException ex)
5358 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5359 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5363 this.RefreshTimeline();
5365 inReplyPost = inReplyToPosts.FirstOrDefault();
5366 if (inReplyPost == null)
5368 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5372 inReplyToTabName = inReplyPost.Tab.TabName;
5373 inReplyToIndex = inReplyPost.Index;
5375 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5376 var tabPage = this.ListTab.TabPages[tabIndex];
5377 var listView = (DetailsListView)tabPage.Tag;
5379 if (this.CurrentTabName != inReplyToTabName)
5381 this.ListTab.SelectedIndex = tabIndex;
5384 this.SelectListItem(listView, inReplyToIndex);
5385 listView.EnsureVisible(inReplyToIndex);
5388 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5390 var curTabClass = this.CurrentTab;
5391 var currentPost = this.CurrentPost;
5393 if (currentPost == null)
5398 if (currentPost.InReplyToStatusId != null)
5400 var posts = from t in this.statuses.Tabs
5402 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5403 let indexOf = t.IndexOf(p.Value.StatusId)
5405 orderby isForward ? indexOf : indexOf * -1
5406 orderby t != curTabClass
5407 select new { Tab = t, Post = p.Value, Index = indexOf };
5410 var postList = posts.ToList();
5411 for (var i = postList.Count - 1; i >= 0; i--)
5414 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5416 postList.RemoveAt(index);
5419 var currentIndex = this.CurrentTab.SelectedIndex;
5420 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5421 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5422 if (post == null) post = postList.First();
5423 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5424 this.ListTab.SelectedIndex = tabIndex;
5425 var listView = this.CurrentListView;
5426 this.SelectListItem(listView, post.Index);
5427 listView.EnsureVisible(post.Index);
5429 catch (InvalidOperationException)
5437 if (this.replyChains == null || this.replyChains.Count < 1)
5439 var posts = from t in this.statuses.Tabs
5441 where p.Value.InReplyToStatusId == currentPost.StatusId
5442 let indexOf = t.IndexOf(p.Value.StatusId)
5445 orderby t != curTabClass
5446 select new { Tab = t, Index = indexOf };
5449 var post = posts.First();
5450 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5451 this.ListTab.SelectedIndex = tabIndex;
5452 var listView = this.CurrentListView;
5453 this.SelectListItem(listView, post.Index);
5454 listView.EnsureVisible(post.Index);
5456 catch (InvalidOperationException)
5463 var chainHead = this.replyChains.Pop();
5464 if (chainHead.InReplyToId == currentPost.StatusId)
5466 var tab = chainHead.OriginalTab;
5467 if (!this.statuses.Tabs.Contains(tab))
5469 this.replyChains = null;
5473 var idx = tab.IndexOf(chainHead.OriginalId);
5476 this.replyChains = null;
5480 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5483 this.ListTab.SelectedIndex = tabIndex;
5487 this.replyChains = null;
5489 var listView = this.CurrentListView;
5490 this.SelectListItem(listView, idx);
5491 listView.EnsureVisible(idx);
5497 this.replyChains = null;
5498 this.GoBackInReplyToPostTree(parallel);
5504 private void GoBackSelectPostChain()
5506 if (this.selectPostChains.Count > 1)
5509 TabModel? foundTab = null;
5515 this.selectPostChains.Pop();
5516 var (tab, post) = this.selectPostChains.Peek();
5518 if (!this.statuses.Tabs.Contains(tab))
5519 continue; // 該当タブが存在しないので無視
5523 idx = tab.IndexOf(post.StatusId);
5524 if (idx == -1) continue; // 該当ポストが存在しないので無視
5529 this.selectPostChains.Pop();
5531 catch (InvalidOperationException)
5537 while (this.selectPostChains.Count > 1);
5539 if (foundTab == null)
5542 // 履歴が残り1つであればクリアしておく
5543 if (this.selectPostChains.Count == 1)
5544 this.selectPostChains.Clear();
5548 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5549 var tabPage = this.ListTab.TabPages[tabIndex];
5550 var lst = (DetailsListView)tabPage.Tag;
5551 this.ListTab.SelectedIndex = tabIndex;
5555 this.SelectListItem(lst, idx);
5556 lst.EnsureVisible(idx);
5562 private void PushSelectPostChain()
5564 var currentTab = this.CurrentTab;
5565 var currentPost = this.CurrentPost;
5567 var count = this.selectPostChains.Count;
5570 var (tab, post) = this.selectPostChains.Peek();
5571 if (tab == currentTab)
5573 if (post == currentPost) return; // 最新の履歴と同一
5574 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5577 if (count >= 2500) this.TrimPostChain();
5578 this.selectPostChains.Push((currentTab, currentPost));
5581 private void TrimPostChain()
5583 if (this.selectPostChains.Count <= 2000) return;
5584 var p = new Stack<(TabModel, PostClass?)>(2000);
5585 for (var i = 0; i < 2000; i++)
5587 p.Push(this.selectPostChains.Pop());
5589 this.selectPostChains.Clear();
5590 for (var i = 0; i < 2000; i++)
5592 this.selectPostChains.Push(p.Pop());
5596 private bool GoStatus(PostId statusId)
5598 var tab = this.statuses.Tabs
5599 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5600 .Where(x => x.Contains(statusId))
5606 var index = tab.IndexOf(statusId);
5608 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5609 this.ListTab.SelectedIndex = tabIndex;
5611 var listView = this.CurrentListView;
5612 this.SelectListItem(listView, index);
5613 listView.EnsureVisible(index);
5618 private bool GoDirectMessage(PostId statusId)
5620 var tab = this.statuses.DirectMessageTab;
5621 var index = tab.IndexOf(statusId);
5626 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5627 this.ListTab.SelectedIndex = tabIndex;
5629 var listView = this.CurrentListView;
5630 this.SelectListItem(listView, index);
5631 listView.EnsureVisible(index);
5636 private void MyList_MouseClick(object sender, MouseEventArgs e)
5637 => this.CurrentTab.ClearAnchor();
5639 private void StatusText_Enter(object sender, EventArgs e)
5641 // フォーカスの戻り先を StatusText に設定
5642 this.Tag = this.StatusText;
5643 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5646 public Color InputBackColor
5647 => this.themeManager.ColorInputBackcolor;
5649 private void StatusText_Leave(object sender, EventArgs e)
5651 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5652 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5653 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5656 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5658 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5661 e.SuppressKeyPress = true;
5664 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5666 if (asyncTask != null)
5670 private void SaveConfigsAll(bool ifModified)
5674 this.SaveConfigsCommon();
5675 this.SaveConfigsLocal();
5676 this.SaveConfigsTabs();
5677 this.SaveConfigsAtId();
5681 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5682 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5683 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5687 private void SaveConfigsAtId()
5689 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5691 this.ModifySettingAtId = false;
5692 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5693 this.settings.SaveAtIdList();
5696 private void SaveConfigsCommon()
5698 if (this.ignoreConfigSave) return;
5700 this.ModifySettingCommon = false;
5701 lock (this.syncObject)
5703 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5704 this.settings.Common.SortColumn = this.statuses.SortMode switch
5706 ComparerMode.Nickname => 1, // ニックネーム
5707 ComparerMode.Data => 2, // 本文
5708 ComparerMode.Id => 3, // 時刻=発言Id
5709 ComparerMode.Name => 4, // 名前
5710 ComparerMode.Source => 7, // Source
5711 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5713 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5714 if (this.HashMgr.IsPermanent)
5716 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5720 this.settings.Common.HashSelected = "";
5722 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5723 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5724 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5725 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5726 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5728 this.settings.SaveCommon();
5732 private void SaveConfigsLocal()
5734 if (this.ignoreConfigSave) return;
5735 lock (this.syncObject)
5737 this.ModifySettingLocal = false;
5738 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5739 this.settings.Local.FormSize = this.mySize;
5740 this.settings.Local.FormLocation = this.myLoc;
5741 this.settings.Local.SplitterDistance = this.mySpDis;
5742 this.settings.Local.PreviewDistance = this.mySpDis3;
5743 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5744 this.settings.Local.StatusTextHeight = this.mySpDis2;
5746 if (this.ignoreConfigSave) return;
5747 this.settings.SaveLocal();
5751 private void SaveConfigsTabs()
5753 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5755 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5757 foreach (var tab in tabs)
5759 if (!tab.IsPermanentTabType)
5762 var tabSetting = new SettingTabs.SettingTabItem
5764 TabName = tab.TabName,
5765 TabType = tab.TabType,
5766 UnreadManage = tab.UnreadManage,
5767 Protected = tab.Protected,
5768 Notify = tab.Notify,
5769 SoundFile = tab.SoundFile,
5774 case FilterTabModel filterTab:
5775 tabSetting.FilterArray = filterTab.FilterArray;
5777 case UserTimelineTabModel userTab:
5778 tabSetting.User = userTab.ScreenName;
5779 tabSetting.UserId = userTab.UserId;
5781 case PublicSearchTabModel searchTab:
5782 tabSetting.SearchWords = searchTab.SearchWords;
5783 tabSetting.SearchLang = searchTab.SearchLang;
5785 case ListTimelineTabModel listTab:
5786 tabSetting.ListInfo = listTab.ListInfo;
5790 tabSettingList.Add(tabSetting);
5793 this.settings.Tabs.Tabs = tabSettingList;
5794 this.settings.SaveTabs();
5797 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5799 static void ShowFormatErrorDialog(IWin32Window owner)
5803 Properties.Resources.OpenURL_InvalidFormat,
5804 Properties.Resources.OpenURL_Caption,
5805 MessageBoxButtons.OK,
5806 MessageBoxIcon.Error
5810 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5811 if (ret != DialogResult.OK)
5814 var match = Twitter.StatusUrlRegex.Match(inputText);
5817 ShowFormatErrorDialog(this);
5823 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5824 await this.OpenRelatedTab(statusId);
5826 catch (OverflowException)
5828 ShowFormatErrorDialog(this);
5830 catch (TabException ex)
5832 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5836 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5838 var tab = this.CurrentTab;
5840 var rslt = MessageBox.Show(
5841 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5842 Properties.Resources.SaveLogMenuItem_ClickText2,
5843 MessageBoxButtons.YesNoCancel,
5844 MessageBoxIcon.Question);
5845 if (rslt == DialogResult.Cancel) return;
5847 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5848 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5849 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5850 this.SaveFileDialog1.FilterIndex = 0;
5851 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5852 this.SaveFileDialog1.RestoreDirectory = true;
5854 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5856 if (!this.SaveFileDialog1.ValidateNames) return;
5857 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5858 if (rslt == DialogResult.Yes)
5861 for (var idx = 0; idx < tab.AllCount; idx++)
5863 var post = tab[idx];
5866 protect = "Protect";
5867 sw.WriteLine(post.Nickname + "\t" +
5868 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5869 post.CreatedAt.ToLocalTimeString() + "\t" +
5870 post.ScreenName + "\t" +
5871 post.StatusId.Id + "\t" +
5872 post.ImageUrl + "\t" +
5873 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5879 foreach (var post in this.CurrentTab.SelectedPosts)
5883 protect = "Protect";
5884 sw.WriteLine(post.Nickname + "\t" +
5885 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5886 post.CreatedAt.ToLocalTimeString() + "\t" +
5887 post.ScreenName + "\t" +
5888 post.StatusId.Id + "\t" +
5889 post.ImageUrl + "\t" +
5890 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5895 this.TopMost = this.settings.Common.AlwaysTop;
5898 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5902 using (var inputName = new InputTabName())
5904 inputName.TabName = origTabName;
5905 inputName.ShowDialog();
5906 if (inputName.DialogResult == DialogResult.Cancel) return false;
5907 newTabName = inputName.TabName;
5909 this.TopMost = this.settings.Common.AlwaysTop;
5910 if (!MyCommon.IsNullOrEmpty(newTabName))
5913 if (this.statuses.ContainsTab(newTabName))
5915 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5916 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5920 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5921 var tabPage = this.ListTab.TabPages[tabIndex];
5924 if (tabPage != null)
5925 tabPage.Text = newTabName;
5927 this.statuses.RenameTab(origTabName, newTabName);
5929 var state = this.listViewState[origTabName];
5930 this.listViewState.Remove(origTabName);
5931 this.listViewState[newTabName] = state;
5933 this.SaveConfigsCommon();
5934 this.SaveConfigsTabs();
5935 this.rclickTabName = newTabName;
5944 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5946 if (e.Button == MouseButtons.Middle)
5948 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5950 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5952 this.RemoveSpecifiedTab(tab.TabName, true);
5953 this.SaveConfigsTabs();
5960 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5961 => this.TabRename(this.CurrentTabName, out _);
5963 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5965 if (this.settings.Common.TabMouseLock) return;
5966 if (e.Button == MouseButtons.Left)
5968 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5970 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5972 this.tabDrag = true;
5973 this.tabMouseDownPoint = e.Location;
5980 this.tabDrag = false;
5984 private void ListTab_DragEnter(object sender, DragEventArgs e)
5986 if (e.Data.GetDataPresent(typeof(TabPage)))
5987 e.Effect = DragDropEffects.Move;
5989 e.Effect = DragDropEffects.None;
5992 private void ListTab_DragDrop(object sender, DragEventArgs e)
5994 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5996 this.tabDrag = false;
5999 var cpos = new Point(e.X, e.Y);
6000 var spos = this.ListTab.PointToClient(cpos);
6001 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6003 var rect = this.ListTab.GetTabRect(index);
6004 if (rect.Contains(spos))
6007 if (spos.X <= (rect.Left + rect.Right) / 2)
6016 // タブのないところにドロップ->最後尾へ移動
6017 if (MyCommon.IsNullOrEmpty(tn))
6019 var lastTab = this.statuses.Tabs.Last();
6020 tn = lastTab.TabName;
6024 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6025 if (tp.Text == tn) return;
6027 this.ReOrderTab(tp.Text, tn, bef);
6030 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6032 var baseIndex = this.GetTabPageIndex(baseTabText);
6033 if (baseIndex == -1)
6036 var targetIndex = this.GetTabPageIndex(targetTabText);
6037 if (targetIndex == -1)
6040 using (ControlTransaction.Layout(this.ListTab))
6042 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6043 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6044 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6045 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6047 var tab = this.statuses.Tabs[targetIndex];
6048 var tabPage = this.ListTab.TabPages[targetIndex];
6050 this.ListTab.TabPages.Remove(tabPage);
6052 if (targetIndex < baseIndex)
6055 if (!isBeforeBaseTab)
6058 this.statuses.MoveTab(baseIndex, tab);
6060 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6063 this.SaveConfigsTabs();
6066 private void MakeDirectMessageText()
6068 var selectedPosts = this.CurrentTab.SelectedPosts;
6069 if (selectedPosts.Length > 1)
6072 var post = selectedPosts.Single();
6073 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6075 this.inReplyTo = null;
6076 this.StatusText.Text = text;
6077 this.StatusText.SelectionStart = text.Length;
6078 this.StatusText.Focus();
6081 private void MakeReplyText(bool atAll = false)
6083 var selectedPosts = this.CurrentTab.SelectedPosts;
6084 if (selectedPosts.Any(x => x.IsDm))
6086 this.MakeDirectMessageText();
6090 if (selectedPosts.Length == 1)
6092 var post = selectedPosts.Single();
6093 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6094 var inReplyToScreenName = post.ScreenName;
6095 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6099 this.inReplyTo = null;
6102 var selfScreenName = this.tw.Username;
6103 var targetScreenNames = new List<string>();
6104 foreach (var post in selectedPosts)
6106 if (post.ScreenName != selfScreenName)
6107 targetScreenNames.Add(post.ScreenName);
6111 foreach (var (_, screenName) in post.ReplyToList)
6113 if (screenName != selfScreenName)
6114 targetScreenNames.Add(screenName);
6119 if (this.inReplyTo != null)
6121 var (_, screenName) = this.inReplyTo.Value;
6122 if (screenName == selfScreenName)
6123 targetScreenNames.Insert(0, screenName);
6126 var text = this.StatusText.Text;
6127 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6129 var atText = $"@{screenName} ";
6130 if (!text.Contains(atText))
6131 text = atText + text;
6134 this.StatusText.Text = text;
6135 this.StatusText.SelectionStart = text.Length;
6136 this.StatusText.Focus();
6139 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6140 => this.tabDrag = false;
6142 private int iconCnt = 0;
6143 private int blinkCnt = 0;
6144 private bool blink = false;
6146 private void RefreshTasktrayIcon()
6148 void EnableTasktrayAnimation()
6149 => this.TimerRefreshIcon.Enabled = true;
6151 void DisableTasktrayAnimation()
6152 => this.TimerRefreshIcon.Enabled = false;
6154 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6158 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6161 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6162 this.myStatusError = false;
6163 EnableTasktrayAnimation();
6167 var replyIconType = this.settings.Common.ReplyIconState;
6169 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6171 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6172 if (replyTab != null && replyTab.UnreadCount > 0)
6176 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6179 if (this.blinkCnt > 10)
6182 if (this.blinkCnt == 0)
6183 this.blink = !this.blink;
6185 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6186 EnableTasktrayAnimation();
6190 DisableTasktrayAnimation();
6196 // 優先度:リプライ→エラー→オフライン→アイドル
6197 // エラーは更新アイコンでクリアされる
6198 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6199 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6200 else if (this.myStatusError)
6201 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6202 else if (this.myStatusOnline)
6203 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6205 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6208 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6209 => this.RefreshTasktrayIcon(); // 200ms
6211 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6213 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6214 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6215 this.rclickTabName = this.CurrentTabName;
6217 if (this.statuses == null) return;
6218 if (this.statuses.Tabs == null) return;
6220 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6223 this.NotifyDispMenuItem.Checked = tb.Notify;
6224 this.NotifyTbMenuItem.Checked = tb.Notify;
6226 this.soundfileListup = true;
6227 this.SoundFileComboBox.Items.Clear();
6228 this.SoundFileTbComboBox.Items.Clear();
6229 this.SoundFileComboBox.Items.Add("");
6230 this.SoundFileTbComboBox.Items.Add("");
6231 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6232 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6234 oDir = oDir.GetDirectories("Sounds")[0];
6236 foreach (var oFile in oDir.GetFiles("*.wav"))
6238 this.SoundFileComboBox.Items.Add(oFile.Name);
6239 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6241 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6242 if (idx == -1) idx = 0;
6243 this.SoundFileComboBox.SelectedIndex = idx;
6244 this.SoundFileTbComboBox.SelectedIndex = idx;
6245 this.soundfileListup = false;
6246 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6247 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6249 this.TabMenuControl(this.rclickTabName);
6252 private void TabMenuControl(string tabName)
6254 var tabInfo = this.statuses.GetTabByName(tabName)!;
6256 this.FilterEditMenuItem.Enabled = true;
6257 this.EditRuleTbMenuItem.Enabled = true;
6259 if (tabInfo.IsDefaultTabType)
6261 this.ProtectTabMenuItem.Enabled = false;
6262 this.ProtectTbMenuItem.Enabled = false;
6266 this.ProtectTabMenuItem.Enabled = true;
6267 this.ProtectTbMenuItem.Enabled = true;
6270 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6272 this.ProtectTabMenuItem.Checked = true;
6273 this.ProtectTbMenuItem.Checked = true;
6274 this.DeleteTabMenuItem.Enabled = false;
6275 this.DeleteTbMenuItem.Enabled = false;
6279 this.ProtectTabMenuItem.Checked = false;
6280 this.ProtectTbMenuItem.Checked = false;
6281 this.DeleteTabMenuItem.Enabled = true;
6282 this.DeleteTbMenuItem.Enabled = true;
6286 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6288 var checkState = ((ToolStripMenuItem)sender).Checked;
6291 this.ProtectTbMenuItem.Checked = checkState;
6292 this.ProtectTabMenuItem.Checked = checkState;
6295 this.DeleteTabMenuItem.Enabled = !checkState;
6296 this.DeleteTbMenuItem.Enabled = !checkState;
6298 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6299 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6301 this.SaveConfigsTabs();
6304 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6306 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6307 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6309 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6310 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6312 this.SaveConfigsTabs();
6315 public void ChangeTabUnreadManage(string tabName, bool isManage)
6317 var idx = this.GetTabPageIndex(tabName);
6321 var tab = this.statuses.Tabs[tabName];
6322 tab.UnreadManage = isManage;
6324 if (this.settings.Common.TabIconDisp)
6326 var tabPage = this.ListTab.TabPages[idx];
6327 if (tab.UnreadCount > 0)
6328 tabPage.ImageIndex = 0;
6330 tabPage.ImageIndex = -1;
6333 if (this.CurrentTabName == tabName)
6335 this.listCache?.PurgeCache();
6336 this.CurrentListView.Refresh();
6339 this.SetMainWindowTitle();
6340 this.SetStatusLabelUrl();
6341 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6344 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6346 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6347 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6349 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6351 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6353 this.SaveConfigsTabs();
6356 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6358 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6360 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6362 this.SaveConfigsTabs();
6365 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6367 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6368 this.rclickTabName = this.CurrentTabName;
6370 this.RemoveSpecifiedTab(this.rclickTabName, true);
6371 this.SaveConfigsTabs();
6374 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6376 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6378 using (var fltDialog = new FilterDialog())
6380 fltDialog.Owner = this;
6381 fltDialog.SetCurrent(this.rclickTabName);
6382 fltDialog.ShowDialog(this);
6384 this.TopMost = this.settings.Common.AlwaysTop;
6386 this.ApplyPostFilters();
6387 this.SaveConfigsTabs();
6390 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6392 string? tabName = null;
6393 MyCommon.TabUsageType tabUsage;
6394 using (var inputName = new InputTabName())
6396 inputName.TabName = this.statuses.MakeTabName("MyTab");
6397 inputName.IsShowUsage = true;
6398 inputName.ShowDialog();
6399 if (inputName.DialogResult == DialogResult.Cancel) return;
6400 tabName = inputName.TabName;
6401 tabUsage = inputName.Usage;
6403 this.TopMost = this.settings.Common.AlwaysTop;
6404 if (!MyCommon.IsNullOrEmpty(tabName))
6407 ListElement? list = null;
6408 if (tabUsage == MyCommon.TabUsageType.Lists)
6410 using var listAvail = new ListAvailable();
6411 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6413 if (listAvail.SelectedList == null)
6415 list = listAvail.SelectedList;
6421 case MyCommon.TabUsageType.UserDefined:
6422 tab = new FilterTabModel(tabName);
6424 case MyCommon.TabUsageType.PublicSearch:
6425 tab = new PublicSearchTabModel(tabName);
6427 case MyCommon.TabUsageType.Lists:
6428 tab = new ListTimelineTabModel(tabName, list!);
6434 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6436 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6437 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6442 this.SaveConfigsTabs();
6444 var tabIndex = this.statuses.Tabs.Count - 1;
6446 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6448 this.ListTab.SelectedIndex = tabIndex;
6449 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6451 if (tabUsage == MyCommon.TabUsageType.Lists)
6453 this.ListTab.SelectedIndex = tabIndex;
6454 await this.RefreshTabAsync(this.CurrentTab);
6460 private void TabMenuItem_Click(object sender, EventArgs e)
6463 foreach (var post in this.CurrentTab.SelectedPosts)
6466 if (!this.SelectTab(out var tab))
6469 using (var fltDialog = new FilterDialog())
6471 fltDialog.Owner = this;
6472 fltDialog.SetCurrent(tab.TabName);
6474 if (post.RetweetedBy == null)
6476 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6480 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6482 fltDialog.ShowDialog(this);
6485 this.TopMost = this.settings.Common.AlwaysTop;
6488 this.ApplyPostFilters();
6489 this.SaveConfigsTabs();
6492 protected override bool ProcessDialogKey(Keys keyData)
6494 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6495 if ((keyData & Keys.KeyCode) == Keys.Enter)
6497 if (this.StatusText.Focused)
6499 var newLine = false;
6502 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6504 if (this.StatusText.Multiline)
6506 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6508 if ((keyData & Keys.Control) == Keys.Control) post = true;
6512 if ((keyData & Keys.Control) == Keys.Control) post = true;
6515 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6517 if (this.StatusText.Multiline)
6519 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6521 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6525 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6530 if (this.StatusText.Multiline)
6532 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6534 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6535 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6539 if (((keyData & Keys.Shift) == Keys.Shift) ||
6540 (((keyData & Keys.Control) != Keys.Control) &&
6541 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6547 var pos1 = this.StatusText.SelectionStart;
6548 if (this.StatusText.SelectionLength > 0)
6550 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6552 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6553 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6558 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6564 var tab = this.CurrentTab;
6565 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6567 var tabPage = this.CurrentTabPage;
6568 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6569 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6571 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6578 return base.ProcessDialogKey(keyData);
6581 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6582 => this.MakeReplyText(atAll: true);
6584 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6586 var tab = this.CurrentTab;
6587 var selectedPosts = tab.SelectedPosts;
6590 if (selectedPosts.Length == 0)
6593 var screenNameArray = selectedPosts
6594 .Select(x => x.RetweetedBy ?? x.ScreenName)
6597 this.AddFilterRuleByScreenName(screenNameArray);
6599 if (screenNameArray.Length != 0)
6601 var atids = new List<string>();
6602 foreach (var screenName in screenNameArray)
6604 atids.Add("@" + screenName);
6606 var cnt = this.AtIdSupl.ItemCount;
6607 this.AtIdSupl.AddRangeItem(atids.ToArray());
6608 if (this.AtIdSupl.ItemCount != cnt)
6609 this.MarkSettingAtIdModified();
6613 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6615 var tab = this.CurrentTab;
6616 var selectedPosts = tab.SelectedPosts;
6618 if (selectedPosts.Length == 0)
6621 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6623 this.AddFilterRuleBySource(sourceArray);
6626 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6629 if (!this.SelectTab(out var tab)) return;
6633 if (tab.TabType != MyCommon.TabUsageType.Mute)
6635 this.MoveOrCopy(out mv, out mk);
6639 // ミュートタブでは常に MoveMatches を true にする
6644 foreach (var screenName in screenNameArray)
6646 tab.AddFilter(new PostFilterRule
6648 FilterName = screenName,
6649 UseNameField = true,
6653 FilterByUrl = false,
6657 this.ApplyPostFilters();
6658 this.SaveConfigsTabs();
6661 public void AddFilterRuleBySource(params string[] sourceArray)
6663 // タブ選択ダイアログを表示(or追加)
6664 if (!this.SelectTab(out var filterTab))
6669 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6671 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6672 this.MoveOrCopy(out mv, out mk);
6676 // ミュートタブでは常に MoveMatches を true にする
6681 // 振り分けルールに追加するSource
6682 foreach (var source in sourceArray)
6684 filterTab.AddFilter(new PostFilterRule
6686 FilterSource = source,
6690 FilterByUrl = false,
6694 this.ApplyPostFilters();
6695 this.SaveConfigsTabs();
6698 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6705 using (var dialog = new TabsDialog(this.statuses))
6707 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6709 tab = dialog.SelectedTab;
6712 this.CurrentTabPage.Focus();
6717 using (var inputName = new InputTabName())
6719 inputName.TabName = this.statuses.MakeTabName("MyTab");
6720 inputName.ShowDialog();
6721 if (inputName.DialogResult == DialogResult.Cancel) return false;
6722 tabName = inputName.TabName;
6724 this.TopMost = this.settings.Common.AlwaysTop;
6725 if (!MyCommon.IsNullOrEmpty(tabName))
6727 var newTab = new FilterTabModel(tabName);
6728 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6730 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6731 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6750 private void MoveOrCopy(out bool move, out bool mark)
6754 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6755 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6763 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6764 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6775 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6778 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6779 => this.CopyIdUri();
6781 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6783 if (this.StatusText.Focused)
6786 this.StatusText.SelectAll();
6790 // ListView上でのCtrl+A
6791 NativeMethods.SelectAllItems(this.CurrentListView);
6795 private void MoveMiddle()
6801 var listView = this.CurrentListView;
6802 if (listView.SelectedIndices.Count == 0) return;
6804 var idx = listView.SelectedIndices[0];
6806 item = listView.GetItemAt(0, 25);
6812 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6814 idx2 = listView.VirtualListSize - 1;
6818 idx -= Math.Abs(idx1 - idx2) / 2;
6819 if (idx < 0) idx = 0;
6821 listView.EnsureVisible(listView.VirtualListSize - 1);
6822 listView.EnsureVisible(idx);
6825 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6827 var linkElements = this.tweetDetailsView.GetLinkElements();
6829 if (linkElements.Length == 0)
6832 var links = new List<OpenUrlItem>(linkElements.Length);
6834 foreach (var linkElm in linkElements)
6836 var displayUrl = linkElm.GetAttribute("title");
6837 var href = linkElm.GetAttribute("href");
6838 var linkedText = linkElm.InnerText;
6840 if (MyCommon.IsNullOrEmpty(displayUrl))
6843 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6847 bool isReverseSettings;
6849 if (links.Count == 1)
6851 // ツイートに含まれる URL が 1 つのみの場合
6852 // => OpenURL ダイアログを表示せずにリンクを開く
6853 selectedUrl = links[0].Href;
6855 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6856 isReverseSettings = false;
6860 // ツイートに含まれる URL が複数ある場合
6861 // => OpenURL を表示しユーザーが選択したリンクを開く
6862 this.urlDialog.ClearUrl();
6864 foreach (var link in links)
6865 this.urlDialog.AddUrl(link);
6867 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6870 this.TopMost = this.settings.Common.AlwaysTop;
6872 selectedUrl = this.urlDialog.SelectedUrl;
6874 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6875 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6878 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6881 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6883 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6884 this.ClearTab(this.rclickTabName, true);
6887 private void ClearTab(string tabName, bool showWarning)
6891 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6892 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6898 this.statuses.ClearTabIds(tabName);
6899 if (this.CurrentTabName == tabName)
6901 this.CurrentTab.ClearAnchor();
6902 this.listCache?.PurgeCache();
6903 this.listCache?.UpdateListSize();
6906 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6907 var tabPage = this.ListTab.TabPages[tabIndex];
6908 tabPage.ImageIndex = -1;
6910 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6912 this.SetMainWindowTitle();
6913 this.SetStatusLabelUrl();
6916 private static long followers = 0;
6918 private void SetMainWindowTitle()
6920 // メインウインドウタイトルの書き換え
6921 var ttl = new StringBuilder(256);
6924 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6925 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6926 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6927 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6929 foreach (var tab in this.statuses.Tabs)
6931 ur += tab.UnreadCount;
6936 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6937 ttl.Append(ApplicationSettings.ApplicationName);
6939 switch (this.settings.Common.DispLatestPost)
6941 case MyCommon.DispTitleEnum.Ver:
6942 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6944 case MyCommon.DispTitleEnum.Post:
6945 if (this.history != null && this.history.Count > 1)
6946 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6948 case MyCommon.DispTitleEnum.UnreadRepCount:
6949 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6951 case MyCommon.DispTitleEnum.UnreadAllCount:
6952 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6954 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6955 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6957 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6958 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6960 case MyCommon.DispTitleEnum.OwnStatus:
6961 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6962 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6968 this.Text = ttl.ToString();
6970 catch (AccessViolationException)
6972 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6976 private string GetStatusLabelText()
6979 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6980 if (this.statuses == null) return "";
6981 var tbRep = this.statuses.MentionTab;
6982 var tbDm = this.statuses.DirectMessageTab;
6983 if (tbRep == null || tbDm == null) return "";
6984 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6989 var slbl = new StringBuilder(256);
6992 foreach (var tab in this.statuses.Tabs)
6994 ur += tab.UnreadCount;
6996 if (tab.TabName == this.CurrentTabName)
6998 tur = tab.UnreadCount;
7008 this.unreadCounter = ur;
7009 this.unreadAtCounter = urat;
7011 var homeTab = this.statuses.HomeTab;
7013 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7014 if (this.settings.Common.TimelinePeriod == 0)
7016 slbl.Append(Properties.Resources.SetStatusLabelText2);
7020 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7022 return slbl.ToString();
7025 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7029 if (this.InvokeRequired && !this.IsDisposed)
7031 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7035 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7036 this.SetApiStatusLabel(endpointName);
7039 catch (ObjectDisposedException)
7043 catch (InvalidOperationException)
7049 private void SetApiStatusLabel(string? endpointName = null)
7051 var tabType = this.CurrentTab.TabType;
7053 if (endpointName == null)
7055 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
7058 endpointName = tabType switch
7060 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
7061 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7062 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7063 MyCommon.TabUsageType.Favorites => "/favorites/list",
7064 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7065 MyCommon.TabUsageType.UserTimeline =>
7066 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7067 MyCommon.TabUsageType.Lists =>
7068 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7069 MyCommon.TabUsageType.PublicSearch =>
7070 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7071 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7074 this.toolStripApiGauge.ApiEndpoint = endpointName;
7078 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7079 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7083 private void SetStatusLabelUrl()
7084 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7086 public void SetStatusLabel(string text)
7087 => this.StatusLabel.Text = text;
7089 private void SetNotifyIconText()
7091 var ur = new StringBuilder(64);
7093 // タスクトレイアイコンのツールチップテキスト書き換え
7095 ur.Remove(0, ur.Length);
7096 if (this.settings.Common.DispUsername)
7098 ur.Append(this.tw.Username);
7101 ur.Append(ApplicationSettings.ApplicationName);
7103 ur.Append("(Debug Build)");
7105 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7108 ur.Append(this.unreadCounter);
7110 ur.Append(this.unreadAtCounter);
7113 this.NotifyIcon1.Text = ur.ToString();
7116 internal void CheckReplyTo(string statusText)
7120 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7122 foreach (Match hm in m)
7124 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7126 hstr += "#" + hm.Result("$3") + " ";
7127 this.HashSupl.AddItem("#" + hm.Result("$3"));
7130 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7132 hstr += this.HashMgr.UseHash;
7134 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7136 // 本当にリプライ先指定すべきかどうかの判定
7137 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7139 if (this.settings.Common.UseAtIdSupplement)
7141 var bCnt = this.AtIdSupl.ItemCount;
7142 foreach (Match mid in m)
7144 this.AtIdSupl.AddItem(mid.Result("${id}"));
7146 if (bCnt != this.AtIdSupl.ItemCount)
7147 this.MarkSettingAtIdModified();
7150 // リプライ先ステータスIDの指定がない場合は指定しない
7151 if (this.inReplyTo == null)
7155 // 次の条件を満たす場合に in_reply_to_status_id 指定
7156 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7157 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7158 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7162 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7163 if (statusText.StartsWith("@", StringComparison.Ordinal))
7165 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7169 foreach (Match mid in m)
7171 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7176 this.inReplyTo = null;
7179 private void TweenMain_Resize(object sender, EventArgs e)
7181 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7183 this.Visible = false;
7185 if (this.WindowState != FormWindowState.Minimized)
7187 this.formWindowState = this.WindowState;
7191 private void ApplyLayoutFromSettings()
7193 // 現在の DPI と設定保存時の DPI との比を取得する
7194 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7196 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7199 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7200 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7201 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7203 this.SplitContainer1.SplitterDistance = splitterDistance;
7207 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7208 if (this.StatusText.Multiline)
7210 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7211 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7212 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7214 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7216 this.StatusText.Height = statusTextHeight;
7220 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7222 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7226 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7227 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7229 this.SplitContainer3.SplitterDistance = previewDistance;
7232 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7233 this.SplitContainer3.Panel2Collapsed = true;
7234 this.initialLayout = false;
7237 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7239 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7240 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7241 if (this.PlaySoundMenuItem.Checked)
7243 this.settings.Common.PlaySound = true;
7247 this.settings.Common.PlaySound = false;
7249 this.MarkSettingCommonModified();
7252 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7254 if (this.initialLayout)
7257 int splitterDistance;
7258 switch (this.WindowState)
7260 case FormWindowState.Normal:
7261 splitterDistance = this.SplitContainer1.SplitterDistance;
7263 case FormWindowState.Maximized:
7264 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7265 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7266 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7267 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7273 this.mySpDis = splitterDistance;
7274 this.MarkSettingLocalModified();
7277 private async Task DoRepliedStatusOpen()
7279 var currentPost = this.CurrentPost;
7280 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7282 if (MyCommon.IsKeyDown(Keys.Shift))
7284 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7287 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7289 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7293 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7295 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7296 repPost = tb.Posts[currentPost.InReplyToStatusId];
7297 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7300 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7305 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7306 => await this.DoRepliedStatusOpen();
7308 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7310 if (this.initialLayout)
7311 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7313 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7314 if (multiline != this.StatusText.Multiline)
7316 this.StatusText.Multiline = multiline;
7317 this.settings.Local.StatusMultiline = multiline;
7318 this.MarkSettingLocalModified();
7322 private void StatusText_MultilineChanged(object sender, EventArgs e)
7324 if (this.StatusText.Multiline)
7325 this.StatusText.ScrollBars = ScrollBars.Vertical;
7327 this.StatusText.ScrollBars = ScrollBars.None;
7329 if (!this.initialLayout)
7330 this.MarkSettingLocalModified();
7333 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7336 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7337 this.StatusText.Multiline = menuItemChecked;
7338 this.settings.Local.StatusMultiline = menuItemChecked;
7339 if (menuItemChecked)
7341 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7342 this.SplitContainer2.SplitterDistance = 0;
7344 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7348 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7350 this.MarkSettingLocalModified();
7353 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7355 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7357 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7358 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7359 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7361 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7366 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7367 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7368 // Appendix A. Collected ABNF for URI
7369 // http://www.ietf.org/rfc/rfc3986.txt
7371 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7374 if (this.StatusText.SelectionLength > 0)
7376 var tmp = this.StatusText.SelectedText;
7377 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7378 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7380 // 文字列が選択されている場合はその文字列について処理
7382 // nico.ms使用、nicovideoにマッチしたら変換
7383 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7385 result = Nicoms.Shorten(tmp);
7387 else if (converterType != MyCommon.UrlConverter.Nicoms)
7392 var srcUri = new Uri(tmp);
7393 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7394 result = resultUri.AbsoluteUri;
7396 catch (WebApiException e)
7398 this.StatusLabel.Text = converterType + ":" + e.Message;
7401 catch (UriFormatException e)
7403 this.StatusLabel.Text = converterType + ":" + e.Message;
7412 if (!MyCommon.IsNullOrEmpty(result))
7414 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7415 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7416 if (origUrlIndex == -1)
7419 this.StatusText.Select(origUrlIndex, tmp.Length);
7420 this.StatusText.SelectedText = result;
7423 var undo = new UrlUndo
7429 if (this.urlUndoBuffer == null)
7431 this.urlUndoBuffer = new List<UrlUndo>();
7432 this.UrlUndoToolStripMenuItem.Enabled = true;
7435 this.urlUndoBuffer.Add(undo);
7441 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7442 @"(?<url>(?<protocol>https?://)" +
7443 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7444 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7445 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7446 // 正規表現にマッチしたURL文字列をtinyurl化
7447 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7449 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7451 var tmp = mt.Result("${url}");
7452 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7453 tmp = "http://" + tmp;
7456 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7458 // nico.ms使用、nicovideoにマッチしたら変換
7459 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7461 result = Nicoms.Shorten(tmp);
7463 else if (converterType != MyCommon.UrlConverter.Nicoms)
7468 var srcUri = new Uri(tmp);
7469 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7470 result = resultUri.AbsoluteUri;
7472 catch (HttpRequestException e)
7474 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7475 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7476 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7478 this.StatusLabel.Text = converterType + ":" + message;
7481 catch (WebApiException e)
7483 this.StatusLabel.Text = converterType + ":" + e.Message;
7486 catch (UriFormatException e)
7488 this.StatusLabel.Text = converterType + ":" + e.Message;
7497 if (!MyCommon.IsNullOrEmpty(result))
7499 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7500 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7501 if (origUrlIndex == -1)
7504 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7505 this.StatusText.SelectedText = result;
7507 var undo = new UrlUndo
7509 Before = mt.Result("${url}"),
7513 if (this.urlUndoBuffer == null)
7515 this.urlUndoBuffer = new List<UrlUndo>();
7516 this.UrlUndoToolStripMenuItem.Enabled = true;
7519 this.urlUndoBuffer.Add(undo);
7527 private void DoUrlUndo()
7529 if (this.urlUndoBuffer != null)
7531 var tmp = this.StatusText.Text;
7532 foreach (var data in this.urlUndoBuffer)
7534 tmp = tmp.Replace(data.After, data.Before);
7536 this.StatusText.Text = tmp;
7537 this.urlUndoBuffer = null;
7538 this.UrlUndoToolStripMenuItem.Enabled = false;
7539 this.StatusText.SelectionStart = 0;
7540 this.StatusText.SelectionLength = 0;
7544 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7545 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7547 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7548 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7550 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7551 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7553 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7555 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7557 var rnd = new Random();
7559 MyCommon.UrlConverter svc;
7560 // 前回使用した短縮URLサービス以外を選択する
7563 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7565 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7566 await this.UrlConvertAsync(svc);
7570 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7571 => this.DoUrlUndo();
7573 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7575 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7576 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7577 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7578 this.MarkSettingCommonModified();
7581 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7583 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7584 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7585 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7586 this.MarkSettingCommonModified();
7589 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7591 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7592 this.MenuStrip1.Tag = new object();
7593 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7596 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7598 var currentTabPage = this.CurrentTabPage;
7599 if (this.Tag != null) // 設定された戻り先へ遷移
7601 if (this.Tag == currentTabPage)
7602 ((Control)currentTabPage.Tag).Select();
7604 ((Control)this.Tag).Select();
7606 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7608 this.Tag = currentTabPage.Tag;
7609 ((Control)this.Tag).Select();
7611 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7612 this.MenuStrip1.Tag = null;
7615 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7617 if (this.Use2ColumnsMode)
7623 var lst = (DetailsListView)sender;
7624 var columnsCount = lst.Columns.Count;
7626 var darr = new int[columnsCount];
7627 for (var i = 0; i < columnsCount; i++)
7628 darr[lst.Columns[i].DisplayIndex] = i;
7630 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7632 for (var i = 0; i < columnsCount; i++)
7633 this.settings.Local.ColumnsOrder[darr[i]] = i;
7635 this.MarkSettingLocalModified();
7636 this.isColumnChanged = true;
7639 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7641 var lst = (DetailsListView)sender;
7642 if (this.settings.Local == null) return;
7644 var modified = false;
7645 if (this.Use2ColumnsMode)
7647 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7649 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7652 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7654 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7660 var columnsCount = lst.Columns.Count;
7661 for (var i = 0; i < columnsCount; i++)
7663 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7666 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7672 this.MarkSettingLocalModified();
7673 this.isColumnChanged = true;
7677 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7679 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7680 this.MarkSettingLocalModified();
7683 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7685 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7687 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7689 this.SelectMedia_DragDrop(e);
7692 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7694 var (url, title) = GetUrlFromDataObject(e.Data);
7700 appendText = title + " " + url;
7702 if (this.StatusText.TextLength == 0)
7703 this.StatusText.Text = appendText;
7705 this.StatusText.Text += " " + appendText;
7707 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7709 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7711 this.StatusText.Text += text;
7713 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7715 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7716 if (data != null) this.StatusText.Text += data;
7721 /// IDataObject から URL とタイトルの対を取得します
7724 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7726 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7727 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7728 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7730 if (data.GetDataPresent("text/x-moz-url"))
7732 // Firefox, Google Chrome で利用可能
7733 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7735 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7736 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7737 if (lines.Length < 2)
7738 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7740 return (lines[0], lines[1]);
7742 else if (data.GetDataPresent("IESiteModeToUrl"))
7744 // Internet Exproler 用
7745 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7747 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7748 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7749 if (lines.Length < 2)
7750 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7752 return (lines[0], lines[1]);
7754 else if (data.GetDataPresent("UniformResourceLocatorW"))
7758 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7759 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7763 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7766 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7768 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7770 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7772 this.SelectMedia_DragEnter(e);
7776 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7778 e.Effect = DragDropEffects.Copy;
7781 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7783 e.Effect = DragDropEffects.Copy;
7786 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7788 e.Effect = DragDropEffects.Copy;
7792 e.Effect = DragDropEffects.None;
7795 private void TweenMain_DragOver(object sender, DragEventArgs e)
7799 public bool IsNetworkAvailable()
7801 var nw = MyCommon.IsNetworkAvailable();
7802 this.myStatusOnline = nw;
7806 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7808 var uriStr = uri.AbsoluteUri;
7810 // OpenTween 内部で使用する URL
7811 if (uri.Authority == "opentween")
7813 await this.OpenInternalUriAsync(uri);
7817 // ハッシュタグを含む Twitter 検索
7818 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7821 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7822 var pos = unescapedQuery.IndexOf('#');
7823 if (pos == -1) return;
7825 var hash = unescapedQuery.Substring(pos);
7826 this.HashSupl.AddItem(hash);
7827 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7828 this.AddNewTabForSearch(hash);
7833 // フラグが立っている場合は設定と逆の動作をする
7834 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7835 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7837 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7838 if (userUriMatch.Success)
7840 var screenName = userUriMatch.Groups["ScreenName"].Value;
7841 if (this.IsTwitterId(screenName))
7843 await this.AddNewTabForUserTimeline(screenName);
7850 await MyCommon.OpenInBrowserAsync(this, uriStr);
7854 /// OpenTween 内部の機能を呼び出すための URL を開きます
7856 private async Task OpenInternalUriAsync(Uri uri)
7858 // ツイートを開く (//opentween/status/:status_id)
7859 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7862 var statusId = new TwitterStatusId(match.Groups[1].Value);
7863 await this.OpenRelatedTab(statusId);
7868 private void ListTabSelect(TabPage tabPage)
7870 this.SetListProperty();
7872 var previousTabName = this.CurrentTabName;
7873 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7874 previousListViewState.Save(this.ListLockMenuItem.Checked);
7876 this.listCache?.PurgeCache();
7878 this.statuses.SelectTab(tabPage.Text);
7880 this.InitializeTimelineListView();
7882 var tab = this.CurrentTab;
7885 var listView = this.CurrentListView;
7887 var currentListViewState = this.listViewState[tab.TabName];
7888 currentListViewState.Restore(forceScroll: true);
7890 if (this.Use2ColumnsMode)
7892 listView.Columns[1].Text = this.columnText[2];
7896 for (var i = 0; i < listView.Columns.Count; i++)
7898 listView.Columns[i].Text = this.columnText[i];
7903 private void InitializeTimelineListView()
7905 var listView = this.CurrentListView;
7906 var tab = this.CurrentTab;
7908 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7909 (this.listCache, var oldCache) = (newCache, this.listCache);
7910 oldCache?.Dispose();
7912 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7913 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7914 oldDrawer?.Dispose();
7916 newDrawer.IconSize = this.settings.Common.IconSize;
7917 newDrawer.UpdateItemHeight();
7920 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7921 => this.ListTabSelect(e.TabPage);
7923 private void SelectListItem(DetailsListView lView, int index)
7926 var bnd = new Rectangle();
7928 var item = lView.FocusedItem;
7937 lView.SelectedIndices.Clear();
7939 while (lView.SelectedIndices.Count > 0);
7940 item = lView.Items[index];
7941 item.Selected = true;
7942 item.Focused = true;
7944 if (flg) lView.Invalidate(bnd);
7947 private async void TweenMain_Shown(object sender, EventArgs e)
7949 this.NotifyIcon1.Visible = true;
7952 if (this.settings.IsFirstRun)
7954 // 初回起動時だけ右下のメニューを目立たせる
7955 this.HashStripSplitButton.ShowDropDown();
7958 if (this.IsNetworkAvailable())
7960 var loadTasks = new TaskCollection();
7964 this.RefreshMuteUserIdsAsync,
7965 this.RefreshBlockIdsAsync,
7966 this.RefreshNoRetweetIdsAsync,
7967 this.RefreshTwitterConfigurationAsync,
7968 this.RefreshTabAsync<HomeTabModel>,
7969 this.RefreshTabAsync<MentionsTabModel>,
7970 this.RefreshTabAsync<DirectMessagesTabModel>,
7971 this.RefreshTabAsync<PublicSearchTabModel>,
7972 this.RefreshTabAsync<UserTimelineTabModel>,
7973 this.RefreshTabAsync<ListTimelineTabModel>,
7976 if (this.settings.Common.StartupFollowers)
7977 loadTasks.Add(this.RefreshFollowerIdsAsync);
7979 if (this.settings.Common.GetFav)
7980 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7982 var allTasks = loadTasks.RunAll();
7987 var timeout = Task.Delay(5000);
7988 if (await Task.WhenAny(allTasks, timeout) != timeout)
7992 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7994 if (MyCommon.EndingFlag)
7998 if (MyCommon.EndingFlag) return;
8000 if (ApplicationSettings.VersionInfoUrl != null)
8002 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8003 if (this.settings.Common.StartupVersion)
8004 await this.CheckNewVersion(true);
8008 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8009 this.VerUpMenuItem.Enabled = false;
8010 this.VerUpMenuItem.Available = false;
8011 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8014 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8015 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8017 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8018 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8022 var reloadTasks = new TaskCollection();
8024 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8025 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
8027 if (!this.tw.GetNoRetweetSuccess)
8028 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
8030 if (this.tw.Configuration.PhotoSizeLimit == 0)
8031 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
8033 await reloadTasks.RunAll();
8036 this.initial = false;
8039 private void StartTimers()
8041 if (!this.StopRefreshAllMenuItem.Checked)
8042 this.timelineScheduler.Enabled = true;
8044 this.selectionDebouncer.Enabled = true;
8045 this.saveConfigDebouncer.Enabled = true;
8046 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
8049 private async Task DoGetFollowersMenu()
8051 await this.RefreshFollowerIdsAsync();
8052 this.DispSelectedPost(true);
8055 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8056 => await this.DoGetFollowersMenu();
8058 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8059 => this.DoReTweetUnofficial();
8061 private async Task DoReTweetOfficial(bool isConfirm)
8064 if (this.ExistCurrentPost)
8066 var selectedPosts = this.CurrentTab.SelectedPosts;
8068 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8070 if (selectedPosts.Any(x => x.IsProtect))
8071 MessageBox.Show("Protected.");
8073 this.doFavRetweetFlags = false;
8077 if (selectedPosts.Length > 15)
8079 MessageBox.Show(Properties.Resources.RetweetLimitText);
8080 this.doFavRetweetFlags = false;
8083 else if (selectedPosts.Length > 1)
8085 var questionText = Properties.Resources.RetweetQuestion2;
8086 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8087 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8089 case DialogResult.Cancel:
8090 case DialogResult.No:
8091 this.doFavRetweetFlags = false;
8097 if (!this.settings.Common.RetweetNoConfirm)
8099 var questiontext = Properties.Resources.RetweetQuestion1;
8100 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8101 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8103 this.doFavRetweetFlags = false;
8109 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8111 await this.RetweetAsync(statusIds);
8115 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8116 => await this.DoReTweetOfficial(true);
8118 private async Task FavoritesRetweetOfficial()
8120 if (!this.ExistCurrentPost) return;
8121 this.doFavRetweetFlags = true;
8123 var tasks = new TaskCollection();
8124 tasks.Add(() => this.DoReTweetOfficial(true));
8126 if (this.doFavRetweetFlags)
8128 this.doFavRetweetFlags = false;
8129 tasks.Add(() => this.FavoriteChange(true, false));
8132 await tasks.RunAll();
8135 private async Task FavoritesRetweetUnofficial()
8137 var post = this.CurrentPost;
8138 if (this.ExistCurrentPost && post != null && !post.IsDm)
8140 this.doFavRetweetFlags = true;
8141 var favoriteTask = this.FavoriteChange(true);
8142 if (!post.IsProtect && this.doFavRetweetFlags)
8144 this.doFavRetweetFlags = false;
8145 this.DoReTweetUnofficial();
8153 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8155 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8156 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8157 /// <returns>復元されたツイート本文</returns>
8158 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8160 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8163 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8165 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8167 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8169 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8173 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8175 statusHtml = statusHtml.Replace("<br>", " ");
8177 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8178 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8179 statusHtml = statusHtml.Replace(" ", " ");
8181 return WebUtility.HtmlDecode(statusHtml);
8184 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8186 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8188 if (this.CurrentPost != null)
8189 this.DispSelectedPost(true);
8192 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8194 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8195 this.DebugModeToolStripMenuItem.Visible = true;
8197 this.DebugModeToolStripMenuItem.Visible = false;
8200 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8201 => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8203 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8204 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8206 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8207 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8209 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8211 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8212 this.MarkSettingCommonModified();
8215 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8217 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8218 this.MarkSettingCommonModified();
8221 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8223 this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8224 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8225 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8226 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8227 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8228 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8231 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8233 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8234 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8235 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8236 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8237 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8238 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8241 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8243 if (this.TraceOutToolStripMenuItem.Checked)
8244 MyCommon.TraceFlag = true;
8246 MyCommon.TraceFlag = false;
8249 private void TweenMain_Deactivate(object sender, EventArgs e)
8250 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8252 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8254 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8256 _ = this.TabRename(this.rclickTabName, out _);
8259 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8260 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8262 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8263 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8265 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8267 TwitterApiStatus? apiStatus;
8269 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8271 var cancellationToken = dialog.EnableCancellation();
8275 var task = this.tw.GetInfoApi();
8276 apiStatus = await dialog.WaitForAsync(this, task);
8278 catch (WebApiException)
8283 if (cancellationToken.IsCancellationRequested)
8286 if (apiStatus == null)
8288 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8293 using var apiDlg = new ApiInfoDialog();
8294 apiDlg.ShowDialog(this);
8297 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8299 var id = this.CurrentPost?.ScreenName ?? "";
8301 await this.FollowCommand(id);
8304 internal async Task FollowCommand(string id)
8306 using (var inputName = new InputTabName())
8308 inputName.FormTitle = "Follow";
8309 inputName.FormDescription = Properties.Resources.FRMessage1;
8310 inputName.TabName = id;
8312 if (inputName.ShowDialog(this) != DialogResult.OK)
8314 if (string.IsNullOrWhiteSpace(inputName.TabName))
8317 id = inputName.TabName.Trim();
8320 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8324 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8325 await dialog.WaitForAsync(this, task);
8327 catch (WebApiException ex)
8329 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8334 MessageBox.Show(Properties.Resources.FRMessage3);
8337 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8339 var id = this.CurrentPost?.ScreenName ?? "";
8341 await this.RemoveCommand(id, false);
8344 internal async Task RemoveCommand(string id, bool skipInput)
8348 using var inputName = new InputTabName();
8349 inputName.FormTitle = "Unfollow";
8350 inputName.FormDescription = Properties.Resources.FRMessage1;
8351 inputName.TabName = id;
8353 if (inputName.ShowDialog(this) != DialogResult.OK)
8355 if (string.IsNullOrWhiteSpace(inputName.TabName))
8358 id = inputName.TabName.Trim();
8361 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8365 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8366 await dialog.WaitForAsync(this, task);
8368 catch (WebApiException ex)
8370 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8375 MessageBox.Show(Properties.Resources.FRMessage3);
8378 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8380 var id = this.CurrentPost?.ScreenName ?? "";
8382 await this.ShowFriendship(id);
8385 internal async Task ShowFriendship(string id)
8387 using (var inputName = new InputTabName())
8389 inputName.FormTitle = "Show Friendships";
8390 inputName.FormDescription = Properties.Resources.FRMessage1;
8391 inputName.TabName = id;
8393 if (inputName.ShowDialog(this) != DialogResult.OK)
8395 if (string.IsNullOrWhiteSpace(inputName.TabName))
8398 id = inputName.TabName.Trim();
8401 bool isFollowing, isFollowed;
8403 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8405 var cancellationToken = dialog.EnableCancellation();
8409 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8410 var friendship = await dialog.WaitForAsync(this, task);
8412 isFollowing = friendship.Relationship.Source.Following;
8413 isFollowed = friendship.Relationship.Source.FollowedBy;
8415 catch (WebApiException ex)
8417 if (!cancellationToken.IsCancellationRequested)
8418 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8422 if (cancellationToken.IsCancellationRequested)
8429 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8433 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8437 result += Properties.Resources.GetFriendshipInfo3;
8441 result += Properties.Resources.GetFriendshipInfo4;
8443 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8444 MessageBox.Show(result);
8447 internal async Task ShowFriendship(string[] ids)
8449 foreach (var id in ids)
8451 bool isFollowing, isFollowed;
8453 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8455 var cancellationToken = dialog.EnableCancellation();
8459 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8460 var friendship = await dialog.WaitForAsync(this, task);
8462 isFollowing = friendship.Relationship.Source.Following;
8463 isFollowed = friendship.Relationship.Source.FollowedBy;
8465 catch (WebApiException ex)
8467 if (!cancellationToken.IsCancellationRequested)
8468 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8472 if (cancellationToken.IsCancellationRequested)
8482 ff += Properties.Resources.GetFriendshipInfo1;
8486 ff += Properties.Resources.GetFriendshipInfo2;
8489 ff += System.Environment.NewLine + " ";
8492 ff += Properties.Resources.GetFriendshipInfo3;
8496 ff += Properties.Resources.GetFriendshipInfo4;
8498 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8501 if (MessageBox.Show(
8502 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8503 Properties.Resources.GetFriendshipInfo8,
8504 MessageBoxButtons.YesNo,
8505 MessageBoxIcon.Question,
8506 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8508 await this.RemoveCommand(id, true);
8513 MessageBox.Show(result);
8518 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8519 => await this.DoShowUserStatus(this.tw.Username, false);
8521 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8524 public bool IsTwitterId(string name)
8526 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8527 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8529 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8532 private void DoQuoteOfficial()
8534 var post = this.CurrentPost;
8535 if (this.ExistCurrentPost && post != null)
8537 if (post.IsDm || !this.StatusText.Enabled)
8542 MessageBox.Show("Protected.");
8546 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8548 this.inReplyTo = null;
8550 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8552 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8553 this.StatusText.Focus();
8557 private void DoReTweetUnofficial()
8560 var post = this.CurrentPost;
8561 if (this.ExistCurrentPost && post != null)
8563 if (post.IsDm || !this.StatusText.Enabled)
8568 MessageBox.Show("Protected.");
8571 var rtdata = post.Text;
8572 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8574 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8576 // 投稿時に in_reply_to_status_id を付加する
8577 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8578 var inReplyToScreenName = post.ScreenName;
8579 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8581 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8583 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8584 this.StatusText.Focus();
8588 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8589 => this.DoQuoteOfficial();
8591 private async void SearchButton_Click(object sender, EventArgs e)
8594 var pnl = ((Control)sender).Parent;
8595 if (pnl == null) return;
8596 var tbName = pnl.Parent.Text;
8597 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8598 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8599 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8600 cmb.Text = cmb.Text.Trim();
8601 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8603 var buf = new StringBuilder();
8604 var c = cmb.Text.ToCharArray();
8605 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8607 if (cnt > cmb.Text.Length - 4)
8609 buf.Append(cmb.Text.Substring(cnt));
8618 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8627 cmb.Text = buf.ToString();
8629 var listView = (DetailsListView)pnl.Parent.Tag;
8631 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8633 tb.SearchWords = cmb.Text;
8634 tb.SearchLang = cmbLang.Text;
8635 if (MyCommon.IsNullOrEmpty(cmb.Text))
8638 this.SaveConfigsTabs();
8643 var idx = cmb.Items.IndexOf(tb.SearchWords);
8644 if (idx > -1) cmb.Items.RemoveAt(idx);
8645 cmb.Items.Insert(0, tb.SearchWords);
8646 cmb.Text = tb.SearchWords;
8648 this.statuses.ClearTabIds(tbName);
8649 this.listCache?.PurgeCache();
8650 this.listCache?.UpdateListSize();
8651 this.SaveConfigsTabs(); // 検索条件の保存
8655 await this.RefreshTabAsync(tb);
8658 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8659 => await this.DoRefreshMore(); // もっと前を取得
8662 /// 指定されたタブのListTabにおける位置を返します
8665 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8667 public int GetTabPageIndex(string tabName)
8668 => this.statuses.Tabs.IndexOf(tabName);
8670 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8674 var restoredTab = this.statuses.UndoRemovedTab();
8675 this.AddNewTab(restoredTab, startup: false);
8677 var tabIndex = this.statuses.Tabs.Count - 1;
8678 this.ListTab.SelectedIndex = tabIndex;
8680 this.SaveConfigsTabs();
8682 catch (TabException ex)
8684 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8688 private async Task DoMoveToRTHome()
8690 var post = this.CurrentPost;
8691 if (post != null && post.RetweetedId != null)
8692 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8695 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8696 => await this.DoMoveToRTHome();
8698 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8700 var screenName = this.CurrentPost?.ScreenName;
8701 if (screenName != null)
8702 this.ListManageUserContext(screenName);
8705 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8707 var screenName = this.CurrentPost?.RetweetedBy;
8708 if (screenName != null)
8709 this.ListManageUserContext(screenName);
8712 public void ListManageUserContext(string screenName)
8714 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8715 listSelectForm.ShowDialog(this);
8718 private void SearchControls_Enter(object sender, EventArgs e)
8720 var pnl = (Control)sender;
8721 foreach (Control ctl in pnl.Controls)
8727 private void SearchControls_Leave(object sender, EventArgs e)
8729 var pnl = (Control)sender;
8730 foreach (Control ctl in pnl.Controls)
8732 ctl.TabStop = false;
8736 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8738 var tab = this.CurrentTab;
8739 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8740 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8743 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8744 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8746 private void HashManageMenuItem_Click(object sender, EventArgs e)
8751 rslt = this.HashMgr.ShowDialog();
8757 this.TopMost = this.settings.Common.AlwaysTop;
8758 if (rslt == DialogResult.Cancel) return;
8759 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8761 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8762 this.HashTogglePullDownMenuItem.Checked = true;
8763 this.HashToggleMenuItem.Checked = true;
8767 this.HashStripSplitButton.Text = "#[-]";
8768 this.HashTogglePullDownMenuItem.Checked = false;
8769 this.HashToggleMenuItem.Checked = false;
8772 this.MarkSettingCommonModified();
8773 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8776 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8778 this.HashMgr.ToggleHash();
8779 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8781 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8782 this.HashToggleMenuItem.Checked = true;
8783 this.HashTogglePullDownMenuItem.Checked = true;
8787 this.HashStripSplitButton.Text = "#[-]";
8788 this.HashToggleMenuItem.Checked = false;
8789 this.HashTogglePullDownMenuItem.Checked = false;
8791 this.MarkSettingCommonModified();
8792 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8795 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8796 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8798 public void SetPermanentHashtag(string hashtag)
8800 this.HashMgr.SetPermanentHash("#" + hashtag);
8801 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8802 this.HashTogglePullDownMenuItem.Checked = true;
8803 this.HashToggleMenuItem.Checked = true;
8805 this.MarkSettingCommonModified();
8808 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8810 var tab = this.CurrentTab;
8811 var post = this.CurrentPost;
8812 if (!this.ExistCurrentPost)
8814 this.ReplyOpMenuItem.Enabled = false;
8815 this.ReplyAllOpMenuItem.Enabled = false;
8816 this.DmOpMenuItem.Enabled = false;
8817 this.CreateTabRuleOpMenuItem.Enabled = false;
8818 this.CreateIdRuleOpMenuItem.Enabled = false;
8819 this.CreateSourceRuleOpMenuItem.Enabled = false;
8820 this.ReadOpMenuItem.Enabled = false;
8821 this.UnreadOpMenuItem.Enabled = false;
8822 this.AuthorMenuItem.Visible = false;
8823 this.RetweetedByMenuItem.Visible = false;
8827 this.ReplyOpMenuItem.Enabled = true;
8828 this.ReplyAllOpMenuItem.Enabled = true;
8829 this.DmOpMenuItem.Enabled = true;
8830 this.CreateTabRuleOpMenuItem.Enabled = true;
8831 this.CreateIdRuleOpMenuItem.Enabled = true;
8832 this.CreateSourceRuleOpMenuItem.Enabled = true;
8833 this.ReadOpMenuItem.Enabled = true;
8834 this.UnreadOpMenuItem.Enabled = true;
8835 this.AuthorMenuItem.Visible = true;
8836 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8837 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8838 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8841 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8843 this.FavOpMenuItem.Enabled = false;
8844 this.UnFavOpMenuItem.Enabled = false;
8845 this.OpenStatusOpMenuItem.Enabled = false;
8846 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8847 this.RtOpMenuItem.Enabled = false;
8848 this.RtUnOpMenuItem.Enabled = false;
8849 this.QtOpMenuItem.Enabled = false;
8850 this.FavoriteRetweetMenuItem.Enabled = false;
8851 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8855 this.FavOpMenuItem.Enabled = true;
8856 this.UnFavOpMenuItem.Enabled = true;
8857 this.OpenStatusOpMenuItem.Enabled = true;
8858 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8860 if (!post.CanRetweetBy(this.tw.UserId))
8862 this.RtOpMenuItem.Enabled = false;
8863 this.RtUnOpMenuItem.Enabled = false;
8864 this.QtOpMenuItem.Enabled = false;
8865 this.FavoriteRetweetMenuItem.Enabled = false;
8866 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8870 this.RtOpMenuItem.Enabled = true;
8871 this.RtUnOpMenuItem.Enabled = true;
8872 this.QtOpMenuItem.Enabled = true;
8873 this.FavoriteRetweetMenuItem.Enabled = true;
8874 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8878 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8880 this.RefreshPrevOpMenuItem.Enabled = true;
8884 this.RefreshPrevOpMenuItem.Enabled = false;
8886 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8888 this.OpenRepSourceOpMenuItem.Enabled = false;
8892 this.OpenRepSourceOpMenuItem.Enabled = true;
8895 if (this.ExistCurrentPost && post != null)
8897 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8901 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8902 => this.ContextMenuTabProperty_Opening(sender, null!);
8904 public Twitter TwitterInstance
8907 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8909 if (this.initialLayout)
8912 int splitterDistance;
8913 switch (this.WindowState)
8915 case FormWindowState.Normal:
8916 splitterDistance = this.SplitContainer3.SplitterDistance;
8918 case FormWindowState.Maximized:
8919 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8920 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8921 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8922 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8928 this.mySpDis3 = splitterDistance;
8929 this.MarkSettingLocalModified();
8932 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8934 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8936 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8937 this.PublicSearchQueryMenuItem.Enabled = true;
8939 this.PublicSearchQueryMenuItem.Enabled = false;
8941 var post = this.CurrentPost;
8942 if (!this.ExistCurrentPost || post == null)
8944 this.CopySTOTMenuItem.Enabled = false;
8945 this.CopyURLMenuItem.Enabled = false;
8946 this.CopyUserIdStripMenuItem.Enabled = false;
8950 this.CopySTOTMenuItem.Enabled = true;
8951 this.CopyURLMenuItem.Enabled = true;
8952 this.CopyUserIdStripMenuItem.Enabled = true;
8954 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8955 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8959 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8960 => this.SetNotifyIconText();
8962 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8963 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8965 private async Task DoShowUserStatus(string id, bool showInputDialog)
8967 TwitterUser? user = null;
8969 if (showInputDialog)
8971 using var inputName = new InputTabName();
8972 inputName.FormTitle = "Show UserStatus";
8973 inputName.FormDescription = Properties.Resources.FRMessage1;
8974 inputName.TabName = id;
8976 if (inputName.ShowDialog(this) != DialogResult.OK)
8978 if (string.IsNullOrWhiteSpace(inputName.TabName))
8981 id = inputName.TabName.Trim();
8984 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8986 var cancellationToken = dialog.EnableCancellation();
8990 var task = this.tw.GetUserInfo(id);
8991 user = await dialog.WaitForAsync(this, task);
8993 catch (WebApiException ex)
8995 if (!cancellationToken.IsCancellationRequested)
8996 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9000 if (cancellationToken.IsCancellationRequested)
9004 await this.DoShowUserStatus(user);
9007 private async Task DoShowUserStatus(TwitterUser user)
9009 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9010 var showUserTask = userDialog.ShowUserAsync(user);
9011 userDialog.ShowDialog(this);
9014 this.BringToFront();
9016 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9020 internal Task ShowUserStatus(string id, bool showInputDialog)
9021 => this.DoShowUserStatus(id, showInputDialog);
9023 internal Task ShowUserStatus(string id)
9024 => this.DoShowUserStatus(id, true);
9026 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9028 var post = this.CurrentPost;
9031 await this.ShowUserStatus(post.ScreenName, false);
9035 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9037 var retweetedBy = this.CurrentPost?.RetweetedBy;
9038 if (retweetedBy != null)
9040 await this.ShowUserStatus(retweetedBy, false);
9044 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9046 var post = this.CurrentPost;
9047 if (!this.ExistCurrentPost || post == null)
9050 var statusId = post.RetweetedId ?? post.StatusId;
9051 TwitterStatus status;
9053 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9055 var cancellationToken = dialog.EnableCancellation();
9059 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9060 status = await dialog.WaitForAsync(this, task);
9062 catch (WebApiException ex)
9064 if (!cancellationToken.IsCancellationRequested)
9065 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9069 if (cancellationToken.IsCancellationRequested)
9073 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9076 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9078 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9081 this.Visible = false;
9083 else if (Form.ActiveForm == null)
9085 this.Visible = true;
9086 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9088 this.BringToFront();
9089 this.StatusText.Focus();
9093 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9094 => this.MultiLinePullDownMenuItem.PerformClick();
9097 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9099 if (this.ImageSelector.Visible)
9100 this.ImageSelector.EndSelection();
9102 this.ImageSelector.BeginSelection();
9105 private void SelectMedia_DragEnter(DragEventArgs e)
9107 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9109 e.Effect = DragDropEffects.Copy;
9112 e.Effect = DragDropEffects.None;
9115 private void SelectMedia_DragDrop(DragEventArgs e)
9118 this.BringToFront();
9120 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9121 this.ImageSelector.BeginSelection();
9122 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9123 this.StatusText.Focus();
9126 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9128 this.TimelinePanel.Visible = false;
9129 this.TimelinePanel.Enabled = false;
9132 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9134 this.TimelinePanel.Visible = true;
9135 this.TimelinePanel.Enabled = true;
9136 this.CurrentListView.Focus();
9139 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9140 => this.AllowDrop = false;
9142 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9143 => this.AllowDrop = true;
9145 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9147 if (this.ImageSelector.Visible)
9149 this.MarkSettingCommonModified();
9150 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9154 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9155 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9158 /// StatusTextでCtrl+Vが押下された時の処理
9160 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9164 if (Clipboard.ContainsText())
9166 // clipboardにテキストがある場合は貼り付け処理
9167 this.StatusText.Paste(Clipboard.GetText());
9169 else if (Clipboard.ContainsImage())
9172 using var image = Clipboard.GetImage();
9173 this.ImageSelector.BeginSelection();
9174 this.ImageSelector.Model.AddMediaItemFromImage(image);
9176 else if (Clipboard.ContainsFileDropList())
9178 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9179 this.ImageSelector.BeginSelection();
9180 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9183 catch (ExternalException ex)
9185 MessageBox.Show(ex.Message);
9190 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9192 using var form = new ListManage(this.tw);
9193 form.ShowDialog(this);
9196 private bool ModifySettingCommon { get; set; }
9198 private bool ModifySettingLocal { get; set; }
9200 private bool ModifySettingAtId { get; set; }
9202 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9204 var post = this.CurrentPost;
9205 if (this.ExistCurrentPost && post != null && !post.IsDm)
9206 this.RtCountMenuItem.Enabled = true;
9208 this.RtCountMenuItem.Enabled = false;
9211 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9212 => this.CopyUserId();
9214 private void CopyUserId()
9216 var post = this.CurrentPost;
9217 if (post == null) return;
9218 var clstr = post.ScreenName;
9221 Clipboard.SetDataObject(clstr, false, 5, 100);
9223 catch (Exception ex)
9225 MessageBox.Show(ex.Message);
9229 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9231 var post = this.CurrentPost;
9232 if (this.ExistCurrentPost && post != null && !post.IsDm)
9236 await this.OpenRelatedTab(post);
9238 catch (TabException ex)
9240 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9246 /// 指定されたツイートに対する関連発言タブを開きます
9248 /// <param name="statusId">表示するツイートのID</param>
9249 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9250 public async Task OpenRelatedTab(PostId statusId)
9252 var post = this.statuses[statusId];
9257 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9259 catch (WebApiException ex)
9261 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9266 await this.OpenRelatedTab(post);
9270 /// 指定されたツイートに対する関連発言タブを開きます
9272 /// <param name="post">表示する対象となるツイート</param>
9273 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9274 private async Task OpenRelatedTab(PostClass post)
9276 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9277 if (tabRelated != null)
9279 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9282 var tabName = this.statuses.MakeTabName("Related Tweets");
9284 tabRelated = new RelatedPostsTabModel(tabName, post)
9286 UnreadManage = false,
9290 this.statuses.AddTab(tabRelated);
9291 this.AddNewTab(tabRelated, startup: false);
9293 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9295 await this.RefreshTabAsync(tabRelated);
9297 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9301 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9303 var tabPage = this.ListTab.TabPages[tabIndex];
9304 var listView = (DetailsListView)tabPage.Tag;
9305 var targetPost = tabRelated.TargetPost;
9306 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9308 if (index != -1 && index < listView.Items.Count)
9310 listView.SelectedIndices.Add(index);
9311 listView.Items[index].Focused = true;
9316 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9318 var buf = new StringBuilder();
9319 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9320 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9321 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9324 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9326 MyCommon.EndingFlag = true;
9330 Application.Restart();
9334 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9338 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9339 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9341 private bool ExistCurrentPost
9345 var post = this.CurrentPost;
9346 return post != null && !post.IsDeleted;
9350 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9351 => await this.ShowUserTimeline();
9353 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9354 => await this.ShowRetweeterTimeline();
9356 private string GetUserIdFromCurPostOrInput(string caption)
9358 var id = this.CurrentPost?.ScreenName ?? "";
9360 using var inputName = new InputTabName();
9361 inputName.FormTitle = caption;
9362 inputName.FormDescription = Properties.Resources.FRMessage1;
9363 inputName.TabName = id;
9365 if (inputName.ShowDialog() == DialogResult.OK &&
9366 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9368 id = inputName.TabName.Trim();
9377 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9379 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9380 if (!MyCommon.IsNullOrEmpty(id))
9382 await this.AddNewTabForUserTimeline(id);
9386 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9388 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9389 this.timelineScheduler.SystemResumed();
9392 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9394 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9396 TimeZoneInfo.ClearCachedData();
9398 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9400 if (curTimeOffset != prevTimeOffset)
9403 this.listCache?.PurgeCache();
9404 this.CurrentListView.Refresh();
9406 this.DispSelectedPost(forceupdate: true);
9409 this.timelineScheduler.Reset();
9412 private void TimelineRefreshEnableChange(bool isEnable)
9414 this.timelineScheduler.Enabled = isEnable;
9417 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9418 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9420 private async Task OpenUserAppointUrl()
9422 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9424 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9426 var post = this.CurrentPost;
9429 var xUrl = this.settings.Common.UserAppointUrl;
9430 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9432 var statusId = post.RetweetedId ?? post.StatusId;
9433 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9435 await MyCommon.OpenInBrowserAsync(this, xUrl);
9440 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9445 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9446 => await this.OpenUserAppointUrl();
9448 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9450 if (Form.ActiveForm == null)
9452 await this.InvokeAsync(() =>
9454 this.Visible = true;
9455 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9457 this.BringToFront();
9458 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9460 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9464 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9470 private void ReplaceAppName()
9472 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9473 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9476 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9477 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9479 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9481 if (e.KeyCode == Keys.Space)
9483 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9485 e.SuppressKeyPress = true;
9489 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9491 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9492 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9493 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9494 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9495 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9497 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9500 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9501 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9503 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9504 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9506 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9507 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9509 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9510 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9512 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9513 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9515 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9517 if (this.settings.Common.IconSize == iconSize) return;
9519 var oldIconCol = this.Use2ColumnsMode;
9521 this.settings.Common.IconSize = iconSize;
9522 this.ApplyListViewIconSize(iconSize);
9524 if (this.Use2ColumnsMode != oldIconCol)
9526 foreach (TabPage tp in this.ListTab.TabPages)
9528 this.ResetColumns((DetailsListView)tp.Tag);
9532 this.CurrentListView.Refresh();
9533 this.MarkSettingCommonModified();
9536 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9538 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9539 if (this.settings.Common.SortOrderLock == state) return;
9541 this.settings.Common.SortOrderLock = state;
9542 this.MarkSettingCommonModified();
9545 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9547 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9549 this.StatusLabelUrl.Text = e.StatusText;
9553 this.SetStatusLabelUrl();