1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.TwitterV2;
56 using OpenTween.Connection;
57 using OpenTween.MediaUploadServices;
58 using OpenTween.Models;
59 using OpenTween.OpenTweenCustomControl;
60 using OpenTween.Setting;
61 using OpenTween.Thumbnail;
65 public partial class TweenMain : OTBaseForm
69 /// <summary>画面サイズ</summary>
72 /// <summary>画面位置</summary>
75 /// <summary>区切り位置</summary>
78 /// <summary>発言欄区切り位置</summary>
81 /// <summary>プレビュー区切り位置</summary>
85 private bool initial; // true:起動時処理中
86 private bool initialLayout = true;
87 private bool ignoreConfigSave; // true:起動時処理中
89 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
92 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
93 private Point tabMouseDownPoint;
95 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
96 private string? rclickTabName;
98 private readonly object syncObject = new(); // ロック用
100 private const string DetailHtmlFormatHead =
101 """<head><meta http-equiv="X-UA-Compatible" content="IE=8">"""
102 + """<style type="text/css"><!-- """
103 + "body, p, pre {margin: 0;} "
104 + """body {font-family: "%FONT_FAMILY%", "Segoe UI Emoji", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} """
105 + "pre {font-family: inherit;} "
106 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
107 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
108 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
109 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
110 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
114 private const string DetailHtmlFormatTemplateMono =
115 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
117 private const string DetailHtmlFormatTemplateNormal =
118 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
120 private string detailHtmlFormatPreparedTemplate = null!;
122 private bool myStatusError = false;
123 private bool myStatusOnline = false;
124 private bool soundfileListup = false;
125 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
128 private readonly SettingManager settings;
131 private readonly Twitter tw;
134 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
138 /// <summary>検索画面インスタンス</summary>
139 internal SearchWordDialog SearchDialog = new();
141 private readonly OpenURL urlDialog = new();
143 /// <summary>@id補助</summary>
144 public AtIdSupplement AtIdSupl = null!;
146 /// <summary>Hashtag補助</summary>
147 public AtIdSupplement HashSupl = null!;
149 public HashtagManage HashMgr = null!;
152 private ThemeManager themeManager;
154 /// <summary>アイコン画像リスト</summary>
155 private readonly ImageCache iconCache;
157 private readonly IconAssetsManager iconAssets;
159 private readonly ThumbnailGenerator thumbGenerator;
161 /// <summary>発言履歴</summary>
162 private readonly List<StatusTextHistory> history = new();
164 /// <summary>発言履歴カレントインデックス</summary>
167 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169 /// <summary>リプライ先のステータスID・スクリーン名</summary>
170 private (PostId StatusId, string ScreenName)? inReplyTo = null;
173 private readonly List<DateTimeUtc> postTimestamps = new();
174 private readonly List<DateTimeUtc> favTimestamps = new();
177 private readonly StringFormat sfTab = new();
179 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 /// <summary>発言保持クラス</summary>
182 private readonly TabInformations statuses;
184 private TimelineListViewCache? listCache;
185 private TimelineListViewDrawer? listDrawer;
186 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
188 private bool isColumnChanged = false;
190 private const int MaxWorderThreads = 20;
191 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
192 private readonly CancellationTokenSource workerCts = new();
193 private readonly IProgress<string> workerProgress = null!;
195 private int unreadCounter = -1;
196 private int unreadAtCounter = -1;
198 private readonly string[] columnOrgText = new string[9];
199 private readonly string[] columnText = new string[9];
201 private bool doFavRetweetFlags = false;
203 //////////////////////////////////////////////////////////////////////////////////////////////////////////
205 private readonly TimelineScheduler timelineScheduler = new();
206 private readonly DebounceTimer selectionDebouncer;
207 private readonly DebounceTimer saveConfigDebouncer;
209 private readonly string recommendedStatusFooter;
210 private bool urlMultibyteSplit = false;
211 private bool preventSmsCommand = true;
214 private readonly record struct UrlUndo(
219 private List<UrlUndo>? urlUndoBuffer = null;
221 private readonly record struct ReplyChain(
227 /// <summary>[, ]でのリプライ移動の履歴</summary>
228 private Stack<ReplyChain>? replyChains;
230 /// <summary>ポスト選択履歴</summary>
231 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
233 public TabModel CurrentTab
234 => this.statuses.SelectedTab;
236 public string CurrentTabName
237 => this.statuses.SelectedTabName;
239 public TabPage CurrentTabPage
240 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
242 public DetailsListView CurrentListView
243 => (DetailsListView)this.CurrentTabPage.Tag;
245 public PostClass? CurrentPost
246 => this.CurrentTab.SelectedPost;
248 public bool Use2ColumnsMode
249 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
251 /// <summary>検索処理タイプ</summary>
252 internal enum SEARCHTYPE
259 private readonly record struct StatusTextHistory(
261 (PostId StatusId, string ScreenName)? InReplyTo = null
264 private readonly HookGlobalHotkey hookGlobalHotkey;
266 private void TweenMain_Activated(object sender, EventArgs e)
268 // 画面がアクティブになったら、発言欄の背景色戻す
269 if (this.StatusText.Focused)
271 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
275 private bool disposed = false;
278 /// 使用中のリソースをすべてクリーンアップします。
280 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
281 protected override void Dispose(bool disposing)
283 base.Dispose(disposing);
290 this.components?.Dispose();
293 this.SearchDialog.Dispose();
294 this.urlDialog.Dispose();
295 this.themeManager.Dispose();
296 this.sfTab.Dispose();
298 this.timelineScheduler.Dispose();
299 this.workerCts.Cancel();
300 this.thumbnailTokenSource?.Dispose();
302 this.hookGlobalHotkey.Dispose();
305 // 終了時にRemoveHandlerしておかないとメモリリークする
306 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
307 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
308 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
310 this.disposed = true;
313 private void InitColumns(ListView list, bool startup)
315 this.InitColumnText();
317 ColumnHeader[]? columns = null;
320 if (this.Use2ColumnsMode)
324 new ColumnHeader(), // アイコン
325 new ColumnHeader(), // 本文
328 columns[0].Text = this.columnText[0];
329 columns[1].Text = this.columnText[2];
333 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
335 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
336 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
337 columns[0].DisplayIndex = 0;
338 columns[1].DisplayIndex = 1;
343 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
345 columns[idx].Width = curListColumn.Width;
346 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
355 new ColumnHeader(), // アイコン
356 new ColumnHeader(), // ニックネーム
357 new ColumnHeader(), // 本文
358 new ColumnHeader(), // 日付
359 new ColumnHeader(), // ユーザID
360 new ColumnHeader(), // 未読
361 new ColumnHeader(), // マーク&プロテクト
362 new ColumnHeader(), // ソース
365 foreach (var i in Enumerable.Range(0, columns.Length))
366 columns[i].Text = this.columnText[i];
370 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
372 foreach (var (column, index) in columns.WithIndex())
374 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
375 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
381 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
383 columns[idx].Width = curListColumn.Width;
384 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
390 list.Columns.AddRange(columns);
398 foreach (var column in columns)
404 private void InitColumnText()
406 this.columnText[0] = "";
407 this.columnText[1] = Properties.Resources.AddNewTabText2;
408 this.columnText[2] = Properties.Resources.AddNewTabText3;
409 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
410 this.columnText[4] = Properties.Resources.AddNewTabText5;
411 this.columnText[5] = "";
412 this.columnText[6] = "";
413 this.columnText[7] = "Source";
415 this.columnOrgText[0] = "";
416 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
417 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
418 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
419 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
420 this.columnOrgText[5] = "";
421 this.columnOrgText[6] = "";
422 this.columnOrgText[7] = "Source";
424 var c = this.statuses.SortMode switch
426 ComparerMode.Nickname => 1, // ニックネーム
427 ComparerMode.Data => 2, // 本文
428 ComparerMode.Id => 3, // 時刻=発言Id
429 ComparerMode.Name => 4, // 名前
430 ComparerMode.Source => 7, // Source
434 if (this.Use2ColumnsMode)
436 if (this.statuses.SortOrder == SortOrder.Descending)
438 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
439 this.columnText[2] = this.columnOrgText[2] + "▾";
443 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
444 this.columnText[2] = this.columnOrgText[2] + "▴";
449 if (this.statuses.SortOrder == SortOrder.Descending)
451 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
452 this.columnText[c] = this.columnOrgText[c] + "▾";
456 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
457 this.columnText[c] = this.columnOrgText[c] + "▴";
463 SettingManager settingManager,
464 TabInformations tabInfo,
466 ImageCache imageCache,
467 IconAssetsManager iconAssets,
468 ThumbnailGenerator thumbGenerator
471 this.settings = settingManager;
472 this.statuses = tabInfo;
474 this.iconCache = imageCache;
475 this.iconAssets = iconAssets;
476 this.thumbGenerator = thumbGenerator;
478 this.InitializeComponent();
480 if (!this.DesignMode)
482 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
483 this.StatusText.Dock = DockStyle.Fill;
486 this.hookGlobalHotkey = new HookGlobalHotkey(this);
488 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
489 this.gh.NotifyClicked += this.GrowlHelper_Callback;
491 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
492 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
494 this.ImageSelector.Visible = false;
495 this.ImageSelector.Enabled = false;
496 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
498 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
500 this.ReplaceAppName();
501 this.InitializeShortcuts();
503 this.ignoreConfigSave = true;
504 this.Visible = false;
506 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
508 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
510 Regex.CacheSize = 100;
513 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
514 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
515 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
517 // <<<<<<<<<設定関連>>>>>>>>>
521 // 現在の DPI と設定保存時の DPI との比を取得する
522 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
525 var account = this.settings.Common.SelectedAccount;
527 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
529 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
533 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
534 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
536 // アクセストークンが有効であるか確認する
537 // ここが Twitter API への最初のアクセスになるようにすること
540 this.tw.VerifyCredentials();
542 catch (WebApiException ex)
546 string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
547 ApplicationSettings.ApplicationName,
548 MessageBoxButtons.OK,
549 MessageBoxIcon.Warning);
553 // プロキシ設定等の通信まわりの初期化が済んでから処理する
554 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
555 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
556 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
557 imgazyobizinet.AutoUpdate = true;
559 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
562 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
563 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
565 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
568 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
569 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
570 this.HashMgr = new HashtagManage(this.HashSupl,
571 this.settings.Common.HashTags.ToArray(),
572 this.settings.Common.HashSelected,
573 this.settings.Common.HashIsPermanent,
574 this.settings.Common.HashIsHead,
575 this.settings.Common.HashIsNotAddToAtReply);
576 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
579 this.themeManager = new(this.settings.Local);
580 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
582 // StringFormatオブジェクトへの事前設定
583 this.sfTab.Alignment = StringAlignment.Center;
584 this.sfTab.LineAlignment = StringAlignment.Center;
586 this.InitDetailHtmlFormat();
587 this.tweetDetailsView.ClearPostBrowser();
589 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
591 this.history.Add(new StatusTextHistory(""));
593 this.inReplyTo = null;
596 this.SearchDialog.Owner = this;
597 this.urlDialog.Owner = this;
600 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
601 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
603 // 新着取得時のリストスクロールをするか。trueならスクロールしない
604 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
605 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
607 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
608 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
611 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
612 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
613 this.myLoc = this.settings.Local.FormLocation;
615 if (this.WindowState != FormWindowState.Minimized)
617 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
618 var outOfScreen = true;
619 if (Screen.AllScreens.Length == 1) // ハングするとの報告
621 foreach (var scr in Screen.AllScreens)
623 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
631 this.myLoc = new Point(0, 0);
633 this.DesktopLocation = this.myLoc;
635 this.TopMost = this.settings.Common.AlwaysTop;
636 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
637 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
638 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
640 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
641 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
643 this.StatusText.Font = this.themeManager.FontInputFont;
644 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
646 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
647 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
648 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
650 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
651 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
653 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
654 if (this.settings.Common.UnreadManage == false)
656 this.ReadedStripMenuItem.Enabled = false;
657 this.UnreadStripMenuItem.Enabled = false;
660 // リンク先URL表示部の初期化(画面左下)
661 this.StatusLabelUrl.Text = "";
663 this.StatusLabel.Text = "";
664 this.StatusLabel.AutoToolTip = false;
665 this.StatusLabel.ToolTipText = "";
667 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
669 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
670 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
671 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
672 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
674 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
675 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
676 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
677 this.SplitContainer2.Panel2.AccessibleName = "";
679 ////////////////////////////////////////////////////////////////////////////////
680 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
681 var mode = this.settings.Common.SortColumn switch
683 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
684 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
685 1 => ComparerMode.Nickname, // ニックネーム
686 2 => ComparerMode.Data, // 本文
687 3 => ComparerMode.Id, // 時刻=発言Id
688 4 => ComparerMode.Name, // 名前
689 7 => ComparerMode.Source, // Source
690 _ => ComparerMode.Id,
692 this.statuses.SetSortMode(mode, sortOrder);
693 ////////////////////////////////////////////////////////////////////////////////
695 this.ApplyListViewIconSize(this.settings.Common.IconSize);
697 // <<<<<<<<タブ関連>>>>>>>
698 foreach (var tab in this.statuses.Tabs)
700 if (!this.AddNewTab(tab, startup: true))
701 throw new TabException(Properties.Resources.TweenMain_LoadText1);
704 this.ListTabSelect(this.ListTab.SelectedTab);
707 this.SetTabAlignment();
709 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
710 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
712 if (this.settings.Common.TabIconDisp)
714 this.ListTab.DrawMode = TabDrawMode.Normal;
718 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
719 this.ListTab.DrawItem += this.ListTab_DrawItem;
720 this.ListTab.ImageList = null;
723 if (this.settings.Common.HotkeyEnabled)
726 var modKey = HookGlobalHotkey.ModKeys.None;
727 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
728 modKey |= HookGlobalHotkey.ModKeys.Alt;
729 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
730 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
731 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
732 modKey |= HookGlobalHotkey.ModKeys.Shift;
733 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
734 modKey |= HookGlobalHotkey.ModKeys.Win;
736 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
739 if (this.settings.Common.IsUseNotifyGrowl)
740 this.gh.RegisterGrowl();
742 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
744 this.SetMainWindowTitle();
745 this.SetNotifyIconText();
747 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
754 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
755 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
756 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
757 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
758 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
759 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
760 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
762 this.DoGetFollowersMenu(),
763 this.RefreshBlockIdsAsync(),
764 this.RefreshMuteUserIdsAsync(),
765 this.RefreshNoRetweetIdsAsync(),
766 this.RefreshTwitterConfigurationAsync(),
768 this.RefreshTimelineScheduler();
770 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
771 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
774 this.TimerRefreshIcon.Interval = 200;
775 this.TimerRefreshIcon.Enabled = false;
777 this.ignoreConfigSave = false;
778 this.TweenMain_Resize(this, EventArgs.Empty);
780 if (this.settings.IsFirstRun)
782 // 初回起動時だけ右下のメニューを目立たせる
783 this.HashStripSplitButton.ShowDropDown();
787 private void InitDetailHtmlFormat()
789 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
791 static string ColorToRGBString(Color color)
792 => $"{color.R},{color.G},{color.B}";
794 this.detailHtmlFormatPreparedTemplate = htmlTemplate
795 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
796 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
797 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
798 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
799 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
800 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
803 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
808 txt = this.statuses.Tabs[e.Index].TabName;
815 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
816 if (e.State == DrawItemState.Selected)
818 e.DrawFocusRectangle();
823 if (this.statuses.Tabs[txt].UnreadCount > 0)
826 fore = System.Drawing.SystemBrushes.ControlText;
830 fore = System.Drawing.SystemBrushes.ControlText;
832 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
835 private void LoadConfig()
837 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
838 this.statuses.AddDefaultTabs();
841 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
843 this.RefreshTimelineScheduler();
846 private void RefreshTimelineScheduler()
848 static TimeSpan IntervalSecondsOrDisabled(int seconds)
849 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
851 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
852 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
853 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
854 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
855 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
856 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
857 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
858 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
860 this.timelineScheduler.RefreshSchedule();
863 private void MarkSettingCommonModified()
865 if (this.saveConfigDebouncer == null)
868 this.ModifySettingCommon = true;
869 _ = this.saveConfigDebouncer.Call();
872 private void MarkSettingLocalModified()
874 if (this.saveConfigDebouncer == null)
877 this.ModifySettingLocal = true;
878 _ = this.saveConfigDebouncer.Call();
881 internal void MarkSettingAtIdModified()
883 if (this.saveConfigDebouncer == null)
886 this.ModifySettingAtId = true;
887 _ = this.saveConfigDebouncer.Call();
890 private void RefreshTimeline()
892 var curListView = this.CurrentListView;
894 // 現在表示中のタブのスクロール位置を退避
895 var currentListViewState = this.listViewState[this.CurrentTabName];
896 currentListViewState.Save(this.ListLockMenuItem.Checked);
900 addCount = this.statuses.SubmitUpdate(
903 out var newMentionOrDm,
906 if (MyCommon.EndingFlag) return;
909 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
911 using (ControlTransaction.Update(curListView))
913 this.listCache.PurgeCache();
914 this.listCache.UpdateListSize();
917 currentListViewState.RestoreSelection();
923 if (this.settings.Common.TabIconDisp)
925 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
927 var tabPage = this.ListTab.TabPages[index];
928 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
929 tabPage.ImageIndex = 0; // 未読アイコン
934 this.ListTab.Refresh();
939 currentListViewState.RestoreScroll();
942 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
944 this.SetMainWindowTitle();
945 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
947 this.HashSupl.AddRangeItem(this.tw.GetHashList());
950 private bool BalloonRequired()
955 if (NativeMethods.IsScreenSaverRunning())
959 if (!this.NewPostPopMenuItem.Checked)
962 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
963 if (this.settings.Common.LimitBalloon)
965 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
972 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
974 if (this.settings.Common.ReadOwnPost)
976 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
981 if (this.BalloonRequired())
983 if (notifyPosts != null && notifyPosts.Length > 0)
985 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
986 if (this.settings.Common.IsUseNotifyGrowl)
988 var sb = new StringBuilder();
992 foreach (var post in notifyPosts)
994 if (!(notifyPosts.Length > 3))
1000 if (post.IsReply && !post.IsExcludeReply) reply = true;
1001 if (post.IsDm) dm = true;
1002 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1003 switch (this.settings.Common.NameBalloon)
1005 case MyCommon.NameBalloonEnum.UserID:
1006 sb.Append(post.ScreenName).Append(" : ");
1008 case MyCommon.NameBalloonEnum.NickName:
1009 sb.Append(post.Nickname).Append(" : ");
1012 sb.Append(post.TextFromApi);
1013 if (notifyPosts.Length > 3)
1015 if (notifyPosts.Last() != post) continue;
1018 var title = new StringBuilder();
1019 GrowlHelper.NotifyType nt;
1020 if (this.settings.Common.DispUsername)
1022 title.Append(this.tw.Username);
1023 title.Append(" - ");
1028 title.Append(ApplicationSettings.ApplicationName);
1029 title.Append(" [DM] ");
1030 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1031 nt = GrowlHelper.NotifyType.DirectMessage;
1035 title.Append(ApplicationSettings.ApplicationName);
1036 title.Append(" [Reply!] ");
1037 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1038 nt = GrowlHelper.NotifyType.Reply;
1042 title.Append(ApplicationSettings.ApplicationName);
1044 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1045 nt = GrowlHelper.NotifyType.Notify;
1047 var bText = sb.ToString();
1048 if (MyCommon.IsNullOrEmpty(bText)) return;
1050 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1051 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
1056 var sb = new StringBuilder();
1059 foreach (var post in notifyPosts)
1061 if (post.IsReply && !post.IsExcludeReply) reply = true;
1062 if (post.IsDm) dm = true;
1063 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1064 switch (this.settings.Common.NameBalloon)
1066 case MyCommon.NameBalloonEnum.UserID:
1067 sb.Append(post.ScreenName).Append(" : ");
1069 case MyCommon.NameBalloonEnum.NickName:
1070 sb.Append(post.Nickname).Append(" : ");
1073 sb.Append(post.TextFromApi);
1076 var title = new StringBuilder();
1078 if (this.settings.Common.DispUsername)
1080 title.Append(this.tw.Username);
1081 title.Append(" - ");
1086 ntIcon = ToolTipIcon.Warning;
1087 title.Append(ApplicationSettings.ApplicationName);
1088 title.Append(" [DM] ");
1089 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1093 ntIcon = ToolTipIcon.Warning;
1094 title.Append(ApplicationSettings.ApplicationName);
1095 title.Append(" [Reply!] ");
1096 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1100 ntIcon = ToolTipIcon.Info;
1101 title.Append(ApplicationSettings.ApplicationName);
1103 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1105 var bText = sb.ToString();
1106 if (MyCommon.IsNullOrEmpty(bText)) return;
1108 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1109 this.NotifyIcon1.BalloonTipText = bText;
1110 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1111 this.NotifyIcon1.ShowBalloonTip(500);
1117 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1121 var dir = Application.StartupPath;
1122 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1124 dir = Path.Combine(dir, "Sounds");
1126 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1134 // mentions新着時に画面ブリンク
1135 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1137 NativeMethods.FlashMyWindow(this.Handle, 3);
1141 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1143 var listView = this.CurrentListView;
1144 if (listView != sender)
1147 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1148 this.CurrentTab.SelectPosts(indices);
1150 if (indices.Length != 1)
1153 var index = indices[0];
1154 if (index > listView.VirtualListSize - 1) return;
1156 this.PushSelectPostChain();
1158 var post = this.CurrentPost!;
1159 this.statuses.SetReadAllTab(post.StatusId, read: true);
1161 this.listCache?.RefreshStyle();
1162 await this.selectionDebouncer.Call();
1165 private void StatusTextHistoryBack()
1167 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1168 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1171 if (this.hisIdx < 0)
1174 var historyItem = this.history[this.hisIdx];
1175 this.inReplyTo = historyItem.InReplyTo;
1176 this.StatusText.Text = historyItem.Status;
1177 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1180 private void StatusTextHistoryForward()
1182 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1183 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1186 if (this.hisIdx > this.history.Count - 1)
1187 this.hisIdx = this.history.Count - 1;
1189 var historyItem = this.history[this.hisIdx];
1190 this.inReplyTo = historyItem.InReplyTo;
1191 this.StatusText.Text = historyItem.Status;
1192 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1195 private async void PostButton_Click(object sender, EventArgs e)
1197 if (this.StatusText.Text.Trim().Length == 0)
1199 if (!this.ImageSelector.Enabled)
1201 await this.DoRefresh();
1206 var currentPost = this.CurrentPost;
1207 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1209 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1211 MessageBoxButtons.YesNoCancel,
1212 MessageBoxIcon.Question);
1215 case DialogResult.Yes:
1216 this.StatusText.Text = "";
1217 await this.DoReTweetOfficial(false);
1219 case DialogResult.Cancel:
1224 if (TextContainsOnlyMentions(this.StatusText.Text))
1226 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1227 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1229 if (ret != DialogResult.OK)
1233 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1235 if (this.settings.Common.Nicoms)
1237 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1238 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1241 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1242 this.CheckReplyTo(this.StatusText.Text);
1244 var status = new PostStatusParams();
1246 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1247 if (this.GetRestStatusCount(statusTextCompat) >= 0)
1249 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1250 // 収まる場合はこれらのオプションを使用せずに投稿する
1251 status.Text = statusTextCompat;
1252 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1256 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1257 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1259 status.AttachmentUrl = attachmentUrl;
1261 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1263 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1264 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1266 status.AutoPopulateReplyMetadata = true;
1268 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1269 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1274 if (this.GetRestStatusCount(status.Text) < 0)
1276 // 文字数制限を超えているが強制的に投稿するか
1277 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1278 if (ret != DialogResult.OK)
1282 IMediaUploadService? uploadService = null;
1283 IMediaItem[]? uploadItems = null;
1284 if (this.ImageSelector.Visible)
1287 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1290 this.ImageSelector.EndSelection();
1291 uploadService = this.ImageSelector.Model.GetService(serviceName);
1294 this.inReplyTo = null;
1295 this.StatusText.Text = "";
1296 this.history.Add(new StatusTextHistory(""));
1297 this.hisIdx = this.history.Count - 1;
1298 if (!this.settings.Common.FocusLockToStatusText)
1299 this.CurrentListView.Focus();
1300 this.urlUndoBuffer = null;
1301 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1304 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1306 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1307 await MyCommon.OpenInBrowserAsync(this, tmp);
1310 await this.PostMessageAsync(status, uploadService, uploadItems);
1313 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1315 MyCommon.EndingFlag = true;
1319 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1321 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1323 // _endingFlag=false:フォームの×ボタン
1325 this.Visible = false;
1329 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1330 this.ignoreConfigSave = true;
1331 MyCommon.EndingFlag = true;
1332 this.timelineScheduler.Enabled = false;
1333 this.TimerRefreshIcon.Enabled = false;
1337 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1339 this.Visible = true;
1340 if (this.WindowState == FormWindowState.Minimized)
1342 this.WindowState = FormWindowState.Normal;
1345 this.BringToFront();
1348 private static int errorCount = 0;
1350 private static bool CheckAccountValid()
1352 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1358 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1367 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1368 private Task RefreshTabAsync<T>()
1370 => this.RefreshTabAsync<T>(backward: false);
1372 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1373 private Task RefreshTabAsync<T>(bool backward)
1377 from tab in this.statuses.GetTabsByType<T>()
1378 select this.RefreshTabAsync(tab, backward);
1380 return Task.WhenAll(loadTasks);
1383 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1384 private Task RefreshTabAsync(TabModel tab)
1385 => this.RefreshTabAsync(tab, backward: false);
1387 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1388 private async Task RefreshTabAsync(TabModel tab, bool backward)
1390 await this.workerSemaphore.WaitAsync();
1394 this.RefreshTasktrayIcon();
1395 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1397 catch (WebApiException ex)
1399 this.myStatusError = true;
1400 var tabType = tab switch
1402 HomeTabModel => "GetTimeline",
1403 MentionsTabModel => "GetTimeline",
1404 DirectMessagesTabModel => "GetDirectMessage",
1405 FavoritesTabModel => "GetFavorites",
1406 PublicSearchTabModel => "GetSearch",
1407 UserTimelineTabModel => "GetUserTimeline",
1408 ListTimelineTabModel => "GetListStatus",
1409 RelatedPostsTabModel => "GetRelatedTweets",
1410 _ => tab.GetType().Name.Replace("Model", ""),
1412 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1416 this.RefreshTimeline();
1417 this.workerSemaphore.Release();
1421 private async Task FavAddAsync(PostId statusId, TabModel tab)
1423 await this.workerSemaphore.WaitAsync();
1427 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1429 this.RefreshTasktrayIcon();
1430 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1432 catch (WebApiException ex)
1434 this.myStatusError = true;
1435 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1439 this.workerSemaphore.Release();
1443 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1445 if (ct.IsCancellationRequested)
1448 if (!CheckAccountValid())
1449 throw new WebApiException("Auth error. Check your account");
1451 if (!tab.Posts.TryGetValue(statusId, out var post))
1457 await Task.Run(async () =>
1459 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1463 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1466 await this.tw.Api.FavoritesCreate(twitterStatusId)
1468 .ConfigureAwait(false);
1470 catch (TwitterApiException ex)
1471 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1473 // エラーコード 139 のみの場合は成功と見なす
1476 if (this.settings.Common.RestrictFavCheck)
1478 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1479 .ConfigureAwait(false);
1481 if (status.Favorited != true)
1482 throw new WebApiException("NG(Restricted?)");
1485 this.favTimestamps.Add(DateTimeUtc.Now);
1488 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1490 postTl.IsFav = true;
1492 var favTab = this.statuses.FavoriteTab;
1493 favTab.AddPostQueue(postTl);
1496 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1497 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1499 if (tb.Contains(statusId))
1500 tb.Posts[statusId].IsFav = true;
1503 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1505 catch (WebApiException)
1507 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1512 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1513 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1515 if (this.favTimestamps[i] < oneHour)
1516 this.favTimestamps.RemoveAt(i);
1519 this.statuses.DistributePosts();
1522 if (ct.IsCancellationRequested)
1525 this.RefreshTimeline();
1527 if (this.CurrentTabName == tab.TabName)
1529 using (ControlTransaction.Update(this.CurrentListView))
1531 var idx = tab.IndexOf(statusId);
1533 this.listCache?.RefreshStyle(idx);
1536 var currentPost = this.CurrentPost;
1537 if (currentPost != null && statusId == currentPost.StatusId)
1538 this.DispSelectedPost(true); // 選択アイテム再表示
1542 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1544 await this.workerSemaphore.WaitAsync();
1548 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1550 this.RefreshTasktrayIcon();
1551 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1553 catch (WebApiException ex)
1555 this.myStatusError = true;
1556 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1560 this.workerSemaphore.Release();
1564 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1566 if (ct.IsCancellationRequested)
1569 if (!CheckAccountValid())
1570 throw new WebApiException("Auth error. Check your account");
1572 var successIds = new List<PostId>();
1574 await Task.Run(async () =>
1578 var failedCount = 0;
1579 foreach (var statusId in statusIds)
1583 var post = tab.Posts[statusId];
1585 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1590 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1594 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1596 .ConfigureAwait(false);
1598 catch (WebApiException)
1604 successIds.Add(statusId);
1605 post.IsFav = false; // リスト再描画必要
1607 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1608 tabinfoPost.IsFav = false;
1610 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1611 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1613 if (tb.Contains(statusId))
1614 tb.Posts[statusId].IsFav = false;
1619 if (ct.IsCancellationRequested)
1622 var favTab = this.statuses.FavoriteTab;
1623 foreach (var statusId in successIds)
1625 // ツイートが削除された訳ではないので IsDeleted はセットしない
1626 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1629 this.RefreshTimeline();
1631 if (this.CurrentTabName == tab.TabName)
1633 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1639 using (ControlTransaction.Update(this.CurrentListView))
1641 foreach (var statusId in successIds)
1643 var idx = tab.IndexOf(statusId);
1645 this.listCache?.RefreshStyle(idx);
1649 var currentPost = this.CurrentPost;
1650 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1651 this.DispSelectedPost(true); // 選択アイテム再表示
1656 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1658 await this.workerSemaphore.WaitAsync();
1662 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1664 this.RefreshTasktrayIcon();
1665 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1667 catch (WebApiException ex)
1669 this.myStatusError = true;
1670 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1674 this.workerSemaphore.Release();
1678 private async Task PostMessageAsyncInternal(
1679 IProgress<string> p,
1680 CancellationToken ct,
1681 PostStatusParams postParams,
1682 IMediaUploadService? uploadService,
1683 IMediaItem[]? uploadItems)
1685 if (ct.IsCancellationRequested)
1688 if (!CheckAccountValid())
1689 throw new WebApiException("Auth error. Check your account");
1691 p.Report("Posting...");
1693 PostClass? post = null;
1698 await Task.Run(async () =>
1700 var postParamsWithMedia = postParams;
1702 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1704 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1705 .ConfigureAwait(false);
1708 post = await this.tw.PostStatus(postParamsWithMedia)
1709 .ConfigureAwait(false);
1712 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1714 catch (WebApiException ex)
1716 // 処理は中断せずエラーの表示のみ行う
1717 errMsg = $"Err:{ex.Message}(PostMessage)";
1719 this.myStatusError = true;
1721 catch (UnauthorizedAccessException ex)
1723 // アップロード対象のファイルが開けなかった場合など
1724 errMsg = $"Err:{ex.Message}(PostMessage)";
1726 this.myStatusError = true;
1730 // 使い終わった MediaItem は破棄する
1731 if (uploadItems != null)
1733 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1735 disposableItem.Dispose();
1740 if (ct.IsCancellationRequested)
1743 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1744 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1745 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1747 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1749 var ret = MessageBox.Show(
1751 "Failed to update status",
1752 MessageBoxButtons.RetryCancel,
1753 MessageBoxIcon.Question);
1755 if (ret == DialogResult.Retry)
1757 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1761 this.StatusTextHistoryBack();
1762 this.StatusText.Focus();
1764 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1765 if (this.settings.Common.FocusLockToStatusText)
1766 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1771 this.postTimestamps.Add(DateTimeUtc.Now);
1773 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1774 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1776 if (this.postTimestamps[i] < oneHour)
1777 this.postTimestamps.RemoveAt(i);
1780 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1782 this.HashMgr.ClearHashtag();
1783 this.HashStripSplitButton.Text = "#[-]";
1784 this.HashTogglePullDownMenuItem.Checked = false;
1785 this.HashToggleMenuItem.Checked = false;
1788 this.SetMainWindowTitle();
1793 this.statuses.AddPost(post);
1794 this.statuses.DistributePosts();
1795 this.RefreshTimeline();
1798 if (this.settings.Common.PostAndGet)
1799 await this.RefreshTabAsync<HomeTabModel>();
1802 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1804 await this.workerSemaphore.WaitAsync();
1808 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1810 this.RefreshTasktrayIcon();
1811 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1813 catch (WebApiException ex)
1815 this.myStatusError = true;
1816 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1820 this.workerSemaphore.Release();
1824 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1826 if (ct.IsCancellationRequested)
1829 if (!CheckAccountValid())
1830 throw new WebApiException("Auth error. Check your account");
1833 if (!this.settings.Common.UnreadManage)
1836 read = this.initial && this.settings.Common.Read;
1838 p.Report("Posting...");
1840 var posts = new List<PostClass>();
1842 await Task.Run(async () =>
1844 foreach (var statusId in statusIds)
1846 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1847 if (post != null) posts.Add(post);
1851 if (ct.IsCancellationRequested)
1854 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1856 this.postTimestamps.Add(DateTimeUtc.Now);
1858 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1859 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1861 if (this.postTimestamps[i] < oneHour)
1862 this.postTimestamps.RemoveAt(i);
1865 // 自分のRTはTLの更新では取得できない場合があるので、
1866 // 投稿時取得の有無に関わらず追加しておく
1867 posts.ForEach(post => this.statuses.AddPost(post));
1869 if (this.settings.Common.PostAndGet)
1871 await this.RefreshTabAsync<HomeTabModel>();
1875 this.statuses.DistributePosts();
1876 this.RefreshTimeline();
1880 private async Task RefreshFollowerIdsAsync()
1882 await this.workerSemaphore.WaitAsync();
1886 this.RefreshTasktrayIcon();
1887 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1889 await this.tw.RefreshFollowerIds();
1891 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1893 this.RefreshTimeline();
1894 this.listCache?.PurgeCache();
1895 this.CurrentListView.Refresh();
1897 catch (WebApiException ex)
1899 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1903 this.workerSemaphore.Release();
1907 private async Task RefreshNoRetweetIdsAsync()
1909 await this.workerSemaphore.WaitAsync();
1913 this.RefreshTasktrayIcon();
1914 await this.tw.RefreshNoRetweetIds();
1916 this.StatusLabel.Text = "NoRetweetIds refreshed";
1918 catch (WebApiException ex)
1920 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1924 this.workerSemaphore.Release();
1928 private async Task RefreshBlockIdsAsync()
1930 await this.workerSemaphore.WaitAsync();
1934 this.RefreshTasktrayIcon();
1935 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1937 await this.tw.RefreshBlockIds();
1939 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1941 catch (WebApiException ex)
1943 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1947 this.workerSemaphore.Release();
1951 private async Task RefreshTwitterConfigurationAsync()
1953 await this.workerSemaphore.WaitAsync();
1957 this.RefreshTasktrayIcon();
1958 await this.tw.RefreshConfiguration();
1960 if (this.tw.Configuration.PhotoSizeLimit != 0)
1962 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1964 service.UpdateTwitterConfiguration(this.tw.Configuration);
1968 this.listCache?.PurgeCache();
1969 this.CurrentListView.Refresh();
1971 catch (WebApiException ex)
1973 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1977 this.workerSemaphore.Release();
1981 private async Task RefreshMuteUserIdsAsync()
1983 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1987 await this.tw.RefreshMuteUserIdsAsync();
1989 catch (WebApiException ex)
1991 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1995 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1998 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2000 if (e.Button == MouseButtons.Left)
2002 this.Visible = true;
2003 if (this.WindowState == FormWindowState.Minimized)
2005 this.WindowState = this.formWindowState;
2008 this.BringToFront();
2012 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2013 => await this.ListItemDoubleClickAction();
2015 private async Task ListItemDoubleClickAction()
2017 switch (this.settings.Common.ListDoubleClickAction)
2019 case MyCommon.ListItemDoubleClickActionType.Reply:
2020 this.MakeReplyText();
2022 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2023 this.MakeReplyText(atAll: true);
2025 case MyCommon.ListItemDoubleClickActionType.Favorite:
2026 await this.FavoriteChange(true);
2028 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2029 var post = this.CurrentPost;
2031 await this.ShowUserStatus(post.ScreenName, false);
2033 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2034 await this.ShowUserTimeline();
2036 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2037 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2039 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2040 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2042 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2043 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2045 case MyCommon.ListItemDoubleClickActionType.None:
2052 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2053 => await this.FavoriteChange(true);
2055 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2056 => await this.FavoriteChange(false);
2058 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2059 => await this.FavoritesRetweetOfficial();
2061 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2062 => await this.FavoritesRetweetUnofficial();
2064 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2066 var tab = this.CurrentTab;
2067 var posts = tab.SelectedPosts;
2069 // trueでFavAdd,falseでFavRemove
2070 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2071 || !this.ExistCurrentPost) return;
2073 if (posts.Length > 1)
2078 // https://support.twitter.com/articles/76915#favoriting
2079 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2080 this.doFavRetweetFlags = false;
2085 if (multiFavoriteChangeDialogEnable)
2087 var confirm = MessageBox.Show(
2088 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2089 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2090 MessageBoxButtons.OKCancel,
2091 MessageBoxIcon.Question);
2093 if (confirm == DialogResult.Cancel)
2101 var selectedPost = posts.Single();
2102 if (selectedPost.IsFav)
2104 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2108 await this.FavAddAsync(selectedPost.StatusId, tab);
2112 var selectedPosts = posts.Where(x => x.IsFav);
2113 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2114 if (statusIds.Length == 0)
2116 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2120 await this.FavRemoveAsync(statusIds, tab);
2124 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2126 var post = this.CurrentPost;
2128 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2130 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2133 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2135 if ((!this.initialLayout) && this.Visible)
2137 if (this.WindowState == FormWindowState.Normal)
2139 this.mySize = this.ClientSize;
2140 this.mySpDis = this.SplitContainer1.SplitterDistance;
2141 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2142 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2143 this.MarkSettingLocalModified();
2148 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2150 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2151 if (comparerMode == null)
2154 this.SetSortColumn(comparerMode.Value);
2158 /// 列インデックスからソートを行う ComparerMode を求める
2160 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2161 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2162 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2164 if (this.Use2ColumnsMode)
2165 return ComparerMode.Id;
2167 return columnIndex switch
2169 1 => ComparerMode.Nickname, // ニックネーム
2170 2 => ComparerMode.Data, // 本文
2171 3 => ComparerMode.Id, // 時刻=発言Id
2172 4 => ComparerMode.Name, // 名前
2173 7 => ComparerMode.Source, // Source
2174 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2179 /// 発言一覧の指定した位置の列でソートする
2181 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2182 private void SetSortColumnByDisplayIndex(int columnIndex)
2184 // 表示上の列の位置から ColumnHeader を求める
2185 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2186 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2191 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2192 if (comparerMode == null)
2195 this.SetSortColumn(comparerMode.Value);
2199 /// 発言一覧の最後列の項目でソートする
2201 private void SetSortLastColumn()
2203 // 表示上の最後列にある ColumnHeader を求める
2204 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2205 .OrderByDescending(x => x.DisplayIndex)
2208 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2209 if (comparerMode == null)
2212 this.SetSortColumn(comparerMode.Value);
2216 /// 発言一覧を指定された ComparerMode に基づいてソートする
2218 private void SetSortColumn(ComparerMode sortColumn)
2220 if (this.settings.Common.SortOrderLock)
2223 this.statuses.ToggleSortOrder(sortColumn);
2224 this.InitColumnText();
2226 var list = this.CurrentListView;
2227 if (this.Use2ColumnsMode)
2229 list.Columns[0].Text = this.columnText[0];
2230 list.Columns[1].Text = this.columnText[2];
2234 for (var i = 0; i <= 7; i++)
2236 list.Columns[i].Text = this.columnText[i];
2240 this.listCache?.PurgeCache();
2242 var tab = this.CurrentTab;
2243 var post = this.CurrentPost;
2244 if (tab.AllCount > 0 && post != null)
2246 var idx = tab.IndexOf(post.StatusId);
2249 this.SelectListItem(list, idx);
2250 list.EnsureVisible(idx);
2255 this.MarkSettingCommonModified();
2258 private void TweenMain_LocationChanged(object sender, EventArgs e)
2260 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2262 this.myLoc = this.DesktopLocation;
2263 this.MarkSettingLocalModified();
2267 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2269 var post = this.CurrentPost;
2270 if (!this.ExistCurrentPost)
2272 this.ReplyStripMenuItem.Enabled = false;
2273 this.ReplyAllStripMenuItem.Enabled = false;
2274 this.DMStripMenuItem.Enabled = false;
2275 this.TabMenuItem.Enabled = false;
2276 this.IDRuleMenuItem.Enabled = false;
2277 this.SourceRuleMenuItem.Enabled = false;
2278 this.ReadedStripMenuItem.Enabled = false;
2279 this.UnreadStripMenuItem.Enabled = false;
2280 this.AuthorContextMenuItem.Visible = false;
2281 this.RetweetedByContextMenuItem.Visible = false;
2285 this.ReplyStripMenuItem.Enabled = true;
2286 this.ReplyAllStripMenuItem.Enabled = true;
2287 this.DMStripMenuItem.Enabled = true;
2288 this.TabMenuItem.Enabled = true;
2289 this.IDRuleMenuItem.Enabled = true;
2290 this.SourceRuleMenuItem.Enabled = true;
2291 this.ReadedStripMenuItem.Enabled = true;
2292 this.UnreadStripMenuItem.Enabled = true;
2293 this.AuthorContextMenuItem.Visible = true;
2294 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2295 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2296 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2298 var tab = this.CurrentTab;
2299 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2301 this.FavAddToolStripMenuItem.Enabled = false;
2302 this.FavRemoveToolStripMenuItem.Enabled = false;
2303 this.StatusOpenMenuItem.Enabled = false;
2304 this.ShowRelatedStatusesMenuItem.Enabled = false;
2306 this.ReTweetStripMenuItem.Enabled = false;
2307 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2308 this.QuoteStripMenuItem.Enabled = false;
2309 this.FavoriteRetweetContextMenu.Enabled = false;
2310 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2314 this.FavAddToolStripMenuItem.Enabled = true;
2315 this.FavRemoveToolStripMenuItem.Enabled = true;
2316 this.StatusOpenMenuItem.Enabled = true;
2317 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2319 if (!post.CanRetweetBy(this.tw.UserId))
2321 this.ReTweetStripMenuItem.Enabled = false;
2322 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2323 this.QuoteStripMenuItem.Enabled = false;
2324 this.FavoriteRetweetContextMenu.Enabled = false;
2325 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2329 this.ReTweetStripMenuItem.Enabled = true;
2330 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2331 this.QuoteStripMenuItem.Enabled = true;
2332 this.FavoriteRetweetContextMenu.Enabled = true;
2333 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2337 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2339 this.RepliedStatusOpenMenuItem.Enabled = false;
2343 this.RepliedStatusOpenMenuItem.Enabled = true;
2346 if (this.ExistCurrentPost && post != null)
2348 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2349 if (post.RetweetedByUserId == this.tw.UserId)
2350 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2352 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2356 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2357 => this.MakeReplyText();
2359 private void DMStripMenuItem_Click(object sender, EventArgs e)
2360 => this.MakeDirectMessageText();
2362 private async Task DoStatusDelete()
2364 var posts = this.CurrentTab.SelectedPosts;
2365 if (posts.Length == 0)
2368 // 選択されたツイートの中に削除可能なものが一つでもあるか
2369 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2372 var ret = MessageBox.Show(
2374 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2375 Properties.Resources.DeleteStripMenuItem_ClickText2,
2376 MessageBoxButtons.OKCancel,
2377 MessageBoxIcon.Question);
2379 if (ret != DialogResult.OK)
2382 var currentListView = this.CurrentListView;
2383 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2385 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2387 Exception? lastException = null;
2388 foreach (var post in posts)
2390 if (!post.CanDeleteBy(this.tw.UserId))
2395 if (post.StatusId is TwitterDirectMessageId dmId)
2397 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2401 if (post.RetweetedByUserId == this.tw.UserId)
2403 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2405 await this.tw.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
2410 if (post.UserId == this.tw.UserId)
2412 if (post.RetweetedId != null)
2414 // 他人に RT された自分のツイート
2415 // => RT 元の自分のツイートを削除
2416 await this.tw.Api.StatusesDestroy(post.RetweetedId.ToTwitterStatusId())
2423 await this.tw.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
2430 catch (WebApiException ex)
2436 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2439 if (lastException == null)
2440 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2442 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2444 using (ControlTransaction.Update(currentListView))
2446 this.listCache?.PurgeCache();
2447 this.listCache?.UpdateListSize();
2449 currentListView.SelectedIndices.Clear();
2451 var currentTab = this.CurrentTab;
2452 if (currentTab.AllCount != 0)
2455 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2456 selectedIndex = focusedIndex;
2458 selectedIndex = currentTab.AllCount - 1;
2460 currentListView.SelectedIndices.Add(selectedIndex);
2461 currentListView.EnsureVisible(selectedIndex);
2462 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2466 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2468 var tabPage = this.ListTab.TabPages[index];
2469 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2471 if (tabPage.ImageIndex == 0)
2472 tabPage.ImageIndex = -1; // タブアイコン
2476 if (!this.settings.Common.TabIconDisp)
2477 this.ListTab.Refresh();
2481 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2482 => await this.DoStatusDelete();
2484 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2486 using (ControlTransaction.Update(this.CurrentListView))
2488 var tab = this.CurrentTab;
2489 foreach (var statusId in tab.SelectedStatusIds)
2491 this.statuses.SetReadAllTab(statusId, read: true);
2492 var idx = tab.IndexOf(statusId);
2493 this.listCache?.RefreshStyle(idx);
2496 if (this.settings.Common.TabIconDisp)
2498 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2500 if (tab.UnreadCount == 0)
2502 var tabPage = this.ListTab.TabPages[index];
2503 if (tabPage.ImageIndex == 0)
2504 tabPage.ImageIndex = -1; // タブアイコン
2508 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2511 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2513 using (ControlTransaction.Update(this.CurrentListView))
2515 var tab = this.CurrentTab;
2516 foreach (var statusId in tab.SelectedStatusIds)
2518 this.statuses.SetReadAllTab(statusId, read: false);
2519 var idx = tab.IndexOf(statusId);
2520 this.listCache?.RefreshStyle(idx);
2523 if (this.settings.Common.TabIconDisp)
2525 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2527 if (tab.UnreadCount > 0)
2529 var tabPage = this.ListTab.TabPages[index];
2530 if (tabPage.ImageIndex == -1)
2531 tabPage.ImageIndex = 0; // タブアイコン
2535 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2538 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2539 => await this.DoRefresh();
2541 private async Task DoRefresh()
2542 => await this.RefreshTabAsync(this.CurrentTab);
2544 private async Task DoRefreshMore()
2545 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2547 private DialogResult ShowSettingDialog()
2549 using var settingDialog = new AppendSettingDialog();
2550 settingDialog.Icon = this.iconAssets.IconMain;
2551 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2553 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2555 DialogResult result;
2558 result = settingDialog.ShowDialog(this);
2562 return DialogResult.Abort;
2565 if (result == DialogResult.OK)
2567 lock (this.syncObject)
2569 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2576 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2579 var previousUserId = this.settings.Common.UserId;
2580 var oldIconCol = this.Use2ColumnsMode;
2582 if (this.ShowSettingDialog() == DialogResult.OK)
2584 lock (this.syncObject)
2586 this.settings.ApplySettings();
2588 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2589 this.tw.ClearAuthInfo();
2591 var account = this.settings.Common.SelectedAccount;
2592 if (account != null)
2593 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
2595 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
2597 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2598 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2600 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2604 if (this.settings.Common.TabIconDisp)
2606 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2607 this.ListTab.DrawMode = TabDrawMode.Normal;
2608 this.ListTab.ImageList = this.TabImage;
2612 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2613 this.ListTab.DrawItem += this.ListTab_DrawItem;
2614 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2615 this.ListTab.ImageList = null;
2618 catch (Exception ex)
2620 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2621 ex.Data["IsTerminatePermission"] = false;
2627 if (!this.settings.Common.UnreadManage)
2629 this.ReadedStripMenuItem.Enabled = false;
2630 this.UnreadStripMenuItem.Enabled = false;
2631 if (this.settings.Common.TabIconDisp)
2633 foreach (TabPage myTab in this.ListTab.TabPages)
2635 myTab.ImageIndex = -1;
2641 this.ReadedStripMenuItem.Enabled = true;
2642 this.UnreadStripMenuItem.Enabled = true;
2645 catch (Exception ex)
2647 ex.Data["Instance"] = "ListTab(UnreadManage)";
2648 ex.Data["IsTerminatePermission"] = false;
2653 this.SetTabAlignment();
2655 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2657 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2658 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2659 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2661 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2662 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2663 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2664 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2666 var newTheme = new ThemeManager(this.settings.Local);
2667 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2668 this.tweetDetailsView.Theme = this.themeManager;
2669 if (this.listDrawer != null)
2670 this.listDrawer.Theme = this.themeManager;
2675 if (this.StatusText.Focused)
2676 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2678 this.StatusText.Font = this.themeManager.FontInputFont;
2679 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2681 catch (Exception ex)
2683 MessageBox.Show(ex.Message);
2688 this.InitDetailHtmlFormat();
2690 catch (Exception ex)
2692 ex.Data["Instance"] = "Font";
2693 ex.Data["IsTerminatePermission"] = false;
2699 if (this.settings.Common.TabIconDisp)
2701 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2703 var tabPage = this.ListTab.TabPages[index];
2704 if (tab.UnreadCount == 0)
2705 tabPage.ImageIndex = -1;
2707 tabPage.ImageIndex = 0;
2711 catch (Exception ex)
2713 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2714 ex.Data["IsTerminatePermission"] = false;
2720 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2722 foreach (TabPage tp in this.ListTab.TabPages)
2724 var lst = (DetailsListView)tp.Tag;
2726 using (ControlTransaction.Update(lst))
2728 lst.GridLines = this.settings.Common.ShowGrid;
2730 if (this.Use2ColumnsMode != oldIconCol)
2731 this.ResetColumns(lst);
2735 catch (Exception ex)
2737 ex.Data["Instance"] = "ListView(IconSize)";
2738 ex.Data["IsTerminatePermission"] = false;
2742 this.SetMainWindowTitle();
2743 this.SetNotifyIconText();
2745 this.listCache?.PurgeCache();
2746 this.CurrentListView.Refresh();
2747 this.ListTab.Refresh();
2749 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2750 if (this.settings.Common.HotkeyEnabled)
2752 // グローバルホットキーの登録。設定で変更可能にするかも
2753 var modKey = HookGlobalHotkey.ModKeys.None;
2754 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2755 modKey |= HookGlobalHotkey.ModKeys.Alt;
2756 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2757 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2758 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2759 modKey |= HookGlobalHotkey.ModKeys.Shift;
2760 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2761 modKey |= HookGlobalHotkey.ModKeys.Win;
2763 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2766 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2769 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2777 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2779 this.TopMost = this.settings.Common.AlwaysTop;
2780 this.SaveConfigsAll(false);
2782 if (this.tw.UserId != previousUserId)
2783 await this.DoGetFollowersMenu();
2789 private void SetTabAlignment()
2791 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2792 if (this.ListTab.Alignment == newAlignment) return;
2795 var currentListViewState = this.listViewState[this.CurrentTabName];
2796 currentListViewState.Save(this.ListLockMenuItem.Checked);
2798 this.ListTab.Alignment = newAlignment;
2800 currentListViewState.Restore(forceScroll: true);
2803 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2806 if (this.listDrawer != null)
2808 this.listDrawer.IconSize = iconSz;
2809 this.listDrawer.UpdateItemHeight();
2812 this.listCache?.PurgeCache();
2815 private void ResetColumns(DetailsListView list)
2817 using (ControlTransaction.Update(list))
2818 using (ControlTransaction.Layout(list, false))
2821 list.ColumnClick -= this.MyList_ColumnClick;
2822 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2823 list.ColumnReordered -= this.MyList_ColumnReordered;
2824 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2826 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2827 list.Columns.Clear();
2828 cols.ForEach(col => col.Dispose());
2831 this.InitColumns(list, true);
2833 list.ColumnClick += this.MyList_ColumnClick;
2834 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2835 list.ColumnReordered += this.MyList_ColumnReordered;
2836 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2840 public void AddNewTabForSearch(string searchWord)
2842 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2843 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2845 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2847 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2848 this.ListTab.SelectedIndex = tabIndex;
2853 var tabName = searchWord;
2854 for (var i = 0; i <= 100; i++)
2856 if (this.statuses.ContainsTab(tabName))
2862 var tab = new PublicSearchTabModel(tabName);
2863 this.statuses.AddTab(tab);
2864 this.AddNewTab(tab, startup: false);
2866 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2868 var tabPage = this.CurrentTabPage;
2869 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2870 cmb.Items.Add(searchWord);
2871 cmb.Text = searchWord;
2872 this.SaveConfigsTabs();
2874 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2877 private async Task ShowUserTimeline()
2879 var post = this.CurrentPost;
2880 if (post == null || !this.ExistCurrentPost) return;
2881 await this.AddNewTabForUserTimeline(post.ScreenName);
2884 private async Task ShowRetweeterTimeline()
2886 var retweetedBy = this.CurrentPost?.RetweetedBy;
2887 if (retweetedBy == null || !this.ExistCurrentPost) return;
2888 await this.AddNewTabForUserTimeline(retweetedBy);
2891 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2893 if (e.KeyCode == Keys.Escape)
2895 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2896 this.SaveConfigsTabs();
2897 e.SuppressKeyPress = true;
2901 public async Task AddNewTabForUserTimeline(string user)
2903 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2904 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2906 if (tb.ScreenName == user)
2908 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2909 this.ListTab.SelectedIndex = tabIndex;
2914 var tabName = "user:" + user;
2915 while (this.statuses.ContainsTab(tabName))
2920 var tab = new UserTimelineTabModel(tabName, user);
2921 this.statuses.AddTab(tab);
2922 this.AddNewTab(tab, startup: false);
2924 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2925 this.SaveConfigsTabs();
2927 await this.RefreshTabAsync(tab);
2930 public bool AddNewTab(TabModel tab, bool startup)
2933 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2937 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2939 var tabPage = new TabPage();
2940 var listCustom = new DetailsListView();
2942 var cnt = this.statuses.Tabs.Count;
2944 // ToDo:Create and set controls follow tabtypes
2946 using (ControlTransaction.Update(listCustom))
2947 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2948 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2949 using (ControlTransaction.Layout(this.SplitContainer1, false))
2950 using (ControlTransaction.Layout(this.ListTab, false))
2951 using (ControlTransaction.Layout(this))
2952 using (ControlTransaction.Layout(tabPage, false))
2954 tabPage.Controls.Add(listCustom);
2957 var userTab = tab as UserTimelineTabModel;
2958 var listTab = tab as ListTimelineTabModel;
2959 var searchTab = tab as PublicSearchTabModel;
2961 if (userTab != null || listTab != null)
2963 var label = new Label
2965 Dock = DockStyle.Top,
2970 if (listTab != null)
2972 label.Text = listTab.ListInfo.ToString();
2974 else if (userTab != null)
2976 label.Text = userTab.ScreenName + "'s Timeline";
2978 label.TextAlign = ContentAlignment.MiddleLeft;
2979 using (var tmpComboBox = new ComboBox())
2981 label.Height = tmpComboBox.Height;
2983 tabPage.Controls.Add(label);
2986 else if (searchTab != null)
2988 var pnl = new Panel();
2990 var lbl = new Label();
2991 var cmb = new ComboBox();
2992 var btn = new Button();
2993 var cmbLang = new ComboBox();
2995 using (ControlTransaction.Layout(pnl, false))
2997 pnl.Controls.Add(cmb);
2998 pnl.Controls.Add(cmbLang);
2999 pnl.Controls.Add(btn);
3000 pnl.Controls.Add(lbl);
3001 pnl.Name = "panelSearch";
3003 pnl.Dock = DockStyle.Top;
3004 pnl.Height = cmb.Height;
3005 pnl.Enter += this.SearchControls_Enter;
3006 pnl.Leave += this.SearchControls_Leave;
3009 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3010 cmb.Dock = DockStyle.Fill;
3011 cmb.Name = "comboSearch";
3012 cmb.DropDownStyle = ComboBoxStyle.DropDown;
3013 cmb.ImeMode = ImeMode.NoControl;
3014 cmb.TabStop = false;
3016 cmb.AutoCompleteMode = AutoCompleteMode.None;
3017 cmb.KeyDown += this.SearchComboBox_KeyDown;
3020 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3021 cmbLang.Dock = DockStyle.Right;
3023 cmbLang.Name = "comboLang";
3024 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3025 cmbLang.TabStop = false;
3026 cmbLang.TabIndex = 2;
3027 cmbLang.Items.Add("");
3028 cmbLang.Items.Add("ja");
3029 cmbLang.Items.Add("en");
3030 cmbLang.Items.Add("ar");
3031 cmbLang.Items.Add("da");
3032 cmbLang.Items.Add("nl");
3033 cmbLang.Items.Add("fa");
3034 cmbLang.Items.Add("fi");
3035 cmbLang.Items.Add("fr");
3036 cmbLang.Items.Add("de");
3037 cmbLang.Items.Add("hu");
3038 cmbLang.Items.Add("is");
3039 cmbLang.Items.Add("it");
3040 cmbLang.Items.Add("no");
3041 cmbLang.Items.Add("pl");
3042 cmbLang.Items.Add("pt");
3043 cmbLang.Items.Add("ru");
3044 cmbLang.Items.Add("es");
3045 cmbLang.Items.Add("sv");
3046 cmbLang.Items.Add("th");
3048 lbl.Text = "Search(C-S-f)";
3049 lbl.Name = "label1";
3050 lbl.Dock = DockStyle.Left;
3052 lbl.Height = cmb.Height;
3053 lbl.TextAlign = ContentAlignment.MiddleLeft;
3056 btn.Text = "Search";
3057 btn.Name = "buttonSearch";
3058 btn.UseVisualStyleBackColor = true;
3059 btn.Dock = DockStyle.Right;
3060 btn.TabStop = false;
3062 btn.Click += this.SearchButton_Click;
3064 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3066 cmb.Items.Add(searchTab.SearchWords);
3067 cmb.Text = searchTab.SearchWords;
3070 cmbLang.Text = searchTab.SearchLang;
3072 tabPage.Controls.Add(pnl);
3076 tabPage.Tag = listCustom;
3077 this.ListTab.Controls.Add(tabPage);
3079 tabPage.Location = new Point(4, 4);
3080 tabPage.Name = "CTab" + cnt;
3081 tabPage.Size = new Size(380, 260);
3082 tabPage.TabIndex = 2 + cnt;
3083 tabPage.Text = tab.TabName;
3084 tabPage.UseVisualStyleBackColor = true;
3085 tabPage.AccessibleRole = AccessibleRole.PageTab;
3087 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3088 listCustom.TabIndex = 1;
3089 listCustom.AllowColumnReorder = true;
3090 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3091 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3092 listCustom.Dock = DockStyle.Fill;
3093 listCustom.FullRowSelect = true;
3094 listCustom.HideSelection = false;
3095 listCustom.Location = new Point(0, 0);
3096 listCustom.Margin = new Padding(0);
3097 listCustom.Name = "CList" + Environment.TickCount;
3098 listCustom.ShowItemToolTips = true;
3099 listCustom.Size = new Size(380, 260);
3100 listCustom.UseCompatibleStateImageBehavior = false;
3101 listCustom.View = View.Details;
3102 listCustom.OwnerDraw = true;
3103 listCustom.VirtualMode = true;
3105 listCustom.GridLines = this.settings.Common.ShowGrid;
3106 listCustom.AllowDrop = true;
3108 this.InitColumns(listCustom, startup);
3110 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3111 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3112 listCustom.ColumnClick += this.MyList_ColumnClick;
3113 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3114 listCustom.DragDrop += this.TweenMain_DragDrop;
3115 listCustom.DragEnter += this.TweenMain_DragEnter;
3116 listCustom.DragOver += this.TweenMain_DragOver;
3117 listCustom.MouseClick += this.MyList_MouseClick;
3118 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3119 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3120 listCustom.HScrolled += this.MyList_HScrolled;
3123 var state = new TimelineListViewState(listCustom, tab);
3124 this.listViewState[tab.TabName] = state;
3129 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3131 var tabInfo = this.statuses.GetTabByName(tabName);
3132 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3137 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3138 var result = MessageBox.Show(
3140 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3141 MessageBoxButtons.OKCancel,
3142 MessageBoxIcon.Question,
3143 MessageBoxDefaultButton.Button2);
3144 if (result == DialogResult.Cancel)
3150 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3154 var tabPage = this.ListTab.TabPages[tabIndex];
3156 this.SetListProperty(); // 他のタブに列幅等を反映
3158 this.listViewState.Remove(tabName);
3161 var listCustom = (DetailsListView)tabPage.Tag;
3164 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3165 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3166 using (ControlTransaction.Layout(this.SplitContainer1, false))
3167 using (ControlTransaction.Layout(this.ListTab, false))
3168 using (ControlTransaction.Layout(this))
3169 using (ControlTransaction.Layout(tabPage, false))
3171 if (this.CurrentTabName == tabName)
3173 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3174 this.beforeSelectedTab = null;
3176 this.ListTab.Controls.Remove(tabPage);
3179 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3181 using var label = tabPage.Controls["labelUser"];
3182 tabPage.Controls.Remove(label);
3184 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3186 using var pnl = tabPage.Controls["panelSearch"];
3188 pnl.Enter -= this.SearchControls_Enter;
3189 pnl.Leave -= this.SearchControls_Leave;
3190 tabPage.Controls.Remove(pnl);
3192 foreach (Control ctrl in pnl.Controls)
3194 if (ctrl.Name == "buttonSearch")
3196 ctrl.Click -= this.SearchButton_Click;
3198 else if (ctrl.Name == "comboSearch")
3200 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3202 pnl.Controls.Remove(ctrl);
3207 tabPage.Controls.Remove(listCustom);
3209 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3210 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3211 listCustom.ColumnClick -= this.MyList_ColumnClick;
3212 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3213 listCustom.DragDrop -= this.TweenMain_DragDrop;
3214 listCustom.DragEnter -= this.TweenMain_DragEnter;
3215 listCustom.DragOver -= this.TweenMain_DragOver;
3216 listCustom.MouseClick -= this.MyList_MouseClick;
3217 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3218 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3219 listCustom.HScrolled -= this.MyList_HScrolled;
3221 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3222 listCustom.Columns.Clear();
3223 cols.ForEach(col => col.Dispose());
3226 listCustom.ContextMenuStrip = null;
3227 listCustom.ColumnHeaderContextMenuStrip = null;
3228 listCustom.Font = null;
3230 listCustom.SmallImageList = null;
3231 listCustom.ListViewItemSorter = null;
3234 this.listCache?.PurgeCache();
3238 listCustom.Dispose();
3239 this.statuses.RemoveTab(tabName);
3244 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3246 this.listCache?.PurgeCache();
3247 this.beforeSelectedTab = e.TabPage;
3250 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3254 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3257 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3258 if (!dragEnableRectangle.Contains(e.Location))
3260 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3261 tn = this.CurrentTabName;
3264 if (MyCommon.IsNullOrEmpty(tn)) return;
3266 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3269 var tabPage = this.ListTab.TabPages[tabIndex];
3270 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3275 this.tabDrag = false;
3278 var cpos = new Point(e.X, e.Y);
3279 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3281 var rect = this.ListTab.GetTabRect(index);
3282 if (rect.Contains(cpos))
3284 this.rclickTabName = tab.TabName;
3290 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3292 this.SetMainWindowTitle();
3293 this.SetStatusLabelUrl();
3294 this.SetApiStatusLabel();
3295 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3296 this.Tag = this.ListTab.Tag;
3297 this.TabMenuControl(this.CurrentTabName);
3298 this.PushSelectPostChain();
3299 this.DispSelectedPost();
3302 private void SetListProperty()
3304 if (!this.isColumnChanged) return;
3306 var currentListView = this.CurrentListView;
3308 var dispOrder = new int[currentListView.Columns.Count];
3309 for (var i = 0; i < currentListView.Columns.Count; i++)
3311 for (var j = 0; j < currentListView.Columns.Count; j++)
3313 if (currentListView.Columns[j].DisplayIndex == i)
3322 foreach (TabPage tb in this.ListTab.TabPages)
3324 if (tb.Text == this.CurrentTabName)
3327 if (tb.Tag != null && tb.Controls.Count > 0)
3329 var lst = (DetailsListView)tb.Tag;
3330 for (var i = 0; i < lst.Columns.Count; i++)
3332 lst.Columns[dispOrder[i]].DisplayIndex = i;
3333 lst.Columns[i].Width = currentListView.Columns[i].Width;
3338 this.isColumnChanged = false;
3341 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3343 if (e.KeyChar == '@')
3345 if (!this.settings.Common.UseAtIdSupplement) return;
3347 var cnt = this.AtIdSupl.ItemCount;
3348 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3349 if (cnt != this.AtIdSupl.ItemCount)
3350 this.MarkSettingAtIdModified();
3353 else if (e.KeyChar == '#')
3355 if (!this.settings.Common.UseHashSupplement) return;
3356 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3361 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3362 => this.ShowSuplDialog(owner, dialog, 0, "");
3364 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3365 => this.ShowSuplDialog(owner, dialog, offset, "");
3367 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3369 dialog.StartsWith = startswith;
3376 dialog.ShowDialog();
3378 this.TopMost = this.settings.Common.AlwaysTop;
3379 var selStart = owner.SelectionStart;
3382 if (dialog.DialogResult == DialogResult.OK)
3384 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3388 fHalf = owner.Text.Substring(0, selStart - offset);
3390 if (selStart < owner.Text.Length)
3392 eHalf = owner.Text.Substring(selStart);
3394 owner.Text = fHalf + dialog.InputText + eHalf;
3395 owner.SelectionStart = selStart + dialog.InputText.Length;
3402 fHalf = owner.Text.Substring(0, selStart);
3404 if (selStart < owner.Text.Length)
3406 eHalf = owner.Text.Substring(selStart);
3408 owner.Text = fHalf + eHalf;
3411 owner.SelectionStart = selStart;
3417 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3420 if (!e.Alt && !e.Control && !e.Shift)
3422 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3424 var isSpace = false;
3425 foreach (var c in this.StatusText.Text)
3427 if (c == ' ' || c == ' ')
3440 this.StatusText.Text = "";
3441 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3445 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3448 private void StatusText_TextChanged(object sender, EventArgs e)
3451 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3452 this.lblLen.Text = pLen.ToString();
3455 this.StatusText.ForeColor = Color.Red;
3459 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3462 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3464 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3466 this.inReplyTo = null;
3471 /// メンション以外の文字列が含まれていないテキストであるか判定します
3473 internal static bool TextContainsOnlyMentions(string text)
3475 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3478 foreach (var mention in mentions)
3480 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3482 if (!string.IsNullOrWhiteSpace(textPart))
3485 startIndex = mention.Indices[1];
3488 var textPartLast = text.Substring(startIndex);
3490 if (!string.IsNullOrWhiteSpace(textPartLast))
3497 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3499 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3501 var autoPopulatedUserIdList = new List<long>();
3503 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3504 if (replyToPost != null)
3506 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3508 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3509 autoPopulatedUserIdList.Add(replyToPost.UserId);
3511 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3513 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3515 statusText = statusText.Substring(screenName.Length + 2);
3516 autoPopulatedUserIdList.Add(userId);
3522 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3528 /// attachment_url に指定可能な URL が含まれていれば除去
3530 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3532 attachmentUrl = null;
3534 // attachment_url は media_id と同時に使用できない
3535 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3538 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3542 attachmentUrl = match.Value;
3545 statusText = statusText.Substring(0, match.Index);
3547 // テキストと URL の間にスペースが含まれていれば除去
3548 return statusText.TrimEnd(' ');
3551 private string FormatStatusTextExtended(string statusText)
3552 => this.FormatStatusTextExtended(statusText, out _, out _);
3555 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3557 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3559 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3561 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3563 return this.FormatStatusText(statusText);
3567 /// ツイート投稿前のフッター付与などの前処理を行います
3569 private string FormatStatusText(string statusText)
3571 statusText = statusText.Replace("\r\n", "\n");
3573 if (this.urlMultibyteSplit)
3576 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3579 if (this.settings.Common.WideSpaceConvert)
3581 // 文中の全角スペースを半角スペース1個にする
3582 statusText = statusText.Replace(" ", " ");
3585 // DM の場合はこれ以降の処理を行わない
3586 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3590 if (this.settings.Common.PostShiftEnter)
3592 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3596 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3597 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3599 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3602 if (statusText.Contains("RT @"))
3603 disableFooter = true;
3605 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3606 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3608 var mentionSelf = $"@{this.tw.Username} ";
3609 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3611 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3612 statusText = statusText.Substring(mentionSelf.Length);
3619 var hashtag = this.HashMgr.UseHash;
3620 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3622 if (this.HashMgr.IsHead)
3623 header = this.HashMgr.UseHash + " ";
3625 footer = " " + this.HashMgr.UseHash;
3630 if (this.settings.Local.UseRecommendStatus)
3633 footer += this.recommendedStatusFooter;
3635 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3637 // テキストボックスに入力されている文字列を使用する
3638 footer += " " + this.settings.Local.StatusText.Trim();
3642 statusText = header + statusText + footer;
3644 if (this.preventSmsCommand)
3646 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3647 // 参照: https://support.twitter.com/articles/14020
3649 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3650 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3652 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3653 statusText = '\u200b' + statusText;
3661 /// 投稿欄に表示する入力可能な文字数を計算します
3663 private int GetRestStatusCount(string statusText)
3665 var remainCount = this.tw.GetTextLengthRemain(statusText);
3667 var uploadService = this.GetSelectedImageService();
3668 if (uploadService != null)
3670 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3671 remainCount -= uploadService.GetReservedTextLength(1);
3677 private IMediaUploadService? GetSelectedImageService()
3678 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3681 /// 全てのタブの振り分けルールを反映し直します
3683 private void ApplyPostFilters()
3685 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3687 this.statuses.FilterAll();
3689 var listView = this.CurrentListView;
3690 using (ControlTransaction.Update(listView))
3692 this.listCache?.PurgeCache();
3693 this.listCache?.UpdateListSize();
3696 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3698 var tabPage = this.ListTab.TabPages[index];
3700 if (this.settings.Common.TabIconDisp)
3702 if (tab.UnreadCount > 0)
3703 tabPage.ImageIndex = 0;
3705 tabPage.ImageIndex = -1;
3709 if (!this.settings.Common.TabIconDisp)
3710 this.ListTab.Refresh();
3712 this.SetMainWindowTitle();
3713 this.SetStatusLabelUrl();
3717 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3718 => e.DrawDefault = true;
3720 private void MyList_HScrolled(object sender, EventArgs e)
3721 => ((DetailsListView)sender).Refresh();
3723 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3725 base.ScaleControl(factor, specified);
3727 ScaleChildControl(this.TabImage, factor);
3729 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3730 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3732 foreach (var listview in listviews)
3734 ScaleChildControl(listview, factor);
3738 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3740 var tab = this.CurrentTab;
3742 if (tab.AllCount == 0)
3744 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3748 var selectedIndex = tab.SelectedIndex;
3753 case SEARCHTYPE.NextSearch: // 次を検索
3754 if (selectedIndex != -1)
3755 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3759 case SEARCHTYPE.PrevSearch: // 前を検索
3760 if (selectedIndex != -1)
3761 startIndex = Math.Max(selectedIndex - 1, 0);
3763 startIndex = tab.AllCount - 1;
3765 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3767 if (selectedIndex != -1)
3768 startIndex = selectedIndex;
3774 Func<string, bool> stringComparer;
3777 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3779 catch (ArgumentException)
3781 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3785 var reverse = searchType == SEARCHTYPE.PrevSearch;
3786 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3787 .DefaultIfEmpty(-1).First();
3789 if (foundIndex == -1)
3791 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3795 var listView = this.CurrentListView;
3796 this.SelectListItem(listView, foundIndex);
3797 listView.EnsureVisible(foundIndex);
3800 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3801 => this.ShowSearchDialog(); // 検索メニュー
3803 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3805 var previousSearch = this.SearchDialog.ResultOptions;
3806 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3808 this.SearchDialog.Reset();
3809 this.ShowSearchDialog();
3815 previousSearch.Query,
3816 previousSearch.CaseSensitive,
3817 previousSearch.UseRegex,
3818 SEARCHTYPE.NextSearch);
3821 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3823 var previousSearch = this.SearchDialog.ResultOptions;
3824 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3826 this.SearchDialog.Reset();
3827 this.ShowSearchDialog();
3833 previousSearch.Query,
3834 previousSearch.CaseSensitive,
3835 previousSearch.UseRegex,
3836 SEARCHTYPE.PrevSearch);
3840 /// 検索ダイアログを表示し、検索を実行します
3842 private void ShowSearchDialog()
3844 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3846 this.TopMost = this.settings.Common.AlwaysTop;
3849 this.TopMost = this.settings.Common.AlwaysTop;
3851 var searchOptions = this.SearchDialog.ResultOptions!;
3852 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3854 if (searchOptions.NewTab)
3856 var tabName = Properties.Resources.SearchResults_TabName;
3860 tabName = this.statuses.MakeTabName(tabName);
3862 catch (TabException ex)
3864 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3867 var resultTab = new LocalSearchTabModel(tabName);
3868 this.AddNewTab(resultTab, startup: false);
3869 this.statuses.AddTab(resultTab);
3871 var targetTab = this.CurrentTab;
3873 Func<string, bool> stringComparer;
3876 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3878 catch (ArgumentException)
3880 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3884 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3885 if (foundIndices.Length == 0)
3887 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3891 var foundPosts = foundIndices.Select(x => targetTab[x]);
3892 foreach (var post in foundPosts)
3894 resultTab.AddPostQueue(post);
3897 this.statuses.DistributePosts();
3898 this.RefreshTimeline();
3900 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3901 this.ListTab.SelectedIndex = tabIndex;
3906 searchOptions.Query,
3907 searchOptions.CaseSensitive,
3908 searchOptions.UseRegex,
3909 SEARCHTYPE.DialogSearch);
3912 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3914 this.AddNewTabForSearch(searchOptions.Query);
3918 /// <summary>発言検索に使用するメソッドを生成します</summary>
3919 /// <exception cref="ArgumentException">
3920 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3922 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3926 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3927 var regex = new Regex(query, regexOption);
3929 return x => regex.IsMatch(x);
3933 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3935 return x => x.IndexOf(query, comparisonType) != -1;
3939 private void AboutMenuItem_Click(object sender, EventArgs e)
3941 using (var about = new TweenAboutBox())
3943 about.ShowDialog(this);
3945 this.TopMost = this.settings.Common.AlwaysTop;
3948 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3950 var bgnIdx = this.statuses.SelectedTabIndex;
3952 if (this.ImageSelector.Enabled)
3955 TabModel? foundTab = null;
3959 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3961 var unreadIndex = tab.NextUnreadIndex;
3962 if (unreadIndex != -1)
3964 this.ListTab.SelectedIndex = index;
3966 foundIndex = unreadIndex;
3971 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3972 if (foundTab == null && bgnIdx > 0)
3974 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3976 var unreadIndex = tab.NextUnreadIndex;
3977 if (unreadIndex != -1)
3979 this.ListTab.SelectedIndex = index;
3981 foundIndex = unreadIndex;
3987 DetailsListView lst;
3989 if (foundTab == null)
3991 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3992 this.ListTab.SelectedIndex = 0;
3993 var tabPage = this.ListTab.TabPages[0];
3994 var tab = this.statuses.Tabs[0];
3996 if (tab.AllCount == 0)
3999 if (this.statuses.SortOrder == SortOrder.Ascending)
4000 foundIndex = tab.AllCount - 1;
4004 lst = (DetailsListView)tabPage.Tag;
4008 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
4009 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
4012 this.SelectListItem(lst, foundIndex);
4014 if (this.statuses.SortMode == ComparerMode.Id)
4016 var rowHeight = lst.SmallImageList.ImageSize.Height;
4017 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4018 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4024 lst.EnsureVisible(foundIndex);
4029 lst.EnsureVisible(foundIndex);
4035 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4037 var tab = this.CurrentTab;
4038 var post = this.CurrentPost;
4039 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4040 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4043 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4044 => await this.CheckNewVersion(false);
4046 private void RunTweenUp()
4048 var pinfo = new ProcessStartInfo
4050 UseShellExecute = true,
4051 WorkingDirectory = this.settings.SettingsPath,
4052 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4053 Arguments = "\"" + Application.StartupPath + "\"",
4058 Process.Start(pinfo);
4062 MessageBox.Show("Failed to execute TweenUp3.exe.");
4066 public readonly record struct VersionInfo(
4073 /// OpenTween の最新バージョンの情報を取得します
4075 public async Task<VersionInfo> GetVersionInfoAsync()
4077 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4078 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4080 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4081 .ConfigureAwait(false);
4083 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4084 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4086 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4087 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4089 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4091 return new VersionInfo
4093 Version = Version.Parse(msgHeader[0]),
4094 DownloadUri = new Uri(msgHeader[1]),
4095 ReleaseNote = msgBody,
4099 private async Task CheckNewVersion(bool startup = false)
4101 if (ApplicationSettings.VersionInfoUrl == null)
4102 return; // 更新チェック無効化
4106 var versionInfo = await this.GetVersionInfoAsync();
4108 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4113 var msgtext = string.Format(
4114 Properties.Resources.CheckNewVersionText7,
4115 MyCommon.GetReadableVersion(),
4116 MyCommon.GetReadableVersion(versionInfo.Version));
4117 msgtext = MyCommon.ReplaceAppName(msgtext);
4121 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4122 MessageBoxButtons.OK,
4123 MessageBoxIcon.Information);
4128 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4131 using var dialog = new UpdateDialog();
4133 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4134 MyCommon.GetReadableVersion(versionInfo.Version));
4135 dialog.DetailsText = versionInfo.ReleaseNote;
4137 if (dialog.ShowDialog(this) == DialogResult.Yes)
4139 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4141 else if (dialog.SkipButtonPressed)
4143 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4144 this.MarkSettingCommonModified();
4149 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4153 Properties.Resources.CheckNewVersionText10,
4154 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4155 MessageBoxButtons.OK,
4156 MessageBoxIcon.Exclamation,
4157 MessageBoxDefaultButton.Button2);
4162 private void UpdateSelectedPost()
4164 // 件数関連の場合、タイトル即時書き換え
4165 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4166 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4167 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4168 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4170 this.SetMainWindowTitle();
4172 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4173 this.SetStatusLabelUrl();
4175 if (this.settings.Common.TabIconDisp)
4177 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4179 if (tab.UnreadCount == 0)
4181 var tabPage = this.ListTab.TabPages[index];
4182 if (tabPage.ImageIndex == 0)
4183 tabPage.ImageIndex = -1;
4189 this.ListTab.Refresh();
4192 this.DispSelectedPost();
4195 public string CreateDetailHtml(string orgdata)
4196 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4198 private void DispSelectedPost()
4199 => this.DispSelectedPost(false);
4201 private PostClass displayPost = new();
4204 /// サムネイル表示に使用する CancellationToken の生成元
4206 private CancellationTokenSource? thumbnailTokenSource = null;
4208 private void DispSelectedPost(bool forceupdate)
4210 var currentPost = this.CurrentPost;
4211 if (currentPost == null)
4214 var oldDisplayPost = this.displayPost;
4215 this.displayPost = currentPost;
4217 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4220 var loadTasks = new List<Task>
4222 this.tweetDetailsView.ShowPostDetails(currentPost),
4225 this.SplitContainer3.Panel2Collapsed = true;
4227 if (this.settings.Common.PreviewEnable)
4229 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4230 oldTokenSource?.Cancel();
4232 var token = this.thumbnailTokenSource!.Token;
4233 loadTasks.Add(this.tweetThumbnail1.Model.PrepareThumbnails(currentPost, token));
4236 async Task DelayedTasks()
4240 await Task.WhenAll(loadTasks);
4242 catch (OperationCanceledException)
4247 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4251 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4252 => await this.OpenApplicationWebsite();
4254 private async Task OpenApplicationWebsite()
4255 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4257 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4258 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4260 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4262 var tab = this.CurrentTab;
4263 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4265 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4266 if (pnl.Controls["comboSearch"].Focused ||
4267 pnl.Controls["comboLang"].Focused ||
4268 pnl.Controls["buttonSearch"].Focused) return;
4271 if (e.Control || e.Shift || e.Alt)
4274 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4277 e.SuppressKeyPress = true;
4280 if (asyncTask != null)
4284 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4286 private void InitializeShortcuts()
4288 this.shortcutCommands = new[]
4290 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4291 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4292 .FocusedOn(FocusedControl.ListTab)
4293 .Do(() => SendKeys.Send("{DOWN}")),
4295 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4296 .FocusedOn(FocusedControl.ListTab)
4297 .Do(() => SendKeys.Send("{UP}")),
4299 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4300 .FocusedOn(FocusedControl.ListTab)
4301 .Do(() => SendKeys.Send("{PGDN}")),
4303 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4304 .FocusedOn(FocusedControl.ListTab)
4305 .Do(() => SendKeys.Send("{PGUP}")),
4307 ShortcutCommand.Create(Keys.F1)
4308 .Do(() => this.OpenApplicationWebsite()),
4310 ShortcutCommand.Create(Keys.F3)
4311 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4313 ShortcutCommand.Create(Keys.F5)
4314 .Do(() => this.DoRefresh()),
4316 ShortcutCommand.Create(Keys.F6)
4317 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4319 ShortcutCommand.Create(Keys.F7)
4320 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4322 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4323 .NotFocusedOn(FocusedControl.StatusText)
4326 this.CurrentTab.ClearAnchor();
4327 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4330 ShortcutCommand.Create(Keys.G)
4331 .NotFocusedOn(FocusedControl.StatusText)
4334 this.CurrentTab.ClearAnchor();
4335 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4338 ShortcutCommand.Create(Keys.Right, Keys.N)
4339 .FocusedOn(FocusedControl.ListTab)
4340 .Do(() => this.GoRelPost(forward: true)),
4342 ShortcutCommand.Create(Keys.Left, Keys.P)
4343 .FocusedOn(FocusedControl.ListTab)
4344 .Do(() => this.GoRelPost(forward: false)),
4346 ShortcutCommand.Create(Keys.OemPeriod)
4347 .FocusedOn(FocusedControl.ListTab)
4348 .Do(() => this.GoAnchor()),
4350 ShortcutCommand.Create(Keys.I)
4351 .FocusedOn(FocusedControl.ListTab)
4352 .OnlyWhen(() => this.StatusText.Enabled)
4353 .Do(() => this.StatusText.Focus()),
4355 ShortcutCommand.Create(Keys.Enter)
4356 .FocusedOn(FocusedControl.ListTab)
4357 .Do(() => this.ListItemDoubleClickAction()),
4359 ShortcutCommand.Create(Keys.R)
4360 .FocusedOn(FocusedControl.ListTab)
4361 .Do(() => this.DoRefresh()),
4363 ShortcutCommand.Create(Keys.L)
4364 .FocusedOn(FocusedControl.ListTab)
4367 this.CurrentTab.ClearAnchor();
4368 this.GoPost(forward: true);
4371 ShortcutCommand.Create(Keys.H)
4372 .FocusedOn(FocusedControl.ListTab)
4375 this.CurrentTab.ClearAnchor();
4376 this.GoPost(forward: false);
4379 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4380 .FocusedOn(FocusedControl.ListTab)
4383 this.CurrentTab.ClearAnchor();
4387 ShortcutCommand.Create(Keys.S)
4388 .FocusedOn(FocusedControl.ListTab)
4391 this.CurrentTab.ClearAnchor();
4392 this.GoNextTab(forward: true);
4395 ShortcutCommand.Create(Keys.A)
4396 .FocusedOn(FocusedControl.ListTab)
4399 this.CurrentTab.ClearAnchor();
4400 this.GoNextTab(forward: false);
4403 // ] in_reply_to参照元へ戻る
4404 ShortcutCommand.Create(Keys.Oem4)
4405 .FocusedOn(FocusedControl.ListTab)
4408 this.CurrentTab.ClearAnchor();
4409 return this.GoInReplyToPostTree();
4412 // [ in_reply_toへジャンプ
4413 ShortcutCommand.Create(Keys.Oem6)
4414 .FocusedOn(FocusedControl.ListTab)
4417 this.CurrentTab.ClearAnchor();
4418 this.GoBackInReplyToPostTree();
4421 ShortcutCommand.Create(Keys.Escape)
4422 .FocusedOn(FocusedControl.ListTab)
4425 this.CurrentTab.ClearAnchor();
4426 var tab = this.CurrentTab;
4427 var tabtype = tab.TabType;
4428 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4430 this.RemoveSpecifiedTab(tab.TabName, false);
4431 this.SaveConfigsTabs();
4435 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4436 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4437 .FocusedOn(FocusedControl.ListTab)
4438 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4440 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4441 ShortcutCommand.Create(Keys.Up, Keys.Down)
4442 .FocusedOn(FocusedControl.PostBrowser)
4445 ShortcutCommand.Create(Keys.Control | Keys.R)
4446 .Do(() => this.MakeReplyText()),
4448 ShortcutCommand.Create(Keys.Control | Keys.D)
4449 .Do(() => this.DoStatusDelete()),
4451 ShortcutCommand.Create(Keys.Control | Keys.M)
4452 .Do(() => this.MakeDirectMessageText()),
4454 ShortcutCommand.Create(Keys.Control | Keys.S)
4455 .Do(() => this.FavoriteChange(favAdd: true)),
4457 ShortcutCommand.Create(Keys.Control | Keys.I)
4458 .Do(() => this.DoRepliedStatusOpen()),
4460 ShortcutCommand.Create(Keys.Control | Keys.Q)
4461 .Do(() => this.DoQuoteOfficial()),
4463 ShortcutCommand.Create(Keys.Control | Keys.B)
4464 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4466 ShortcutCommand.Create(Keys.Control | Keys.T)
4467 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4469 ShortcutCommand.Create(Keys.Control | Keys.L)
4470 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4472 ShortcutCommand.Create(Keys.Control | Keys.Y)
4473 .NotFocusedOn(FocusedControl.PostBrowser)
4474 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4476 ShortcutCommand.Create(Keys.Control | Keys.F)
4477 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4479 ShortcutCommand.Create(Keys.Control | Keys.U)
4480 .Do(() => this.ShowUserTimeline()),
4482 ShortcutCommand.Create(Keys.Control | Keys.H)
4483 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4485 ShortcutCommand.Create(Keys.Control | Keys.O)
4486 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4488 ShortcutCommand.Create(Keys.Control | Keys.E)
4489 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4491 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4492 .FocusedOn(FocusedControl.ListTab)
4493 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4495 ShortcutCommand.Create(Keys.Control | Keys.N)
4496 .FocusedOn(FocusedControl.ListTab)
4497 .Do(() => this.GoNextTab(forward: true)),
4499 ShortcutCommand.Create(Keys.Control | Keys.P)
4500 .FocusedOn(FocusedControl.ListTab)
4501 .Do(() => this.GoNextTab(forward: false)),
4503 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4504 .FocusedOn(FocusedControl.ListTab)
4505 .Do(() => this.CopyStot()),
4507 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4508 ShortcutCommand.Create(Keys.Control | Keys.D1)
4509 .FocusedOn(FocusedControl.ListTab)
4510 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4511 .Do(() => this.ListTab.SelectedIndex = 0),
4513 ShortcutCommand.Create(Keys.Control | Keys.D2)
4514 .FocusedOn(FocusedControl.ListTab)
4515 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4516 .Do(() => this.ListTab.SelectedIndex = 1),
4518 ShortcutCommand.Create(Keys.Control | Keys.D3)
4519 .FocusedOn(FocusedControl.ListTab)
4520 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4521 .Do(() => this.ListTab.SelectedIndex = 2),
4523 ShortcutCommand.Create(Keys.Control | Keys.D4)
4524 .FocusedOn(FocusedControl.ListTab)
4525 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4526 .Do(() => this.ListTab.SelectedIndex = 3),
4528 ShortcutCommand.Create(Keys.Control | Keys.D5)
4529 .FocusedOn(FocusedControl.ListTab)
4530 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4531 .Do(() => this.ListTab.SelectedIndex = 4),
4533 ShortcutCommand.Create(Keys.Control | Keys.D6)
4534 .FocusedOn(FocusedControl.ListTab)
4535 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4536 .Do(() => this.ListTab.SelectedIndex = 5),
4538 ShortcutCommand.Create(Keys.Control | Keys.D7)
4539 .FocusedOn(FocusedControl.ListTab)
4540 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4541 .Do(() => this.ListTab.SelectedIndex = 6),
4543 ShortcutCommand.Create(Keys.Control | Keys.D8)
4544 .FocusedOn(FocusedControl.ListTab)
4545 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4546 .Do(() => this.ListTab.SelectedIndex = 7),
4548 ShortcutCommand.Create(Keys.Control | Keys.D9)
4549 .FocusedOn(FocusedControl.ListTab)
4550 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4552 ShortcutCommand.Create(Keys.Control | Keys.A)
4553 .FocusedOn(FocusedControl.StatusText)
4554 .Do(() => this.StatusText.SelectAll()),
4556 ShortcutCommand.Create(Keys.Control | Keys.V)
4557 .FocusedOn(FocusedControl.StatusText)
4558 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4560 ShortcutCommand.Create(Keys.Control | Keys.Up)
4561 .FocusedOn(FocusedControl.StatusText)
4562 .Do(() => this.StatusTextHistoryBack()),
4564 ShortcutCommand.Create(Keys.Control | Keys.Down)
4565 .FocusedOn(FocusedControl.StatusText)
4566 .Do(() => this.StatusTextHistoryForward()),
4568 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4569 .FocusedOn(FocusedControl.StatusText)
4572 if (this.ListTab.SelectedIndex == 0)
4574 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4578 this.ListTab.SelectedIndex -= 1;
4580 this.StatusText.Focus();
4583 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4584 .FocusedOn(FocusedControl.StatusText)
4587 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4589 this.ListTab.SelectedIndex = 0;
4593 this.ListTab.SelectedIndex += 1;
4595 this.StatusText.Focus();
4598 ShortcutCommand.Create(Keys.Control | Keys.Y)
4599 .FocusedOn(FocusedControl.PostBrowser)
4602 var multiline = !this.settings.Local.StatusMultiline;
4603 this.settings.Local.StatusMultiline = multiline;
4604 this.MultiLineMenuItem.Checked = multiline;
4605 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4608 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4609 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4611 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4612 .Do(() => this.DoRefreshMore()),
4614 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4615 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4617 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4618 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4620 ShortcutCommand.Create(Keys.Shift | Keys.R)
4621 .NotFocusedOn(FocusedControl.StatusText)
4622 .Do(() => this.DoRefreshMore()),
4624 ShortcutCommand.Create(Keys.Shift | Keys.H)
4625 .FocusedOn(FocusedControl.ListTab)
4626 .Do(() => this.GoTopEnd(goTop: true)),
4628 ShortcutCommand.Create(Keys.Shift | Keys.L)
4629 .FocusedOn(FocusedControl.ListTab)
4630 .Do(() => this.GoTopEnd(goTop: false)),
4632 ShortcutCommand.Create(Keys.Shift | Keys.M)
4633 .FocusedOn(FocusedControl.ListTab)
4634 .Do(() => this.GoMiddle()),
4636 ShortcutCommand.Create(Keys.Shift | Keys.G)
4637 .FocusedOn(FocusedControl.ListTab)
4638 .Do(() => this.GoLast()),
4640 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4641 .FocusedOn(FocusedControl.ListTab)
4642 .Do(() => this.MoveMiddle()),
4644 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4645 .FocusedOn(FocusedControl.ListTab)
4646 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4648 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4649 .FocusedOn(FocusedControl.ListTab)
4650 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4652 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4653 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4654 .FocusedOn(FocusedControl.ListTab)
4655 .Do(() => this.GoFav(forward: true)),
4657 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4658 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4659 .FocusedOn(FocusedControl.ListTab)
4660 .Do(() => this.GoFav(forward: false)),
4662 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4663 .FocusedOn(FocusedControl.ListTab)
4664 .Do(() => this.GoBackSelectPostChain()),
4666 ShortcutCommand.Create(Keys.Alt | Keys.R)
4667 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4669 ShortcutCommand.Create(Keys.Alt | Keys.P)
4670 .OnlyWhen(() => this.CurrentPost != null)
4671 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4673 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4674 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4676 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4677 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4679 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4680 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4682 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4683 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4685 // 別タブの同じ書き込みへ(ALT+←/→)
4686 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4687 .FocusedOn(FocusedControl.ListTab)
4688 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4690 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4691 .FocusedOn(FocusedControl.ListTab)
4692 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4694 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4695 .Do(() => this.MakeReplyText(atAll: true)),
4697 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4698 .Do(() => this.CopyIdUri()),
4700 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4701 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4702 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4704 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4705 .Do(() => this.DoQuoteOfficial()),
4707 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4708 .Do(() => this.FavoriteChange(favAdd: false)),
4710 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4711 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4713 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4714 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4716 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4717 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4719 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4720 .Do(() => this.DoMoveToRTHome()),
4722 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4723 .FocusedOn(FocusedControl.StatusText)
4726 var tab = this.CurrentTab;
4727 var selectedIndex = tab.SelectedIndex;
4728 if (selectedIndex != -1 && selectedIndex > 0)
4730 var listView = this.CurrentListView;
4731 var idx = selectedIndex - 1;
4732 this.SelectListItem(listView, idx);
4733 listView.EnsureVisible(idx);
4737 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4738 .FocusedOn(FocusedControl.StatusText)
4741 var tab = this.CurrentTab;
4742 var selectedIndex = tab.SelectedIndex;
4743 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4745 var listView = this.CurrentListView;
4746 var idx = selectedIndex + 1;
4747 this.SelectListItem(listView, idx);
4748 listView.EnsureVisible(idx);
4752 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4753 .FocusedOn(FocusedControl.StatusText)
4756 if (this.StatusText.SelectionStart > 0)
4758 var endidx = this.StatusText.SelectionStart - 1;
4760 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4762 var c = this.StatusText.Text[i];
4763 if (char.IsLetterOrDigit(c) || c == '_')
4769 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4770 var cnt = this.AtIdSupl.ItemCount;
4771 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4772 if (this.AtIdSupl.ItemCount != cnt)
4773 this.MarkSettingAtIdModified();
4777 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4778 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4788 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4789 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4790 .FocusedOn(FocusedControl.ListTab)
4791 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4793 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4794 .FocusedOn(FocusedControl.ListTab)
4795 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4797 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4798 .FocusedOn(FocusedControl.ListTab)
4799 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4801 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4802 .FocusedOn(FocusedControl.ListTab)
4803 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4805 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4806 .FocusedOn(FocusedControl.ListTab)
4807 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4809 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4810 .FocusedOn(FocusedControl.ListTab)
4811 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4813 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4814 .FocusedOn(FocusedControl.ListTab)
4815 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4817 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4818 .FocusedOn(FocusedControl.ListTab)
4819 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4821 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4822 .FocusedOn(FocusedControl.ListTab)
4823 .Do(() => this.SetSortLastColumn()),
4825 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4826 .FocusedOn(FocusedControl.ListTab)
4827 .Do(() => this.FavoritesRetweetOfficial()),
4829 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4830 .FocusedOn(FocusedControl.ListTab)
4831 .Do(() => this.FavoritesRetweetUnofficial()),
4833 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4834 .FocusedOn(FocusedControl.ListTab)
4835 .Do(() => this.OpenUserAppointUrl()),
4837 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4838 .FocusedOn(FocusedControl.PostBrowser)
4839 .Do(() => this.DoReTweetUnofficial()),
4841 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4842 .OnlyWhen(() => this.ExistCurrentPost)
4843 .Do(() => this.tweetDetailsView.DoTranslation()),
4845 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4846 .Do(() => this.DoReTweetUnofficial()),
4848 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4849 .Do(() => this.CopyUserId()),
4851 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4852 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4854 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4855 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4857 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4858 .FocusedOn(FocusedControl.ListTab)
4859 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4860 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4864 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4866 // Task を返す非同期処理があれば asyncTask に代入する
4869 // ShortcutCommand に対応しているコマンドはここで処理される
4870 foreach (var command in this.shortcutCommands)
4872 if (command.IsMatch(keyData, focusedOn))
4874 asyncTask = command.RunCommand();
4875 return command.PreventDefault;
4882 private void GoNextTab(bool forward)
4884 var idx = this.statuses.SelectedTabIndex;
4885 var tabCount = this.statuses.Tabs.Count;
4889 if (idx > tabCount - 1) idx = 0;
4894 if (idx < 0) idx = tabCount - 1;
4896 this.ListTab.SelectedIndex = idx;
4899 private void CopyStot()
4901 var sb = new StringBuilder();
4902 var tab = this.CurrentTab;
4903 var isProtected = false;
4904 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4905 foreach (var post in tab.SelectedPosts)
4907 if (post.IsDeleted) continue;
4910 if (post.RetweetedId != null)
4911 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4913 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4917 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4922 MessageBox.Show(Properties.Resources.CopyStotText1);
4926 var clstr = sb.ToString();
4929 Clipboard.SetDataObject(clstr, false, 5, 100);
4931 catch (Exception ex)
4933 MessageBox.Show(ex.Message);
4938 private void CopyIdUri()
4940 var tab = this.CurrentTab;
4941 if (tab == null || tab is DirectMessagesTabModel)
4944 var copyUrls = new List<string>();
4945 foreach (var post in tab.SelectedPosts)
4946 copyUrls.Add(MyCommon.GetStatusUrl(post));
4948 if (copyUrls.Count == 0)
4953 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4955 catch (ExternalException ex)
4957 MessageBox.Show(ex.Message);
4961 private void GoFav(bool forward)
4963 var tab = this.CurrentTab;
4964 if (tab.AllCount == 0)
4967 var selectedIndex = tab.SelectedIndex;
4975 if (selectedIndex == -1)
4981 fIdx = selectedIndex + 1;
4982 if (fIdx > tab.AllCount - 1)
4985 toIdx = tab.AllCount;
4990 if (selectedIndex == -1)
4992 fIdx = tab.AllCount - 1;
4996 fIdx = selectedIndex - 1;
5004 for (var idx = fIdx; idx != toIdx; idx += stp)
5008 var listView = this.CurrentListView;
5009 this.SelectListItem(listView, idx);
5010 listView.EnsureVisible(idx);
5016 private void GoSamePostToAnotherTab(bool left)
5018 var tab = this.CurrentTab;
5020 // Directタブは対象外(見つかるはずがない)
5021 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5024 var selectedStatusId = tab.SelectedStatusId;
5025 if (selectedStatusId == null)
5028 int fIdx, toIdx, stp;
5033 if (this.ListTab.SelectedIndex == 0)
5039 fIdx = this.ListTab.SelectedIndex - 1;
5047 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5053 fIdx = this.ListTab.SelectedIndex + 1;
5055 toIdx = this.ListTab.TabCount;
5059 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5061 var targetTab = this.statuses.Tabs[tabidx];
5064 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5067 var foundIndex = targetTab.IndexOf(selectedStatusId);
5068 if (foundIndex != -1)
5070 this.ListTab.SelectedIndex = tabidx;
5071 var listView = this.CurrentListView;
5072 this.SelectListItem(listView, foundIndex);
5073 listView.EnsureVisible(foundIndex);
5079 private void GoPost(bool forward)
5081 var tab = this.CurrentTab;
5082 var currentPost = this.CurrentPost;
5084 if (currentPost == null)
5087 var selectedIndex = tab.SelectedIndex;
5089 int fIdx, toIdx, stp;
5093 fIdx = selectedIndex + 1;
5094 if (fIdx > tab.AllCount - 1) return;
5095 toIdx = tab.AllCount;
5100 fIdx = selectedIndex - 1;
5101 if (fIdx < 0) return;
5107 if (currentPost.RetweetedBy == null)
5109 name = currentPost.ScreenName;
5113 name = currentPost.RetweetedBy;
5115 for (var idx = fIdx; idx != toIdx; idx += stp)
5117 var post = tab[idx];
5118 if (post.RetweetedId == null)
5120 if (post.ScreenName == name)
5122 var listView = this.CurrentListView;
5123 this.SelectListItem(listView, idx);
5124 listView.EnsureVisible(idx);
5130 if (post.RetweetedBy == name)
5132 var listView = this.CurrentListView;
5133 this.SelectListItem(listView, idx);
5134 listView.EnsureVisible(idx);
5141 private void GoRelPost(bool forward)
5143 var tab = this.CurrentTab;
5144 var selectedIndex = tab.SelectedIndex;
5146 if (selectedIndex == -1)
5149 int fIdx, toIdx, stp;
5153 fIdx = selectedIndex + 1;
5154 if (fIdx > tab.AllCount - 1) return;
5155 toIdx = tab.AllCount;
5160 fIdx = selectedIndex - 1;
5161 if (fIdx < 0) return;
5166 var anchorPost = tab.AnchorPost;
5167 if (anchorPost == null)
5169 var currentPost = this.CurrentPost;
5170 if (currentPost == null)
5173 anchorPost = currentPost;
5174 tab.AnchorPost = currentPost;
5177 for (var idx = fIdx; idx != toIdx; idx += stp)
5179 var post = tab[idx];
5180 if (post.ScreenName == anchorPost.ScreenName ||
5181 post.RetweetedBy == anchorPost.ScreenName ||
5182 post.ScreenName == anchorPost.RetweetedBy ||
5183 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5184 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5185 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5186 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5187 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5189 var listView = this.CurrentListView;
5190 this.SelectListItem(listView, idx);
5191 listView.EnsureVisible(idx);
5197 private void GoAnchor()
5199 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5200 if (anchorStatusId == null)
5203 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5207 var listView = this.CurrentListView;
5208 this.SelectListItem(listView, idx);
5209 listView.EnsureVisible(idx);
5212 private void GoTopEnd(bool goTop)
5214 var listView = this.CurrentListView;
5215 if (listView.VirtualListSize == 0)
5223 item = listView.GetItemAt(0, 25);
5231 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5233 idx = listView.VirtualListSize - 1;
5237 this.SelectListItem(listView, idx);
5240 private void GoMiddle()
5242 var listView = this.CurrentListView;
5243 if (listView.VirtualListSize == 0)
5251 item = listView.GetItemAt(0, 0);
5261 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5264 idx2 = listView.VirtualListSize - 1;
5270 idx3 = (idx1 + idx2) / 2;
5272 this.SelectListItem(listView, idx3);
5275 private void GoLast()
5277 var listView = this.CurrentListView;
5278 if (listView.VirtualListSize == 0) return;
5280 if (this.statuses.SortOrder == SortOrder.Ascending)
5282 this.SelectListItem(listView, listView.VirtualListSize - 1);
5283 listView.EnsureVisible(listView.VirtualListSize - 1);
5287 this.SelectListItem(listView, 0);
5288 listView.EnsureVisible(0);
5292 private void MoveTop()
5294 var listView = this.CurrentListView;
5295 if (listView.SelectedIndices.Count == 0) return;
5296 var idx = listView.SelectedIndices[0];
5297 if (this.statuses.SortOrder == SortOrder.Ascending)
5299 listView.EnsureVisible(listView.VirtualListSize - 1);
5303 listView.EnsureVisible(0);
5305 listView.EnsureVisible(idx);
5308 private async Task GoInReplyToPostTree()
5310 var curTabClass = this.CurrentTab;
5311 var currentPost = this.CurrentPost;
5313 if (currentPost == null)
5316 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5320 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5322 currentPost = currentPost with
5324 InReplyToStatusId = post.InReplyToStatusId,
5325 InReplyToUser = post.InReplyToUser,
5326 IsReply = post.IsReply,
5328 curTabClass.ReplacePost(currentPost);
5329 this.listCache?.PurgeCache();
5331 var index = curTabClass.SelectedIndex;
5332 this.CurrentListView.RedrawItems(index, index, false);
5334 catch (WebApiException ex)
5336 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5340 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5342 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5344 this.replyChains = new Stack<ReplyChain>();
5346 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5349 string inReplyToTabName;
5350 var inReplyToId = currentPost.InReplyToStatusId;
5351 var inReplyToUser = currentPost.InReplyToUser;
5353 var inReplyToPosts = from tab in this.statuses.Tabs
5354 orderby tab != curTabClass
5355 from post in tab.Posts.Values
5356 where post.StatusId == inReplyToId
5357 let index = tab.IndexOf(post.StatusId)
5359 select new { Tab = tab, Index = index };
5361 var inReplyPost = inReplyToPosts.FirstOrDefault();
5362 if (inReplyPost == null)
5366 await Task.Run(async () =>
5368 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5369 .ConfigureAwait(false);
5372 this.statuses.AddPost(post);
5373 this.statuses.DistributePosts();
5376 catch (WebApiException ex)
5378 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5379 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5383 this.RefreshTimeline();
5385 inReplyPost = inReplyToPosts.FirstOrDefault();
5386 if (inReplyPost == null)
5388 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5392 inReplyToTabName = inReplyPost.Tab.TabName;
5393 inReplyToIndex = inReplyPost.Index;
5395 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5396 var tabPage = this.ListTab.TabPages[tabIndex];
5397 var listView = (DetailsListView)tabPage.Tag;
5399 if (this.CurrentTabName != inReplyToTabName)
5401 this.ListTab.SelectedIndex = tabIndex;
5404 this.SelectListItem(listView, inReplyToIndex);
5405 listView.EnsureVisible(inReplyToIndex);
5408 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5410 var curTabClass = this.CurrentTab;
5411 var currentPost = this.CurrentPost;
5413 if (currentPost == null)
5418 if (currentPost.InReplyToStatusId != null)
5420 var posts = from t in this.statuses.Tabs
5422 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5423 let indexOf = t.IndexOf(p.Value.StatusId)
5425 orderby isForward ? indexOf : indexOf * -1
5426 orderby t != curTabClass
5427 select new { Tab = t, Post = p.Value, Index = indexOf };
5430 var postList = posts.ToList();
5431 for (var i = postList.Count - 1; i >= 0; i--)
5434 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5436 postList.RemoveAt(index);
5439 var currentIndex = this.CurrentTab.SelectedIndex;
5440 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5441 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5442 if (post == null) post = postList.First();
5443 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5444 this.ListTab.SelectedIndex = tabIndex;
5445 var listView = this.CurrentListView;
5446 this.SelectListItem(listView, post.Index);
5447 listView.EnsureVisible(post.Index);
5449 catch (InvalidOperationException)
5457 if (this.replyChains == null || this.replyChains.Count < 1)
5459 var posts = from t in this.statuses.Tabs
5461 where p.Value.InReplyToStatusId == currentPost.StatusId
5462 let indexOf = t.IndexOf(p.Value.StatusId)
5465 orderby t != curTabClass
5466 select new { Tab = t, Index = indexOf };
5469 var post = posts.First();
5470 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5471 this.ListTab.SelectedIndex = tabIndex;
5472 var listView = this.CurrentListView;
5473 this.SelectListItem(listView, post.Index);
5474 listView.EnsureVisible(post.Index);
5476 catch (InvalidOperationException)
5483 var chainHead = this.replyChains.Pop();
5484 if (chainHead.InReplyToId == currentPost.StatusId)
5486 var tab = chainHead.OriginalTab;
5487 if (!this.statuses.Tabs.Contains(tab))
5489 this.replyChains = null;
5493 var idx = tab.IndexOf(chainHead.OriginalId);
5496 this.replyChains = null;
5500 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5503 this.ListTab.SelectedIndex = tabIndex;
5507 this.replyChains = null;
5509 var listView = this.CurrentListView;
5510 this.SelectListItem(listView, idx);
5511 listView.EnsureVisible(idx);
5517 this.replyChains = null;
5518 this.GoBackInReplyToPostTree(parallel);
5524 private void GoBackSelectPostChain()
5526 if (this.selectPostChains.Count > 1)
5529 TabModel? foundTab = null;
5535 this.selectPostChains.Pop();
5536 var (tab, post) = this.selectPostChains.Peek();
5538 if (!this.statuses.Tabs.Contains(tab))
5539 continue; // 該当タブが存在しないので無視
5543 idx = tab.IndexOf(post.StatusId);
5544 if (idx == -1) continue; // 該当ポストが存在しないので無視
5549 this.selectPostChains.Pop();
5551 catch (InvalidOperationException)
5557 while (this.selectPostChains.Count > 1);
5559 if (foundTab == null)
5562 // 履歴が残り1つであればクリアしておく
5563 if (this.selectPostChains.Count == 1)
5564 this.selectPostChains.Clear();
5568 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5569 var tabPage = this.ListTab.TabPages[tabIndex];
5570 var lst = (DetailsListView)tabPage.Tag;
5571 this.ListTab.SelectedIndex = tabIndex;
5575 this.SelectListItem(lst, idx);
5576 lst.EnsureVisible(idx);
5582 private void PushSelectPostChain()
5584 var currentTab = this.CurrentTab;
5585 var currentPost = this.CurrentPost;
5587 var count = this.selectPostChains.Count;
5590 var (tab, post) = this.selectPostChains.Peek();
5591 if (tab == currentTab)
5593 if (post == currentPost) return; // 最新の履歴と同一
5594 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5597 if (count >= 2500) this.TrimPostChain();
5598 this.selectPostChains.Push((currentTab, currentPost));
5601 private void TrimPostChain()
5603 if (this.selectPostChains.Count <= 2000) return;
5604 var p = new Stack<(TabModel, PostClass?)>(2000);
5605 for (var i = 0; i < 2000; i++)
5607 p.Push(this.selectPostChains.Pop());
5609 this.selectPostChains.Clear();
5610 for (var i = 0; i < 2000; i++)
5612 this.selectPostChains.Push(p.Pop());
5616 private bool GoStatus(PostId statusId)
5618 var tab = this.statuses.Tabs
5619 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5620 .Where(x => x.Contains(statusId))
5626 var index = tab.IndexOf(statusId);
5628 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5629 this.ListTab.SelectedIndex = tabIndex;
5631 var listView = this.CurrentListView;
5632 this.SelectListItem(listView, index);
5633 listView.EnsureVisible(index);
5638 private bool GoDirectMessage(PostId statusId)
5640 var tab = this.statuses.DirectMessageTab;
5641 var index = tab.IndexOf(statusId);
5646 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5647 this.ListTab.SelectedIndex = tabIndex;
5649 var listView = this.CurrentListView;
5650 this.SelectListItem(listView, index);
5651 listView.EnsureVisible(index);
5656 private void MyList_MouseClick(object sender, MouseEventArgs e)
5657 => this.CurrentTab.ClearAnchor();
5659 private void StatusText_Enter(object sender, EventArgs e)
5661 // フォーカスの戻り先を StatusText に設定
5662 this.Tag = this.StatusText;
5663 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5666 public Color InputBackColor
5667 => this.themeManager.ColorInputBackcolor;
5669 private void StatusText_Leave(object sender, EventArgs e)
5671 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5672 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5673 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5676 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5678 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5681 e.SuppressKeyPress = true;
5684 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5686 if (asyncTask != null)
5690 private void SaveConfigsAll(bool ifModified)
5694 this.SaveConfigsCommon();
5695 this.SaveConfigsLocal();
5696 this.SaveConfigsTabs();
5697 this.SaveConfigsAtId();
5701 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5702 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5703 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5707 private void SaveConfigsAtId()
5709 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5711 this.ModifySettingAtId = false;
5712 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5713 this.settings.SaveAtIdList();
5716 private void SaveConfigsCommon()
5718 if (this.ignoreConfigSave) return;
5720 this.ModifySettingCommon = false;
5721 lock (this.syncObject)
5723 this.settings.Common.UserName = this.tw.Username;
5724 this.settings.Common.UserId = this.tw.UserId;
5725 this.settings.Common.Token = this.tw.AccessToken;
5726 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5727 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5728 this.settings.Common.SortColumn = this.statuses.SortMode switch
5730 ComparerMode.Nickname => 1, // ニックネーム
5731 ComparerMode.Data => 2, // 本文
5732 ComparerMode.Id => 3, // 時刻=発言Id
5733 ComparerMode.Name => 4, // 名前
5734 ComparerMode.Source => 7, // Source
5735 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5737 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5738 if (this.HashMgr.IsPermanent)
5740 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5744 this.settings.Common.HashSelected = "";
5746 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5747 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5748 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5749 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5750 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5752 this.settings.SaveCommon();
5756 private void SaveConfigsLocal()
5758 if (this.ignoreConfigSave) return;
5759 lock (this.syncObject)
5761 this.ModifySettingLocal = false;
5762 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5763 this.settings.Local.FormSize = this.mySize;
5764 this.settings.Local.FormLocation = this.myLoc;
5765 this.settings.Local.SplitterDistance = this.mySpDis;
5766 this.settings.Local.PreviewDistance = this.mySpDis3;
5767 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5768 this.settings.Local.StatusTextHeight = this.mySpDis2;
5770 if (this.ignoreConfigSave) return;
5771 this.settings.SaveLocal();
5775 private void SaveConfigsTabs()
5777 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5779 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5781 foreach (var tab in tabs)
5783 if (!tab.IsPermanentTabType)
5786 var tabSetting = new SettingTabs.SettingTabItem
5788 TabName = tab.TabName,
5789 TabType = tab.TabType,
5790 UnreadManage = tab.UnreadManage,
5791 Protected = tab.Protected,
5792 Notify = tab.Notify,
5793 SoundFile = tab.SoundFile,
5798 case FilterTabModel filterTab:
5799 tabSetting.FilterArray = filterTab.FilterArray;
5801 case UserTimelineTabModel userTab:
5802 tabSetting.User = userTab.ScreenName;
5804 case PublicSearchTabModel searchTab:
5805 tabSetting.SearchWords = searchTab.SearchWords;
5806 tabSetting.SearchLang = searchTab.SearchLang;
5808 case ListTimelineTabModel listTab:
5809 tabSetting.ListInfo = listTab.ListInfo;
5813 tabSettingList.Add(tabSetting);
5816 this.settings.Tabs.Tabs = tabSettingList;
5817 this.settings.SaveTabs();
5820 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5822 static void ShowFormatErrorDialog(IWin32Window owner)
5826 Properties.Resources.OpenURL_InvalidFormat,
5827 Properties.Resources.OpenURL_Caption,
5828 MessageBoxButtons.OK,
5829 MessageBoxIcon.Error
5833 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5834 if (ret != DialogResult.OK)
5837 var match = Twitter.StatusUrlRegex.Match(inputText);
5840 ShowFormatErrorDialog(this);
5846 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5847 await this.OpenRelatedTab(statusId);
5849 catch (OverflowException)
5851 ShowFormatErrorDialog(this);
5853 catch (TabException ex)
5855 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5859 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5861 var tab = this.CurrentTab;
5863 var rslt = MessageBox.Show(
5864 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5865 Properties.Resources.SaveLogMenuItem_ClickText2,
5866 MessageBoxButtons.YesNoCancel,
5867 MessageBoxIcon.Question);
5868 if (rslt == DialogResult.Cancel) return;
5870 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5871 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5872 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5873 this.SaveFileDialog1.FilterIndex = 0;
5874 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5875 this.SaveFileDialog1.RestoreDirectory = true;
5877 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5879 if (!this.SaveFileDialog1.ValidateNames) return;
5880 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5881 if (rslt == DialogResult.Yes)
5884 for (var idx = 0; idx < tab.AllCount; idx++)
5886 var post = tab[idx];
5889 protect = "Protect";
5890 sw.WriteLine(post.Nickname + "\t" +
5891 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5892 post.CreatedAt.ToLocalTimeString() + "\t" +
5893 post.ScreenName + "\t" +
5894 post.StatusId.Id + "\t" +
5895 post.ImageUrl + "\t" +
5896 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5902 foreach (var post in this.CurrentTab.SelectedPosts)
5906 protect = "Protect";
5907 sw.WriteLine(post.Nickname + "\t" +
5908 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5909 post.CreatedAt.ToLocalTimeString() + "\t" +
5910 post.ScreenName + "\t" +
5911 post.StatusId.Id + "\t" +
5912 post.ImageUrl + "\t" +
5913 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5918 this.TopMost = this.settings.Common.AlwaysTop;
5921 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5925 using (var inputName = new InputTabName())
5927 inputName.TabName = origTabName;
5928 inputName.ShowDialog();
5929 if (inputName.DialogResult == DialogResult.Cancel) return false;
5930 newTabName = inputName.TabName;
5932 this.TopMost = this.settings.Common.AlwaysTop;
5933 if (!MyCommon.IsNullOrEmpty(newTabName))
5936 if (this.statuses.ContainsTab(newTabName))
5938 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5939 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5943 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5944 var tabPage = this.ListTab.TabPages[tabIndex];
5947 if (tabPage != null)
5948 tabPage.Text = newTabName;
5950 this.statuses.RenameTab(origTabName, newTabName);
5952 var state = this.listViewState[origTabName];
5953 this.listViewState.Remove(origTabName);
5954 this.listViewState[newTabName] = state;
5956 this.SaveConfigsCommon();
5957 this.SaveConfigsTabs();
5958 this.rclickTabName = newTabName;
5967 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5969 if (e.Button == MouseButtons.Middle)
5971 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5973 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5975 this.RemoveSpecifiedTab(tab.TabName, true);
5976 this.SaveConfigsTabs();
5983 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5984 => this.TabRename(this.CurrentTabName, out _);
5986 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5988 if (this.settings.Common.TabMouseLock) return;
5989 if (e.Button == MouseButtons.Left)
5991 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5993 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5995 this.tabDrag = true;
5996 this.tabMouseDownPoint = e.Location;
6003 this.tabDrag = false;
6007 private void ListTab_DragEnter(object sender, DragEventArgs e)
6009 if (e.Data.GetDataPresent(typeof(TabPage)))
6010 e.Effect = DragDropEffects.Move;
6012 e.Effect = DragDropEffects.None;
6015 private void ListTab_DragDrop(object sender, DragEventArgs e)
6017 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
6019 this.tabDrag = false;
6022 var cpos = new Point(e.X, e.Y);
6023 var spos = this.ListTab.PointToClient(cpos);
6024 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6026 var rect = this.ListTab.GetTabRect(index);
6027 if (rect.Contains(spos))
6030 if (spos.X <= (rect.Left + rect.Right) / 2)
6039 // タブのないところにドロップ->最後尾へ移動
6040 if (MyCommon.IsNullOrEmpty(tn))
6042 var lastTab = this.statuses.Tabs.Last();
6043 tn = lastTab.TabName;
6047 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6048 if (tp.Text == tn) return;
6050 this.ReOrderTab(tp.Text, tn, bef);
6053 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6055 var baseIndex = this.GetTabPageIndex(baseTabText);
6056 if (baseIndex == -1)
6059 var targetIndex = this.GetTabPageIndex(targetTabText);
6060 if (targetIndex == -1)
6063 using (ControlTransaction.Layout(this.ListTab))
6065 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6066 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6067 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6068 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6070 var tab = this.statuses.Tabs[targetIndex];
6071 var tabPage = this.ListTab.TabPages[targetIndex];
6073 this.ListTab.TabPages.Remove(tabPage);
6075 if (targetIndex < baseIndex)
6078 if (!isBeforeBaseTab)
6081 this.statuses.MoveTab(baseIndex, tab);
6083 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6086 this.SaveConfigsTabs();
6089 private void MakeDirectMessageText()
6091 var selectedPosts = this.CurrentTab.SelectedPosts;
6092 if (selectedPosts.Length > 1)
6095 var post = selectedPosts.Single();
6096 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6098 this.inReplyTo = null;
6099 this.StatusText.Text = text;
6100 this.StatusText.SelectionStart = text.Length;
6101 this.StatusText.Focus();
6104 private void MakeReplyText(bool atAll = false)
6106 var selectedPosts = this.CurrentTab.SelectedPosts;
6107 if (selectedPosts.Any(x => x.IsDm))
6109 this.MakeDirectMessageText();
6113 if (selectedPosts.Length == 1)
6115 var post = selectedPosts.Single();
6116 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6117 var inReplyToScreenName = post.ScreenName;
6118 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6122 this.inReplyTo = null;
6125 var selfScreenName = this.tw.Username;
6126 var targetScreenNames = new List<string>();
6127 foreach (var post in selectedPosts)
6129 if (post.ScreenName != selfScreenName)
6130 targetScreenNames.Add(post.ScreenName);
6134 foreach (var (_, screenName) in post.ReplyToList)
6136 if (screenName != selfScreenName)
6137 targetScreenNames.Add(screenName);
6142 if (this.inReplyTo != null)
6144 var (_, screenName) = this.inReplyTo.Value;
6145 if (screenName == selfScreenName)
6146 targetScreenNames.Insert(0, screenName);
6149 var text = this.StatusText.Text;
6150 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6152 var atText = $"@{screenName} ";
6153 if (!text.Contains(atText))
6154 text = atText + text;
6157 this.StatusText.Text = text;
6158 this.StatusText.SelectionStart = text.Length;
6159 this.StatusText.Focus();
6162 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6163 => this.tabDrag = false;
6165 private int iconCnt = 0;
6166 private int blinkCnt = 0;
6167 private bool blink = false;
6169 private void RefreshTasktrayIcon()
6171 void EnableTasktrayAnimation()
6172 => this.TimerRefreshIcon.Enabled = true;
6174 void DisableTasktrayAnimation()
6175 => this.TimerRefreshIcon.Enabled = false;
6177 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6181 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6184 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6185 this.myStatusError = false;
6186 EnableTasktrayAnimation();
6190 var replyIconType = this.settings.Common.ReplyIconState;
6192 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6194 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6195 if (replyTab != null && replyTab.UnreadCount > 0)
6199 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6202 if (this.blinkCnt > 10)
6205 if (this.blinkCnt == 0)
6206 this.blink = !this.blink;
6208 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6209 EnableTasktrayAnimation();
6213 DisableTasktrayAnimation();
6219 // 優先度:リプライ→エラー→オフライン→アイドル
6220 // エラーは更新アイコンでクリアされる
6221 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6222 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6223 else if (this.myStatusError)
6224 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6225 else if (this.myStatusOnline)
6226 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6228 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6231 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6232 => this.RefreshTasktrayIcon(); // 200ms
6234 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6236 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6237 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6238 this.rclickTabName = this.CurrentTabName;
6240 if (this.statuses == null) return;
6241 if (this.statuses.Tabs == null) return;
6243 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6246 this.NotifyDispMenuItem.Checked = tb.Notify;
6247 this.NotifyTbMenuItem.Checked = tb.Notify;
6249 this.soundfileListup = true;
6250 this.SoundFileComboBox.Items.Clear();
6251 this.SoundFileTbComboBox.Items.Clear();
6252 this.SoundFileComboBox.Items.Add("");
6253 this.SoundFileTbComboBox.Items.Add("");
6254 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6255 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6257 oDir = oDir.GetDirectories("Sounds")[0];
6259 foreach (var oFile in oDir.GetFiles("*.wav"))
6261 this.SoundFileComboBox.Items.Add(oFile.Name);
6262 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6264 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6265 if (idx == -1) idx = 0;
6266 this.SoundFileComboBox.SelectedIndex = idx;
6267 this.SoundFileTbComboBox.SelectedIndex = idx;
6268 this.soundfileListup = false;
6269 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6270 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6272 this.TabMenuControl(this.rclickTabName);
6275 private void TabMenuControl(string tabName)
6277 var tabInfo = this.statuses.GetTabByName(tabName)!;
6279 this.FilterEditMenuItem.Enabled = true;
6280 this.EditRuleTbMenuItem.Enabled = true;
6282 if (tabInfo.IsDefaultTabType)
6284 this.ProtectTabMenuItem.Enabled = false;
6285 this.ProtectTbMenuItem.Enabled = false;
6289 this.ProtectTabMenuItem.Enabled = true;
6290 this.ProtectTbMenuItem.Enabled = true;
6293 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6295 this.ProtectTabMenuItem.Checked = true;
6296 this.ProtectTbMenuItem.Checked = true;
6297 this.DeleteTabMenuItem.Enabled = false;
6298 this.DeleteTbMenuItem.Enabled = false;
6302 this.ProtectTabMenuItem.Checked = false;
6303 this.ProtectTbMenuItem.Checked = false;
6304 this.DeleteTabMenuItem.Enabled = true;
6305 this.DeleteTbMenuItem.Enabled = true;
6309 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6311 var checkState = ((ToolStripMenuItem)sender).Checked;
6314 this.ProtectTbMenuItem.Checked = checkState;
6315 this.ProtectTabMenuItem.Checked = checkState;
6318 this.DeleteTabMenuItem.Enabled = !checkState;
6319 this.DeleteTbMenuItem.Enabled = !checkState;
6321 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6322 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6324 this.SaveConfigsTabs();
6327 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6329 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6330 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6332 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6333 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6335 this.SaveConfigsTabs();
6338 public void ChangeTabUnreadManage(string tabName, bool isManage)
6340 var idx = this.GetTabPageIndex(tabName);
6344 var tab = this.statuses.Tabs[tabName];
6345 tab.UnreadManage = isManage;
6347 if (this.settings.Common.TabIconDisp)
6349 var tabPage = this.ListTab.TabPages[idx];
6350 if (tab.UnreadCount > 0)
6351 tabPage.ImageIndex = 0;
6353 tabPage.ImageIndex = -1;
6356 if (this.CurrentTabName == tabName)
6358 this.listCache?.PurgeCache();
6359 this.CurrentListView.Refresh();
6362 this.SetMainWindowTitle();
6363 this.SetStatusLabelUrl();
6364 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6367 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6369 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6370 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6372 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6374 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6376 this.SaveConfigsTabs();
6379 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6381 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6383 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6385 this.SaveConfigsTabs();
6388 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6390 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6391 this.rclickTabName = this.CurrentTabName;
6393 this.RemoveSpecifiedTab(this.rclickTabName, true);
6394 this.SaveConfigsTabs();
6397 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6399 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6401 using (var fltDialog = new FilterDialog())
6403 fltDialog.Owner = this;
6404 fltDialog.SetCurrent(this.rclickTabName);
6405 fltDialog.ShowDialog(this);
6407 this.TopMost = this.settings.Common.AlwaysTop;
6409 this.ApplyPostFilters();
6410 this.SaveConfigsTabs();
6413 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6415 string? tabName = null;
6416 MyCommon.TabUsageType tabUsage;
6417 using (var inputName = new InputTabName())
6419 inputName.TabName = this.statuses.MakeTabName("MyTab");
6420 inputName.IsShowUsage = true;
6421 inputName.ShowDialog();
6422 if (inputName.DialogResult == DialogResult.Cancel) return;
6423 tabName = inputName.TabName;
6424 tabUsage = inputName.Usage;
6426 this.TopMost = this.settings.Common.AlwaysTop;
6427 if (!MyCommon.IsNullOrEmpty(tabName))
6430 ListElement? list = null;
6431 if (tabUsage == MyCommon.TabUsageType.Lists)
6433 using var listAvail = new ListAvailable();
6434 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6436 if (listAvail.SelectedList == null)
6438 list = listAvail.SelectedList;
6444 case MyCommon.TabUsageType.UserDefined:
6445 tab = new FilterTabModel(tabName);
6447 case MyCommon.TabUsageType.PublicSearch:
6448 tab = new PublicSearchTabModel(tabName);
6450 case MyCommon.TabUsageType.Lists:
6451 tab = new ListTimelineTabModel(tabName, list!);
6457 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6459 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6460 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6465 this.SaveConfigsTabs();
6467 var tabIndex = this.statuses.Tabs.Count - 1;
6469 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6471 this.ListTab.SelectedIndex = tabIndex;
6472 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6474 if (tabUsage == MyCommon.TabUsageType.Lists)
6476 this.ListTab.SelectedIndex = tabIndex;
6477 await this.RefreshTabAsync(this.CurrentTab);
6483 private void TabMenuItem_Click(object sender, EventArgs e)
6486 foreach (var post in this.CurrentTab.SelectedPosts)
6489 if (!this.SelectTab(out var tab))
6492 using (var fltDialog = new FilterDialog())
6494 fltDialog.Owner = this;
6495 fltDialog.SetCurrent(tab.TabName);
6497 if (post.RetweetedBy == null)
6499 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6503 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6505 fltDialog.ShowDialog(this);
6508 this.TopMost = this.settings.Common.AlwaysTop;
6511 this.ApplyPostFilters();
6512 this.SaveConfigsTabs();
6515 protected override bool ProcessDialogKey(Keys keyData)
6517 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6518 if ((keyData & Keys.KeyCode) == Keys.Enter)
6520 if (this.StatusText.Focused)
6522 var newLine = false;
6525 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6527 if (this.StatusText.Multiline)
6529 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6531 if ((keyData & Keys.Control) == Keys.Control) post = true;
6535 if ((keyData & Keys.Control) == Keys.Control) post = true;
6538 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6540 if (this.StatusText.Multiline)
6542 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6544 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6548 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6553 if (this.StatusText.Multiline)
6555 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6557 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6558 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6562 if (((keyData & Keys.Shift) == Keys.Shift) ||
6563 (((keyData & Keys.Control) != Keys.Control) &&
6564 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6570 var pos1 = this.StatusText.SelectionStart;
6571 if (this.StatusText.SelectionLength > 0)
6573 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6575 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6576 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6581 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6587 var tab = this.CurrentTab;
6588 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6590 var tabPage = this.CurrentTabPage;
6591 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6592 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6594 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6601 return base.ProcessDialogKey(keyData);
6604 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6605 => this.MakeReplyText(atAll: true);
6607 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6609 var tab = this.CurrentTab;
6610 var selectedPosts = tab.SelectedPosts;
6613 if (selectedPosts.Length == 0)
6616 var screenNameArray = selectedPosts
6617 .Select(x => x.RetweetedBy ?? x.ScreenName)
6620 this.AddFilterRuleByScreenName(screenNameArray);
6622 if (screenNameArray.Length != 0)
6624 var atids = new List<string>();
6625 foreach (var screenName in screenNameArray)
6627 atids.Add("@" + screenName);
6629 var cnt = this.AtIdSupl.ItemCount;
6630 this.AtIdSupl.AddRangeItem(atids.ToArray());
6631 if (this.AtIdSupl.ItemCount != cnt)
6632 this.MarkSettingAtIdModified();
6636 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6638 var tab = this.CurrentTab;
6639 var selectedPosts = tab.SelectedPosts;
6641 if (selectedPosts.Length == 0)
6644 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6646 this.AddFilterRuleBySource(sourceArray);
6649 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6652 if (!this.SelectTab(out var tab)) return;
6656 if (tab.TabType != MyCommon.TabUsageType.Mute)
6658 this.MoveOrCopy(out mv, out mk);
6662 // ミュートタブでは常に MoveMatches を true にする
6667 foreach (var screenName in screenNameArray)
6669 tab.AddFilter(new PostFilterRule
6671 FilterName = screenName,
6672 UseNameField = true,
6676 FilterByUrl = false,
6680 this.ApplyPostFilters();
6681 this.SaveConfigsTabs();
6684 public void AddFilterRuleBySource(params string[] sourceArray)
6686 // タブ選択ダイアログを表示(or追加)
6687 if (!this.SelectTab(out var filterTab))
6692 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6694 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6695 this.MoveOrCopy(out mv, out mk);
6699 // ミュートタブでは常に MoveMatches を true にする
6704 // 振り分けルールに追加するSource
6705 foreach (var source in sourceArray)
6707 filterTab.AddFilter(new PostFilterRule
6709 FilterSource = source,
6713 FilterByUrl = false,
6717 this.ApplyPostFilters();
6718 this.SaveConfigsTabs();
6721 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6728 using (var dialog = new TabsDialog(this.statuses))
6730 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6732 tab = dialog.SelectedTab;
6735 this.CurrentTabPage.Focus();
6740 using (var inputName = new InputTabName())
6742 inputName.TabName = this.statuses.MakeTabName("MyTab");
6743 inputName.ShowDialog();
6744 if (inputName.DialogResult == DialogResult.Cancel) return false;
6745 tabName = inputName.TabName;
6747 this.TopMost = this.settings.Common.AlwaysTop;
6748 if (!MyCommon.IsNullOrEmpty(tabName))
6750 var newTab = new FilterTabModel(tabName);
6751 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6753 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6754 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6773 private void MoveOrCopy(out bool move, out bool mark)
6777 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6778 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6786 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6787 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6798 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6801 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6802 => this.CopyIdUri();
6804 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6806 if (this.StatusText.Focused)
6809 this.StatusText.SelectAll();
6813 // ListView上でのCtrl+A
6814 NativeMethods.SelectAllItems(this.CurrentListView);
6818 private void MoveMiddle()
6824 var listView = this.CurrentListView;
6825 if (listView.SelectedIndices.Count == 0) return;
6827 var idx = listView.SelectedIndices[0];
6829 item = listView.GetItemAt(0, 25);
6835 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6837 idx2 = listView.VirtualListSize - 1;
6841 idx -= Math.Abs(idx1 - idx2) / 2;
6842 if (idx < 0) idx = 0;
6844 listView.EnsureVisible(listView.VirtualListSize - 1);
6845 listView.EnsureVisible(idx);
6848 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6850 var linkElements = this.tweetDetailsView.GetLinkElements();
6852 if (linkElements.Length == 0)
6855 var links = new List<OpenUrlItem>(linkElements.Length);
6857 foreach (var linkElm in linkElements)
6859 var displayUrl = linkElm.GetAttribute("title");
6860 var href = linkElm.GetAttribute("href");
6861 var linkedText = linkElm.InnerText;
6863 if (MyCommon.IsNullOrEmpty(displayUrl))
6866 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6870 bool isReverseSettings;
6872 if (links.Count == 1)
6874 // ツイートに含まれる URL が 1 つのみの場合
6875 // => OpenURL ダイアログを表示せずにリンクを開く
6876 selectedUrl = links[0].Href;
6878 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6879 isReverseSettings = false;
6883 // ツイートに含まれる URL が複数ある場合
6884 // => OpenURL を表示しユーザーが選択したリンクを開く
6885 this.urlDialog.ClearUrl();
6887 foreach (var link in links)
6888 this.urlDialog.AddUrl(link);
6890 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6893 this.TopMost = this.settings.Common.AlwaysTop;
6895 selectedUrl = this.urlDialog.SelectedUrl;
6897 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6898 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6901 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6904 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6906 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6907 this.ClearTab(this.rclickTabName, true);
6910 private void ClearTab(string tabName, bool showWarning)
6914 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6915 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6921 this.statuses.ClearTabIds(tabName);
6922 if (this.CurrentTabName == tabName)
6924 this.CurrentTab.ClearAnchor();
6925 this.listCache?.PurgeCache();
6926 this.listCache?.UpdateListSize();
6929 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6930 var tabPage = this.ListTab.TabPages[tabIndex];
6931 tabPage.ImageIndex = -1;
6933 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6935 this.SetMainWindowTitle();
6936 this.SetStatusLabelUrl();
6939 private static long followers = 0;
6941 private void SetMainWindowTitle()
6943 // メインウインドウタイトルの書き換え
6944 var ttl = new StringBuilder(256);
6947 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6948 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6949 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6950 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6952 foreach (var tab in this.statuses.Tabs)
6954 ur += tab.UnreadCount;
6959 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6960 ttl.Append(ApplicationSettings.ApplicationName);
6962 switch (this.settings.Common.DispLatestPost)
6964 case MyCommon.DispTitleEnum.Ver:
6965 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6967 case MyCommon.DispTitleEnum.Post:
6968 if (this.history != null && this.history.Count > 1)
6969 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6971 case MyCommon.DispTitleEnum.UnreadRepCount:
6972 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6974 case MyCommon.DispTitleEnum.UnreadAllCount:
6975 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6977 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6978 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6980 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6981 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6983 case MyCommon.DispTitleEnum.OwnStatus:
6984 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6985 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6991 this.Text = ttl.ToString();
6993 catch (AccessViolationException)
6995 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6999 private string GetStatusLabelText()
7002 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
7003 if (this.statuses == null) return "";
7004 var tbRep = this.statuses.MentionTab;
7005 var tbDm = this.statuses.DirectMessageTab;
7006 if (tbRep == null || tbDm == null) return "";
7007 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
7012 var slbl = new StringBuilder(256);
7015 foreach (var tab in this.statuses.Tabs)
7017 ur += tab.UnreadCount;
7019 if (tab.TabName == this.CurrentTabName)
7021 tur = tab.UnreadCount;
7031 this.unreadCounter = ur;
7032 this.unreadAtCounter = urat;
7034 var homeTab = this.statuses.HomeTab;
7036 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7037 if (this.settings.Common.TimelinePeriod == 0)
7039 slbl.Append(Properties.Resources.SetStatusLabelText2);
7043 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7045 return slbl.ToString();
7048 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7052 if (this.InvokeRequired && !this.IsDisposed)
7054 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7058 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7059 this.SetApiStatusLabel(endpointName);
7062 catch (ObjectDisposedException)
7066 catch (InvalidOperationException)
7072 private void SetApiStatusLabel(string? endpointName = null)
7074 var tabType = this.CurrentTab.TabType;
7076 if (endpointName == null)
7079 endpointName = tabType switch
7081 MyCommon.TabUsageType.Home => GetTimelineRequest.EndpointName,
7082 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7083 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7084 MyCommon.TabUsageType.Favorites => "/favorites/list",
7085 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7086 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7087 MyCommon.TabUsageType.Lists => "/lists/statuses",
7088 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7089 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7092 this.toolStripApiGauge.ApiEndpoint = endpointName;
7096 // 表示中のタブに関連する endpoint であれば更新
7098 if (endpointName == GetTimelineRequest.EndpointName)
7100 update = tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined;
7104 update = endpointName switch
7106 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7107 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7108 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7109 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7110 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7111 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7112 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7119 this.toolStripApiGauge.ApiEndpoint = endpointName;
7124 private void SetStatusLabelUrl()
7125 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7127 public void SetStatusLabel(string text)
7128 => this.StatusLabel.Text = text;
7130 private void SetNotifyIconText()
7132 var ur = new StringBuilder(64);
7134 // タスクトレイアイコンのツールチップテキスト書き換え
7136 ur.Remove(0, ur.Length);
7137 if (this.settings.Common.DispUsername)
7139 ur.Append(this.tw.Username);
7142 ur.Append(ApplicationSettings.ApplicationName);
7144 ur.Append("(Debug Build)");
7146 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7149 ur.Append(this.unreadCounter);
7151 ur.Append(this.unreadAtCounter);
7154 this.NotifyIcon1.Text = ur.ToString();
7157 internal void CheckReplyTo(string statusText)
7161 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7163 foreach (Match hm in m)
7165 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7167 hstr += "#" + hm.Result("$3") + " ";
7168 this.HashSupl.AddItem("#" + hm.Result("$3"));
7171 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7173 hstr += this.HashMgr.UseHash;
7175 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7177 // 本当にリプライ先指定すべきかどうかの判定
7178 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7180 if (this.settings.Common.UseAtIdSupplement)
7182 var bCnt = this.AtIdSupl.ItemCount;
7183 foreach (Match mid in m)
7185 this.AtIdSupl.AddItem(mid.Result("${id}"));
7187 if (bCnt != this.AtIdSupl.ItemCount)
7188 this.MarkSettingAtIdModified();
7191 // リプライ先ステータスIDの指定がない場合は指定しない
7192 if (this.inReplyTo == null)
7196 // 次の条件を満たす場合に in_reply_to_status_id 指定
7197 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7198 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7199 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7203 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7204 if (statusText.StartsWith("@", StringComparison.Ordinal))
7206 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7210 foreach (Match mid in m)
7212 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7217 this.inReplyTo = null;
7220 private void TweenMain_Resize(object sender, EventArgs e)
7222 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7224 this.Visible = false;
7226 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7228 // 現在の DPI と設定保存時の DPI との比を取得する
7229 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7231 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7234 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7235 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7236 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7238 this.SplitContainer1.SplitterDistance = splitterDistance;
7242 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7243 if (this.StatusText.Multiline)
7245 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7246 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7247 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7249 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7251 this.StatusText.Height = statusTextHeight;
7255 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7257 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7261 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7262 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7264 this.SplitContainer3.SplitterDistance = previewDistance;
7267 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7268 this.SplitContainer3.Panel2Collapsed = true;
7270 this.initialLayout = false;
7272 if (this.WindowState != FormWindowState.Minimized)
7274 this.formWindowState = this.WindowState;
7278 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7280 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7281 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7282 if (this.PlaySoundMenuItem.Checked)
7284 this.settings.Common.PlaySound = true;
7288 this.settings.Common.PlaySound = false;
7290 this.MarkSettingCommonModified();
7293 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7295 if (this.initialLayout)
7298 int splitterDistance;
7299 switch (this.WindowState)
7301 case FormWindowState.Normal:
7302 splitterDistance = this.SplitContainer1.SplitterDistance;
7304 case FormWindowState.Maximized:
7305 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7306 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7307 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7308 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7314 this.mySpDis = splitterDistance;
7315 this.MarkSettingLocalModified();
7318 private async Task DoRepliedStatusOpen()
7320 var currentPost = this.CurrentPost;
7321 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7323 if (MyCommon.IsKeyDown(Keys.Shift))
7325 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7328 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7330 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7334 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7336 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7337 repPost = tb.Posts[currentPost.InReplyToStatusId];
7338 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7341 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7346 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7347 => await this.DoRepliedStatusOpen();
7349 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7351 if (this.initialLayout)
7352 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7354 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7355 if (multiline != this.StatusText.Multiline)
7357 this.StatusText.Multiline = multiline;
7358 this.settings.Local.StatusMultiline = multiline;
7359 this.MarkSettingLocalModified();
7363 private void StatusText_MultilineChanged(object sender, EventArgs e)
7365 if (this.StatusText.Multiline)
7366 this.StatusText.ScrollBars = ScrollBars.Vertical;
7368 this.StatusText.ScrollBars = ScrollBars.None;
7370 if (!this.initialLayout)
7371 this.MarkSettingLocalModified();
7374 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7377 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7378 this.StatusText.Multiline = menuItemChecked;
7379 this.settings.Local.StatusMultiline = menuItemChecked;
7380 if (menuItemChecked)
7382 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7383 this.SplitContainer2.SplitterDistance = 0;
7385 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7389 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7391 this.MarkSettingLocalModified();
7394 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7396 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7398 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7399 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7400 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7402 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7407 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7408 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7409 // Appendix A. Collected ABNF for URI
7410 // http://www.ietf.org/rfc/rfc3986.txt
7412 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7415 if (this.StatusText.SelectionLength > 0)
7417 var tmp = this.StatusText.SelectedText;
7418 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7419 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7421 // 文字列が選択されている場合はその文字列について処理
7423 // nico.ms使用、nicovideoにマッチしたら変換
7424 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7426 result = Nicoms.Shorten(tmp);
7428 else if (converterType != MyCommon.UrlConverter.Nicoms)
7433 var srcUri = new Uri(tmp);
7434 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7435 result = resultUri.AbsoluteUri;
7437 catch (WebApiException e)
7439 this.StatusLabel.Text = converterType + ":" + e.Message;
7442 catch (UriFormatException e)
7444 this.StatusLabel.Text = converterType + ":" + e.Message;
7453 if (!MyCommon.IsNullOrEmpty(result))
7455 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7456 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7457 if (origUrlIndex == -1)
7460 this.StatusText.Select(origUrlIndex, tmp.Length);
7461 this.StatusText.SelectedText = result;
7464 var undo = new UrlUndo
7470 if (this.urlUndoBuffer == null)
7472 this.urlUndoBuffer = new List<UrlUndo>();
7473 this.UrlUndoToolStripMenuItem.Enabled = true;
7476 this.urlUndoBuffer.Add(undo);
7482 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7483 @"(?<url>(?<protocol>https?://)" +
7484 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7485 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7486 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7487 // 正規表現にマッチしたURL文字列をtinyurl化
7488 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7490 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7492 var tmp = mt.Result("${url}");
7493 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7494 tmp = "http://" + tmp;
7497 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7499 // nico.ms使用、nicovideoにマッチしたら変換
7500 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7502 result = Nicoms.Shorten(tmp);
7504 else if (converterType != MyCommon.UrlConverter.Nicoms)
7509 var srcUri = new Uri(tmp);
7510 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7511 result = resultUri.AbsoluteUri;
7513 catch (HttpRequestException e)
7515 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7516 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7517 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7519 this.StatusLabel.Text = converterType + ":" + message;
7522 catch (WebApiException e)
7524 this.StatusLabel.Text = converterType + ":" + e.Message;
7527 catch (UriFormatException e)
7529 this.StatusLabel.Text = converterType + ":" + e.Message;
7538 if (!MyCommon.IsNullOrEmpty(result))
7540 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7541 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7542 if (origUrlIndex == -1)
7545 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7546 this.StatusText.SelectedText = result;
7548 var undo = new UrlUndo
7550 Before = mt.Result("${url}"),
7554 if (this.urlUndoBuffer == null)
7556 this.urlUndoBuffer = new List<UrlUndo>();
7557 this.UrlUndoToolStripMenuItem.Enabled = true;
7560 this.urlUndoBuffer.Add(undo);
7568 private void DoUrlUndo()
7570 if (this.urlUndoBuffer != null)
7572 var tmp = this.StatusText.Text;
7573 foreach (var data in this.urlUndoBuffer)
7575 tmp = tmp.Replace(data.After, data.Before);
7577 this.StatusText.Text = tmp;
7578 this.urlUndoBuffer = null;
7579 this.UrlUndoToolStripMenuItem.Enabled = false;
7580 this.StatusText.SelectionStart = 0;
7581 this.StatusText.SelectionLength = 0;
7585 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7586 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7588 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7589 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7591 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7592 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7594 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7596 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7598 var rnd = new Random();
7600 MyCommon.UrlConverter svc;
7601 // 前回使用した短縮URLサービス以外を選択する
7604 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7606 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7607 await this.UrlConvertAsync(svc);
7611 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7612 => this.DoUrlUndo();
7614 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7616 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7617 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7618 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7619 this.MarkSettingCommonModified();
7622 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7624 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7625 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7626 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7627 this.MarkSettingCommonModified();
7630 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7632 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7633 this.MenuStrip1.Tag = new object();
7634 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7637 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7639 var currentTabPage = this.CurrentTabPage;
7640 if (this.Tag != null) // 設定された戻り先へ遷移
7642 if (this.Tag == currentTabPage)
7643 ((Control)currentTabPage.Tag).Select();
7645 ((Control)this.Tag).Select();
7647 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7649 this.Tag = currentTabPage.Tag;
7650 ((Control)this.Tag).Select();
7652 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7653 this.MenuStrip1.Tag = null;
7656 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7658 if (this.Use2ColumnsMode)
7664 var lst = (DetailsListView)sender;
7665 var columnsCount = lst.Columns.Count;
7667 var darr = new int[columnsCount];
7668 for (var i = 0; i < columnsCount; i++)
7669 darr[lst.Columns[i].DisplayIndex] = i;
7671 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7673 for (var i = 0; i < columnsCount; i++)
7674 this.settings.Local.ColumnsOrder[darr[i]] = i;
7676 this.MarkSettingLocalModified();
7677 this.isColumnChanged = true;
7680 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7682 var lst = (DetailsListView)sender;
7683 if (this.settings.Local == null) return;
7685 var modified = false;
7686 if (this.Use2ColumnsMode)
7688 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7690 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7693 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7695 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7701 var columnsCount = lst.Columns.Count;
7702 for (var i = 0; i < columnsCount; i++)
7704 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7707 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7713 this.MarkSettingLocalModified();
7714 this.isColumnChanged = true;
7718 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7720 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7721 this.MarkSettingLocalModified();
7724 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7726 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7728 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7730 this.SelectMedia_DragDrop(e);
7733 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7735 var (url, title) = GetUrlFromDataObject(e.Data);
7741 appendText = title + " " + url;
7743 if (this.StatusText.TextLength == 0)
7744 this.StatusText.Text = appendText;
7746 this.StatusText.Text += " " + appendText;
7748 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7750 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7752 this.StatusText.Text += text;
7754 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7756 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7757 if (data != null) this.StatusText.Text += data;
7762 /// IDataObject から URL とタイトルの対を取得します
7765 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7767 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7768 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7769 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7771 if (data.GetDataPresent("text/x-moz-url"))
7773 // Firefox, Google Chrome で利用可能
7774 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7776 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7777 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7778 if (lines.Length < 2)
7779 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7781 return (lines[0], lines[1]);
7783 else if (data.GetDataPresent("IESiteModeToUrl"))
7785 // Internet Exproler 用
7786 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7788 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7789 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7790 if (lines.Length < 2)
7791 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7793 return (lines[0], lines[1]);
7795 else if (data.GetDataPresent("UniformResourceLocatorW"))
7799 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7800 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7804 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7807 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7809 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7811 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7813 this.SelectMedia_DragEnter(e);
7817 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7819 e.Effect = DragDropEffects.Copy;
7822 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7824 e.Effect = DragDropEffects.Copy;
7827 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7829 e.Effect = DragDropEffects.Copy;
7833 e.Effect = DragDropEffects.None;
7836 private void TweenMain_DragOver(object sender, DragEventArgs e)
7840 public bool IsNetworkAvailable()
7842 var nw = MyCommon.IsNetworkAvailable();
7843 this.myStatusOnline = nw;
7847 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7849 var uriStr = uri.AbsoluteUri;
7851 // OpenTween 内部で使用する URL
7852 if (uri.Authority == "opentween")
7854 await this.OpenInternalUriAsync(uri);
7858 // ハッシュタグを含む Twitter 検索
7859 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7862 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7863 var pos = unescapedQuery.IndexOf('#');
7864 if (pos == -1) return;
7866 var hash = unescapedQuery.Substring(pos);
7867 this.HashSupl.AddItem(hash);
7868 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7869 this.AddNewTabForSearch(hash);
7874 // フラグが立っている場合は設定と逆の動作をする
7875 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7876 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7878 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7879 if (userUriMatch.Success)
7881 var screenName = userUriMatch.Groups["ScreenName"].Value;
7882 if (this.IsTwitterId(screenName))
7884 await this.AddNewTabForUserTimeline(screenName);
7891 await MyCommon.OpenInBrowserAsync(this, uriStr);
7895 /// OpenTween 内部の機能を呼び出すための URL を開きます
7897 private async Task OpenInternalUriAsync(Uri uri)
7899 // ツイートを開く (//opentween/status/:status_id)
7900 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7903 var statusId = new TwitterStatusId(match.Groups[1].Value);
7904 await this.OpenRelatedTab(statusId);
7909 private void ListTabSelect(TabPage tabPage)
7911 this.SetListProperty();
7913 var previousTabName = this.CurrentTabName;
7914 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7915 previousListViewState.Save(this.ListLockMenuItem.Checked);
7917 this.listCache?.PurgeCache();
7919 this.statuses.SelectTab(tabPage.Text);
7921 this.InitializeTimelineListView();
7923 var tab = this.CurrentTab;
7926 var listView = this.CurrentListView;
7928 var currentListViewState = this.listViewState[tab.TabName];
7929 currentListViewState.Restore(forceScroll: true);
7931 if (this.Use2ColumnsMode)
7933 listView.Columns[1].Text = this.columnText[2];
7937 for (var i = 0; i < listView.Columns.Count; i++)
7939 listView.Columns[i].Text = this.columnText[i];
7944 private void InitializeTimelineListView()
7946 var listView = this.CurrentListView;
7947 var tab = this.CurrentTab;
7949 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7950 (this.listCache, var oldCache) = (newCache, this.listCache);
7951 oldCache?.Dispose();
7953 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7954 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7955 oldDrawer?.Dispose();
7957 newDrawer.IconSize = this.settings.Common.IconSize;
7958 newDrawer.UpdateItemHeight();
7961 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7962 => this.ListTabSelect(e.TabPage);
7964 private void SelectListItem(DetailsListView lView, int index)
7967 var bnd = new Rectangle();
7969 var item = lView.FocusedItem;
7978 lView.SelectedIndices.Clear();
7980 while (lView.SelectedIndices.Count > 0);
7981 item = lView.Items[index];
7982 item.Selected = true;
7983 item.Focused = true;
7985 if (flg) lView.Invalidate(bnd);
7988 private async void TweenMain_Shown(object sender, EventArgs e)
7990 this.NotifyIcon1.Visible = true;
7992 if (this.IsNetworkAvailable())
7994 var loadTasks = new List<Task>
7996 this.RefreshMuteUserIdsAsync(),
7997 this.RefreshBlockIdsAsync(),
7998 this.RefreshNoRetweetIdsAsync(),
7999 this.RefreshTwitterConfigurationAsync(),
8000 this.RefreshTabAsync<HomeTabModel>(),
8001 this.RefreshTabAsync<MentionsTabModel>(),
8002 this.RefreshTabAsync<DirectMessagesTabModel>(),
8003 this.RefreshTabAsync<PublicSearchTabModel>(),
8004 this.RefreshTabAsync<UserTimelineTabModel>(),
8005 this.RefreshTabAsync<ListTimelineTabModel>(),
8008 if (this.settings.Common.StartupFollowers)
8009 loadTasks.Add(this.RefreshFollowerIdsAsync());
8011 if (this.settings.Common.GetFav)
8012 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
8014 var allTasks = Task.WhenAll(loadTasks);
8019 var timeout = Task.Delay(5000);
8020 if (await Task.WhenAny(allTasks, timeout) != timeout)
8024 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
8026 if (MyCommon.EndingFlag)
8030 if (MyCommon.EndingFlag) return;
8032 if (ApplicationSettings.VersionInfoUrl != null)
8034 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8035 if (this.settings.Common.StartupVersion)
8036 await this.CheckNewVersion(true);
8040 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8041 this.VerUpMenuItem.Enabled = false;
8042 this.VerUpMenuItem.Available = false;
8043 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8046 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8047 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8049 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8050 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8054 var reloadTasks = new List<Task>();
8056 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8057 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8059 if (!this.tw.GetNoRetweetSuccess)
8060 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8062 if (this.tw.Configuration.PhotoSizeLimit == 0)
8063 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8065 await Task.WhenAll(reloadTasks);
8068 this.initial = false;
8070 this.timelineScheduler.Enabled = true;
8073 private async Task DoGetFollowersMenu()
8075 await this.RefreshFollowerIdsAsync();
8076 this.DispSelectedPost(true);
8079 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8080 => await this.DoGetFollowersMenu();
8082 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8083 => this.DoReTweetUnofficial();
8085 private async Task DoReTweetOfficial(bool isConfirm)
8088 if (this.ExistCurrentPost)
8090 var selectedPosts = this.CurrentTab.SelectedPosts;
8092 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8094 if (selectedPosts.Any(x => x.IsProtect))
8095 MessageBox.Show("Protected.");
8097 this.doFavRetweetFlags = false;
8101 if (selectedPosts.Length > 15)
8103 MessageBox.Show(Properties.Resources.RetweetLimitText);
8104 this.doFavRetweetFlags = false;
8107 else if (selectedPosts.Length > 1)
8109 var questionText = Properties.Resources.RetweetQuestion2;
8110 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8111 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8113 case DialogResult.Cancel:
8114 case DialogResult.No:
8115 this.doFavRetweetFlags = false;
8121 if (!this.settings.Common.RetweetNoConfirm)
8123 var questiontext = Properties.Resources.RetweetQuestion1;
8124 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8125 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8127 this.doFavRetweetFlags = false;
8133 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8135 await this.RetweetAsync(statusIds);
8139 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8140 => await this.DoReTweetOfficial(true);
8142 private async Task FavoritesRetweetOfficial()
8144 if (!this.ExistCurrentPost) return;
8145 this.doFavRetweetFlags = true;
8146 var retweetTask = this.DoReTweetOfficial(true);
8147 if (this.doFavRetweetFlags)
8149 this.doFavRetweetFlags = false;
8150 var favoriteTask = this.FavoriteChange(true, false);
8152 await Task.WhenAll(retweetTask, favoriteTask);
8160 private async Task FavoritesRetweetUnofficial()
8162 var post = this.CurrentPost;
8163 if (this.ExistCurrentPost && post != null && !post.IsDm)
8165 this.doFavRetweetFlags = true;
8166 var favoriteTask = this.FavoriteChange(true);
8167 if (!post.IsProtect && this.doFavRetweetFlags)
8169 this.doFavRetweetFlags = false;
8170 this.DoReTweetUnofficial();
8178 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8180 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8181 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8182 /// <returns>復元されたツイート本文</returns>
8183 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8185 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8188 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8190 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8192 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8194 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8198 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8200 statusHtml = statusHtml.Replace("<br>", " ");
8202 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8203 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8204 statusHtml = statusHtml.Replace(" ", " ");
8206 return WebUtility.HtmlDecode(statusHtml);
8209 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8211 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8213 if (this.CurrentPost != null)
8214 this.DispSelectedPost(true);
8217 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8219 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8220 this.DebugModeToolStripMenuItem.Visible = true;
8222 this.DebugModeToolStripMenuItem.Visible = false;
8225 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8226 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8228 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8229 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8231 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8232 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8234 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8236 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8237 this.MarkSettingCommonModified();
8240 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8242 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8243 this.MarkSettingCommonModified();
8246 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8248 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8249 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8250 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8251 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8252 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8253 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8256 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8258 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8259 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8260 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8261 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8262 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8263 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8266 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8268 if (this.TraceOutToolStripMenuItem.Checked)
8269 MyCommon.TraceFlag = true;
8271 MyCommon.TraceFlag = false;
8274 private void TweenMain_Deactivate(object sender, EventArgs e)
8275 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8277 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8279 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8281 _ = this.TabRename(this.rclickTabName, out _);
8284 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8285 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8287 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8288 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8290 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8292 TwitterApiStatus? apiStatus;
8294 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8296 var cancellationToken = dialog.EnableCancellation();
8300 var task = this.tw.GetInfoApi();
8301 apiStatus = await dialog.WaitForAsync(this, task);
8303 catch (WebApiException)
8308 if (cancellationToken.IsCancellationRequested)
8311 if (apiStatus == null)
8313 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8318 using var apiDlg = new ApiInfoDialog();
8319 apiDlg.ShowDialog(this);
8322 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8324 var id = this.CurrentPost?.ScreenName ?? "";
8326 await this.FollowCommand(id);
8329 internal async Task FollowCommand(string id)
8331 using (var inputName = new InputTabName())
8333 inputName.FormTitle = "Follow";
8334 inputName.FormDescription = Properties.Resources.FRMessage1;
8335 inputName.TabName = id;
8337 if (inputName.ShowDialog(this) != DialogResult.OK)
8339 if (string.IsNullOrWhiteSpace(inputName.TabName))
8342 id = inputName.TabName.Trim();
8345 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8349 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8350 await dialog.WaitForAsync(this, task);
8352 catch (WebApiException ex)
8354 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8359 MessageBox.Show(Properties.Resources.FRMessage3);
8362 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8364 var id = this.CurrentPost?.ScreenName ?? "";
8366 await this.RemoveCommand(id, false);
8369 internal async Task RemoveCommand(string id, bool skipInput)
8373 using var inputName = new InputTabName();
8374 inputName.FormTitle = "Unfollow";
8375 inputName.FormDescription = Properties.Resources.FRMessage1;
8376 inputName.TabName = id;
8378 if (inputName.ShowDialog(this) != DialogResult.OK)
8380 if (string.IsNullOrWhiteSpace(inputName.TabName))
8383 id = inputName.TabName.Trim();
8386 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8390 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8391 await dialog.WaitForAsync(this, task);
8393 catch (WebApiException ex)
8395 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8400 MessageBox.Show(Properties.Resources.FRMessage3);
8403 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8405 var id = this.CurrentPost?.ScreenName ?? "";
8407 await this.ShowFriendship(id);
8410 internal async Task ShowFriendship(string id)
8412 using (var inputName = new InputTabName())
8414 inputName.FormTitle = "Show Friendships";
8415 inputName.FormDescription = Properties.Resources.FRMessage1;
8416 inputName.TabName = id;
8418 if (inputName.ShowDialog(this) != DialogResult.OK)
8420 if (string.IsNullOrWhiteSpace(inputName.TabName))
8423 id = inputName.TabName.Trim();
8426 bool isFollowing, isFollowed;
8428 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8430 var cancellationToken = dialog.EnableCancellation();
8434 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8435 var friendship = await dialog.WaitForAsync(this, task);
8437 isFollowing = friendship.Relationship.Source.Following;
8438 isFollowed = friendship.Relationship.Source.FollowedBy;
8440 catch (WebApiException ex)
8442 if (!cancellationToken.IsCancellationRequested)
8443 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8447 if (cancellationToken.IsCancellationRequested)
8454 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8458 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8462 result += Properties.Resources.GetFriendshipInfo3;
8466 result += Properties.Resources.GetFriendshipInfo4;
8468 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8469 MessageBox.Show(result);
8472 internal async Task ShowFriendship(string[] ids)
8474 foreach (var id in ids)
8476 bool isFollowing, isFollowed;
8478 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8480 var cancellationToken = dialog.EnableCancellation();
8484 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8485 var friendship = await dialog.WaitForAsync(this, task);
8487 isFollowing = friendship.Relationship.Source.Following;
8488 isFollowed = friendship.Relationship.Source.FollowedBy;
8490 catch (WebApiException ex)
8492 if (!cancellationToken.IsCancellationRequested)
8493 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8497 if (cancellationToken.IsCancellationRequested)
8507 ff += Properties.Resources.GetFriendshipInfo1;
8511 ff += Properties.Resources.GetFriendshipInfo2;
8514 ff += System.Environment.NewLine + " ";
8517 ff += Properties.Resources.GetFriendshipInfo3;
8521 ff += Properties.Resources.GetFriendshipInfo4;
8523 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8526 if (MessageBox.Show(
8527 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8528 Properties.Resources.GetFriendshipInfo8,
8529 MessageBoxButtons.YesNo,
8530 MessageBoxIcon.Question,
8531 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8533 await this.RemoveCommand(id, true);
8538 MessageBox.Show(result);
8543 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8544 => await this.DoShowUserStatus(this.tw.Username, false);
8546 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8549 public bool IsTwitterId(string name)
8551 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8552 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8554 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8557 private void DoQuoteOfficial()
8559 var post = this.CurrentPost;
8560 if (this.ExistCurrentPost && post != null)
8562 if (post.IsDm || !this.StatusText.Enabled)
8567 MessageBox.Show("Protected.");
8571 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8573 this.inReplyTo = null;
8575 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8577 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8578 this.StatusText.Focus();
8582 private void DoReTweetUnofficial()
8585 var post = this.CurrentPost;
8586 if (this.ExistCurrentPost && post != null)
8588 if (post.IsDm || !this.StatusText.Enabled)
8593 MessageBox.Show("Protected.");
8596 var rtdata = post.Text;
8597 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8599 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8601 // 投稿時に in_reply_to_status_id を付加する
8602 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8603 var inReplyToScreenName = post.ScreenName;
8604 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8606 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8608 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8609 this.StatusText.Focus();
8613 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8614 => this.DoQuoteOfficial();
8616 private async void SearchButton_Click(object sender, EventArgs e)
8619 var pnl = ((Control)sender).Parent;
8620 if (pnl == null) return;
8621 var tbName = pnl.Parent.Text;
8622 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8623 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8624 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8625 cmb.Text = cmb.Text.Trim();
8626 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8628 var buf = new StringBuilder();
8629 var c = cmb.Text.ToCharArray();
8630 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8632 if (cnt > cmb.Text.Length - 4)
8634 buf.Append(cmb.Text.Substring(cnt));
8643 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8652 cmb.Text = buf.ToString();
8654 var listView = (DetailsListView)pnl.Parent.Tag;
8656 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8658 tb.SearchWords = cmb.Text;
8659 tb.SearchLang = cmbLang.Text;
8660 if (MyCommon.IsNullOrEmpty(cmb.Text))
8663 this.SaveConfigsTabs();
8668 var idx = cmb.Items.IndexOf(tb.SearchWords);
8669 if (idx > -1) cmb.Items.RemoveAt(idx);
8670 cmb.Items.Insert(0, tb.SearchWords);
8671 cmb.Text = tb.SearchWords;
8673 this.statuses.ClearTabIds(tbName);
8674 this.listCache?.PurgeCache();
8675 this.listCache?.UpdateListSize();
8676 this.SaveConfigsTabs(); // 検索条件の保存
8680 await this.RefreshTabAsync(tb);
8683 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8684 => await this.DoRefreshMore(); // もっと前を取得
8687 /// 指定されたタブのListTabにおける位置を返します
8690 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8692 public int GetTabPageIndex(string tabName)
8693 => this.statuses.Tabs.IndexOf(tabName);
8695 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8699 var restoredTab = this.statuses.UndoRemovedTab();
8700 this.AddNewTab(restoredTab, startup: false);
8702 var tabIndex = this.statuses.Tabs.Count - 1;
8703 this.ListTab.SelectedIndex = tabIndex;
8705 this.SaveConfigsTabs();
8707 catch (TabException ex)
8709 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8713 private async Task DoMoveToRTHome()
8715 var post = this.CurrentPost;
8716 if (post != null && post.RetweetedId != null)
8717 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8720 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8721 => await this.DoMoveToRTHome();
8723 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8725 var screenName = this.CurrentPost?.ScreenName;
8726 if (screenName != null)
8727 this.ListManageUserContext(screenName);
8730 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8732 var screenName = this.CurrentPost?.RetweetedBy;
8733 if (screenName != null)
8734 this.ListManageUserContext(screenName);
8737 public void ListManageUserContext(string screenName)
8739 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8740 listSelectForm.ShowDialog(this);
8743 private void SearchControls_Enter(object sender, EventArgs e)
8745 var pnl = (Control)sender;
8746 foreach (Control ctl in pnl.Controls)
8752 private void SearchControls_Leave(object sender, EventArgs e)
8754 var pnl = (Control)sender;
8755 foreach (Control ctl in pnl.Controls)
8757 ctl.TabStop = false;
8761 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8763 var tab = this.CurrentTab;
8764 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8765 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8768 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8769 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8771 private void HashManageMenuItem_Click(object sender, EventArgs e)
8776 rslt = this.HashMgr.ShowDialog();
8782 this.TopMost = this.settings.Common.AlwaysTop;
8783 if (rslt == DialogResult.Cancel) return;
8784 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8786 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8787 this.HashTogglePullDownMenuItem.Checked = true;
8788 this.HashToggleMenuItem.Checked = true;
8792 this.HashStripSplitButton.Text = "#[-]";
8793 this.HashTogglePullDownMenuItem.Checked = false;
8794 this.HashToggleMenuItem.Checked = false;
8797 this.MarkSettingCommonModified();
8798 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8801 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8803 this.HashMgr.ToggleHash();
8804 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8806 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8807 this.HashToggleMenuItem.Checked = true;
8808 this.HashTogglePullDownMenuItem.Checked = true;
8812 this.HashStripSplitButton.Text = "#[-]";
8813 this.HashToggleMenuItem.Checked = false;
8814 this.HashTogglePullDownMenuItem.Checked = false;
8816 this.MarkSettingCommonModified();
8817 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8820 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8821 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8823 public void SetPermanentHashtag(string hashtag)
8825 this.HashMgr.SetPermanentHash("#" + hashtag);
8826 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8827 this.HashTogglePullDownMenuItem.Checked = true;
8828 this.HashToggleMenuItem.Checked = true;
8830 this.MarkSettingCommonModified();
8833 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8835 var tab = this.CurrentTab;
8836 var post = this.CurrentPost;
8837 if (!this.ExistCurrentPost)
8839 this.ReplyOpMenuItem.Enabled = false;
8840 this.ReplyAllOpMenuItem.Enabled = false;
8841 this.DmOpMenuItem.Enabled = false;
8842 this.CreateTabRuleOpMenuItem.Enabled = false;
8843 this.CreateIdRuleOpMenuItem.Enabled = false;
8844 this.CreateSourceRuleOpMenuItem.Enabled = false;
8845 this.ReadOpMenuItem.Enabled = false;
8846 this.UnreadOpMenuItem.Enabled = false;
8847 this.AuthorMenuItem.Visible = false;
8848 this.RetweetedByMenuItem.Visible = false;
8852 this.ReplyOpMenuItem.Enabled = true;
8853 this.ReplyAllOpMenuItem.Enabled = true;
8854 this.DmOpMenuItem.Enabled = true;
8855 this.CreateTabRuleOpMenuItem.Enabled = true;
8856 this.CreateIdRuleOpMenuItem.Enabled = true;
8857 this.CreateSourceRuleOpMenuItem.Enabled = true;
8858 this.ReadOpMenuItem.Enabled = true;
8859 this.UnreadOpMenuItem.Enabled = true;
8860 this.AuthorMenuItem.Visible = true;
8861 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8862 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8863 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8866 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8868 this.FavOpMenuItem.Enabled = false;
8869 this.UnFavOpMenuItem.Enabled = false;
8870 this.OpenStatusOpMenuItem.Enabled = false;
8871 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8872 this.RtOpMenuItem.Enabled = false;
8873 this.RtUnOpMenuItem.Enabled = false;
8874 this.QtOpMenuItem.Enabled = false;
8875 this.FavoriteRetweetMenuItem.Enabled = false;
8876 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8880 this.FavOpMenuItem.Enabled = true;
8881 this.UnFavOpMenuItem.Enabled = true;
8882 this.OpenStatusOpMenuItem.Enabled = true;
8883 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8885 if (!post.CanRetweetBy(this.tw.UserId))
8887 this.RtOpMenuItem.Enabled = false;
8888 this.RtUnOpMenuItem.Enabled = false;
8889 this.QtOpMenuItem.Enabled = false;
8890 this.FavoriteRetweetMenuItem.Enabled = false;
8891 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8895 this.RtOpMenuItem.Enabled = true;
8896 this.RtUnOpMenuItem.Enabled = true;
8897 this.QtOpMenuItem.Enabled = true;
8898 this.FavoriteRetweetMenuItem.Enabled = true;
8899 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8903 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8905 this.RefreshPrevOpMenuItem.Enabled = true;
8909 this.RefreshPrevOpMenuItem.Enabled = false;
8911 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8913 this.OpenRepSourceOpMenuItem.Enabled = false;
8917 this.OpenRepSourceOpMenuItem.Enabled = true;
8920 if (this.ExistCurrentPost && post != null)
8922 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8926 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8927 => this.ContextMenuTabProperty_Opening(sender, null!);
8929 public Twitter TwitterInstance
8932 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8934 if (this.initialLayout)
8937 int splitterDistance;
8938 switch (this.WindowState)
8940 case FormWindowState.Normal:
8941 splitterDistance = this.SplitContainer3.SplitterDistance;
8943 case FormWindowState.Maximized:
8944 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8945 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8946 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8947 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8953 this.mySpDis3 = splitterDistance;
8954 this.MarkSettingLocalModified();
8957 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8959 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8961 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8962 this.PublicSearchQueryMenuItem.Enabled = true;
8964 this.PublicSearchQueryMenuItem.Enabled = false;
8966 var post = this.CurrentPost;
8967 if (!this.ExistCurrentPost || post == null)
8969 this.CopySTOTMenuItem.Enabled = false;
8970 this.CopyURLMenuItem.Enabled = false;
8971 this.CopyUserIdStripMenuItem.Enabled = false;
8975 this.CopySTOTMenuItem.Enabled = true;
8976 this.CopyURLMenuItem.Enabled = true;
8977 this.CopyUserIdStripMenuItem.Enabled = true;
8979 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8980 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8984 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8985 => this.SetNotifyIconText();
8987 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8988 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8990 private async Task DoShowUserStatus(string id, bool showInputDialog)
8992 TwitterUser? user = null;
8994 if (showInputDialog)
8996 using var inputName = new InputTabName();
8997 inputName.FormTitle = "Show UserStatus";
8998 inputName.FormDescription = Properties.Resources.FRMessage1;
8999 inputName.TabName = id;
9001 if (inputName.ShowDialog(this) != DialogResult.OK)
9003 if (string.IsNullOrWhiteSpace(inputName.TabName))
9006 id = inputName.TabName.Trim();
9009 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9011 var cancellationToken = dialog.EnableCancellation();
9015 var task = this.tw.Api.UsersShow(id);
9016 user = await dialog.WaitForAsync(this, task);
9018 catch (WebApiException ex)
9020 if (!cancellationToken.IsCancellationRequested)
9021 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9025 if (cancellationToken.IsCancellationRequested)
9029 await this.DoShowUserStatus(user);
9032 private async Task DoShowUserStatus(TwitterUser user)
9034 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9035 var showUserTask = userDialog.ShowUserAsync(user);
9036 userDialog.ShowDialog(this);
9039 this.BringToFront();
9041 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9045 internal Task ShowUserStatus(string id, bool showInputDialog)
9046 => this.DoShowUserStatus(id, showInputDialog);
9048 internal Task ShowUserStatus(string id)
9049 => this.DoShowUserStatus(id, true);
9051 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9053 var post = this.CurrentPost;
9056 await this.ShowUserStatus(post.ScreenName, false);
9060 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9062 var retweetedBy = this.CurrentPost?.RetweetedBy;
9063 if (retweetedBy != null)
9065 await this.ShowUserStatus(retweetedBy, false);
9069 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9071 var post = this.CurrentPost;
9072 if (!this.ExistCurrentPost || post == null)
9075 var statusId = post.RetweetedId ?? post.StatusId;
9076 TwitterStatus status;
9078 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9080 var cancellationToken = dialog.EnableCancellation();
9084 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9085 status = await dialog.WaitForAsync(this, task);
9087 catch (WebApiException ex)
9089 if (!cancellationToken.IsCancellationRequested)
9090 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9094 if (cancellationToken.IsCancellationRequested)
9098 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9101 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9103 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9106 this.Visible = false;
9108 else if (Form.ActiveForm == null)
9110 this.Visible = true;
9111 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9113 this.BringToFront();
9114 this.StatusText.Focus();
9118 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9119 => this.MultiLinePullDownMenuItem.PerformClick();
9122 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9124 if (this.ImageSelector.Visible)
9125 this.ImageSelector.EndSelection();
9127 this.ImageSelector.BeginSelection();
9130 private void SelectMedia_DragEnter(DragEventArgs e)
9132 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9134 e.Effect = DragDropEffects.Copy;
9137 e.Effect = DragDropEffects.None;
9140 private void SelectMedia_DragDrop(DragEventArgs e)
9143 this.BringToFront();
9145 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9146 this.ImageSelector.BeginSelection();
9147 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9148 this.StatusText.Focus();
9151 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9153 this.TimelinePanel.Visible = false;
9154 this.TimelinePanel.Enabled = false;
9157 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9159 this.TimelinePanel.Visible = true;
9160 this.TimelinePanel.Enabled = true;
9161 this.CurrentListView.Focus();
9164 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9165 => this.AllowDrop = false;
9167 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9168 => this.AllowDrop = true;
9170 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9172 if (this.ImageSelector.Visible)
9174 this.MarkSettingCommonModified();
9175 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9179 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9180 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9183 /// StatusTextでCtrl+Vが押下された時の処理
9185 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9189 if (Clipboard.ContainsText())
9191 // clipboardにテキストがある場合は貼り付け処理
9192 this.StatusText.Paste(Clipboard.GetText());
9194 else if (Clipboard.ContainsImage())
9197 using var image = Clipboard.GetImage();
9198 this.ImageSelector.BeginSelection();
9199 this.ImageSelector.Model.AddMediaItemFromImage(image);
9201 else if (Clipboard.ContainsFileDropList())
9203 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9204 this.ImageSelector.BeginSelection();
9205 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9208 catch (ExternalException ex)
9210 MessageBox.Show(ex.Message);
9215 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9217 using var form = new ListManage(this.tw);
9218 form.ShowDialog(this);
9221 private bool ModifySettingCommon { get; set; }
9223 private bool ModifySettingLocal { get; set; }
9225 private bool ModifySettingAtId { get; set; }
9227 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9229 var post = this.CurrentPost;
9230 if (this.ExistCurrentPost && post != null && !post.IsDm)
9231 this.RtCountMenuItem.Enabled = true;
9233 this.RtCountMenuItem.Enabled = false;
9236 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9237 => this.CopyUserId();
9239 private void CopyUserId()
9241 var post = this.CurrentPost;
9242 if (post == null) return;
9243 var clstr = post.ScreenName;
9246 Clipboard.SetDataObject(clstr, false, 5, 100);
9248 catch (Exception ex)
9250 MessageBox.Show(ex.Message);
9254 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9256 var post = this.CurrentPost;
9257 if (this.ExistCurrentPost && post != null && !post.IsDm)
9261 await this.OpenRelatedTab(post);
9263 catch (TabException ex)
9265 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9271 /// 指定されたツイートに対する関連発言タブを開きます
9273 /// <param name="statusId">表示するツイートのID</param>
9274 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9275 public async Task OpenRelatedTab(PostId statusId)
9277 var post = this.statuses[statusId];
9282 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9284 catch (WebApiException ex)
9286 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9291 await this.OpenRelatedTab(post);
9295 /// 指定されたツイートに対する関連発言タブを開きます
9297 /// <param name="post">表示する対象となるツイート</param>
9298 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9299 private async Task OpenRelatedTab(PostClass post)
9301 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9302 if (tabRelated != null)
9304 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9307 var tabName = this.statuses.MakeTabName("Related Tweets");
9309 tabRelated = new RelatedPostsTabModel(tabName, post)
9311 UnreadManage = false,
9315 this.statuses.AddTab(tabRelated);
9316 this.AddNewTab(tabRelated, startup: false);
9318 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9320 await this.RefreshTabAsync(tabRelated);
9322 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9326 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9328 var tabPage = this.ListTab.TabPages[tabIndex];
9329 var listView = (DetailsListView)tabPage.Tag;
9330 var targetPost = tabRelated.TargetPost;
9331 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9333 if (index != -1 && index < listView.Items.Count)
9335 listView.SelectedIndices.Add(index);
9336 listView.Items[index].Focused = true;
9341 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9343 var buf = new StringBuilder();
9344 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9345 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9346 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9349 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9351 MyCommon.EndingFlag = true;
9355 Application.Restart();
9359 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9363 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9364 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9366 private bool ExistCurrentPost
9370 var post = this.CurrentPost;
9371 return post != null && !post.IsDeleted;
9375 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9376 => await this.ShowUserTimeline();
9378 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9379 => await this.ShowRetweeterTimeline();
9381 private string GetUserIdFromCurPostOrInput(string caption)
9383 var id = this.CurrentPost?.ScreenName ?? "";
9385 using var inputName = new InputTabName();
9386 inputName.FormTitle = caption;
9387 inputName.FormDescription = Properties.Resources.FRMessage1;
9388 inputName.TabName = id;
9390 if (inputName.ShowDialog() == DialogResult.OK &&
9391 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9393 id = inputName.TabName.Trim();
9402 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9404 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9405 if (!MyCommon.IsNullOrEmpty(id))
9407 await this.AddNewTabForUserTimeline(id);
9411 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9413 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9414 this.timelineScheduler.SystemResumed();
9417 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9419 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9421 TimeZoneInfo.ClearCachedData();
9423 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9425 if (curTimeOffset != prevTimeOffset)
9428 this.listCache?.PurgeCache();
9429 this.CurrentListView.Refresh();
9431 this.DispSelectedPost(forceupdate: true);
9434 this.timelineScheduler.Reset();
9437 private void TimelineRefreshEnableChange(bool isEnable)
9439 this.timelineScheduler.Enabled = isEnable;
9442 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9443 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9445 private async Task OpenUserAppointUrl()
9447 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9449 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9451 var post = this.CurrentPost;
9454 var xUrl = this.settings.Common.UserAppointUrl;
9455 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9457 var statusId = post.RetweetedId ?? post.StatusId;
9458 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9460 await MyCommon.OpenInBrowserAsync(this, xUrl);
9465 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9470 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9471 => await this.OpenUserAppointUrl();
9473 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9475 if (Form.ActiveForm == null)
9477 await this.InvokeAsync(() =>
9479 this.Visible = true;
9480 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9482 this.BringToFront();
9483 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9485 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9489 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9495 private void ReplaceAppName()
9497 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9498 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9501 private void TweetThumbnailControl_ThumbnailLoading(object sender, EventArgs e)
9502 => this.SplitContainer3.Panel2Collapsed = false;
9504 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9505 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9507 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9509 if (e.KeyCode == Keys.Space)
9511 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9513 e.SuppressKeyPress = true;
9517 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9519 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9520 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9521 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9522 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9523 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9525 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9528 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9529 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9531 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9532 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9534 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9535 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9537 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9538 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9540 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9541 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9543 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9545 if (this.settings.Common.IconSize == iconSize) return;
9547 var oldIconCol = this.Use2ColumnsMode;
9549 this.settings.Common.IconSize = iconSize;
9550 this.ApplyListViewIconSize(iconSize);
9552 if (this.Use2ColumnsMode != oldIconCol)
9554 foreach (TabPage tp in this.ListTab.TabPages)
9556 this.ResetColumns((DetailsListView)tp.Tag);
9560 this.CurrentListView.Refresh();
9561 this.MarkSettingCommonModified();
9564 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9566 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9567 if (this.settings.Common.SortOrderLock == state) return;
9569 this.settings.Common.SortOrderLock = state;
9570 this.MarkSettingCommonModified();
9573 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9575 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9577 this.StatusLabelUrl.Text = e.StatusText;
9581 this.SetStatusLabelUrl();