1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.Thumbnail;
66 public partial class TweenMain : OTBaseForm
70 /// <summary>画面サイズ</summary>
73 /// <summary>画面位置</summary>
76 /// <summary>区切り位置</summary>
79 /// <summary>発言欄区切り位置</summary>
82 /// <summary>プレビュー区切り位置</summary>
86 private bool initial; // true:起動時処理中
87 private bool initialLayout = true;
88 private bool ignoreConfigSave; // true:起動時処理中
90 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
93 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
94 private Point tabMouseDownPoint;
96 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
97 private string? rclickTabName;
99 private readonly object syncObject = new(); // ロック用
101 private const string DetailHtmlFormatHead =
102 """<head><meta http-equiv="X-UA-Compatible" content="IE=8">"""
103 + """<style type="text/css"><!-- """
104 + "body, p, pre {margin: 0;} "
105 + """body {font-family: "%FONT_FAMILY%", "Segoe UI Emoji", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} """
106 + "pre {font-family: inherit;} "
107 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
108 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
109 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
110 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
111 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
115 private const string DetailHtmlFormatTemplateMono =
116 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
118 private const string DetailHtmlFormatTemplateNormal =
119 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
121 private string detailHtmlFormatPreparedTemplate = null!;
123 private bool myStatusError = false;
124 private bool myStatusOnline = false;
125 private bool soundfileListup = false;
126 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
129 private readonly SettingManager settings;
132 private readonly Twitter tw;
135 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
139 /// <summary>検索画面インスタンス</summary>
140 internal SearchWordDialog SearchDialog = new();
142 private readonly OpenURL urlDialog = new();
144 /// <summary>@id補助</summary>
145 public AtIdSupplement AtIdSupl = null!;
147 /// <summary>Hashtag補助</summary>
148 public AtIdSupplement HashSupl = null!;
150 public HashtagManage HashMgr = null!;
153 private ThemeManager themeManager;
155 /// <summary>アイコン画像リスト</summary>
156 private readonly ImageCache iconCache;
158 private readonly IconAssetsManager iconAssets;
160 private readonly ThumbnailGenerator thumbGenerator;
162 /// <summary>発言履歴</summary>
163 private readonly List<StatusTextHistory> history = new();
165 /// <summary>発言履歴カレントインデックス</summary>
168 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
170 /// <summary>リプライ先のステータスID・スクリーン名</summary>
171 private (PostId StatusId, string ScreenName)? inReplyTo = null;
174 private readonly List<DateTimeUtc> postTimestamps = new();
175 private readonly List<DateTimeUtc> favTimestamps = new();
178 private readonly StringFormat sfTab = new();
180 //////////////////////////////////////////////////////////////////////////////////////////////////////////
182 /// <summary>発言保持クラス</summary>
183 private readonly TabInformations statuses;
185 private TimelineListViewCache? listCache;
186 private TimelineListViewDrawer? listDrawer;
187 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
189 private bool isColumnChanged = false;
191 private const int MaxWorderThreads = 20;
192 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
193 private readonly CancellationTokenSource workerCts = new();
194 private readonly IProgress<string> workerProgress = null!;
196 private int unreadCounter = -1;
197 private int unreadAtCounter = -1;
199 private readonly string[] columnOrgText = new string[9];
200 private readonly string[] columnText = new string[9];
202 private bool doFavRetweetFlags = false;
204 //////////////////////////////////////////////////////////////////////////////////////////////////////////
206 private readonly TimelineScheduler timelineScheduler = new();
207 private readonly DebounceTimer selectionDebouncer;
208 private readonly DebounceTimer saveConfigDebouncer;
210 private readonly string recommendedStatusFooter;
211 private bool urlMultibyteSplit = false;
212 private bool preventSmsCommand = true;
215 private readonly record struct UrlUndo(
220 private List<UrlUndo>? urlUndoBuffer = null;
222 private readonly record struct ReplyChain(
228 /// <summary>[, ]でのリプライ移動の履歴</summary>
229 private Stack<ReplyChain>? replyChains;
231 /// <summary>ポスト選択履歴</summary>
232 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
234 public TabModel CurrentTab
235 => this.statuses.SelectedTab;
237 public string CurrentTabName
238 => this.statuses.SelectedTabName;
240 public TabPage CurrentTabPage
241 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
243 public DetailsListView CurrentListView
244 => (DetailsListView)this.CurrentTabPage.Tag;
246 public PostClass? CurrentPost
247 => this.CurrentTab.SelectedPost;
249 public bool Use2ColumnsMode
250 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
252 /// <summary>検索処理タイプ</summary>
253 internal enum SEARCHTYPE
260 private readonly record struct StatusTextHistory(
262 (PostId StatusId, string ScreenName)? InReplyTo = null
265 private readonly HookGlobalHotkey hookGlobalHotkey;
268 SettingManager settingManager,
269 TabInformations tabInfo,
271 ImageCache imageCache,
272 IconAssetsManager iconAssets,
273 ThumbnailGenerator thumbGenerator
276 this.settings = settingManager;
277 this.statuses = tabInfo;
279 this.iconCache = imageCache;
280 this.iconAssets = iconAssets;
281 this.thumbGenerator = thumbGenerator;
283 this.InitializeComponent();
285 if (!this.DesignMode)
287 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
288 this.StatusText.Dock = DockStyle.Fill;
291 this.hookGlobalHotkey = new HookGlobalHotkey(this);
293 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
294 this.gh.NotifyClicked += this.GrowlHelper_Callback;
296 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
297 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
299 this.ImageSelector.Visible = false;
300 this.ImageSelector.Enabled = false;
301 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
303 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
305 this.ReplaceAppName();
306 this.InitializeShortcuts();
308 this.ignoreConfigSave = true;
310 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
312 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
314 Regex.CacheSize = 100;
317 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
318 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
319 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
321 // <<<<<<<<<設定関連>>>>>>>>>
325 // 現在の DPI と設定保存時の DPI との比を取得する
326 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
331 // プロキシ設定等の通信まわりの初期化が済んでから処理する
332 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
333 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
334 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
336 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
339 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
340 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
342 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
345 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
346 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
347 this.HashMgr = new HashtagManage(this.HashSupl,
348 this.settings.Common.HashTags.ToArray(),
349 this.settings.Common.HashSelected,
350 this.settings.Common.HashIsPermanent,
351 this.settings.Common.HashIsHead,
352 this.settings.Common.HashIsNotAddToAtReply);
353 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
356 this.themeManager = new(this.settings.Local);
357 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
359 // StringFormatオブジェクトへの事前設定
360 this.sfTab.Alignment = StringAlignment.Center;
361 this.sfTab.LineAlignment = StringAlignment.Center;
363 this.InitDetailHtmlFormat();
364 this.tweetDetailsView.ClearPostBrowser();
366 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
368 this.history.Add(new StatusTextHistory(""));
370 this.inReplyTo = null;
373 this.SearchDialog.Owner = this;
374 this.urlDialog.Owner = this;
377 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
378 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
380 // 新着取得時のリストスクロールをするか。trueならスクロールしない
381 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
382 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
384 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
385 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
388 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
389 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
390 this.myLoc = this.settings.Local.FormLocation;
392 if (this.WindowState != FormWindowState.Minimized)
394 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
395 var outOfScreen = true;
396 if (Screen.AllScreens.Length == 1) // ハングするとの報告
398 foreach (var scr in Screen.AllScreens)
400 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
408 this.myLoc = new Point(0, 0);
410 this.DesktopLocation = this.myLoc;
412 this.TopMost = this.settings.Common.AlwaysTop;
413 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
414 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
415 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
417 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
418 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
420 this.StatusText.Font = this.themeManager.FontInputFont;
421 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
423 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
424 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
425 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
427 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
428 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
430 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
431 if (this.settings.Common.UnreadManage == false)
433 this.ReadedStripMenuItem.Enabled = false;
434 this.UnreadStripMenuItem.Enabled = false;
437 // リンク先URL表示部の初期化(画面左下)
438 this.StatusLabelUrl.Text = "";
440 this.StatusLabel.Text = "";
441 this.StatusLabel.AutoToolTip = false;
442 this.StatusLabel.ToolTipText = "";
444 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
446 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
447 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
448 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
449 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
451 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
452 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
453 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
454 this.SplitContainer2.Panel2.AccessibleName = "";
456 ////////////////////////////////////////////////////////////////////////////////
457 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
458 var mode = this.settings.Common.SortColumn switch
460 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
461 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
462 1 => ComparerMode.Nickname, // ニックネーム
463 2 => ComparerMode.Data, // 本文
464 3 => ComparerMode.Id, // 時刻=発言Id
465 4 => ComparerMode.Name, // 名前
466 7 => ComparerMode.Source, // Source
467 _ => ComparerMode.Id,
469 this.statuses.SetSortMode(mode, sortOrder);
470 ////////////////////////////////////////////////////////////////////////////////
472 this.ApplyListViewIconSize(this.settings.Common.IconSize);
474 // <<<<<<<<タブ関連>>>>>>>
475 foreach (var tab in this.statuses.Tabs)
477 if (!this.AddNewTab(tab, startup: true))
478 throw new TabException(Properties.Resources.TweenMain_LoadText1);
481 this.ListTabSelect(this.ListTab.SelectedTab);
484 this.SetTabAlignment();
486 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
487 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
489 if (this.settings.Common.TabIconDisp)
491 this.ListTab.DrawMode = TabDrawMode.Normal;
495 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
496 this.ListTab.DrawItem += this.ListTab_DrawItem;
497 this.ListTab.ImageList = null;
500 if (this.settings.Common.HotkeyEnabled)
503 var modKey = HookGlobalHotkey.ModKeys.None;
504 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
505 modKey |= HookGlobalHotkey.ModKeys.Alt;
506 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
507 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
508 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
509 modKey |= HookGlobalHotkey.ModKeys.Shift;
510 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
511 modKey |= HookGlobalHotkey.ModKeys.Win;
513 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
516 if (this.settings.Common.IsUseNotifyGrowl)
517 this.gh.RegisterGrowl();
519 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
521 this.SetMainWindowTitle();
522 this.SetNotifyIconText();
524 if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
526 this.Visible = false;
531 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
532 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
533 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
534 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
535 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
536 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
537 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
539 this.DoGetFollowersMenu(),
540 this.RefreshBlockIdsAsync(),
541 this.RefreshMuteUserIdsAsync(),
542 this.RefreshNoRetweetIdsAsync(),
543 this.RefreshTwitterConfigurationAsync(),
545 this.RefreshTimelineScheduler();
547 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
548 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
551 this.TimerRefreshIcon.Interval = 200;
552 this.TimerRefreshIcon.Enabled = false;
554 this.ignoreConfigSave = false;
555 this.ApplyLayoutFromSettings();
558 private void TweenMain_Activated(object sender, EventArgs e)
560 // 画面がアクティブになったら、発言欄の背景色戻す
561 if (this.StatusText.Focused)
563 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
567 private bool disposed = false;
570 /// 使用中のリソースをすべてクリーンアップします。
572 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
573 protected override void Dispose(bool disposing)
575 base.Dispose(disposing);
582 this.components?.Dispose();
585 this.SearchDialog.Dispose();
586 this.urlDialog.Dispose();
587 this.themeManager.Dispose();
588 this.sfTab.Dispose();
590 this.timelineScheduler.Dispose();
591 this.workerCts.Cancel();
592 this.thumbnailTokenSource?.Dispose();
594 this.hookGlobalHotkey.Dispose();
597 // 終了時にRemoveHandlerしておかないとメモリリークする
598 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
599 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
600 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
601 MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
603 this.disposed = true;
606 private void InitColumns(ListView list, bool startup)
608 this.InitColumnText();
610 ColumnHeader[]? columns = null;
613 if (this.Use2ColumnsMode)
617 new ColumnHeader(), // アイコン
618 new ColumnHeader(), // 本文
621 columns[0].Text = this.columnText[0];
622 columns[1].Text = this.columnText[2];
626 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
628 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
629 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
630 columns[0].DisplayIndex = 0;
631 columns[1].DisplayIndex = 1;
636 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
638 columns[idx].Width = curListColumn.Width;
639 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
648 new ColumnHeader(), // アイコン
649 new ColumnHeader(), // ニックネーム
650 new ColumnHeader(), // 本文
651 new ColumnHeader(), // 日付
652 new ColumnHeader(), // ユーザID
653 new ColumnHeader(), // 未読
654 new ColumnHeader(), // マーク&プロテクト
655 new ColumnHeader(), // ソース
658 foreach (var i in Enumerable.Range(0, columns.Length))
659 columns[i].Text = this.columnText[i];
663 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
665 foreach (var (column, index) in columns.WithIndex())
667 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
668 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
674 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
676 columns[idx].Width = curListColumn.Width;
677 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
683 list.Columns.AddRange(columns);
691 foreach (var column in columns)
697 private void InitColumnText()
699 this.columnText[0] = "";
700 this.columnText[1] = Properties.Resources.AddNewTabText2;
701 this.columnText[2] = Properties.Resources.AddNewTabText3;
702 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
703 this.columnText[4] = Properties.Resources.AddNewTabText5;
704 this.columnText[5] = "";
705 this.columnText[6] = "";
706 this.columnText[7] = "Source";
708 this.columnOrgText[0] = "";
709 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
710 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
711 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
712 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
713 this.columnOrgText[5] = "";
714 this.columnOrgText[6] = "";
715 this.columnOrgText[7] = "Source";
717 var c = this.statuses.SortMode switch
719 ComparerMode.Nickname => 1, // ニックネーム
720 ComparerMode.Data => 2, // 本文
721 ComparerMode.Id => 3, // 時刻=発言Id
722 ComparerMode.Name => 4, // 名前
723 ComparerMode.Source => 7, // Source
727 if (this.Use2ColumnsMode)
729 if (this.statuses.SortOrder == SortOrder.Descending)
731 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
732 this.columnText[2] = this.columnOrgText[2] + "▾";
736 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
737 this.columnText[2] = this.columnOrgText[2] + "▴";
742 if (this.statuses.SortOrder == SortOrder.Descending)
744 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
745 this.columnText[c] = this.columnOrgText[c] + "▾";
749 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
750 this.columnText[c] = this.columnOrgText[c] + "▴";
755 private void InitDetailHtmlFormat()
757 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
759 static string ColorToRGBString(Color color)
760 => $"{color.R},{color.G},{color.B}";
762 this.detailHtmlFormatPreparedTemplate = htmlTemplate
763 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
764 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
765 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
766 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
767 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
768 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
771 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
776 txt = this.statuses.Tabs[e.Index].TabName;
783 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
784 if (e.State == DrawItemState.Selected)
786 e.DrawFocusRectangle();
791 if (this.statuses.Tabs[txt].UnreadCount > 0)
794 fore = System.Drawing.SystemBrushes.ControlText;
798 fore = System.Drawing.SystemBrushes.ControlText;
800 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
803 private void LoadConfig()
805 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
806 this.statuses.AddDefaultTabs();
809 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
811 this.RefreshTimelineScheduler();
814 private void RefreshTimelineScheduler()
816 static TimeSpan IntervalSecondsOrDisabled(int seconds)
817 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
819 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
820 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
821 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
822 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
823 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
824 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
825 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
826 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
828 this.timelineScheduler.RefreshSchedule();
831 private void MarkSettingCommonModified()
833 if (this.saveConfigDebouncer == null)
836 this.ModifySettingCommon = true;
837 _ = this.saveConfigDebouncer.Call();
840 private void MarkSettingLocalModified()
842 if (this.saveConfigDebouncer == null)
845 this.ModifySettingLocal = true;
846 _ = this.saveConfigDebouncer.Call();
849 internal void MarkSettingAtIdModified()
851 if (this.saveConfigDebouncer == null)
854 this.ModifySettingAtId = true;
855 _ = this.saveConfigDebouncer.Call();
858 private void RefreshTimeline()
860 var curListView = this.CurrentListView;
862 // 現在表示中のタブのスクロール位置を退避
863 var currentListViewState = this.listViewState[this.CurrentTabName];
864 currentListViewState.Save(this.ListLockMenuItem.Checked);
868 addCount = this.statuses.SubmitUpdate(
871 out var newMentionOrDm,
874 if (MyCommon.EndingFlag) return;
877 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
879 using (ControlTransaction.Update(curListView))
881 this.listCache.PurgeCache();
882 this.listCache.UpdateListSize();
885 currentListViewState.RestoreSelection();
891 if (this.settings.Common.TabIconDisp)
893 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
895 var tabPage = this.ListTab.TabPages[index];
896 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
897 tabPage.ImageIndex = 0; // 未読アイコン
902 this.ListTab.Refresh();
907 currentListViewState.RestoreScroll();
910 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
912 this.SetMainWindowTitle();
913 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
915 this.HashSupl.AddRangeItem(this.tw.GetHashList());
918 private bool BalloonRequired()
923 if (NativeMethods.IsScreenSaverRunning())
927 if (!this.NewPostPopMenuItem.Checked)
930 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
931 if (this.settings.Common.LimitBalloon)
933 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
940 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
942 if (this.settings.Common.ReadOwnPost)
944 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
949 if (this.BalloonRequired())
951 if (notifyPosts != null && notifyPosts.Length > 0)
953 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
954 if (this.settings.Common.IsUseNotifyGrowl)
956 var sb = new StringBuilder();
960 foreach (var post in notifyPosts)
962 if (!(notifyPosts.Length > 3))
968 if (post.IsReply && !post.IsExcludeReply) reply = true;
969 if (post.IsDm) dm = true;
970 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
971 switch (this.settings.Common.NameBalloon)
973 case MyCommon.NameBalloonEnum.UserID:
974 sb.Append(post.ScreenName).Append(" : ");
976 case MyCommon.NameBalloonEnum.NickName:
977 sb.Append(post.Nickname).Append(" : ");
980 sb.Append(post.TextFromApi);
981 if (notifyPosts.Length > 3)
983 if (notifyPosts.Last() != post) continue;
986 var title = new StringBuilder();
987 GrowlHelper.NotifyType nt;
988 if (this.settings.Common.DispUsername)
990 title.Append(this.tw.Username);
996 title.Append(ApplicationSettings.ApplicationName);
997 title.Append(" [DM] ");
998 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
999 nt = GrowlHelper.NotifyType.DirectMessage;
1003 title.Append(ApplicationSettings.ApplicationName);
1004 title.Append(" [Reply!] ");
1005 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1006 nt = GrowlHelper.NotifyType.Reply;
1010 title.Append(ApplicationSettings.ApplicationName);
1012 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1013 nt = GrowlHelper.NotifyType.Notify;
1015 var bText = sb.ToString();
1016 if (MyCommon.IsNullOrEmpty(bText)) return;
1018 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1019 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
1024 var sb = new StringBuilder();
1027 foreach (var post in notifyPosts)
1029 if (post.IsReply && !post.IsExcludeReply) reply = true;
1030 if (post.IsDm) dm = true;
1031 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1032 switch (this.settings.Common.NameBalloon)
1034 case MyCommon.NameBalloonEnum.UserID:
1035 sb.Append(post.ScreenName).Append(" : ");
1037 case MyCommon.NameBalloonEnum.NickName:
1038 sb.Append(post.Nickname).Append(" : ");
1041 sb.Append(post.TextFromApi);
1044 var title = new StringBuilder();
1046 if (this.settings.Common.DispUsername)
1048 title.Append(this.tw.Username);
1049 title.Append(" - ");
1054 ntIcon = ToolTipIcon.Warning;
1055 title.Append(ApplicationSettings.ApplicationName);
1056 title.Append(" [DM] ");
1057 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1061 ntIcon = ToolTipIcon.Warning;
1062 title.Append(ApplicationSettings.ApplicationName);
1063 title.Append(" [Reply!] ");
1064 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1068 ntIcon = ToolTipIcon.Info;
1069 title.Append(ApplicationSettings.ApplicationName);
1071 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1073 var bText = sb.ToString();
1074 if (MyCommon.IsNullOrEmpty(bText)) return;
1076 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1077 this.NotifyIcon1.BalloonTipText = bText;
1078 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1079 this.NotifyIcon1.ShowBalloonTip(500);
1085 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1089 var dir = Application.StartupPath;
1090 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1092 dir = Path.Combine(dir, "Sounds");
1094 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1102 // mentions新着時に画面ブリンク
1103 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1105 NativeMethods.FlashMyWindow(this.Handle, 3);
1109 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1111 var listView = this.CurrentListView;
1112 if (listView != sender)
1115 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1116 this.CurrentTab.SelectPosts(indices);
1118 if (indices.Length != 1)
1121 var index = indices[0];
1122 if (index > listView.VirtualListSize - 1) return;
1124 this.PushSelectPostChain();
1126 var post = this.CurrentPost!;
1127 this.statuses.SetReadAllTab(post.StatusId, read: true);
1129 this.listCache?.RefreshStyle();
1130 await this.selectionDebouncer.Call();
1133 private void StatusTextHistoryBack()
1135 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1136 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1139 if (this.hisIdx < 0)
1142 var historyItem = this.history[this.hisIdx];
1143 this.inReplyTo = historyItem.InReplyTo;
1144 this.StatusText.Text = historyItem.Status;
1145 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1148 private void StatusTextHistoryForward()
1150 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1151 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1154 if (this.hisIdx > this.history.Count - 1)
1155 this.hisIdx = this.history.Count - 1;
1157 var historyItem = this.history[this.hisIdx];
1158 this.inReplyTo = historyItem.InReplyTo;
1159 this.StatusText.Text = historyItem.Status;
1160 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1163 private async void PostButton_Click(object sender, EventArgs e)
1165 if (this.StatusText.Text.Trim().Length == 0)
1167 if (!this.ImageSelector.Enabled)
1169 await this.DoRefresh();
1174 var currentPost = this.CurrentPost;
1175 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1177 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1179 MessageBoxButtons.YesNoCancel,
1180 MessageBoxIcon.Question);
1183 case DialogResult.Yes:
1184 this.StatusText.Text = "";
1185 await this.DoReTweetOfficial(false);
1187 case DialogResult.Cancel:
1192 if (TextContainsOnlyMentions(this.StatusText.Text))
1194 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1195 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1197 if (ret != DialogResult.OK)
1201 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1203 if (this.settings.Common.Nicoms)
1205 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1206 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1209 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1210 this.CheckReplyTo(this.StatusText.Text);
1212 var status = new PostStatusParams();
1214 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1215 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1217 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1218 // 収まる場合はこれらのオプションを使用せずに投稿する
1219 status.Text = statusTextCompat;
1220 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1224 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1225 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1227 status.AttachmentUrl = attachmentUrl;
1229 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1231 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1232 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1234 status.AutoPopulateReplyMetadata = true;
1236 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1237 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1242 if (this.GetRestStatusCount(status.Text) < 0)
1244 // 文字数制限を超えているが強制的に投稿するか
1245 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1246 if (ret != DialogResult.OK)
1250 IMediaUploadService? uploadService = null;
1251 IMediaItem[]? uploadItems = null;
1252 if (this.ImageSelector.Visible)
1255 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1258 this.ImageSelector.EndSelection();
1259 uploadService = this.ImageSelector.Model.GetService(serviceName);
1262 this.inReplyTo = null;
1263 this.StatusText.Text = "";
1264 this.history.Add(new StatusTextHistory(""));
1265 this.hisIdx = this.history.Count - 1;
1266 if (!this.settings.Common.FocusLockToStatusText)
1267 this.CurrentListView.Focus();
1268 this.urlUndoBuffer = null;
1269 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1272 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1274 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1275 await MyCommon.OpenInBrowserAsync(this, tmp);
1278 await this.PostMessageAsync(status, uploadService, uploadItems);
1281 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1283 MyCommon.EndingFlag = true;
1287 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1289 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1291 // _endingFlag=false:フォームの×ボタン
1293 this.Visible = false;
1297 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1298 this.ignoreConfigSave = true;
1299 MyCommon.EndingFlag = true;
1300 this.timelineScheduler.Enabled = false;
1301 this.TimerRefreshIcon.Enabled = false;
1305 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1307 this.Visible = true;
1308 if (this.WindowState == FormWindowState.Minimized)
1310 this.WindowState = FormWindowState.Normal;
1313 this.BringToFront();
1316 private static int errorCount = 0;
1318 private static bool CheckAccountValid()
1320 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1326 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1335 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1336 private Task RefreshTabAsync<T>()
1338 => this.RefreshTabAsync<T>(backward: false);
1340 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1341 private Task RefreshTabAsync<T>(bool backward)
1345 from tab in this.statuses.GetTabsByType<T>()
1346 select this.RefreshTabAsync(tab, backward);
1348 return Task.WhenAll(loadTasks);
1351 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1352 private Task RefreshTabAsync(TabModel tab)
1353 => this.RefreshTabAsync(tab, backward: false);
1355 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1356 private async Task RefreshTabAsync(TabModel tab, bool backward)
1358 await this.workerSemaphore.WaitAsync();
1362 this.RefreshTasktrayIcon();
1363 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1365 catch (WebApiException ex)
1367 this.myStatusError = true;
1368 var tabType = tab switch
1370 HomeTabModel => "GetTimeline",
1371 MentionsTabModel => "GetTimeline",
1372 DirectMessagesTabModel => "GetDirectMessage",
1373 FavoritesTabModel => "GetFavorites",
1374 PublicSearchTabModel => "GetSearch",
1375 UserTimelineTabModel => "GetUserTimeline",
1376 ListTimelineTabModel => "GetListStatus",
1377 RelatedPostsTabModel => "GetRelatedTweets",
1378 _ => tab.GetType().Name.Replace("Model", ""),
1380 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1384 this.RefreshTimeline();
1385 this.workerSemaphore.Release();
1389 private async Task FavAddAsync(PostId statusId, TabModel tab)
1391 await this.workerSemaphore.WaitAsync();
1395 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1397 this.RefreshTasktrayIcon();
1398 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1400 catch (WebApiException ex)
1402 this.myStatusError = true;
1403 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1407 this.workerSemaphore.Release();
1411 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1413 if (ct.IsCancellationRequested)
1416 if (!CheckAccountValid())
1417 throw new WebApiException("Auth error. Check your account");
1419 if (!tab.Posts.TryGetValue(statusId, out var post))
1425 await Task.Run(async () =>
1427 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1431 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1434 await this.tw.Api.FavoritesCreate(twitterStatusId)
1436 .ConfigureAwait(false);
1438 catch (TwitterApiException ex)
1439 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1441 // エラーコード 139 のみの場合は成功と見なす
1444 if (this.settings.Common.RestrictFavCheck)
1446 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1447 .ConfigureAwait(false);
1449 if (status.Favorited != true)
1450 throw new WebApiException("NG(Restricted?)");
1453 this.favTimestamps.Add(DateTimeUtc.Now);
1456 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1458 postTl.IsFav = true;
1460 var favTab = this.statuses.FavoriteTab;
1461 favTab.AddPostQueue(postTl);
1464 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1465 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1467 if (tb.Contains(statusId))
1468 tb.Posts[statusId].IsFav = true;
1471 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1473 catch (WebApiException)
1475 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1480 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1481 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1483 if (this.favTimestamps[i] < oneHour)
1484 this.favTimestamps.RemoveAt(i);
1487 this.statuses.DistributePosts();
1490 if (ct.IsCancellationRequested)
1493 this.RefreshTimeline();
1495 if (this.CurrentTabName == tab.TabName)
1497 using (ControlTransaction.Update(this.CurrentListView))
1499 var idx = tab.IndexOf(statusId);
1501 this.listCache?.RefreshStyle(idx);
1504 var currentPost = this.CurrentPost;
1505 if (currentPost != null && statusId == currentPost.StatusId)
1506 this.DispSelectedPost(true); // 選択アイテム再表示
1510 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1512 await this.workerSemaphore.WaitAsync();
1516 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1518 this.RefreshTasktrayIcon();
1519 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1521 catch (WebApiException ex)
1523 this.myStatusError = true;
1524 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1528 this.workerSemaphore.Release();
1532 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1534 if (ct.IsCancellationRequested)
1537 if (!CheckAccountValid())
1538 throw new WebApiException("Auth error. Check your account");
1540 var successIds = new List<PostId>();
1542 await Task.Run(async () =>
1546 var failedCount = 0;
1547 foreach (var statusId in statusIds)
1551 var post = tab.Posts[statusId];
1553 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1558 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1562 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1564 .ConfigureAwait(false);
1566 catch (WebApiException)
1572 successIds.Add(statusId);
1573 post.IsFav = false; // リスト再描画必要
1575 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1576 tabinfoPost.IsFav = false;
1578 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1579 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1581 if (tb.Contains(statusId))
1582 tb.Posts[statusId].IsFav = false;
1587 if (ct.IsCancellationRequested)
1590 var favTab = this.statuses.FavoriteTab;
1591 foreach (var statusId in successIds)
1593 // ツイートが削除された訳ではないので IsDeleted はセットしない
1594 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1597 this.RefreshTimeline();
1599 if (this.CurrentTabName == tab.TabName)
1601 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1607 using (ControlTransaction.Update(this.CurrentListView))
1609 foreach (var statusId in successIds)
1611 var idx = tab.IndexOf(statusId);
1613 this.listCache?.RefreshStyle(idx);
1617 var currentPost = this.CurrentPost;
1618 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1619 this.DispSelectedPost(true); // 選択アイテム再表示
1624 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1626 await this.workerSemaphore.WaitAsync();
1630 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1632 this.RefreshTasktrayIcon();
1633 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1635 catch (WebApiException ex)
1637 this.myStatusError = true;
1638 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1642 this.workerSemaphore.Release();
1646 private async Task PostMessageAsyncInternal(
1647 IProgress<string> p,
1648 CancellationToken ct,
1649 PostStatusParams postParams,
1650 IMediaUploadService? uploadService,
1651 IMediaItem[]? uploadItems)
1653 if (ct.IsCancellationRequested)
1656 if (!CheckAccountValid())
1657 throw new WebApiException("Auth error. Check your account");
1659 p.Report("Posting...");
1661 PostClass? post = null;
1666 await Task.Run(async () =>
1668 var postParamsWithMedia = postParams;
1670 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1672 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1673 .ConfigureAwait(false);
1676 post = await this.tw.PostStatus(postParamsWithMedia)
1677 .ConfigureAwait(false);
1680 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1682 catch (WebApiException ex)
1684 // 処理は中断せずエラーの表示のみ行う
1685 errMsg = $"Err:{ex.Message}(PostMessage)";
1687 this.myStatusError = true;
1689 catch (UnauthorizedAccessException ex)
1691 // アップロード対象のファイルが開けなかった場合など
1692 errMsg = $"Err:{ex.Message}(PostMessage)";
1694 this.myStatusError = true;
1698 // 使い終わった MediaItem は破棄する
1699 if (uploadItems != null)
1701 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1703 disposableItem.Dispose();
1708 if (ct.IsCancellationRequested)
1711 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1712 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1713 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1715 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1717 var ret = MessageBox.Show(
1719 "Failed to update status",
1720 MessageBoxButtons.RetryCancel,
1721 MessageBoxIcon.Question);
1723 if (ret == DialogResult.Retry)
1725 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1729 this.StatusTextHistoryBack();
1730 this.StatusText.Focus();
1732 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1733 if (this.settings.Common.FocusLockToStatusText)
1734 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1739 this.postTimestamps.Add(DateTimeUtc.Now);
1741 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1742 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1744 if (this.postTimestamps[i] < oneHour)
1745 this.postTimestamps.RemoveAt(i);
1748 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1750 this.HashMgr.ClearHashtag();
1751 this.HashStripSplitButton.Text = "#[-]";
1752 this.HashTogglePullDownMenuItem.Checked = false;
1753 this.HashToggleMenuItem.Checked = false;
1756 this.SetMainWindowTitle();
1761 this.statuses.AddPost(post);
1762 this.statuses.DistributePosts();
1763 this.RefreshTimeline();
1766 if (this.settings.Common.PostAndGet)
1767 await this.RefreshTabAsync<HomeTabModel>();
1770 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1772 await this.workerSemaphore.WaitAsync();
1776 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1778 this.RefreshTasktrayIcon();
1779 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1781 catch (WebApiException ex)
1783 this.myStatusError = true;
1784 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1788 this.workerSemaphore.Release();
1792 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1794 if (ct.IsCancellationRequested)
1797 if (!CheckAccountValid())
1798 throw new WebApiException("Auth error. Check your account");
1801 if (!this.settings.Common.UnreadManage)
1804 read = this.initial && this.settings.Common.Read;
1806 p.Report("Posting...");
1808 var posts = new List<PostClass>();
1810 await Task.Run(async () =>
1812 foreach (var statusId in statusIds)
1814 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1815 if (post != null) posts.Add(post);
1819 if (ct.IsCancellationRequested)
1822 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1824 this.postTimestamps.Add(DateTimeUtc.Now);
1826 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1827 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1829 if (this.postTimestamps[i] < oneHour)
1830 this.postTimestamps.RemoveAt(i);
1833 // 自分のRTはTLの更新では取得できない場合があるので、
1834 // 投稿時取得の有無に関わらず追加しておく
1835 posts.ForEach(post => this.statuses.AddPost(post));
1837 if (this.settings.Common.PostAndGet)
1839 await this.RefreshTabAsync<HomeTabModel>();
1843 this.statuses.DistributePosts();
1844 this.RefreshTimeline();
1848 private async Task RefreshFollowerIdsAsync()
1850 await this.workerSemaphore.WaitAsync();
1854 this.RefreshTasktrayIcon();
1855 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1857 await this.tw.RefreshFollowerIds();
1859 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1861 this.RefreshTimeline();
1862 this.listCache?.PurgeCache();
1863 this.CurrentListView.Refresh();
1865 catch (WebApiException ex)
1867 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1871 this.workerSemaphore.Release();
1875 private async Task RefreshNoRetweetIdsAsync()
1877 await this.workerSemaphore.WaitAsync();
1881 this.RefreshTasktrayIcon();
1882 await this.tw.RefreshNoRetweetIds();
1884 this.StatusLabel.Text = "NoRetweetIds refreshed";
1886 catch (WebApiException ex)
1888 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1892 this.workerSemaphore.Release();
1896 private async Task RefreshBlockIdsAsync()
1898 await this.workerSemaphore.WaitAsync();
1902 this.RefreshTasktrayIcon();
1903 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1905 await this.tw.RefreshBlockIds();
1907 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1909 catch (WebApiException ex)
1911 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1915 this.workerSemaphore.Release();
1919 private async Task RefreshTwitterConfigurationAsync()
1921 await this.workerSemaphore.WaitAsync();
1925 this.RefreshTasktrayIcon();
1926 await this.tw.RefreshConfiguration();
1928 if (this.tw.Configuration.PhotoSizeLimit != 0)
1930 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1932 service.UpdateTwitterConfiguration(this.tw.Configuration);
1936 this.listCache?.PurgeCache();
1937 this.CurrentListView.Refresh();
1939 catch (WebApiException ex)
1941 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1945 this.workerSemaphore.Release();
1949 private async Task RefreshMuteUserIdsAsync()
1951 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1955 await this.tw.RefreshMuteUserIdsAsync();
1957 catch (WebApiException ex)
1959 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1963 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1966 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1968 if (e.Button == MouseButtons.Left)
1970 this.Visible = true;
1971 if (this.WindowState == FormWindowState.Minimized)
1973 this.WindowState = this.formWindowState;
1976 this.BringToFront();
1980 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1981 => await this.ListItemDoubleClickAction();
1983 private async Task ListItemDoubleClickAction()
1985 switch (this.settings.Common.ListDoubleClickAction)
1987 case MyCommon.ListItemDoubleClickActionType.Reply:
1988 this.MakeReplyText();
1990 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1991 this.MakeReplyText(atAll: true);
1993 case MyCommon.ListItemDoubleClickActionType.Favorite:
1994 await this.FavoriteChange(true);
1996 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1997 var post = this.CurrentPost;
1999 await this.ShowUserStatus(post.ScreenName, false);
2001 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2002 await this.ShowUserTimeline();
2004 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2005 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2007 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2008 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2010 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2011 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2013 case MyCommon.ListItemDoubleClickActionType.None:
2020 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2021 => await this.FavoriteChange(true);
2023 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2024 => await this.FavoriteChange(false);
2026 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2027 => await this.FavoritesRetweetOfficial();
2029 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2030 => await this.FavoritesRetweetUnofficial();
2032 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2034 var tab = this.CurrentTab;
2035 var posts = tab.SelectedPosts;
2037 // trueでFavAdd,falseでFavRemove
2038 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2039 || !this.ExistCurrentPost) return;
2041 if (posts.Length > 1)
2046 // https://support.twitter.com/articles/76915#favoriting
2047 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2048 this.doFavRetweetFlags = false;
2053 if (multiFavoriteChangeDialogEnable)
2055 var confirm = MessageBox.Show(
2056 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2057 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2058 MessageBoxButtons.OKCancel,
2059 MessageBoxIcon.Question);
2061 if (confirm == DialogResult.Cancel)
2069 var selectedPost = posts.Single();
2070 if (selectedPost.IsFav)
2072 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2076 await this.FavAddAsync(selectedPost.StatusId, tab);
2080 var selectedPosts = posts.Where(x => x.IsFav);
2081 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2082 if (statusIds.Length == 0)
2084 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2088 await this.FavRemoveAsync(statusIds, tab);
2092 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2094 var post = this.CurrentPost;
2096 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2098 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2101 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2103 if ((!this.initialLayout) && this.Visible)
2105 if (this.WindowState == FormWindowState.Normal)
2107 this.mySize = this.ClientSize;
2108 this.mySpDis = this.SplitContainer1.SplitterDistance;
2109 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2110 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2111 this.MarkSettingLocalModified();
2116 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2118 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2119 if (comparerMode == null)
2122 this.SetSortColumn(comparerMode.Value);
2126 /// 列インデックスからソートを行う ComparerMode を求める
2128 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2129 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2130 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2132 if (this.Use2ColumnsMode)
2133 return ComparerMode.Id;
2135 return columnIndex switch
2137 1 => ComparerMode.Nickname, // ニックネーム
2138 2 => ComparerMode.Data, // 本文
2139 3 => ComparerMode.Id, // 時刻=発言Id
2140 4 => ComparerMode.Name, // 名前
2141 7 => ComparerMode.Source, // Source
2142 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2147 /// 発言一覧の指定した位置の列でソートする
2149 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2150 private void SetSortColumnByDisplayIndex(int columnIndex)
2152 // 表示上の列の位置から ColumnHeader を求める
2153 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2154 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2159 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2160 if (comparerMode == null)
2163 this.SetSortColumn(comparerMode.Value);
2167 /// 発言一覧の最後列の項目でソートする
2169 private void SetSortLastColumn()
2171 // 表示上の最後列にある ColumnHeader を求める
2172 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2173 .OrderByDescending(x => x.DisplayIndex)
2176 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2177 if (comparerMode == null)
2180 this.SetSortColumn(comparerMode.Value);
2184 /// 発言一覧を指定された ComparerMode に基づいてソートする
2186 private void SetSortColumn(ComparerMode sortColumn)
2188 if (this.settings.Common.SortOrderLock)
2191 this.statuses.ToggleSortOrder(sortColumn);
2192 this.InitColumnText();
2194 var list = this.CurrentListView;
2195 if (this.Use2ColumnsMode)
2197 list.Columns[0].Text = this.columnText[0];
2198 list.Columns[1].Text = this.columnText[2];
2202 for (var i = 0; i <= 7; i++)
2204 list.Columns[i].Text = this.columnText[i];
2208 this.listCache?.PurgeCache();
2210 var tab = this.CurrentTab;
2211 var post = this.CurrentPost;
2212 if (tab.AllCount > 0 && post != null)
2214 var idx = tab.IndexOf(post.StatusId);
2217 this.SelectListItem(list, idx);
2218 list.EnsureVisible(idx);
2223 this.MarkSettingCommonModified();
2226 private void TweenMain_LocationChanged(object sender, EventArgs e)
2228 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2230 this.myLoc = this.DesktopLocation;
2231 this.MarkSettingLocalModified();
2235 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2237 var post = this.CurrentPost;
2238 if (!this.ExistCurrentPost)
2240 this.ReplyStripMenuItem.Enabled = false;
2241 this.ReplyAllStripMenuItem.Enabled = false;
2242 this.DMStripMenuItem.Enabled = false;
2243 this.TabMenuItem.Enabled = false;
2244 this.IDRuleMenuItem.Enabled = false;
2245 this.SourceRuleMenuItem.Enabled = false;
2246 this.ReadedStripMenuItem.Enabled = false;
2247 this.UnreadStripMenuItem.Enabled = false;
2248 this.AuthorContextMenuItem.Visible = false;
2249 this.RetweetedByContextMenuItem.Visible = false;
2253 this.ReplyStripMenuItem.Enabled = true;
2254 this.ReplyAllStripMenuItem.Enabled = true;
2255 this.DMStripMenuItem.Enabled = true;
2256 this.TabMenuItem.Enabled = true;
2257 this.IDRuleMenuItem.Enabled = true;
2258 this.SourceRuleMenuItem.Enabled = true;
2259 this.ReadedStripMenuItem.Enabled = true;
2260 this.UnreadStripMenuItem.Enabled = true;
2261 this.AuthorContextMenuItem.Visible = true;
2262 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2263 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2264 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2266 var tab = this.CurrentTab;
2267 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2269 this.FavAddToolStripMenuItem.Enabled = false;
2270 this.FavRemoveToolStripMenuItem.Enabled = false;
2271 this.StatusOpenMenuItem.Enabled = false;
2272 this.ShowRelatedStatusesMenuItem.Enabled = false;
2274 this.ReTweetStripMenuItem.Enabled = false;
2275 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2276 this.QuoteStripMenuItem.Enabled = false;
2277 this.FavoriteRetweetContextMenu.Enabled = false;
2278 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2282 this.FavAddToolStripMenuItem.Enabled = true;
2283 this.FavRemoveToolStripMenuItem.Enabled = true;
2284 this.StatusOpenMenuItem.Enabled = true;
2285 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2287 if (!post.CanRetweetBy(this.tw.UserId))
2289 this.ReTweetStripMenuItem.Enabled = false;
2290 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2291 this.QuoteStripMenuItem.Enabled = false;
2292 this.FavoriteRetweetContextMenu.Enabled = false;
2293 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2297 this.ReTweetStripMenuItem.Enabled = true;
2298 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2299 this.QuoteStripMenuItem.Enabled = true;
2300 this.FavoriteRetweetContextMenu.Enabled = true;
2301 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2305 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2307 this.RepliedStatusOpenMenuItem.Enabled = false;
2311 this.RepliedStatusOpenMenuItem.Enabled = true;
2314 if (this.ExistCurrentPost && post != null)
2316 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2317 if (post.RetweetedByUserId == this.tw.UserId)
2318 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2320 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2324 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2325 => this.MakeReplyText();
2327 private void DMStripMenuItem_Click(object sender, EventArgs e)
2328 => this.MakeDirectMessageText();
2330 private async Task DoStatusDelete()
2332 var posts = this.CurrentTab.SelectedPosts;
2333 if (posts.Length == 0)
2336 // 選択されたツイートの中に削除可能なものが一つでもあるか
2337 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2340 var ret = MessageBox.Show(
2342 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2343 Properties.Resources.DeleteStripMenuItem_ClickText2,
2344 MessageBoxButtons.OKCancel,
2345 MessageBoxIcon.Question);
2347 if (ret != DialogResult.OK)
2350 var currentListView = this.CurrentListView;
2351 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2353 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2355 Exception? lastException = null;
2356 foreach (var post in posts)
2358 if (!post.CanDeleteBy(this.tw.UserId))
2363 if (post.StatusId is TwitterDirectMessageId dmId)
2365 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2369 if (post.RetweetedByUserId == this.tw.UserId)
2371 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2373 await this.tw.DeleteRetweet(post);
2377 if (post.UserId == this.tw.UserId)
2379 if (post.RetweetedId != null)
2381 // 他人に RT された自分のツイート
2382 // => RT 元の自分のツイートを削除
2383 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2389 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2395 catch (WebApiException ex)
2401 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2404 if (lastException == null)
2405 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2407 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2409 using (ControlTransaction.Update(currentListView))
2411 this.listCache?.PurgeCache();
2412 this.listCache?.UpdateListSize();
2414 currentListView.SelectedIndices.Clear();
2416 var currentTab = this.CurrentTab;
2417 if (currentTab.AllCount != 0)
2420 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2421 selectedIndex = focusedIndex;
2423 selectedIndex = currentTab.AllCount - 1;
2425 currentListView.SelectedIndices.Add(selectedIndex);
2426 currentListView.EnsureVisible(selectedIndex);
2427 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2431 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2433 var tabPage = this.ListTab.TabPages[index];
2434 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2436 if (tabPage.ImageIndex == 0)
2437 tabPage.ImageIndex = -1; // タブアイコン
2441 if (!this.settings.Common.TabIconDisp)
2442 this.ListTab.Refresh();
2446 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2447 => await this.DoStatusDelete();
2449 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2451 using (ControlTransaction.Update(this.CurrentListView))
2453 var tab = this.CurrentTab;
2454 foreach (var statusId in tab.SelectedStatusIds)
2456 this.statuses.SetReadAllTab(statusId, read: true);
2457 var idx = tab.IndexOf(statusId);
2458 this.listCache?.RefreshStyle(idx);
2461 if (this.settings.Common.TabIconDisp)
2463 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2465 if (tab.UnreadCount == 0)
2467 var tabPage = this.ListTab.TabPages[index];
2468 if (tabPage.ImageIndex == 0)
2469 tabPage.ImageIndex = -1; // タブアイコン
2473 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2476 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2478 using (ControlTransaction.Update(this.CurrentListView))
2480 var tab = this.CurrentTab;
2481 foreach (var statusId in tab.SelectedStatusIds)
2483 this.statuses.SetReadAllTab(statusId, read: false);
2484 var idx = tab.IndexOf(statusId);
2485 this.listCache?.RefreshStyle(idx);
2488 if (this.settings.Common.TabIconDisp)
2490 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2492 if (tab.UnreadCount > 0)
2494 var tabPage = this.ListTab.TabPages[index];
2495 if (tabPage.ImageIndex == -1)
2496 tabPage.ImageIndex = 0; // タブアイコン
2500 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2503 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2504 => await this.DoRefresh();
2506 private async Task DoRefresh()
2507 => await this.RefreshTabAsync(this.CurrentTab);
2509 private async Task DoRefreshMore()
2510 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2512 private DialogResult ShowSettingDialog()
2514 using var settingDialog = new AppendSettingDialog();
2515 settingDialog.Icon = this.iconAssets.IconMain;
2516 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2518 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2520 DialogResult result;
2523 result = settingDialog.ShowDialog(this);
2527 return DialogResult.Abort;
2530 if (result == DialogResult.OK)
2532 lock (this.syncObject)
2534 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2541 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2544 var previousUserId = this.settings.Common.UserId;
2545 var oldIconCol = this.Use2ColumnsMode;
2547 if (this.ShowSettingDialog() == DialogResult.OK)
2549 lock (this.syncObject)
2551 this.settings.ApplySettings();
2553 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2554 this.tw.ClearAuthInfo();
2556 var account = this.settings.Common.SelectedAccount;
2557 if (account != null)
2558 this.tw.Initialize(account.GetTwitterCredential(), account.Username, account.UserId);
2560 this.tw.Initialize(new TwitterCredentialNone(), "", 0L);
2562 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2563 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2565 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2569 if (this.settings.Common.TabIconDisp)
2571 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2572 this.ListTab.DrawMode = TabDrawMode.Normal;
2573 this.ListTab.ImageList = this.TabImage;
2577 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2578 this.ListTab.DrawItem += this.ListTab_DrawItem;
2579 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2580 this.ListTab.ImageList = null;
2583 catch (Exception ex)
2585 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2586 ex.Data["IsTerminatePermission"] = false;
2592 if (!this.settings.Common.UnreadManage)
2594 this.ReadedStripMenuItem.Enabled = false;
2595 this.UnreadStripMenuItem.Enabled = false;
2596 if (this.settings.Common.TabIconDisp)
2598 foreach (TabPage myTab in this.ListTab.TabPages)
2600 myTab.ImageIndex = -1;
2606 this.ReadedStripMenuItem.Enabled = true;
2607 this.UnreadStripMenuItem.Enabled = true;
2610 catch (Exception ex)
2612 ex.Data["Instance"] = "ListTab(UnreadManage)";
2613 ex.Data["IsTerminatePermission"] = false;
2618 this.SetTabAlignment();
2620 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2622 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2623 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2624 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2626 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2627 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2628 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2629 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2631 var newTheme = new ThemeManager(this.settings.Local);
2632 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2633 this.tweetDetailsView.Theme = this.themeManager;
2634 if (this.listDrawer != null)
2635 this.listDrawer.Theme = this.themeManager;
2640 if (this.StatusText.Focused)
2641 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2643 this.StatusText.Font = this.themeManager.FontInputFont;
2644 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2646 catch (Exception ex)
2648 MessageBox.Show(ex.Message);
2653 this.InitDetailHtmlFormat();
2655 catch (Exception ex)
2657 ex.Data["Instance"] = "Font";
2658 ex.Data["IsTerminatePermission"] = false;
2664 if (this.settings.Common.TabIconDisp)
2666 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2668 var tabPage = this.ListTab.TabPages[index];
2669 if (tab.UnreadCount == 0)
2670 tabPage.ImageIndex = -1;
2672 tabPage.ImageIndex = 0;
2676 catch (Exception ex)
2678 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2679 ex.Data["IsTerminatePermission"] = false;
2685 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2687 foreach (TabPage tp in this.ListTab.TabPages)
2689 var lst = (DetailsListView)tp.Tag;
2691 using (ControlTransaction.Update(lst))
2693 lst.GridLines = this.settings.Common.ShowGrid;
2695 if (this.Use2ColumnsMode != oldIconCol)
2696 this.ResetColumns(lst);
2700 catch (Exception ex)
2702 ex.Data["Instance"] = "ListView(IconSize)";
2703 ex.Data["IsTerminatePermission"] = false;
2707 this.SetMainWindowTitle();
2708 this.SetNotifyIconText();
2710 this.listCache?.PurgeCache();
2711 this.CurrentListView.Refresh();
2712 this.ListTab.Refresh();
2714 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2715 if (this.settings.Common.HotkeyEnabled)
2717 // グローバルホットキーの登録。設定で変更可能にするかも
2718 var modKey = HookGlobalHotkey.ModKeys.None;
2719 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2720 modKey |= HookGlobalHotkey.ModKeys.Alt;
2721 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2722 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2723 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2724 modKey |= HookGlobalHotkey.ModKeys.Shift;
2725 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2726 modKey |= HookGlobalHotkey.ModKeys.Win;
2728 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2731 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2734 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2742 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2744 this.TopMost = this.settings.Common.AlwaysTop;
2745 this.SaveConfigsAll(false);
2747 if (this.tw.UserId != previousUserId)
2748 await this.DoGetFollowersMenu();
2754 private void SetTabAlignment()
2756 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2757 if (this.ListTab.Alignment == newAlignment) return;
2760 var currentListViewState = this.listViewState[this.CurrentTabName];
2761 currentListViewState.Save(this.ListLockMenuItem.Checked);
2763 this.ListTab.Alignment = newAlignment;
2765 currentListViewState.Restore(forceScroll: true);
2768 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2771 if (this.listDrawer != null)
2773 this.listDrawer.IconSize = iconSz;
2774 this.listDrawer.UpdateItemHeight();
2777 this.listCache?.PurgeCache();
2780 private void ResetColumns(DetailsListView list)
2782 using (ControlTransaction.Update(list))
2783 using (ControlTransaction.Layout(list, false))
2786 list.ColumnClick -= this.MyList_ColumnClick;
2787 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2788 list.ColumnReordered -= this.MyList_ColumnReordered;
2789 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2791 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2792 list.Columns.Clear();
2793 cols.ForEach(col => col.Dispose());
2796 this.InitColumns(list, true);
2798 list.ColumnClick += this.MyList_ColumnClick;
2799 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2800 list.ColumnReordered += this.MyList_ColumnReordered;
2801 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2805 public void AddNewTabForSearch(string searchWord)
2807 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2808 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2810 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2812 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2813 this.ListTab.SelectedIndex = tabIndex;
2818 var tabName = searchWord;
2819 for (var i = 0; i <= 100; i++)
2821 if (this.statuses.ContainsTab(tabName))
2827 var tab = new PublicSearchTabModel(tabName);
2828 this.statuses.AddTab(tab);
2829 this.AddNewTab(tab, startup: false);
2831 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2833 var tabPage = this.CurrentTabPage;
2834 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2835 cmb.Items.Add(searchWord);
2836 cmb.Text = searchWord;
2837 this.SaveConfigsTabs();
2839 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2842 private async Task ShowUserTimeline()
2844 var post = this.CurrentPost;
2845 if (post == null || !this.ExistCurrentPost) return;
2846 await this.AddNewTabForUserTimeline(post.ScreenName);
2849 private async Task ShowRetweeterTimeline()
2851 var retweetedBy = this.CurrentPost?.RetweetedBy;
2852 if (retweetedBy == null || !this.ExistCurrentPost) return;
2853 await this.AddNewTabForUserTimeline(retweetedBy);
2856 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2858 if (e.KeyCode == Keys.Escape)
2860 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2861 this.SaveConfigsTabs();
2862 e.SuppressKeyPress = true;
2866 public async Task AddNewTabForUserTimeline(string user)
2868 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2869 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2871 if (tb.ScreenName == user)
2873 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2874 this.ListTab.SelectedIndex = tabIndex;
2879 var tabName = "user:" + user;
2880 while (this.statuses.ContainsTab(tabName))
2885 var tab = new UserTimelineTabModel(tabName, user);
2886 this.statuses.AddTab(tab);
2887 this.AddNewTab(tab, startup: false);
2889 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2890 this.SaveConfigsTabs();
2892 await this.RefreshTabAsync(tab);
2895 public bool AddNewTab(TabModel tab, bool startup)
2898 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2902 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2904 var tabPage = new TabPage();
2905 var listCustom = new DetailsListView();
2907 var cnt = this.statuses.Tabs.Count;
2909 // ToDo:Create and set controls follow tabtypes
2911 using (ControlTransaction.Update(listCustom))
2912 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2913 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2914 using (ControlTransaction.Layout(this.SplitContainer1, false))
2915 using (ControlTransaction.Layout(this.ListTab, false))
2916 using (ControlTransaction.Layout(this))
2917 using (ControlTransaction.Layout(tabPage, false))
2919 tabPage.Controls.Add(listCustom);
2922 var userTab = tab as UserTimelineTabModel;
2923 var listTab = tab as ListTimelineTabModel;
2924 var searchTab = tab as PublicSearchTabModel;
2926 if (userTab != null || listTab != null)
2928 var label = new Label
2930 Dock = DockStyle.Top,
2935 if (listTab != null)
2937 label.Text = listTab.ListInfo.ToString();
2939 else if (userTab != null)
2941 label.Text = userTab.ScreenName + "'s Timeline";
2943 label.TextAlign = ContentAlignment.MiddleLeft;
2944 using (var tmpComboBox = new ComboBox())
2946 label.Height = tmpComboBox.Height;
2948 tabPage.Controls.Add(label);
2951 else if (searchTab != null)
2953 var pnl = new Panel();
2955 var lbl = new Label();
2956 var cmb = new ComboBox();
2957 var btn = new Button();
2958 var cmbLang = new ComboBox();
2960 using (ControlTransaction.Layout(pnl, false))
2962 pnl.Controls.Add(cmb);
2963 pnl.Controls.Add(cmbLang);
2964 pnl.Controls.Add(btn);
2965 pnl.Controls.Add(lbl);
2966 pnl.Name = "panelSearch";
2968 pnl.Dock = DockStyle.Top;
2969 pnl.Height = cmb.Height;
2970 pnl.Enter += this.SearchControls_Enter;
2971 pnl.Leave += this.SearchControls_Leave;
2974 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2975 cmb.Dock = DockStyle.Fill;
2976 cmb.Name = "comboSearch";
2977 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2978 cmb.ImeMode = ImeMode.NoControl;
2979 cmb.TabStop = false;
2981 cmb.AutoCompleteMode = AutoCompleteMode.None;
2982 cmb.KeyDown += this.SearchComboBox_KeyDown;
2985 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2986 cmbLang.Dock = DockStyle.Right;
2988 cmbLang.Name = "comboLang";
2989 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2990 cmbLang.TabStop = false;
2991 cmbLang.TabIndex = 2;
2992 cmbLang.Items.Add("");
2993 cmbLang.Items.Add("ja");
2994 cmbLang.Items.Add("en");
2995 cmbLang.Items.Add("ar");
2996 cmbLang.Items.Add("da");
2997 cmbLang.Items.Add("nl");
2998 cmbLang.Items.Add("fa");
2999 cmbLang.Items.Add("fi");
3000 cmbLang.Items.Add("fr");
3001 cmbLang.Items.Add("de");
3002 cmbLang.Items.Add("hu");
3003 cmbLang.Items.Add("is");
3004 cmbLang.Items.Add("it");
3005 cmbLang.Items.Add("no");
3006 cmbLang.Items.Add("pl");
3007 cmbLang.Items.Add("pt");
3008 cmbLang.Items.Add("ru");
3009 cmbLang.Items.Add("es");
3010 cmbLang.Items.Add("sv");
3011 cmbLang.Items.Add("th");
3013 lbl.Text = "Search(C-S-f)";
3014 lbl.Name = "label1";
3015 lbl.Dock = DockStyle.Left;
3017 lbl.Height = cmb.Height;
3018 lbl.TextAlign = ContentAlignment.MiddleLeft;
3021 btn.Text = "Search";
3022 btn.Name = "buttonSearch";
3023 btn.UseVisualStyleBackColor = true;
3024 btn.Dock = DockStyle.Right;
3025 btn.TabStop = false;
3027 btn.Click += this.SearchButton_Click;
3029 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3031 cmb.Items.Add(searchTab.SearchWords);
3032 cmb.Text = searchTab.SearchWords;
3035 cmbLang.Text = searchTab.SearchLang;
3037 tabPage.Controls.Add(pnl);
3041 tabPage.Tag = listCustom;
3042 this.ListTab.Controls.Add(tabPage);
3044 tabPage.Location = new Point(4, 4);
3045 tabPage.Name = "CTab" + cnt;
3046 tabPage.Size = new Size(380, 260);
3047 tabPage.TabIndex = 2 + cnt;
3048 tabPage.Text = tab.TabName;
3049 tabPage.UseVisualStyleBackColor = true;
3050 tabPage.AccessibleRole = AccessibleRole.PageTab;
3052 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3053 listCustom.TabIndex = 1;
3054 listCustom.AllowColumnReorder = true;
3055 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3056 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3057 listCustom.Dock = DockStyle.Fill;
3058 listCustom.FullRowSelect = true;
3059 listCustom.HideSelection = false;
3060 listCustom.Location = new Point(0, 0);
3061 listCustom.Margin = new Padding(0);
3062 listCustom.Name = "CList" + Environment.TickCount;
3063 listCustom.ShowItemToolTips = true;
3064 listCustom.Size = new Size(380, 260);
3065 listCustom.UseCompatibleStateImageBehavior = false;
3066 listCustom.View = View.Details;
3067 listCustom.OwnerDraw = true;
3068 listCustom.VirtualMode = true;
3070 listCustom.GridLines = this.settings.Common.ShowGrid;
3071 listCustom.AllowDrop = true;
3073 this.InitColumns(listCustom, startup);
3075 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3076 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3077 listCustom.ColumnClick += this.MyList_ColumnClick;
3078 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3079 listCustom.DragDrop += this.TweenMain_DragDrop;
3080 listCustom.DragEnter += this.TweenMain_DragEnter;
3081 listCustom.DragOver += this.TweenMain_DragOver;
3082 listCustom.MouseClick += this.MyList_MouseClick;
3083 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3084 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3085 listCustom.HScrolled += this.MyList_HScrolled;
3088 var state = new TimelineListViewState(listCustom, tab);
3089 this.listViewState[tab.TabName] = state;
3094 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3096 var tabInfo = this.statuses.GetTabByName(tabName);
3097 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3102 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3103 var result = MessageBox.Show(
3105 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3106 MessageBoxButtons.OKCancel,
3107 MessageBoxIcon.Question,
3108 MessageBoxDefaultButton.Button2);
3109 if (result == DialogResult.Cancel)
3115 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3119 var tabPage = this.ListTab.TabPages[tabIndex];
3121 this.SetListProperty(); // 他のタブに列幅等を反映
3123 this.listViewState.Remove(tabName);
3126 var listCustom = (DetailsListView)tabPage.Tag;
3129 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3130 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3131 using (ControlTransaction.Layout(this.SplitContainer1, false))
3132 using (ControlTransaction.Layout(this.ListTab, false))
3133 using (ControlTransaction.Layout(this))
3134 using (ControlTransaction.Layout(tabPage, false))
3136 if (this.CurrentTabName == tabName)
3138 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3139 this.beforeSelectedTab = null;
3141 this.ListTab.Controls.Remove(tabPage);
3144 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3146 using var label = tabPage.Controls["labelUser"];
3147 tabPage.Controls.Remove(label);
3149 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3151 using var pnl = tabPage.Controls["panelSearch"];
3153 pnl.Enter -= this.SearchControls_Enter;
3154 pnl.Leave -= this.SearchControls_Leave;
3155 tabPage.Controls.Remove(pnl);
3157 foreach (Control ctrl in pnl.Controls)
3159 if (ctrl.Name == "buttonSearch")
3161 ctrl.Click -= this.SearchButton_Click;
3163 else if (ctrl.Name == "comboSearch")
3165 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3167 pnl.Controls.Remove(ctrl);
3172 tabPage.Controls.Remove(listCustom);
3174 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3175 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3176 listCustom.ColumnClick -= this.MyList_ColumnClick;
3177 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3178 listCustom.DragDrop -= this.TweenMain_DragDrop;
3179 listCustom.DragEnter -= this.TweenMain_DragEnter;
3180 listCustom.DragOver -= this.TweenMain_DragOver;
3181 listCustom.MouseClick -= this.MyList_MouseClick;
3182 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3183 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3184 listCustom.HScrolled -= this.MyList_HScrolled;
3186 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3187 listCustom.Columns.Clear();
3188 cols.ForEach(col => col.Dispose());
3191 listCustom.ContextMenuStrip = null;
3192 listCustom.ColumnHeaderContextMenuStrip = null;
3193 listCustom.Font = null;
3195 listCustom.SmallImageList = null;
3196 listCustom.ListViewItemSorter = null;
3199 this.listCache?.PurgeCache();
3203 listCustom.Dispose();
3204 this.statuses.RemoveTab(tabName);
3209 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3211 this.listCache?.PurgeCache();
3212 this.beforeSelectedTab = e.TabPage;
3215 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3219 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3222 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3223 if (!dragEnableRectangle.Contains(e.Location))
3225 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3226 tn = this.CurrentTabName;
3229 if (MyCommon.IsNullOrEmpty(tn)) return;
3231 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3234 var tabPage = this.ListTab.TabPages[tabIndex];
3235 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3240 this.tabDrag = false;
3243 var cpos = new Point(e.X, e.Y);
3244 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3246 var rect = this.ListTab.GetTabRect(index);
3247 if (rect.Contains(cpos))
3249 this.rclickTabName = tab.TabName;
3255 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3257 this.SetMainWindowTitle();
3258 this.SetStatusLabelUrl();
3259 this.SetApiStatusLabel();
3260 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3261 this.Tag = this.ListTab.Tag;
3262 this.TabMenuControl(this.CurrentTabName);
3263 this.PushSelectPostChain();
3264 this.DispSelectedPost();
3267 private void SetListProperty()
3269 if (!this.isColumnChanged) return;
3271 var currentListView = this.CurrentListView;
3273 var dispOrder = new int[currentListView.Columns.Count];
3274 for (var i = 0; i < currentListView.Columns.Count; i++)
3276 for (var j = 0; j < currentListView.Columns.Count; j++)
3278 if (currentListView.Columns[j].DisplayIndex == i)
3287 foreach (TabPage tb in this.ListTab.TabPages)
3289 if (tb.Text == this.CurrentTabName)
3292 if (tb.Tag != null && tb.Controls.Count > 0)
3294 var lst = (DetailsListView)tb.Tag;
3295 for (var i = 0; i < lst.Columns.Count; i++)
3297 lst.Columns[dispOrder[i]].DisplayIndex = i;
3298 lst.Columns[i].Width = currentListView.Columns[i].Width;
3303 this.isColumnChanged = false;
3306 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3308 if (e.KeyChar == '@')
3310 if (!this.settings.Common.UseAtIdSupplement) return;
3312 var cnt = this.AtIdSupl.ItemCount;
3313 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3314 if (cnt != this.AtIdSupl.ItemCount)
3315 this.MarkSettingAtIdModified();
3318 else if (e.KeyChar == '#')
3320 if (!this.settings.Common.UseHashSupplement) return;
3321 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3326 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3327 => this.ShowSuplDialog(owner, dialog, 0, "");
3329 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3330 => this.ShowSuplDialog(owner, dialog, offset, "");
3332 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3334 dialog.StartsWith = startswith;
3341 dialog.ShowDialog();
3343 this.TopMost = this.settings.Common.AlwaysTop;
3344 var selStart = owner.SelectionStart;
3347 if (dialog.DialogResult == DialogResult.OK)
3349 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3353 fHalf = owner.Text.Substring(0, selStart - offset);
3355 if (selStart < owner.Text.Length)
3357 eHalf = owner.Text.Substring(selStart);
3359 owner.Text = fHalf + dialog.InputText + eHalf;
3360 owner.SelectionStart = selStart + dialog.InputText.Length;
3367 fHalf = owner.Text.Substring(0, selStart);
3369 if (selStart < owner.Text.Length)
3371 eHalf = owner.Text.Substring(selStart);
3373 owner.Text = fHalf + eHalf;
3376 owner.SelectionStart = selStart;
3382 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3385 if (!e.Alt && !e.Control && !e.Shift)
3387 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3389 var isSpace = false;
3390 foreach (var c in this.StatusText.Text)
3392 if (c == ' ' || c == ' ')
3405 this.StatusText.Text = "";
3406 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3410 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3413 private void StatusText_TextChanged(object sender, EventArgs e)
3416 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3417 this.lblLen.Text = pLen.ToString();
3420 this.StatusText.ForeColor = Color.Red;
3424 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3427 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3429 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3431 this.inReplyTo = null;
3436 /// メンション以外の文字列が含まれていないテキストであるか判定します
3438 internal static bool TextContainsOnlyMentions(string text)
3440 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3443 foreach (var mention in mentions)
3445 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3447 if (!string.IsNullOrWhiteSpace(textPart))
3450 startIndex = mention.Indices[1];
3453 var textPartLast = text.Substring(startIndex);
3455 if (!string.IsNullOrWhiteSpace(textPartLast))
3462 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3464 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3466 var autoPopulatedUserIdList = new List<long>();
3468 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3469 if (replyToPost != null)
3471 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3473 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3474 autoPopulatedUserIdList.Add(replyToPost.UserId);
3476 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3478 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3480 statusText = statusText.Substring(screenName.Length + 2);
3481 autoPopulatedUserIdList.Add(userId);
3487 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3493 /// attachment_url に指定可能な URL が含まれていれば除去
3495 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3497 attachmentUrl = null;
3499 // attachment_url は media_id と同時に使用できない
3500 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3503 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3507 attachmentUrl = match.Value;
3510 statusText = statusText.Substring(0, match.Index);
3512 // テキストと URL の間にスペースが含まれていれば除去
3513 return statusText.TrimEnd(' ');
3516 private string FormatStatusTextExtended(string statusText)
3517 => this.FormatStatusTextExtended(statusText, out _, out _);
3520 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3522 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3524 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3526 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3528 return this.FormatStatusText(statusText);
3532 /// ツイート投稿前のフッター付与などの前処理を行います
3534 private string FormatStatusText(string statusText)
3536 statusText = statusText.Replace("\r\n", "\n");
3538 if (this.urlMultibyteSplit)
3541 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3544 if (this.settings.Common.WideSpaceConvert)
3546 // 文中の全角スペースを半角スペース1個にする
3547 statusText = statusText.Replace(" ", " ");
3550 // DM の場合はこれ以降の処理を行わない
3551 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3555 if (this.settings.Common.PostShiftEnter)
3557 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3561 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3562 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3564 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3567 if (statusText.Contains("RT @"))
3568 disableFooter = true;
3570 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3571 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3573 var mentionSelf = $"@{this.tw.Username} ";
3574 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3576 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3577 statusText = statusText.Substring(mentionSelf.Length);
3584 var hashtag = this.HashMgr.UseHash;
3585 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3587 if (this.HashMgr.IsHead)
3588 header = this.HashMgr.UseHash + " ";
3590 footer = " " + this.HashMgr.UseHash;
3595 if (this.settings.Local.UseRecommendStatus)
3598 footer += this.recommendedStatusFooter;
3600 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3602 // テキストボックスに入力されている文字列を使用する
3603 footer += " " + this.settings.Local.StatusText.Trim();
3607 statusText = header + statusText + footer;
3609 if (this.preventSmsCommand)
3611 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3612 // 参照: https://support.twitter.com/articles/14020
3614 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3615 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3617 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3618 statusText = '\u200b' + statusText;
3626 /// 投稿欄に表示する入力可能な文字数を計算します
3628 private int GetRestStatusCount(string statusText)
3630 var remainCount = this.tw.GetTextLengthRemain(statusText);
3632 var uploadService = this.GetSelectedImageService();
3633 if (uploadService != null)
3635 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3636 remainCount -= uploadService.GetReservedTextLength(1);
3642 private IMediaUploadService? GetSelectedImageService()
3643 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3646 /// 全てのタブの振り分けルールを反映し直します
3648 private void ApplyPostFilters()
3650 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3652 this.statuses.FilterAll();
3654 var listView = this.CurrentListView;
3655 using (ControlTransaction.Update(listView))
3657 this.listCache?.PurgeCache();
3658 this.listCache?.UpdateListSize();
3661 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3663 var tabPage = this.ListTab.TabPages[index];
3665 if (this.settings.Common.TabIconDisp)
3667 if (tab.UnreadCount > 0)
3668 tabPage.ImageIndex = 0;
3670 tabPage.ImageIndex = -1;
3674 if (!this.settings.Common.TabIconDisp)
3675 this.ListTab.Refresh();
3677 this.SetMainWindowTitle();
3678 this.SetStatusLabelUrl();
3682 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3683 => e.DrawDefault = true;
3685 private void MyList_HScrolled(object sender, EventArgs e)
3686 => ((DetailsListView)sender).Refresh();
3688 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3690 base.ScaleControl(factor, specified);
3692 ScaleChildControl(this.TabImage, factor);
3694 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3695 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3697 foreach (var listview in listviews)
3699 ScaleChildControl(listview, factor);
3703 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3705 var tab = this.CurrentTab;
3707 if (tab.AllCount == 0)
3709 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3713 var selectedIndex = tab.SelectedIndex;
3718 case SEARCHTYPE.NextSearch: // 次を検索
3719 if (selectedIndex != -1)
3720 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3724 case SEARCHTYPE.PrevSearch: // 前を検索
3725 if (selectedIndex != -1)
3726 startIndex = Math.Max(selectedIndex - 1, 0);
3728 startIndex = tab.AllCount - 1;
3730 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3732 if (selectedIndex != -1)
3733 startIndex = selectedIndex;
3739 Func<string, bool> stringComparer;
3742 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3744 catch (ArgumentException)
3746 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3750 var reverse = searchType == SEARCHTYPE.PrevSearch;
3751 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3752 .DefaultIfEmpty(-1).First();
3754 if (foundIndex == -1)
3756 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3760 var listView = this.CurrentListView;
3761 this.SelectListItem(listView, foundIndex);
3762 listView.EnsureVisible(foundIndex);
3765 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3766 => this.ShowSearchDialog(); // 検索メニュー
3768 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3770 var previousSearch = this.SearchDialog.ResultOptions;
3771 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3773 this.SearchDialog.Reset();
3774 this.ShowSearchDialog();
3780 previousSearch.Query,
3781 previousSearch.CaseSensitive,
3782 previousSearch.UseRegex,
3783 SEARCHTYPE.NextSearch);
3786 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3788 var previousSearch = this.SearchDialog.ResultOptions;
3789 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3791 this.SearchDialog.Reset();
3792 this.ShowSearchDialog();
3798 previousSearch.Query,
3799 previousSearch.CaseSensitive,
3800 previousSearch.UseRegex,
3801 SEARCHTYPE.PrevSearch);
3805 /// 検索ダイアログを表示し、検索を実行します
3807 private void ShowSearchDialog()
3809 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3811 this.TopMost = this.settings.Common.AlwaysTop;
3814 this.TopMost = this.settings.Common.AlwaysTop;
3816 var searchOptions = this.SearchDialog.ResultOptions!;
3817 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3819 if (searchOptions.NewTab)
3821 var tabName = Properties.Resources.SearchResults_TabName;
3825 tabName = this.statuses.MakeTabName(tabName);
3827 catch (TabException ex)
3829 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3832 var resultTab = new LocalSearchTabModel(tabName);
3833 this.AddNewTab(resultTab, startup: false);
3834 this.statuses.AddTab(resultTab);
3836 var targetTab = this.CurrentTab;
3838 Func<string, bool> stringComparer;
3841 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3843 catch (ArgumentException)
3845 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3849 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3850 if (foundIndices.Length == 0)
3852 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3856 var foundPosts = foundIndices.Select(x => targetTab[x]);
3857 foreach (var post in foundPosts)
3859 resultTab.AddPostQueue(post);
3862 this.statuses.DistributePosts();
3863 this.RefreshTimeline();
3865 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3866 this.ListTab.SelectedIndex = tabIndex;
3871 searchOptions.Query,
3872 searchOptions.CaseSensitive,
3873 searchOptions.UseRegex,
3874 SEARCHTYPE.DialogSearch);
3877 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3879 this.AddNewTabForSearch(searchOptions.Query);
3883 /// <summary>発言検索に使用するメソッドを生成します</summary>
3884 /// <exception cref="ArgumentException">
3885 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3887 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3891 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3892 var regex = new Regex(query, regexOption);
3894 return x => regex.IsMatch(x);
3898 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3900 return x => x.IndexOf(query, comparisonType) != -1;
3904 private void AboutMenuItem_Click(object sender, EventArgs e)
3906 using (var about = new TweenAboutBox())
3908 about.ShowDialog(this);
3910 this.TopMost = this.settings.Common.AlwaysTop;
3913 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3915 var bgnIdx = this.statuses.SelectedTabIndex;
3917 if (this.ImageSelector.Enabled)
3920 TabModel? foundTab = null;
3924 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3926 var unreadIndex = tab.NextUnreadIndex;
3927 if (unreadIndex != -1)
3929 this.ListTab.SelectedIndex = index;
3931 foundIndex = unreadIndex;
3936 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3937 if (foundTab == null && bgnIdx > 0)
3939 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3941 var unreadIndex = tab.NextUnreadIndex;
3942 if (unreadIndex != -1)
3944 this.ListTab.SelectedIndex = index;
3946 foundIndex = unreadIndex;
3952 DetailsListView lst;
3954 if (foundTab == null)
3956 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3957 this.ListTab.SelectedIndex = 0;
3958 var tabPage = this.ListTab.TabPages[0];
3959 var tab = this.statuses.Tabs[0];
3961 if (tab.AllCount == 0)
3964 if (this.statuses.SortOrder == SortOrder.Ascending)
3965 foundIndex = tab.AllCount - 1;
3969 lst = (DetailsListView)tabPage.Tag;
3973 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3974 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3977 this.SelectListItem(lst, foundIndex);
3979 if (this.statuses.SortMode == ComparerMode.Id)
3981 var rowHeight = lst.SmallImageList.ImageSize.Height;
3982 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3983 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3989 lst.EnsureVisible(foundIndex);
3994 lst.EnsureVisible(foundIndex);
4000 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4002 var tab = this.CurrentTab;
4003 var post = this.CurrentPost;
4004 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4005 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4008 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4009 => await this.CheckNewVersion(false);
4011 private void RunTweenUp()
4013 var pinfo = new ProcessStartInfo
4015 UseShellExecute = true,
4016 WorkingDirectory = this.settings.SettingsPath,
4017 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4018 Arguments = "\"" + Application.StartupPath + "\"",
4023 Process.Start(pinfo);
4027 MessageBox.Show("Failed to execute TweenUp3.exe.");
4031 public readonly record struct VersionInfo(
4038 /// OpenTween の最新バージョンの情報を取得します
4040 public async Task<VersionInfo> GetVersionInfoAsync()
4042 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4043 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4045 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4046 .ConfigureAwait(false);
4048 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4049 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4051 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4052 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4054 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4056 return new VersionInfo
4058 Version = Version.Parse(msgHeader[0]),
4059 DownloadUri = new Uri(msgHeader[1]),
4060 ReleaseNote = msgBody,
4064 private async Task CheckNewVersion(bool startup = false)
4066 if (ApplicationSettings.VersionInfoUrl == null)
4067 return; // 更新チェック無効化
4071 var versionInfo = await this.GetVersionInfoAsync();
4073 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4078 var msgtext = string.Format(
4079 Properties.Resources.CheckNewVersionText7,
4080 MyCommon.GetReadableVersion(),
4081 MyCommon.GetReadableVersion(versionInfo.Version));
4082 msgtext = MyCommon.ReplaceAppName(msgtext);
4086 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4087 MessageBoxButtons.OK,
4088 MessageBoxIcon.Information);
4093 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4096 using var dialog = new UpdateDialog();
4098 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4099 MyCommon.GetReadableVersion(versionInfo.Version));
4100 dialog.DetailsText = versionInfo.ReleaseNote;
4102 if (dialog.ShowDialog(this) == DialogResult.Yes)
4104 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4106 else if (dialog.SkipButtonPressed)
4108 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4109 this.MarkSettingCommonModified();
4114 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4118 Properties.Resources.CheckNewVersionText10,
4119 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4120 MessageBoxButtons.OK,
4121 MessageBoxIcon.Exclamation,
4122 MessageBoxDefaultButton.Button2);
4127 private void UpdateSelectedPost()
4129 // 件数関連の場合、タイトル即時書き換え
4130 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4131 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4132 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4133 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4135 this.SetMainWindowTitle();
4137 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4138 this.SetStatusLabelUrl();
4140 if (this.settings.Common.TabIconDisp)
4142 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4144 if (tab.UnreadCount == 0)
4146 var tabPage = this.ListTab.TabPages[index];
4147 if (tabPage.ImageIndex == 0)
4148 tabPage.ImageIndex = -1;
4154 this.ListTab.Refresh();
4157 this.DispSelectedPost();
4160 public string CreateDetailHtml(string orgdata)
4161 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4163 private void DispSelectedPost()
4164 => this.DispSelectedPost(false);
4166 private PostClass displayPost = new();
4169 /// サムネイル表示に使用する CancellationToken の生成元
4171 private CancellationTokenSource? thumbnailTokenSource = null;
4173 private void DispSelectedPost(bool forceupdate)
4175 var currentPost = this.CurrentPost;
4176 if (currentPost == null)
4179 var oldDisplayPost = this.displayPost;
4180 this.displayPost = currentPost;
4182 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4185 var loadTasks = new TaskCollection();
4186 loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4188 if (this.settings.Common.PreviewEnable)
4190 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4191 oldTokenSource?.Cancel();
4193 var token = this.thumbnailTokenSource!.Token;
4194 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4198 this.SplitContainer3.Panel2Collapsed = true;
4201 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4203 .IgnoreException(x => x is OperationCanceledException)
4207 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4209 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4211 var timeout = Task.Delay(100);
4212 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4214 token.ThrowIfCancellationRequested();
4216 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4217 this.SplitContainer3.Panel2Collapsed = true;
4221 token.ThrowIfCancellationRequested();
4223 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4226 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4227 => await this.OpenApplicationWebsite();
4229 private async Task OpenApplicationWebsite()
4230 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4232 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4233 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4235 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4237 var tab = this.CurrentTab;
4238 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4240 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4241 if (pnl.Controls["comboSearch"].Focused ||
4242 pnl.Controls["comboLang"].Focused ||
4243 pnl.Controls["buttonSearch"].Focused) return;
4246 if (e.Control || e.Shift || e.Alt)
4249 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4252 e.SuppressKeyPress = true;
4255 if (asyncTask != null)
4259 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4261 private void InitializeShortcuts()
4263 this.shortcutCommands = new[]
4265 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4266 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4267 .FocusedOn(FocusedControl.ListTab)
4268 .Do(() => SendKeys.Send("{DOWN}")),
4270 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4271 .FocusedOn(FocusedControl.ListTab)
4272 .Do(() => SendKeys.Send("{UP}")),
4274 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4275 .FocusedOn(FocusedControl.ListTab)
4276 .Do(() => SendKeys.Send("{PGDN}")),
4278 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4279 .FocusedOn(FocusedControl.ListTab)
4280 .Do(() => SendKeys.Send("{PGUP}")),
4282 ShortcutCommand.Create(Keys.F1)
4283 .Do(() => this.OpenApplicationWebsite()),
4285 ShortcutCommand.Create(Keys.F3)
4286 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4288 ShortcutCommand.Create(Keys.F5)
4289 .Do(() => this.DoRefresh()),
4291 ShortcutCommand.Create(Keys.F6)
4292 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4294 ShortcutCommand.Create(Keys.F7)
4295 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4297 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4298 .NotFocusedOn(FocusedControl.StatusText)
4301 this.CurrentTab.ClearAnchor();
4302 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4305 ShortcutCommand.Create(Keys.G)
4306 .NotFocusedOn(FocusedControl.StatusText)
4309 this.CurrentTab.ClearAnchor();
4310 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4313 ShortcutCommand.Create(Keys.Right, Keys.N)
4314 .FocusedOn(FocusedControl.ListTab)
4315 .Do(() => this.GoRelPost(forward: true)),
4317 ShortcutCommand.Create(Keys.Left, Keys.P)
4318 .FocusedOn(FocusedControl.ListTab)
4319 .Do(() => this.GoRelPost(forward: false)),
4321 ShortcutCommand.Create(Keys.OemPeriod)
4322 .FocusedOn(FocusedControl.ListTab)
4323 .Do(() => this.GoAnchor()),
4325 ShortcutCommand.Create(Keys.I)
4326 .FocusedOn(FocusedControl.ListTab)
4327 .OnlyWhen(() => this.StatusText.Enabled)
4328 .Do(() => this.StatusText.Focus()),
4330 ShortcutCommand.Create(Keys.Enter)
4331 .FocusedOn(FocusedControl.ListTab)
4332 .Do(() => this.ListItemDoubleClickAction()),
4334 ShortcutCommand.Create(Keys.R)
4335 .FocusedOn(FocusedControl.ListTab)
4336 .Do(() => this.DoRefresh()),
4338 ShortcutCommand.Create(Keys.L)
4339 .FocusedOn(FocusedControl.ListTab)
4342 this.CurrentTab.ClearAnchor();
4343 this.GoPost(forward: true);
4346 ShortcutCommand.Create(Keys.H)
4347 .FocusedOn(FocusedControl.ListTab)
4350 this.CurrentTab.ClearAnchor();
4351 this.GoPost(forward: false);
4354 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4355 .FocusedOn(FocusedControl.ListTab)
4358 this.CurrentTab.ClearAnchor();
4362 ShortcutCommand.Create(Keys.S)
4363 .FocusedOn(FocusedControl.ListTab)
4366 this.CurrentTab.ClearAnchor();
4367 this.GoNextTab(forward: true);
4370 ShortcutCommand.Create(Keys.A)
4371 .FocusedOn(FocusedControl.ListTab)
4374 this.CurrentTab.ClearAnchor();
4375 this.GoNextTab(forward: false);
4378 // ] in_reply_to参照元へ戻る
4379 ShortcutCommand.Create(Keys.Oem4)
4380 .FocusedOn(FocusedControl.ListTab)
4383 this.CurrentTab.ClearAnchor();
4384 return this.GoInReplyToPostTree();
4387 // [ in_reply_toへジャンプ
4388 ShortcutCommand.Create(Keys.Oem6)
4389 .FocusedOn(FocusedControl.ListTab)
4392 this.CurrentTab.ClearAnchor();
4393 this.GoBackInReplyToPostTree();
4396 ShortcutCommand.Create(Keys.Escape)
4397 .FocusedOn(FocusedControl.ListTab)
4400 this.CurrentTab.ClearAnchor();
4401 var tab = this.CurrentTab;
4402 var tabtype = tab.TabType;
4403 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4405 this.RemoveSpecifiedTab(tab.TabName, false);
4406 this.SaveConfigsTabs();
4410 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4411 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4412 .FocusedOn(FocusedControl.ListTab)
4413 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4415 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4416 ShortcutCommand.Create(Keys.Up, Keys.Down)
4417 .FocusedOn(FocusedControl.PostBrowser)
4420 ShortcutCommand.Create(Keys.Control | Keys.R)
4421 .Do(() => this.MakeReplyText()),
4423 ShortcutCommand.Create(Keys.Control | Keys.D)
4424 .Do(() => this.DoStatusDelete()),
4426 ShortcutCommand.Create(Keys.Control | Keys.M)
4427 .Do(() => this.MakeDirectMessageText()),
4429 ShortcutCommand.Create(Keys.Control | Keys.S)
4430 .Do(() => this.FavoriteChange(favAdd: true)),
4432 ShortcutCommand.Create(Keys.Control | Keys.I)
4433 .Do(() => this.DoRepliedStatusOpen()),
4435 ShortcutCommand.Create(Keys.Control | Keys.Q)
4436 .Do(() => this.DoQuoteOfficial()),
4438 ShortcutCommand.Create(Keys.Control | Keys.B)
4439 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4441 ShortcutCommand.Create(Keys.Control | Keys.T)
4442 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4444 ShortcutCommand.Create(Keys.Control | Keys.L)
4445 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4447 ShortcutCommand.Create(Keys.Control | Keys.Y)
4448 .NotFocusedOn(FocusedControl.PostBrowser)
4449 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4451 ShortcutCommand.Create(Keys.Control | Keys.F)
4452 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4454 ShortcutCommand.Create(Keys.Control | Keys.U)
4455 .Do(() => this.ShowUserTimeline()),
4457 ShortcutCommand.Create(Keys.Control | Keys.H)
4458 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4460 ShortcutCommand.Create(Keys.Control | Keys.O)
4461 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4463 ShortcutCommand.Create(Keys.Control | Keys.E)
4464 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4466 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4467 .FocusedOn(FocusedControl.ListTab)
4468 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4470 ShortcutCommand.Create(Keys.Control | Keys.N)
4471 .FocusedOn(FocusedControl.ListTab)
4472 .Do(() => this.GoNextTab(forward: true)),
4474 ShortcutCommand.Create(Keys.Control | Keys.P)
4475 .FocusedOn(FocusedControl.ListTab)
4476 .Do(() => this.GoNextTab(forward: false)),
4478 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4479 .FocusedOn(FocusedControl.ListTab)
4480 .Do(() => this.CopyStot()),
4482 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4483 ShortcutCommand.Create(Keys.Control | Keys.D1)
4484 .FocusedOn(FocusedControl.ListTab)
4485 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4486 .Do(() => this.ListTab.SelectedIndex = 0),
4488 ShortcutCommand.Create(Keys.Control | Keys.D2)
4489 .FocusedOn(FocusedControl.ListTab)
4490 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4491 .Do(() => this.ListTab.SelectedIndex = 1),
4493 ShortcutCommand.Create(Keys.Control | Keys.D3)
4494 .FocusedOn(FocusedControl.ListTab)
4495 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4496 .Do(() => this.ListTab.SelectedIndex = 2),
4498 ShortcutCommand.Create(Keys.Control | Keys.D4)
4499 .FocusedOn(FocusedControl.ListTab)
4500 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4501 .Do(() => this.ListTab.SelectedIndex = 3),
4503 ShortcutCommand.Create(Keys.Control | Keys.D5)
4504 .FocusedOn(FocusedControl.ListTab)
4505 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4506 .Do(() => this.ListTab.SelectedIndex = 4),
4508 ShortcutCommand.Create(Keys.Control | Keys.D6)
4509 .FocusedOn(FocusedControl.ListTab)
4510 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4511 .Do(() => this.ListTab.SelectedIndex = 5),
4513 ShortcutCommand.Create(Keys.Control | Keys.D7)
4514 .FocusedOn(FocusedControl.ListTab)
4515 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4516 .Do(() => this.ListTab.SelectedIndex = 6),
4518 ShortcutCommand.Create(Keys.Control | Keys.D8)
4519 .FocusedOn(FocusedControl.ListTab)
4520 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4521 .Do(() => this.ListTab.SelectedIndex = 7),
4523 ShortcutCommand.Create(Keys.Control | Keys.D9)
4524 .FocusedOn(FocusedControl.ListTab)
4525 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4527 ShortcutCommand.Create(Keys.Control | Keys.A)
4528 .FocusedOn(FocusedControl.StatusText)
4529 .Do(() => this.StatusText.SelectAll()),
4531 ShortcutCommand.Create(Keys.Control | Keys.V)
4532 .FocusedOn(FocusedControl.StatusText)
4533 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4535 ShortcutCommand.Create(Keys.Control | Keys.Up)
4536 .FocusedOn(FocusedControl.StatusText)
4537 .Do(() => this.StatusTextHistoryBack()),
4539 ShortcutCommand.Create(Keys.Control | Keys.Down)
4540 .FocusedOn(FocusedControl.StatusText)
4541 .Do(() => this.StatusTextHistoryForward()),
4543 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4544 .FocusedOn(FocusedControl.StatusText)
4547 if (this.ListTab.SelectedIndex == 0)
4549 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4553 this.ListTab.SelectedIndex -= 1;
4555 this.StatusText.Focus();
4558 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4559 .FocusedOn(FocusedControl.StatusText)
4562 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4564 this.ListTab.SelectedIndex = 0;
4568 this.ListTab.SelectedIndex += 1;
4570 this.StatusText.Focus();
4573 ShortcutCommand.Create(Keys.Control | Keys.Y)
4574 .FocusedOn(FocusedControl.PostBrowser)
4577 var multiline = !this.settings.Local.StatusMultiline;
4578 this.settings.Local.StatusMultiline = multiline;
4579 this.MultiLineMenuItem.Checked = multiline;
4580 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4583 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4584 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4586 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4587 .Do(() => this.DoRefreshMore()),
4589 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4590 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4592 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4593 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4595 ShortcutCommand.Create(Keys.Shift | Keys.R)
4596 .NotFocusedOn(FocusedControl.StatusText)
4597 .Do(() => this.DoRefreshMore()),
4599 ShortcutCommand.Create(Keys.Shift | Keys.H)
4600 .FocusedOn(FocusedControl.ListTab)
4601 .Do(() => this.GoTopEnd(goTop: true)),
4603 ShortcutCommand.Create(Keys.Shift | Keys.L)
4604 .FocusedOn(FocusedControl.ListTab)
4605 .Do(() => this.GoTopEnd(goTop: false)),
4607 ShortcutCommand.Create(Keys.Shift | Keys.M)
4608 .FocusedOn(FocusedControl.ListTab)
4609 .Do(() => this.GoMiddle()),
4611 ShortcutCommand.Create(Keys.Shift | Keys.G)
4612 .FocusedOn(FocusedControl.ListTab)
4613 .Do(() => this.GoLast()),
4615 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4616 .FocusedOn(FocusedControl.ListTab)
4617 .Do(() => this.MoveMiddle()),
4619 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4620 .FocusedOn(FocusedControl.ListTab)
4621 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4623 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4624 .FocusedOn(FocusedControl.ListTab)
4625 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4627 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4628 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4629 .FocusedOn(FocusedControl.ListTab)
4630 .Do(() => this.GoFav(forward: true)),
4632 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4633 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4634 .FocusedOn(FocusedControl.ListTab)
4635 .Do(() => this.GoFav(forward: false)),
4637 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4638 .FocusedOn(FocusedControl.ListTab)
4639 .Do(() => this.GoBackSelectPostChain()),
4641 ShortcutCommand.Create(Keys.Alt | Keys.R)
4642 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4644 ShortcutCommand.Create(Keys.Alt | Keys.P)
4645 .OnlyWhen(() => this.CurrentPost != null)
4646 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4648 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4649 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4651 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4652 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4654 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4655 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4657 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4658 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4660 // 別タブの同じ書き込みへ(ALT+←/→)
4661 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4662 .FocusedOn(FocusedControl.ListTab)
4663 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4665 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4666 .FocusedOn(FocusedControl.ListTab)
4667 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4669 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4670 .Do(() => this.MakeReplyText(atAll: true)),
4672 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4673 .Do(() => this.CopyIdUri()),
4675 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4676 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4677 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4679 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4680 .Do(() => this.DoQuoteOfficial()),
4682 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4683 .Do(() => this.FavoriteChange(favAdd: false)),
4685 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4686 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4688 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4689 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4691 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4692 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4694 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4695 .Do(() => this.DoMoveToRTHome()),
4697 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4698 .FocusedOn(FocusedControl.StatusText)
4701 var tab = this.CurrentTab;
4702 var selectedIndex = tab.SelectedIndex;
4703 if (selectedIndex != -1 && selectedIndex > 0)
4705 var listView = this.CurrentListView;
4706 var idx = selectedIndex - 1;
4707 this.SelectListItem(listView, idx);
4708 listView.EnsureVisible(idx);
4712 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4713 .FocusedOn(FocusedControl.StatusText)
4716 var tab = this.CurrentTab;
4717 var selectedIndex = tab.SelectedIndex;
4718 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4720 var listView = this.CurrentListView;
4721 var idx = selectedIndex + 1;
4722 this.SelectListItem(listView, idx);
4723 listView.EnsureVisible(idx);
4727 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4728 .FocusedOn(FocusedControl.StatusText)
4731 if (this.StatusText.SelectionStart > 0)
4733 var endidx = this.StatusText.SelectionStart - 1;
4735 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4737 var c = this.StatusText.Text[i];
4738 if (char.IsLetterOrDigit(c) || c == '_')
4744 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4745 var cnt = this.AtIdSupl.ItemCount;
4746 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4747 if (this.AtIdSupl.ItemCount != cnt)
4748 this.MarkSettingAtIdModified();
4752 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4753 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4763 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4764 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4765 .FocusedOn(FocusedControl.ListTab)
4766 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4768 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4769 .FocusedOn(FocusedControl.ListTab)
4770 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4772 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4773 .FocusedOn(FocusedControl.ListTab)
4774 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4776 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4777 .FocusedOn(FocusedControl.ListTab)
4778 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4780 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4781 .FocusedOn(FocusedControl.ListTab)
4782 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4784 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4785 .FocusedOn(FocusedControl.ListTab)
4786 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4788 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4789 .FocusedOn(FocusedControl.ListTab)
4790 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4792 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4793 .FocusedOn(FocusedControl.ListTab)
4794 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4796 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4797 .FocusedOn(FocusedControl.ListTab)
4798 .Do(() => this.SetSortLastColumn()),
4800 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4801 .FocusedOn(FocusedControl.ListTab)
4802 .Do(() => this.FavoritesRetweetOfficial()),
4804 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4805 .FocusedOn(FocusedControl.ListTab)
4806 .Do(() => this.FavoritesRetweetUnofficial()),
4808 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4809 .FocusedOn(FocusedControl.ListTab)
4810 .Do(() => this.OpenUserAppointUrl()),
4812 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4813 .FocusedOn(FocusedControl.PostBrowser)
4814 .Do(() => this.DoReTweetUnofficial()),
4816 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4817 .OnlyWhen(() => this.ExistCurrentPost)
4818 .Do(() => this.tweetDetailsView.DoTranslation()),
4820 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4821 .Do(() => this.DoReTweetUnofficial()),
4823 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4824 .Do(() => this.CopyUserId()),
4826 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4827 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4829 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4830 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4832 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4833 .FocusedOn(FocusedControl.ListTab)
4834 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4835 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4839 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4841 // Task を返す非同期処理があれば asyncTask に代入する
4844 // ShortcutCommand に対応しているコマンドはここで処理される
4845 foreach (var command in this.shortcutCommands)
4847 if (command.IsMatch(keyData, focusedOn))
4849 asyncTask = command.RunCommand();
4850 return command.PreventDefault;
4857 private void GoNextTab(bool forward)
4859 var idx = this.statuses.SelectedTabIndex;
4860 var tabCount = this.statuses.Tabs.Count;
4864 if (idx > tabCount - 1) idx = 0;
4869 if (idx < 0) idx = tabCount - 1;
4871 this.ListTab.SelectedIndex = idx;
4874 private void CopyStot()
4876 var sb = new StringBuilder();
4877 var tab = this.CurrentTab;
4878 var isProtected = false;
4879 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4880 foreach (var post in tab.SelectedPosts)
4882 if (post.IsDeleted) continue;
4885 if (post.RetweetedId != null)
4886 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4888 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4892 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4897 MessageBox.Show(Properties.Resources.CopyStotText1);
4901 var clstr = sb.ToString();
4904 Clipboard.SetDataObject(clstr, false, 5, 100);
4906 catch (Exception ex)
4908 MessageBox.Show(ex.Message);
4913 private void CopyIdUri()
4915 var tab = this.CurrentTab;
4916 if (tab == null || tab is DirectMessagesTabModel)
4919 var copyUrls = new List<string>();
4920 foreach (var post in tab.SelectedPosts)
4921 copyUrls.Add(MyCommon.GetStatusUrl(post));
4923 if (copyUrls.Count == 0)
4928 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4930 catch (ExternalException ex)
4932 MessageBox.Show(ex.Message);
4936 private void GoFav(bool forward)
4938 var tab = this.CurrentTab;
4939 if (tab.AllCount == 0)
4942 var selectedIndex = tab.SelectedIndex;
4950 if (selectedIndex == -1)
4956 fIdx = selectedIndex + 1;
4957 if (fIdx > tab.AllCount - 1)
4960 toIdx = tab.AllCount;
4965 if (selectedIndex == -1)
4967 fIdx = tab.AllCount - 1;
4971 fIdx = selectedIndex - 1;
4979 for (var idx = fIdx; idx != toIdx; idx += stp)
4983 var listView = this.CurrentListView;
4984 this.SelectListItem(listView, idx);
4985 listView.EnsureVisible(idx);
4991 private void GoSamePostToAnotherTab(bool left)
4993 var tab = this.CurrentTab;
4995 // Directタブは対象外(見つかるはずがない)
4996 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4999 var selectedStatusId = tab.SelectedStatusId;
5000 if (selectedStatusId == null)
5003 int fIdx, toIdx, stp;
5008 if (this.ListTab.SelectedIndex == 0)
5014 fIdx = this.ListTab.SelectedIndex - 1;
5022 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5028 fIdx = this.ListTab.SelectedIndex + 1;
5030 toIdx = this.ListTab.TabCount;
5034 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5036 var targetTab = this.statuses.Tabs[tabidx];
5039 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5042 var foundIndex = targetTab.IndexOf(selectedStatusId);
5043 if (foundIndex != -1)
5045 this.ListTab.SelectedIndex = tabidx;
5046 var listView = this.CurrentListView;
5047 this.SelectListItem(listView, foundIndex);
5048 listView.EnsureVisible(foundIndex);
5054 private void GoPost(bool forward)
5056 var tab = this.CurrentTab;
5057 var currentPost = this.CurrentPost;
5059 if (currentPost == null)
5062 var selectedIndex = tab.SelectedIndex;
5064 int fIdx, toIdx, stp;
5068 fIdx = selectedIndex + 1;
5069 if (fIdx > tab.AllCount - 1) return;
5070 toIdx = tab.AllCount;
5075 fIdx = selectedIndex - 1;
5076 if (fIdx < 0) return;
5082 if (currentPost.RetweetedBy == null)
5084 name = currentPost.ScreenName;
5088 name = currentPost.RetweetedBy;
5090 for (var idx = fIdx; idx != toIdx; idx += stp)
5092 var post = tab[idx];
5093 if (post.RetweetedId == null)
5095 if (post.ScreenName == name)
5097 var listView = this.CurrentListView;
5098 this.SelectListItem(listView, idx);
5099 listView.EnsureVisible(idx);
5105 if (post.RetweetedBy == name)
5107 var listView = this.CurrentListView;
5108 this.SelectListItem(listView, idx);
5109 listView.EnsureVisible(idx);
5116 private void GoRelPost(bool forward)
5118 var tab = this.CurrentTab;
5119 var selectedIndex = tab.SelectedIndex;
5121 if (selectedIndex == -1)
5124 int fIdx, toIdx, stp;
5128 fIdx = selectedIndex + 1;
5129 if (fIdx > tab.AllCount - 1) return;
5130 toIdx = tab.AllCount;
5135 fIdx = selectedIndex - 1;
5136 if (fIdx < 0) return;
5141 var anchorPost = tab.AnchorPost;
5142 if (anchorPost == null)
5144 var currentPost = this.CurrentPost;
5145 if (currentPost == null)
5148 anchorPost = currentPost;
5149 tab.AnchorPost = currentPost;
5152 for (var idx = fIdx; idx != toIdx; idx += stp)
5154 var post = tab[idx];
5155 if (post.ScreenName == anchorPost.ScreenName ||
5156 post.RetweetedBy == anchorPost.ScreenName ||
5157 post.ScreenName == anchorPost.RetweetedBy ||
5158 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5159 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5160 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5161 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5162 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5164 var listView = this.CurrentListView;
5165 this.SelectListItem(listView, idx);
5166 listView.EnsureVisible(idx);
5172 private void GoAnchor()
5174 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5175 if (anchorStatusId == null)
5178 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5182 var listView = this.CurrentListView;
5183 this.SelectListItem(listView, idx);
5184 listView.EnsureVisible(idx);
5187 private void GoTopEnd(bool goTop)
5189 var listView = this.CurrentListView;
5190 if (listView.VirtualListSize == 0)
5198 item = listView.GetItemAt(0, 25);
5206 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5208 idx = listView.VirtualListSize - 1;
5212 this.SelectListItem(listView, idx);
5215 private void GoMiddle()
5217 var listView = this.CurrentListView;
5218 if (listView.VirtualListSize == 0)
5226 item = listView.GetItemAt(0, 0);
5236 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5239 idx2 = listView.VirtualListSize - 1;
5245 idx3 = (idx1 + idx2) / 2;
5247 this.SelectListItem(listView, idx3);
5250 private void GoLast()
5252 var listView = this.CurrentListView;
5253 if (listView.VirtualListSize == 0) return;
5255 if (this.statuses.SortOrder == SortOrder.Ascending)
5257 this.SelectListItem(listView, listView.VirtualListSize - 1);
5258 listView.EnsureVisible(listView.VirtualListSize - 1);
5262 this.SelectListItem(listView, 0);
5263 listView.EnsureVisible(0);
5267 private void MoveTop()
5269 var listView = this.CurrentListView;
5270 if (listView.SelectedIndices.Count == 0) return;
5271 var idx = listView.SelectedIndices[0];
5272 if (this.statuses.SortOrder == SortOrder.Ascending)
5274 listView.EnsureVisible(listView.VirtualListSize - 1);
5278 listView.EnsureVisible(0);
5280 listView.EnsureVisible(idx);
5283 private async Task GoInReplyToPostTree()
5285 var curTabClass = this.CurrentTab;
5286 var currentPost = this.CurrentPost;
5288 if (currentPost == null)
5291 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5295 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5297 currentPost = currentPost with
5299 InReplyToStatusId = post.InReplyToStatusId,
5300 InReplyToUser = post.InReplyToUser,
5301 IsReply = post.IsReply,
5303 curTabClass.ReplacePost(currentPost);
5304 this.listCache?.PurgeCache();
5306 var index = curTabClass.SelectedIndex;
5307 this.CurrentListView.RedrawItems(index, index, false);
5309 catch (WebApiException ex)
5311 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5315 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5317 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5319 this.replyChains = new Stack<ReplyChain>();
5321 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5324 string inReplyToTabName;
5325 var inReplyToId = currentPost.InReplyToStatusId;
5326 var inReplyToUser = currentPost.InReplyToUser;
5328 var inReplyToPosts = from tab in this.statuses.Tabs
5329 orderby tab != curTabClass
5330 from post in tab.Posts.Values
5331 where post.StatusId == inReplyToId
5332 let index = tab.IndexOf(post.StatusId)
5334 select new { Tab = tab, Index = index };
5336 var inReplyPost = inReplyToPosts.FirstOrDefault();
5337 if (inReplyPost == null)
5341 await Task.Run(async () =>
5343 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5344 .ConfigureAwait(false);
5347 this.statuses.AddPost(post);
5348 this.statuses.DistributePosts();
5351 catch (WebApiException ex)
5353 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5354 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5358 this.RefreshTimeline();
5360 inReplyPost = inReplyToPosts.FirstOrDefault();
5361 if (inReplyPost == null)
5363 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5367 inReplyToTabName = inReplyPost.Tab.TabName;
5368 inReplyToIndex = inReplyPost.Index;
5370 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5371 var tabPage = this.ListTab.TabPages[tabIndex];
5372 var listView = (DetailsListView)tabPage.Tag;
5374 if (this.CurrentTabName != inReplyToTabName)
5376 this.ListTab.SelectedIndex = tabIndex;
5379 this.SelectListItem(listView, inReplyToIndex);
5380 listView.EnsureVisible(inReplyToIndex);
5383 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5385 var curTabClass = this.CurrentTab;
5386 var currentPost = this.CurrentPost;
5388 if (currentPost == null)
5393 if (currentPost.InReplyToStatusId != null)
5395 var posts = from t in this.statuses.Tabs
5397 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5398 let indexOf = t.IndexOf(p.Value.StatusId)
5400 orderby isForward ? indexOf : indexOf * -1
5401 orderby t != curTabClass
5402 select new { Tab = t, Post = p.Value, Index = indexOf };
5405 var postList = posts.ToList();
5406 for (var i = postList.Count - 1; i >= 0; i--)
5409 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5411 postList.RemoveAt(index);
5414 var currentIndex = this.CurrentTab.SelectedIndex;
5415 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5416 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5417 if (post == null) post = postList.First();
5418 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5419 this.ListTab.SelectedIndex = tabIndex;
5420 var listView = this.CurrentListView;
5421 this.SelectListItem(listView, post.Index);
5422 listView.EnsureVisible(post.Index);
5424 catch (InvalidOperationException)
5432 if (this.replyChains == null || this.replyChains.Count < 1)
5434 var posts = from t in this.statuses.Tabs
5436 where p.Value.InReplyToStatusId == currentPost.StatusId
5437 let indexOf = t.IndexOf(p.Value.StatusId)
5440 orderby t != curTabClass
5441 select new { Tab = t, Index = indexOf };
5444 var post = posts.First();
5445 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5446 this.ListTab.SelectedIndex = tabIndex;
5447 var listView = this.CurrentListView;
5448 this.SelectListItem(listView, post.Index);
5449 listView.EnsureVisible(post.Index);
5451 catch (InvalidOperationException)
5458 var chainHead = this.replyChains.Pop();
5459 if (chainHead.InReplyToId == currentPost.StatusId)
5461 var tab = chainHead.OriginalTab;
5462 if (!this.statuses.Tabs.Contains(tab))
5464 this.replyChains = null;
5468 var idx = tab.IndexOf(chainHead.OriginalId);
5471 this.replyChains = null;
5475 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5478 this.ListTab.SelectedIndex = tabIndex;
5482 this.replyChains = null;
5484 var listView = this.CurrentListView;
5485 this.SelectListItem(listView, idx);
5486 listView.EnsureVisible(idx);
5492 this.replyChains = null;
5493 this.GoBackInReplyToPostTree(parallel);
5499 private void GoBackSelectPostChain()
5501 if (this.selectPostChains.Count > 1)
5504 TabModel? foundTab = null;
5510 this.selectPostChains.Pop();
5511 var (tab, post) = this.selectPostChains.Peek();
5513 if (!this.statuses.Tabs.Contains(tab))
5514 continue; // 該当タブが存在しないので無視
5518 idx = tab.IndexOf(post.StatusId);
5519 if (idx == -1) continue; // 該当ポストが存在しないので無視
5524 this.selectPostChains.Pop();
5526 catch (InvalidOperationException)
5532 while (this.selectPostChains.Count > 1);
5534 if (foundTab == null)
5537 // 履歴が残り1つであればクリアしておく
5538 if (this.selectPostChains.Count == 1)
5539 this.selectPostChains.Clear();
5543 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5544 var tabPage = this.ListTab.TabPages[tabIndex];
5545 var lst = (DetailsListView)tabPage.Tag;
5546 this.ListTab.SelectedIndex = tabIndex;
5550 this.SelectListItem(lst, idx);
5551 lst.EnsureVisible(idx);
5557 private void PushSelectPostChain()
5559 var currentTab = this.CurrentTab;
5560 var currentPost = this.CurrentPost;
5562 var count = this.selectPostChains.Count;
5565 var (tab, post) = this.selectPostChains.Peek();
5566 if (tab == currentTab)
5568 if (post == currentPost) return; // 最新の履歴と同一
5569 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5572 if (count >= 2500) this.TrimPostChain();
5573 this.selectPostChains.Push((currentTab, currentPost));
5576 private void TrimPostChain()
5578 if (this.selectPostChains.Count <= 2000) return;
5579 var p = new Stack<(TabModel, PostClass?)>(2000);
5580 for (var i = 0; i < 2000; i++)
5582 p.Push(this.selectPostChains.Pop());
5584 this.selectPostChains.Clear();
5585 for (var i = 0; i < 2000; i++)
5587 this.selectPostChains.Push(p.Pop());
5591 private bool GoStatus(PostId statusId)
5593 var tab = this.statuses.Tabs
5594 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5595 .Where(x => x.Contains(statusId))
5601 var index = tab.IndexOf(statusId);
5603 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5604 this.ListTab.SelectedIndex = tabIndex;
5606 var listView = this.CurrentListView;
5607 this.SelectListItem(listView, index);
5608 listView.EnsureVisible(index);
5613 private bool GoDirectMessage(PostId statusId)
5615 var tab = this.statuses.DirectMessageTab;
5616 var index = tab.IndexOf(statusId);
5621 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5622 this.ListTab.SelectedIndex = tabIndex;
5624 var listView = this.CurrentListView;
5625 this.SelectListItem(listView, index);
5626 listView.EnsureVisible(index);
5631 private void MyList_MouseClick(object sender, MouseEventArgs e)
5632 => this.CurrentTab.ClearAnchor();
5634 private void StatusText_Enter(object sender, EventArgs e)
5636 // フォーカスの戻り先を StatusText に設定
5637 this.Tag = this.StatusText;
5638 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5641 public Color InputBackColor
5642 => this.themeManager.ColorInputBackcolor;
5644 private void StatusText_Leave(object sender, EventArgs e)
5646 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5647 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5648 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5651 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5653 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5656 e.SuppressKeyPress = true;
5659 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5661 if (asyncTask != null)
5665 private void SaveConfigsAll(bool ifModified)
5669 this.SaveConfigsCommon();
5670 this.SaveConfigsLocal();
5671 this.SaveConfigsTabs();
5672 this.SaveConfigsAtId();
5676 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5677 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5678 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5682 private void SaveConfigsAtId()
5684 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5686 this.ModifySettingAtId = false;
5687 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5688 this.settings.SaveAtIdList();
5691 private void SaveConfigsCommon()
5693 if (this.ignoreConfigSave) return;
5695 this.ModifySettingCommon = false;
5696 lock (this.syncObject)
5698 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5699 this.settings.Common.SortColumn = this.statuses.SortMode switch
5701 ComparerMode.Nickname => 1, // ニックネーム
5702 ComparerMode.Data => 2, // 本文
5703 ComparerMode.Id => 3, // 時刻=発言Id
5704 ComparerMode.Name => 4, // 名前
5705 ComparerMode.Source => 7, // Source
5706 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5708 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5709 if (this.HashMgr.IsPermanent)
5711 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5715 this.settings.Common.HashSelected = "";
5717 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5718 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5719 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5720 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5721 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5723 this.settings.SaveCommon();
5727 private void SaveConfigsLocal()
5729 if (this.ignoreConfigSave) return;
5730 lock (this.syncObject)
5732 this.ModifySettingLocal = false;
5733 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5734 this.settings.Local.FormSize = this.mySize;
5735 this.settings.Local.FormLocation = this.myLoc;
5736 this.settings.Local.SplitterDistance = this.mySpDis;
5737 this.settings.Local.PreviewDistance = this.mySpDis3;
5738 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5739 this.settings.Local.StatusTextHeight = this.mySpDis2;
5741 if (this.ignoreConfigSave) return;
5742 this.settings.SaveLocal();
5746 private void SaveConfigsTabs()
5748 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5750 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5752 foreach (var tab in tabs)
5754 if (!tab.IsPermanentTabType)
5757 var tabSetting = new SettingTabs.SettingTabItem
5759 TabName = tab.TabName,
5760 TabType = tab.TabType,
5761 UnreadManage = tab.UnreadManage,
5762 Protected = tab.Protected,
5763 Notify = tab.Notify,
5764 SoundFile = tab.SoundFile,
5769 case FilterTabModel filterTab:
5770 tabSetting.FilterArray = filterTab.FilterArray;
5772 case UserTimelineTabModel userTab:
5773 tabSetting.User = userTab.ScreenName;
5774 tabSetting.UserId = userTab.UserId;
5776 case PublicSearchTabModel searchTab:
5777 tabSetting.SearchWords = searchTab.SearchWords;
5778 tabSetting.SearchLang = searchTab.SearchLang;
5780 case ListTimelineTabModel listTab:
5781 tabSetting.ListInfo = listTab.ListInfo;
5785 tabSettingList.Add(tabSetting);
5788 this.settings.Tabs.Tabs = tabSettingList;
5789 this.settings.SaveTabs();
5792 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5794 static void ShowFormatErrorDialog(IWin32Window owner)
5798 Properties.Resources.OpenURL_InvalidFormat,
5799 Properties.Resources.OpenURL_Caption,
5800 MessageBoxButtons.OK,
5801 MessageBoxIcon.Error
5805 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5806 if (ret != DialogResult.OK)
5809 var match = Twitter.StatusUrlRegex.Match(inputText);
5812 ShowFormatErrorDialog(this);
5818 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5819 await this.OpenRelatedTab(statusId);
5821 catch (OverflowException)
5823 ShowFormatErrorDialog(this);
5825 catch (TabException ex)
5827 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5831 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5833 var tab = this.CurrentTab;
5835 var rslt = MessageBox.Show(
5836 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5837 Properties.Resources.SaveLogMenuItem_ClickText2,
5838 MessageBoxButtons.YesNoCancel,
5839 MessageBoxIcon.Question);
5840 if (rslt == DialogResult.Cancel) return;
5842 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5843 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5844 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5845 this.SaveFileDialog1.FilterIndex = 0;
5846 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5847 this.SaveFileDialog1.RestoreDirectory = true;
5849 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5851 if (!this.SaveFileDialog1.ValidateNames) return;
5852 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5853 if (rslt == DialogResult.Yes)
5856 for (var idx = 0; idx < tab.AllCount; idx++)
5858 var post = tab[idx];
5861 protect = "Protect";
5862 sw.WriteLine(post.Nickname + "\t" +
5863 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5864 post.CreatedAt.ToLocalTimeString() + "\t" +
5865 post.ScreenName + "\t" +
5866 post.StatusId.Id + "\t" +
5867 post.ImageUrl + "\t" +
5868 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5874 foreach (var post in this.CurrentTab.SelectedPosts)
5878 protect = "Protect";
5879 sw.WriteLine(post.Nickname + "\t" +
5880 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5881 post.CreatedAt.ToLocalTimeString() + "\t" +
5882 post.ScreenName + "\t" +
5883 post.StatusId.Id + "\t" +
5884 post.ImageUrl + "\t" +
5885 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5890 this.TopMost = this.settings.Common.AlwaysTop;
5893 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5897 using (var inputName = new InputTabName())
5899 inputName.TabName = origTabName;
5900 inputName.ShowDialog();
5901 if (inputName.DialogResult == DialogResult.Cancel) return false;
5902 newTabName = inputName.TabName;
5904 this.TopMost = this.settings.Common.AlwaysTop;
5905 if (!MyCommon.IsNullOrEmpty(newTabName))
5908 if (this.statuses.ContainsTab(newTabName))
5910 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5911 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5915 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5916 var tabPage = this.ListTab.TabPages[tabIndex];
5919 if (tabPage != null)
5920 tabPage.Text = newTabName;
5922 this.statuses.RenameTab(origTabName, newTabName);
5924 var state = this.listViewState[origTabName];
5925 this.listViewState.Remove(origTabName);
5926 this.listViewState[newTabName] = state;
5928 this.SaveConfigsCommon();
5929 this.SaveConfigsTabs();
5930 this.rclickTabName = newTabName;
5939 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5941 if (e.Button == MouseButtons.Middle)
5943 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5945 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5947 this.RemoveSpecifiedTab(tab.TabName, true);
5948 this.SaveConfigsTabs();
5955 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5956 => this.TabRename(this.CurrentTabName, out _);
5958 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5960 if (this.settings.Common.TabMouseLock) return;
5961 if (e.Button == MouseButtons.Left)
5963 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5965 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5967 this.tabDrag = true;
5968 this.tabMouseDownPoint = e.Location;
5975 this.tabDrag = false;
5979 private void ListTab_DragEnter(object sender, DragEventArgs e)
5981 if (e.Data.GetDataPresent(typeof(TabPage)))
5982 e.Effect = DragDropEffects.Move;
5984 e.Effect = DragDropEffects.None;
5987 private void ListTab_DragDrop(object sender, DragEventArgs e)
5989 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5991 this.tabDrag = false;
5994 var cpos = new Point(e.X, e.Y);
5995 var spos = this.ListTab.PointToClient(cpos);
5996 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5998 var rect = this.ListTab.GetTabRect(index);
5999 if (rect.Contains(spos))
6002 if (spos.X <= (rect.Left + rect.Right) / 2)
6011 // タブのないところにドロップ->最後尾へ移動
6012 if (MyCommon.IsNullOrEmpty(tn))
6014 var lastTab = this.statuses.Tabs.Last();
6015 tn = lastTab.TabName;
6019 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6020 if (tp.Text == tn) return;
6022 this.ReOrderTab(tp.Text, tn, bef);
6025 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6027 var baseIndex = this.GetTabPageIndex(baseTabText);
6028 if (baseIndex == -1)
6031 var targetIndex = this.GetTabPageIndex(targetTabText);
6032 if (targetIndex == -1)
6035 using (ControlTransaction.Layout(this.ListTab))
6037 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6038 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6039 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6040 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6042 var tab = this.statuses.Tabs[targetIndex];
6043 var tabPage = this.ListTab.TabPages[targetIndex];
6045 this.ListTab.TabPages.Remove(tabPage);
6047 if (targetIndex < baseIndex)
6050 if (!isBeforeBaseTab)
6053 this.statuses.MoveTab(baseIndex, tab);
6055 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6058 this.SaveConfigsTabs();
6061 private void MakeDirectMessageText()
6063 var selectedPosts = this.CurrentTab.SelectedPosts;
6064 if (selectedPosts.Length > 1)
6067 var post = selectedPosts.Single();
6068 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6070 this.inReplyTo = null;
6071 this.StatusText.Text = text;
6072 this.StatusText.SelectionStart = text.Length;
6073 this.StatusText.Focus();
6076 private void MakeReplyText(bool atAll = false)
6078 var selectedPosts = this.CurrentTab.SelectedPosts;
6079 if (selectedPosts.Any(x => x.IsDm))
6081 this.MakeDirectMessageText();
6085 if (selectedPosts.Length == 1)
6087 var post = selectedPosts.Single();
6088 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6089 var inReplyToScreenName = post.ScreenName;
6090 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6094 this.inReplyTo = null;
6097 var selfScreenName = this.tw.Username;
6098 var targetScreenNames = new List<string>();
6099 foreach (var post in selectedPosts)
6101 if (post.ScreenName != selfScreenName)
6102 targetScreenNames.Add(post.ScreenName);
6106 foreach (var (_, screenName) in post.ReplyToList)
6108 if (screenName != selfScreenName)
6109 targetScreenNames.Add(screenName);
6114 if (this.inReplyTo != null)
6116 var (_, screenName) = this.inReplyTo.Value;
6117 if (screenName == selfScreenName)
6118 targetScreenNames.Insert(0, screenName);
6121 var text = this.StatusText.Text;
6122 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6124 var atText = $"@{screenName} ";
6125 if (!text.Contains(atText))
6126 text = atText + text;
6129 this.StatusText.Text = text;
6130 this.StatusText.SelectionStart = text.Length;
6131 this.StatusText.Focus();
6134 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6135 => this.tabDrag = false;
6137 private int iconCnt = 0;
6138 private int blinkCnt = 0;
6139 private bool blink = false;
6141 private void RefreshTasktrayIcon()
6143 void EnableTasktrayAnimation()
6144 => this.TimerRefreshIcon.Enabled = true;
6146 void DisableTasktrayAnimation()
6147 => this.TimerRefreshIcon.Enabled = false;
6149 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6153 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6156 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6157 this.myStatusError = false;
6158 EnableTasktrayAnimation();
6162 var replyIconType = this.settings.Common.ReplyIconState;
6164 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6166 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6167 if (replyTab != null && replyTab.UnreadCount > 0)
6171 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6174 if (this.blinkCnt > 10)
6177 if (this.blinkCnt == 0)
6178 this.blink = !this.blink;
6180 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6181 EnableTasktrayAnimation();
6185 DisableTasktrayAnimation();
6191 // 優先度:リプライ→エラー→オフライン→アイドル
6192 // エラーは更新アイコンでクリアされる
6193 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6194 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6195 else if (this.myStatusError)
6196 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6197 else if (this.myStatusOnline)
6198 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6200 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6203 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6204 => this.RefreshTasktrayIcon(); // 200ms
6206 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6208 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6209 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6210 this.rclickTabName = this.CurrentTabName;
6212 if (this.statuses == null) return;
6213 if (this.statuses.Tabs == null) return;
6215 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6218 this.NotifyDispMenuItem.Checked = tb.Notify;
6219 this.NotifyTbMenuItem.Checked = tb.Notify;
6221 this.soundfileListup = true;
6222 this.SoundFileComboBox.Items.Clear();
6223 this.SoundFileTbComboBox.Items.Clear();
6224 this.SoundFileComboBox.Items.Add("");
6225 this.SoundFileTbComboBox.Items.Add("");
6226 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6227 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6229 oDir = oDir.GetDirectories("Sounds")[0];
6231 foreach (var oFile in oDir.GetFiles("*.wav"))
6233 this.SoundFileComboBox.Items.Add(oFile.Name);
6234 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6236 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6237 if (idx == -1) idx = 0;
6238 this.SoundFileComboBox.SelectedIndex = idx;
6239 this.SoundFileTbComboBox.SelectedIndex = idx;
6240 this.soundfileListup = false;
6241 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6242 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6244 this.TabMenuControl(this.rclickTabName);
6247 private void TabMenuControl(string tabName)
6249 var tabInfo = this.statuses.GetTabByName(tabName)!;
6251 this.FilterEditMenuItem.Enabled = true;
6252 this.EditRuleTbMenuItem.Enabled = true;
6254 if (tabInfo.IsDefaultTabType)
6256 this.ProtectTabMenuItem.Enabled = false;
6257 this.ProtectTbMenuItem.Enabled = false;
6261 this.ProtectTabMenuItem.Enabled = true;
6262 this.ProtectTbMenuItem.Enabled = true;
6265 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6267 this.ProtectTabMenuItem.Checked = true;
6268 this.ProtectTbMenuItem.Checked = true;
6269 this.DeleteTabMenuItem.Enabled = false;
6270 this.DeleteTbMenuItem.Enabled = false;
6274 this.ProtectTabMenuItem.Checked = false;
6275 this.ProtectTbMenuItem.Checked = false;
6276 this.DeleteTabMenuItem.Enabled = true;
6277 this.DeleteTbMenuItem.Enabled = true;
6281 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6283 var checkState = ((ToolStripMenuItem)sender).Checked;
6286 this.ProtectTbMenuItem.Checked = checkState;
6287 this.ProtectTabMenuItem.Checked = checkState;
6290 this.DeleteTabMenuItem.Enabled = !checkState;
6291 this.DeleteTbMenuItem.Enabled = !checkState;
6293 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6294 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6296 this.SaveConfigsTabs();
6299 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6301 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6302 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6304 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6305 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6307 this.SaveConfigsTabs();
6310 public void ChangeTabUnreadManage(string tabName, bool isManage)
6312 var idx = this.GetTabPageIndex(tabName);
6316 var tab = this.statuses.Tabs[tabName];
6317 tab.UnreadManage = isManage;
6319 if (this.settings.Common.TabIconDisp)
6321 var tabPage = this.ListTab.TabPages[idx];
6322 if (tab.UnreadCount > 0)
6323 tabPage.ImageIndex = 0;
6325 tabPage.ImageIndex = -1;
6328 if (this.CurrentTabName == tabName)
6330 this.listCache?.PurgeCache();
6331 this.CurrentListView.Refresh();
6334 this.SetMainWindowTitle();
6335 this.SetStatusLabelUrl();
6336 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6339 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6341 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6342 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6344 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6346 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6348 this.SaveConfigsTabs();
6351 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6353 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6355 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6357 this.SaveConfigsTabs();
6360 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6362 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6363 this.rclickTabName = this.CurrentTabName;
6365 this.RemoveSpecifiedTab(this.rclickTabName, true);
6366 this.SaveConfigsTabs();
6369 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6371 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6373 using (var fltDialog = new FilterDialog())
6375 fltDialog.Owner = this;
6376 fltDialog.SetCurrent(this.rclickTabName);
6377 fltDialog.ShowDialog(this);
6379 this.TopMost = this.settings.Common.AlwaysTop;
6381 this.ApplyPostFilters();
6382 this.SaveConfigsTabs();
6385 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6387 string? tabName = null;
6388 MyCommon.TabUsageType tabUsage;
6389 using (var inputName = new InputTabName())
6391 inputName.TabName = this.statuses.MakeTabName("MyTab");
6392 inputName.IsShowUsage = true;
6393 inputName.ShowDialog();
6394 if (inputName.DialogResult == DialogResult.Cancel) return;
6395 tabName = inputName.TabName;
6396 tabUsage = inputName.Usage;
6398 this.TopMost = this.settings.Common.AlwaysTop;
6399 if (!MyCommon.IsNullOrEmpty(tabName))
6402 ListElement? list = null;
6403 if (tabUsage == MyCommon.TabUsageType.Lists)
6405 using var listAvail = new ListAvailable();
6406 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6408 if (listAvail.SelectedList == null)
6410 list = listAvail.SelectedList;
6416 case MyCommon.TabUsageType.UserDefined:
6417 tab = new FilterTabModel(tabName);
6419 case MyCommon.TabUsageType.PublicSearch:
6420 tab = new PublicSearchTabModel(tabName);
6422 case MyCommon.TabUsageType.Lists:
6423 tab = new ListTimelineTabModel(tabName, list!);
6429 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6431 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6432 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6437 this.SaveConfigsTabs();
6439 var tabIndex = this.statuses.Tabs.Count - 1;
6441 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6443 this.ListTab.SelectedIndex = tabIndex;
6444 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6446 if (tabUsage == MyCommon.TabUsageType.Lists)
6448 this.ListTab.SelectedIndex = tabIndex;
6449 await this.RefreshTabAsync(this.CurrentTab);
6455 private void TabMenuItem_Click(object sender, EventArgs e)
6458 foreach (var post in this.CurrentTab.SelectedPosts)
6461 if (!this.SelectTab(out var tab))
6464 using (var fltDialog = new FilterDialog())
6466 fltDialog.Owner = this;
6467 fltDialog.SetCurrent(tab.TabName);
6469 if (post.RetweetedBy == null)
6471 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6475 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6477 fltDialog.ShowDialog(this);
6480 this.TopMost = this.settings.Common.AlwaysTop;
6483 this.ApplyPostFilters();
6484 this.SaveConfigsTabs();
6487 protected override bool ProcessDialogKey(Keys keyData)
6489 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6490 if ((keyData & Keys.KeyCode) == Keys.Enter)
6492 if (this.StatusText.Focused)
6494 var newLine = false;
6497 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6499 if (this.StatusText.Multiline)
6501 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6503 if ((keyData & Keys.Control) == Keys.Control) post = true;
6507 if ((keyData & Keys.Control) == Keys.Control) post = true;
6510 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6512 if (this.StatusText.Multiline)
6514 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6516 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6520 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6525 if (this.StatusText.Multiline)
6527 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6529 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6530 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6534 if (((keyData & Keys.Shift) == Keys.Shift) ||
6535 (((keyData & Keys.Control) != Keys.Control) &&
6536 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6542 var pos1 = this.StatusText.SelectionStart;
6543 if (this.StatusText.SelectionLength > 0)
6545 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6547 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6548 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6553 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6559 var tab = this.CurrentTab;
6560 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6562 var tabPage = this.CurrentTabPage;
6563 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6564 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6566 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6573 return base.ProcessDialogKey(keyData);
6576 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6577 => this.MakeReplyText(atAll: true);
6579 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6581 var tab = this.CurrentTab;
6582 var selectedPosts = tab.SelectedPosts;
6585 if (selectedPosts.Length == 0)
6588 var screenNameArray = selectedPosts
6589 .Select(x => x.RetweetedBy ?? x.ScreenName)
6592 this.AddFilterRuleByScreenName(screenNameArray);
6594 if (screenNameArray.Length != 0)
6596 var atids = new List<string>();
6597 foreach (var screenName in screenNameArray)
6599 atids.Add("@" + screenName);
6601 var cnt = this.AtIdSupl.ItemCount;
6602 this.AtIdSupl.AddRangeItem(atids.ToArray());
6603 if (this.AtIdSupl.ItemCount != cnt)
6604 this.MarkSettingAtIdModified();
6608 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6610 var tab = this.CurrentTab;
6611 var selectedPosts = tab.SelectedPosts;
6613 if (selectedPosts.Length == 0)
6616 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6618 this.AddFilterRuleBySource(sourceArray);
6621 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6624 if (!this.SelectTab(out var tab)) return;
6628 if (tab.TabType != MyCommon.TabUsageType.Mute)
6630 this.MoveOrCopy(out mv, out mk);
6634 // ミュートタブでは常に MoveMatches を true にする
6639 foreach (var screenName in screenNameArray)
6641 tab.AddFilter(new PostFilterRule
6643 FilterName = screenName,
6644 UseNameField = true,
6648 FilterByUrl = false,
6652 this.ApplyPostFilters();
6653 this.SaveConfigsTabs();
6656 public void AddFilterRuleBySource(params string[] sourceArray)
6658 // タブ選択ダイアログを表示(or追加)
6659 if (!this.SelectTab(out var filterTab))
6664 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6666 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6667 this.MoveOrCopy(out mv, out mk);
6671 // ミュートタブでは常に MoveMatches を true にする
6676 // 振り分けルールに追加するSource
6677 foreach (var source in sourceArray)
6679 filterTab.AddFilter(new PostFilterRule
6681 FilterSource = source,
6685 FilterByUrl = false,
6689 this.ApplyPostFilters();
6690 this.SaveConfigsTabs();
6693 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6700 using (var dialog = new TabsDialog(this.statuses))
6702 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6704 tab = dialog.SelectedTab;
6707 this.CurrentTabPage.Focus();
6712 using (var inputName = new InputTabName())
6714 inputName.TabName = this.statuses.MakeTabName("MyTab");
6715 inputName.ShowDialog();
6716 if (inputName.DialogResult == DialogResult.Cancel) return false;
6717 tabName = inputName.TabName;
6719 this.TopMost = this.settings.Common.AlwaysTop;
6720 if (!MyCommon.IsNullOrEmpty(tabName))
6722 var newTab = new FilterTabModel(tabName);
6723 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6725 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6726 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6745 private void MoveOrCopy(out bool move, out bool mark)
6749 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6750 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6758 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6759 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6770 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6773 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6774 => this.CopyIdUri();
6776 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6778 if (this.StatusText.Focused)
6781 this.StatusText.SelectAll();
6785 // ListView上でのCtrl+A
6786 NativeMethods.SelectAllItems(this.CurrentListView);
6790 private void MoveMiddle()
6796 var listView = this.CurrentListView;
6797 if (listView.SelectedIndices.Count == 0) return;
6799 var idx = listView.SelectedIndices[0];
6801 item = listView.GetItemAt(0, 25);
6807 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6809 idx2 = listView.VirtualListSize - 1;
6813 idx -= Math.Abs(idx1 - idx2) / 2;
6814 if (idx < 0) idx = 0;
6816 listView.EnsureVisible(listView.VirtualListSize - 1);
6817 listView.EnsureVisible(idx);
6820 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6822 var linkElements = this.tweetDetailsView.GetLinkElements();
6824 if (linkElements.Length == 0)
6827 var links = new List<OpenUrlItem>(linkElements.Length);
6829 foreach (var linkElm in linkElements)
6831 var displayUrl = linkElm.GetAttribute("title");
6832 var href = linkElm.GetAttribute("href");
6833 var linkedText = linkElm.InnerText;
6835 if (MyCommon.IsNullOrEmpty(displayUrl))
6838 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6842 bool isReverseSettings;
6844 if (links.Count == 1)
6846 // ツイートに含まれる URL が 1 つのみの場合
6847 // => OpenURL ダイアログを表示せずにリンクを開く
6848 selectedUrl = links[0].Href;
6850 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6851 isReverseSettings = false;
6855 // ツイートに含まれる URL が複数ある場合
6856 // => OpenURL を表示しユーザーが選択したリンクを開く
6857 this.urlDialog.ClearUrl();
6859 foreach (var link in links)
6860 this.urlDialog.AddUrl(link);
6862 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6865 this.TopMost = this.settings.Common.AlwaysTop;
6867 selectedUrl = this.urlDialog.SelectedUrl;
6869 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6870 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6873 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6876 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6878 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6879 this.ClearTab(this.rclickTabName, true);
6882 private void ClearTab(string tabName, bool showWarning)
6886 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6887 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6893 this.statuses.ClearTabIds(tabName);
6894 if (this.CurrentTabName == tabName)
6896 this.CurrentTab.ClearAnchor();
6897 this.listCache?.PurgeCache();
6898 this.listCache?.UpdateListSize();
6901 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6902 var tabPage = this.ListTab.TabPages[tabIndex];
6903 tabPage.ImageIndex = -1;
6905 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6907 this.SetMainWindowTitle();
6908 this.SetStatusLabelUrl();
6911 private static long followers = 0;
6913 private void SetMainWindowTitle()
6915 // メインウインドウタイトルの書き換え
6916 var ttl = new StringBuilder(256);
6919 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6920 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6921 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6922 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6924 foreach (var tab in this.statuses.Tabs)
6926 ur += tab.UnreadCount;
6931 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6932 ttl.Append(ApplicationSettings.ApplicationName);
6934 switch (this.settings.Common.DispLatestPost)
6936 case MyCommon.DispTitleEnum.Ver:
6937 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6939 case MyCommon.DispTitleEnum.Post:
6940 if (this.history != null && this.history.Count > 1)
6941 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6943 case MyCommon.DispTitleEnum.UnreadRepCount:
6944 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6946 case MyCommon.DispTitleEnum.UnreadAllCount:
6947 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6949 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6950 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6952 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6953 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6955 case MyCommon.DispTitleEnum.OwnStatus:
6956 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6957 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6963 this.Text = ttl.ToString();
6965 catch (AccessViolationException)
6967 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6971 private string GetStatusLabelText()
6974 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6975 if (this.statuses == null) return "";
6976 var tbRep = this.statuses.MentionTab;
6977 var tbDm = this.statuses.DirectMessageTab;
6978 if (tbRep == null || tbDm == null) return "";
6979 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6984 var slbl = new StringBuilder(256);
6987 foreach (var tab in this.statuses.Tabs)
6989 ur += tab.UnreadCount;
6991 if (tab.TabName == this.CurrentTabName)
6993 tur = tab.UnreadCount;
7003 this.unreadCounter = ur;
7004 this.unreadAtCounter = urat;
7006 var homeTab = this.statuses.HomeTab;
7008 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7009 if (this.settings.Common.TimelinePeriod == 0)
7011 slbl.Append(Properties.Resources.SetStatusLabelText2);
7015 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7017 return slbl.ToString();
7020 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7024 if (this.InvokeRequired && !this.IsDisposed)
7026 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7030 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7031 this.SetApiStatusLabel(endpointName);
7034 catch (ObjectDisposedException)
7038 catch (InvalidOperationException)
7044 private void SetApiStatusLabel(string? endpointName = null)
7046 var tabType = this.CurrentTab.TabType;
7048 if (endpointName == null)
7050 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
7053 endpointName = tabType switch
7055 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
7056 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7057 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7058 MyCommon.TabUsageType.Favorites => "/favorites/list",
7059 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7060 MyCommon.TabUsageType.UserTimeline =>
7061 authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7062 MyCommon.TabUsageType.Lists =>
7063 authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7064 MyCommon.TabUsageType.PublicSearch =>
7065 authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7066 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7069 this.toolStripApiGauge.ApiEndpoint = endpointName;
7073 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7074 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7078 private void SetStatusLabelUrl()
7079 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7081 public void SetStatusLabel(string text)
7082 => this.StatusLabel.Text = text;
7084 private void SetNotifyIconText()
7086 var ur = new StringBuilder(64);
7088 // タスクトレイアイコンのツールチップテキスト書き換え
7090 ur.Remove(0, ur.Length);
7091 if (this.settings.Common.DispUsername)
7093 ur.Append(this.tw.Username);
7096 ur.Append(ApplicationSettings.ApplicationName);
7098 ur.Append("(Debug Build)");
7100 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7103 ur.Append(this.unreadCounter);
7105 ur.Append(this.unreadAtCounter);
7108 this.NotifyIcon1.Text = ur.ToString();
7111 internal void CheckReplyTo(string statusText)
7115 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7117 foreach (Match hm in m)
7119 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7121 hstr += "#" + hm.Result("$3") + " ";
7122 this.HashSupl.AddItem("#" + hm.Result("$3"));
7125 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7127 hstr += this.HashMgr.UseHash;
7129 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7131 // 本当にリプライ先指定すべきかどうかの判定
7132 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7134 if (this.settings.Common.UseAtIdSupplement)
7136 var bCnt = this.AtIdSupl.ItemCount;
7137 foreach (Match mid in m)
7139 this.AtIdSupl.AddItem(mid.Result("${id}"));
7141 if (bCnt != this.AtIdSupl.ItemCount)
7142 this.MarkSettingAtIdModified();
7145 // リプライ先ステータスIDの指定がない場合は指定しない
7146 if (this.inReplyTo == null)
7150 // 次の条件を満たす場合に in_reply_to_status_id 指定
7151 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7152 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7153 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7157 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7158 if (statusText.StartsWith("@", StringComparison.Ordinal))
7160 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7164 foreach (Match mid in m)
7166 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7171 this.inReplyTo = null;
7174 private void TweenMain_Resize(object sender, EventArgs e)
7176 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7178 this.Visible = false;
7180 if (this.WindowState != FormWindowState.Minimized)
7182 this.formWindowState = this.WindowState;
7186 private void ApplyLayoutFromSettings()
7188 // 現在の DPI と設定保存時の DPI との比を取得する
7189 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7191 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7194 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7195 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7196 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7198 this.SplitContainer1.SplitterDistance = splitterDistance;
7202 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7203 if (this.StatusText.Multiline)
7205 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7206 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7207 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7209 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7211 this.StatusText.Height = statusTextHeight;
7215 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7217 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7221 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7222 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7224 this.SplitContainer3.SplitterDistance = previewDistance;
7227 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7228 this.SplitContainer3.Panel2Collapsed = true;
7229 this.initialLayout = false;
7232 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7234 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7235 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7236 if (this.PlaySoundMenuItem.Checked)
7238 this.settings.Common.PlaySound = true;
7242 this.settings.Common.PlaySound = false;
7244 this.MarkSettingCommonModified();
7247 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7249 if (this.initialLayout)
7252 int splitterDistance;
7253 switch (this.WindowState)
7255 case FormWindowState.Normal:
7256 splitterDistance = this.SplitContainer1.SplitterDistance;
7258 case FormWindowState.Maximized:
7259 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7260 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7261 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7262 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7268 this.mySpDis = splitterDistance;
7269 this.MarkSettingLocalModified();
7272 private async Task DoRepliedStatusOpen()
7274 var currentPost = this.CurrentPost;
7275 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7277 if (MyCommon.IsKeyDown(Keys.Shift))
7279 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7282 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7284 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7288 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7290 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7291 repPost = tb.Posts[currentPost.InReplyToStatusId];
7292 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7295 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7300 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7301 => await this.DoRepliedStatusOpen();
7303 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7305 if (this.initialLayout)
7306 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7308 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7309 if (multiline != this.StatusText.Multiline)
7311 this.StatusText.Multiline = multiline;
7312 this.settings.Local.StatusMultiline = multiline;
7313 this.MarkSettingLocalModified();
7317 private void StatusText_MultilineChanged(object sender, EventArgs e)
7319 if (this.StatusText.Multiline)
7320 this.StatusText.ScrollBars = ScrollBars.Vertical;
7322 this.StatusText.ScrollBars = ScrollBars.None;
7324 if (!this.initialLayout)
7325 this.MarkSettingLocalModified();
7328 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7331 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7332 this.StatusText.Multiline = menuItemChecked;
7333 this.settings.Local.StatusMultiline = menuItemChecked;
7334 if (menuItemChecked)
7336 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7337 this.SplitContainer2.SplitterDistance = 0;
7339 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7343 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7345 this.MarkSettingLocalModified();
7348 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7350 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7352 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7353 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7354 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7356 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7361 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7362 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7363 // Appendix A. Collected ABNF for URI
7364 // http://www.ietf.org/rfc/rfc3986.txt
7366 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7369 if (this.StatusText.SelectionLength > 0)
7371 var tmp = this.StatusText.SelectedText;
7372 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7373 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7375 // 文字列が選択されている場合はその文字列について処理
7377 // nico.ms使用、nicovideoにマッチしたら変換
7378 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7380 result = Nicoms.Shorten(tmp);
7382 else if (converterType != MyCommon.UrlConverter.Nicoms)
7387 var srcUri = new Uri(tmp);
7388 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7389 result = resultUri.AbsoluteUri;
7391 catch (WebApiException e)
7393 this.StatusLabel.Text = converterType + ":" + e.Message;
7396 catch (UriFormatException e)
7398 this.StatusLabel.Text = converterType + ":" + e.Message;
7407 if (!MyCommon.IsNullOrEmpty(result))
7409 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7410 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7411 if (origUrlIndex == -1)
7414 this.StatusText.Select(origUrlIndex, tmp.Length);
7415 this.StatusText.SelectedText = result;
7418 var undo = new UrlUndo
7424 if (this.urlUndoBuffer == null)
7426 this.urlUndoBuffer = new List<UrlUndo>();
7427 this.UrlUndoToolStripMenuItem.Enabled = true;
7430 this.urlUndoBuffer.Add(undo);
7436 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7437 @"(?<url>(?<protocol>https?://)" +
7438 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7439 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7440 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7441 // 正規表現にマッチしたURL文字列をtinyurl化
7442 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7444 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7446 var tmp = mt.Result("${url}");
7447 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7448 tmp = "http://" + tmp;
7451 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7453 // nico.ms使用、nicovideoにマッチしたら変換
7454 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7456 result = Nicoms.Shorten(tmp);
7458 else if (converterType != MyCommon.UrlConverter.Nicoms)
7463 var srcUri = new Uri(tmp);
7464 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7465 result = resultUri.AbsoluteUri;
7467 catch (HttpRequestException e)
7469 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7470 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7471 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7473 this.StatusLabel.Text = converterType + ":" + message;
7476 catch (WebApiException e)
7478 this.StatusLabel.Text = converterType + ":" + e.Message;
7481 catch (UriFormatException e)
7483 this.StatusLabel.Text = converterType + ":" + e.Message;
7492 if (!MyCommon.IsNullOrEmpty(result))
7494 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7495 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7496 if (origUrlIndex == -1)
7499 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7500 this.StatusText.SelectedText = result;
7502 var undo = new UrlUndo
7504 Before = mt.Result("${url}"),
7508 if (this.urlUndoBuffer == null)
7510 this.urlUndoBuffer = new List<UrlUndo>();
7511 this.UrlUndoToolStripMenuItem.Enabled = true;
7514 this.urlUndoBuffer.Add(undo);
7522 private void DoUrlUndo()
7524 if (this.urlUndoBuffer != null)
7526 var tmp = this.StatusText.Text;
7527 foreach (var data in this.urlUndoBuffer)
7529 tmp = tmp.Replace(data.After, data.Before);
7531 this.StatusText.Text = tmp;
7532 this.urlUndoBuffer = null;
7533 this.UrlUndoToolStripMenuItem.Enabled = false;
7534 this.StatusText.SelectionStart = 0;
7535 this.StatusText.SelectionLength = 0;
7539 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7540 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7542 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7543 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7545 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7546 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7548 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7550 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7552 var rnd = new Random();
7554 MyCommon.UrlConverter svc;
7555 // 前回使用した短縮URLサービス以外を選択する
7558 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7560 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7561 await this.UrlConvertAsync(svc);
7565 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7566 => this.DoUrlUndo();
7568 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7570 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7571 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7572 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7573 this.MarkSettingCommonModified();
7576 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7578 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7579 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7580 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7581 this.MarkSettingCommonModified();
7584 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7586 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7587 this.MenuStrip1.Tag = new object();
7588 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7591 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7593 var currentTabPage = this.CurrentTabPage;
7594 if (this.Tag != null) // 設定された戻り先へ遷移
7596 if (this.Tag == currentTabPage)
7597 ((Control)currentTabPage.Tag).Select();
7599 ((Control)this.Tag).Select();
7601 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7603 this.Tag = currentTabPage.Tag;
7604 ((Control)this.Tag).Select();
7606 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7607 this.MenuStrip1.Tag = null;
7610 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7612 if (this.Use2ColumnsMode)
7618 var lst = (DetailsListView)sender;
7619 var columnsCount = lst.Columns.Count;
7621 var darr = new int[columnsCount];
7622 for (var i = 0; i < columnsCount; i++)
7623 darr[lst.Columns[i].DisplayIndex] = i;
7625 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7627 for (var i = 0; i < columnsCount; i++)
7628 this.settings.Local.ColumnsOrder[darr[i]] = i;
7630 this.MarkSettingLocalModified();
7631 this.isColumnChanged = true;
7634 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7636 var lst = (DetailsListView)sender;
7637 if (this.settings.Local == null) return;
7639 var modified = false;
7640 if (this.Use2ColumnsMode)
7642 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7644 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7647 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7649 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7655 var columnsCount = lst.Columns.Count;
7656 for (var i = 0; i < columnsCount; i++)
7658 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7661 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7667 this.MarkSettingLocalModified();
7668 this.isColumnChanged = true;
7672 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7674 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7675 this.MarkSettingLocalModified();
7678 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7680 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7682 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7684 this.SelectMedia_DragDrop(e);
7687 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7689 var (url, title) = GetUrlFromDataObject(e.Data);
7695 appendText = title + " " + url;
7697 if (this.StatusText.TextLength == 0)
7698 this.StatusText.Text = appendText;
7700 this.StatusText.Text += " " + appendText;
7702 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7704 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7706 this.StatusText.Text += text;
7708 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7710 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7711 if (data != null) this.StatusText.Text += data;
7716 /// IDataObject から URL とタイトルの対を取得します
7719 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7721 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7722 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7723 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7725 if (data.GetDataPresent("text/x-moz-url"))
7727 // Firefox, Google Chrome で利用可能
7728 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7730 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7731 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7732 if (lines.Length < 2)
7733 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7735 return (lines[0], lines[1]);
7737 else if (data.GetDataPresent("IESiteModeToUrl"))
7739 // Internet Exproler 用
7740 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7742 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7743 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7744 if (lines.Length < 2)
7745 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7747 return (lines[0], lines[1]);
7749 else if (data.GetDataPresent("UniformResourceLocatorW"))
7753 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7754 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7758 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7761 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7763 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7765 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7767 this.SelectMedia_DragEnter(e);
7771 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7773 e.Effect = DragDropEffects.Copy;
7776 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7778 e.Effect = DragDropEffects.Copy;
7781 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7783 e.Effect = DragDropEffects.Copy;
7787 e.Effect = DragDropEffects.None;
7790 private void TweenMain_DragOver(object sender, DragEventArgs e)
7794 public bool IsNetworkAvailable()
7796 var nw = MyCommon.IsNetworkAvailable();
7797 this.myStatusOnline = nw;
7801 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7803 var uriStr = uri.AbsoluteUri;
7805 // OpenTween 内部で使用する URL
7806 if (uri.Authority == "opentween")
7808 await this.OpenInternalUriAsync(uri);
7812 // ハッシュタグを含む Twitter 検索
7813 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7816 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7817 var pos = unescapedQuery.IndexOf('#');
7818 if (pos == -1) return;
7820 var hash = unescapedQuery.Substring(pos);
7821 this.HashSupl.AddItem(hash);
7822 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7823 this.AddNewTabForSearch(hash);
7828 // フラグが立っている場合は設定と逆の動作をする
7829 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7830 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7832 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7833 if (userUriMatch.Success)
7835 var screenName = userUriMatch.Groups["ScreenName"].Value;
7836 if (this.IsTwitterId(screenName))
7838 await this.AddNewTabForUserTimeline(screenName);
7845 await MyCommon.OpenInBrowserAsync(this, uriStr);
7849 /// OpenTween 内部の機能を呼び出すための URL を開きます
7851 private async Task OpenInternalUriAsync(Uri uri)
7853 // ツイートを開く (//opentween/status/:status_id)
7854 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7857 var statusId = new TwitterStatusId(match.Groups[1].Value);
7858 await this.OpenRelatedTab(statusId);
7863 private void ListTabSelect(TabPage tabPage)
7865 this.SetListProperty();
7867 var previousTabName = this.CurrentTabName;
7868 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7869 previousListViewState.Save(this.ListLockMenuItem.Checked);
7871 this.listCache?.PurgeCache();
7873 this.statuses.SelectTab(tabPage.Text);
7875 this.InitializeTimelineListView();
7877 var tab = this.CurrentTab;
7880 var listView = this.CurrentListView;
7882 var currentListViewState = this.listViewState[tab.TabName];
7883 currentListViewState.Restore(forceScroll: true);
7885 if (this.Use2ColumnsMode)
7887 listView.Columns[1].Text = this.columnText[2];
7891 for (var i = 0; i < listView.Columns.Count; i++)
7893 listView.Columns[i].Text = this.columnText[i];
7898 private void InitializeTimelineListView()
7900 var listView = this.CurrentListView;
7901 var tab = this.CurrentTab;
7903 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7904 (this.listCache, var oldCache) = (newCache, this.listCache);
7905 oldCache?.Dispose();
7907 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7908 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7909 oldDrawer?.Dispose();
7911 newDrawer.IconSize = this.settings.Common.IconSize;
7912 newDrawer.UpdateItemHeight();
7915 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7916 => this.ListTabSelect(e.TabPage);
7918 private void SelectListItem(DetailsListView lView, int index)
7921 var bnd = new Rectangle();
7923 var item = lView.FocusedItem;
7932 lView.SelectedIndices.Clear();
7934 while (lView.SelectedIndices.Count > 0);
7935 item = lView.Items[index];
7936 item.Selected = true;
7937 item.Focused = true;
7939 if (flg) lView.Invalidate(bnd);
7942 private async void TweenMain_Shown(object sender, EventArgs e)
7944 this.NotifyIcon1.Visible = true;
7947 if (this.settings.IsFirstRun)
7949 // 初回起動時だけ右下のメニューを目立たせる
7950 this.HashStripSplitButton.ShowDropDown();
7953 if (this.IsNetworkAvailable())
7955 var loadTasks = new TaskCollection();
7959 this.RefreshMuteUserIdsAsync,
7960 this.RefreshBlockIdsAsync,
7961 this.RefreshNoRetweetIdsAsync,
7962 this.RefreshTwitterConfigurationAsync,
7963 this.RefreshTabAsync<HomeTabModel>,
7964 this.RefreshTabAsync<MentionsTabModel>,
7965 this.RefreshTabAsync<DirectMessagesTabModel>,
7966 this.RefreshTabAsync<PublicSearchTabModel>,
7967 this.RefreshTabAsync<UserTimelineTabModel>,
7968 this.RefreshTabAsync<ListTimelineTabModel>,
7971 if (this.settings.Common.StartupFollowers)
7972 loadTasks.Add(this.RefreshFollowerIdsAsync);
7974 if (this.settings.Common.GetFav)
7975 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7977 var allTasks = loadTasks.RunAll();
7982 var timeout = Task.Delay(5000);
7983 if (await Task.WhenAny(allTasks, timeout) != timeout)
7987 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7989 if (MyCommon.EndingFlag)
7993 if (MyCommon.EndingFlag) return;
7995 if (ApplicationSettings.VersionInfoUrl != null)
7997 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7998 if (this.settings.Common.StartupVersion)
7999 await this.CheckNewVersion(true);
8003 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8004 this.VerUpMenuItem.Enabled = false;
8005 this.VerUpMenuItem.Available = false;
8006 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8009 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8010 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8012 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8013 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8017 var reloadTasks = new TaskCollection();
8019 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8020 reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
8022 if (!this.tw.GetNoRetweetSuccess)
8023 reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
8025 if (this.tw.Configuration.PhotoSizeLimit == 0)
8026 reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
8028 await reloadTasks.RunAll();
8031 this.initial = false;
8034 private void StartTimers()
8036 if (!this.StopRefreshAllMenuItem.Checked)
8037 this.timelineScheduler.Enabled = true;
8039 this.selectionDebouncer.Enabled = true;
8040 this.saveConfigDebouncer.Enabled = true;
8041 this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
8044 private async Task DoGetFollowersMenu()
8046 await this.RefreshFollowerIdsAsync();
8047 this.DispSelectedPost(true);
8050 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8051 => await this.DoGetFollowersMenu();
8053 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8054 => this.DoReTweetUnofficial();
8056 private async Task DoReTweetOfficial(bool isConfirm)
8059 if (this.ExistCurrentPost)
8061 var selectedPosts = this.CurrentTab.SelectedPosts;
8063 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8065 if (selectedPosts.Any(x => x.IsProtect))
8066 MessageBox.Show("Protected.");
8068 this.doFavRetweetFlags = false;
8072 if (selectedPosts.Length > 15)
8074 MessageBox.Show(Properties.Resources.RetweetLimitText);
8075 this.doFavRetweetFlags = false;
8078 else if (selectedPosts.Length > 1)
8080 var questionText = Properties.Resources.RetweetQuestion2;
8081 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8082 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8084 case DialogResult.Cancel:
8085 case DialogResult.No:
8086 this.doFavRetweetFlags = false;
8092 if (!this.settings.Common.RetweetNoConfirm)
8094 var questiontext = Properties.Resources.RetweetQuestion1;
8095 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8096 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8098 this.doFavRetweetFlags = false;
8104 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8106 await this.RetweetAsync(statusIds);
8110 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8111 => await this.DoReTweetOfficial(true);
8113 private async Task FavoritesRetweetOfficial()
8115 if (!this.ExistCurrentPost) return;
8116 this.doFavRetweetFlags = true;
8118 var tasks = new TaskCollection();
8119 tasks.Add(() => this.DoReTweetOfficial(true));
8121 if (this.doFavRetweetFlags)
8123 this.doFavRetweetFlags = false;
8124 tasks.Add(() => this.FavoriteChange(true, false));
8127 await tasks.RunAll();
8130 private async Task FavoritesRetweetUnofficial()
8132 var post = this.CurrentPost;
8133 if (this.ExistCurrentPost && post != null && !post.IsDm)
8135 this.doFavRetweetFlags = true;
8136 var favoriteTask = this.FavoriteChange(true);
8137 if (!post.IsProtect && this.doFavRetweetFlags)
8139 this.doFavRetweetFlags = false;
8140 this.DoReTweetUnofficial();
8148 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8150 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8151 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8152 /// <returns>復元されたツイート本文</returns>
8153 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8155 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8158 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8160 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8162 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8164 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8168 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8170 statusHtml = statusHtml.Replace("<br>", " ");
8172 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8173 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8174 statusHtml = statusHtml.Replace(" ", " ");
8176 return WebUtility.HtmlDecode(statusHtml);
8179 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8181 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8183 if (this.CurrentPost != null)
8184 this.DispSelectedPost(true);
8187 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8189 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8190 this.DebugModeToolStripMenuItem.Visible = true;
8192 this.DebugModeToolStripMenuItem.Visible = false;
8195 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8196 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8198 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8199 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8201 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8202 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8204 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8206 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8207 this.MarkSettingCommonModified();
8210 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8212 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8213 this.MarkSettingCommonModified();
8216 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8218 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8219 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8220 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8221 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8222 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8223 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8226 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8228 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8229 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8230 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8231 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8232 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8233 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8236 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8238 if (this.TraceOutToolStripMenuItem.Checked)
8239 MyCommon.TraceFlag = true;
8241 MyCommon.TraceFlag = false;
8244 private void TweenMain_Deactivate(object sender, EventArgs e)
8245 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8247 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8249 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8251 _ = this.TabRename(this.rclickTabName, out _);
8254 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8255 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8257 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8258 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8260 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8262 TwitterApiStatus? apiStatus;
8264 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8266 var cancellationToken = dialog.EnableCancellation();
8270 var task = this.tw.GetInfoApi();
8271 apiStatus = await dialog.WaitForAsync(this, task);
8273 catch (WebApiException)
8278 if (cancellationToken.IsCancellationRequested)
8281 if (apiStatus == null)
8283 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8288 using var apiDlg = new ApiInfoDialog();
8289 apiDlg.ShowDialog(this);
8292 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8294 var id = this.CurrentPost?.ScreenName ?? "";
8296 await this.FollowCommand(id);
8299 internal async Task FollowCommand(string id)
8301 using (var inputName = new InputTabName())
8303 inputName.FormTitle = "Follow";
8304 inputName.FormDescription = Properties.Resources.FRMessage1;
8305 inputName.TabName = id;
8307 if (inputName.ShowDialog(this) != DialogResult.OK)
8309 if (string.IsNullOrWhiteSpace(inputName.TabName))
8312 id = inputName.TabName.Trim();
8315 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8319 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8320 await dialog.WaitForAsync(this, task);
8322 catch (WebApiException ex)
8324 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8329 MessageBox.Show(Properties.Resources.FRMessage3);
8332 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8334 var id = this.CurrentPost?.ScreenName ?? "";
8336 await this.RemoveCommand(id, false);
8339 internal async Task RemoveCommand(string id, bool skipInput)
8343 using var inputName = new InputTabName();
8344 inputName.FormTitle = "Unfollow";
8345 inputName.FormDescription = Properties.Resources.FRMessage1;
8346 inputName.TabName = id;
8348 if (inputName.ShowDialog(this) != DialogResult.OK)
8350 if (string.IsNullOrWhiteSpace(inputName.TabName))
8353 id = inputName.TabName.Trim();
8356 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8360 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8361 await dialog.WaitForAsync(this, task);
8363 catch (WebApiException ex)
8365 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8370 MessageBox.Show(Properties.Resources.FRMessage3);
8373 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8375 var id = this.CurrentPost?.ScreenName ?? "";
8377 await this.ShowFriendship(id);
8380 internal async Task ShowFriendship(string id)
8382 using (var inputName = new InputTabName())
8384 inputName.FormTitle = "Show Friendships";
8385 inputName.FormDescription = Properties.Resources.FRMessage1;
8386 inputName.TabName = id;
8388 if (inputName.ShowDialog(this) != DialogResult.OK)
8390 if (string.IsNullOrWhiteSpace(inputName.TabName))
8393 id = inputName.TabName.Trim();
8396 bool isFollowing, isFollowed;
8398 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8400 var cancellationToken = dialog.EnableCancellation();
8404 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8405 var friendship = await dialog.WaitForAsync(this, task);
8407 isFollowing = friendship.Relationship.Source.Following;
8408 isFollowed = friendship.Relationship.Source.FollowedBy;
8410 catch (WebApiException ex)
8412 if (!cancellationToken.IsCancellationRequested)
8413 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8417 if (cancellationToken.IsCancellationRequested)
8424 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8428 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8432 result += Properties.Resources.GetFriendshipInfo3;
8436 result += Properties.Resources.GetFriendshipInfo4;
8438 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8439 MessageBox.Show(result);
8442 internal async Task ShowFriendship(string[] ids)
8444 foreach (var id in ids)
8446 bool isFollowing, isFollowed;
8448 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8450 var cancellationToken = dialog.EnableCancellation();
8454 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8455 var friendship = await dialog.WaitForAsync(this, task);
8457 isFollowing = friendship.Relationship.Source.Following;
8458 isFollowed = friendship.Relationship.Source.FollowedBy;
8460 catch (WebApiException ex)
8462 if (!cancellationToken.IsCancellationRequested)
8463 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8467 if (cancellationToken.IsCancellationRequested)
8477 ff += Properties.Resources.GetFriendshipInfo1;
8481 ff += Properties.Resources.GetFriendshipInfo2;
8484 ff += System.Environment.NewLine + " ";
8487 ff += Properties.Resources.GetFriendshipInfo3;
8491 ff += Properties.Resources.GetFriendshipInfo4;
8493 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8496 if (MessageBox.Show(
8497 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8498 Properties.Resources.GetFriendshipInfo8,
8499 MessageBoxButtons.YesNo,
8500 MessageBoxIcon.Question,
8501 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8503 await this.RemoveCommand(id, true);
8508 MessageBox.Show(result);
8513 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8514 => await this.DoShowUserStatus(this.tw.Username, false);
8516 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8519 public bool IsTwitterId(string name)
8521 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8522 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8524 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8527 private void DoQuoteOfficial()
8529 var post = this.CurrentPost;
8530 if (this.ExistCurrentPost && post != null)
8532 if (post.IsDm || !this.StatusText.Enabled)
8537 MessageBox.Show("Protected.");
8541 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8543 this.inReplyTo = null;
8545 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8547 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8548 this.StatusText.Focus();
8552 private void DoReTweetUnofficial()
8555 var post = this.CurrentPost;
8556 if (this.ExistCurrentPost && post != null)
8558 if (post.IsDm || !this.StatusText.Enabled)
8563 MessageBox.Show("Protected.");
8566 var rtdata = post.Text;
8567 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8569 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8571 // 投稿時に in_reply_to_status_id を付加する
8572 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8573 var inReplyToScreenName = post.ScreenName;
8574 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8576 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8578 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8579 this.StatusText.Focus();
8583 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8584 => this.DoQuoteOfficial();
8586 private async void SearchButton_Click(object sender, EventArgs e)
8589 var pnl = ((Control)sender).Parent;
8590 if (pnl == null) return;
8591 var tbName = pnl.Parent.Text;
8592 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8593 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8594 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8595 cmb.Text = cmb.Text.Trim();
8596 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8598 var buf = new StringBuilder();
8599 var c = cmb.Text.ToCharArray();
8600 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8602 if (cnt > cmb.Text.Length - 4)
8604 buf.Append(cmb.Text.Substring(cnt));
8613 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8622 cmb.Text = buf.ToString();
8624 var listView = (DetailsListView)pnl.Parent.Tag;
8626 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8628 tb.SearchWords = cmb.Text;
8629 tb.SearchLang = cmbLang.Text;
8630 if (MyCommon.IsNullOrEmpty(cmb.Text))
8633 this.SaveConfigsTabs();
8638 var idx = cmb.Items.IndexOf(tb.SearchWords);
8639 if (idx > -1) cmb.Items.RemoveAt(idx);
8640 cmb.Items.Insert(0, tb.SearchWords);
8641 cmb.Text = tb.SearchWords;
8643 this.statuses.ClearTabIds(tbName);
8644 this.listCache?.PurgeCache();
8645 this.listCache?.UpdateListSize();
8646 this.SaveConfigsTabs(); // 検索条件の保存
8650 await this.RefreshTabAsync(tb);
8653 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8654 => await this.DoRefreshMore(); // もっと前を取得
8657 /// 指定されたタブのListTabにおける位置を返します
8660 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8662 public int GetTabPageIndex(string tabName)
8663 => this.statuses.Tabs.IndexOf(tabName);
8665 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8669 var restoredTab = this.statuses.UndoRemovedTab();
8670 this.AddNewTab(restoredTab, startup: false);
8672 var tabIndex = this.statuses.Tabs.Count - 1;
8673 this.ListTab.SelectedIndex = tabIndex;
8675 this.SaveConfigsTabs();
8677 catch (TabException ex)
8679 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8683 private async Task DoMoveToRTHome()
8685 var post = this.CurrentPost;
8686 if (post != null && post.RetweetedId != null)
8687 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8690 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8691 => await this.DoMoveToRTHome();
8693 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8695 var screenName = this.CurrentPost?.ScreenName;
8696 if (screenName != null)
8697 this.ListManageUserContext(screenName);
8700 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8702 var screenName = this.CurrentPost?.RetweetedBy;
8703 if (screenName != null)
8704 this.ListManageUserContext(screenName);
8707 public void ListManageUserContext(string screenName)
8709 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8710 listSelectForm.ShowDialog(this);
8713 private void SearchControls_Enter(object sender, EventArgs e)
8715 var pnl = (Control)sender;
8716 foreach (Control ctl in pnl.Controls)
8722 private void SearchControls_Leave(object sender, EventArgs e)
8724 var pnl = (Control)sender;
8725 foreach (Control ctl in pnl.Controls)
8727 ctl.TabStop = false;
8731 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8733 var tab = this.CurrentTab;
8734 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8735 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8738 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8739 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8741 private void HashManageMenuItem_Click(object sender, EventArgs e)
8746 rslt = this.HashMgr.ShowDialog();
8752 this.TopMost = this.settings.Common.AlwaysTop;
8753 if (rslt == DialogResult.Cancel) return;
8754 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8756 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8757 this.HashTogglePullDownMenuItem.Checked = true;
8758 this.HashToggleMenuItem.Checked = true;
8762 this.HashStripSplitButton.Text = "#[-]";
8763 this.HashTogglePullDownMenuItem.Checked = false;
8764 this.HashToggleMenuItem.Checked = false;
8767 this.MarkSettingCommonModified();
8768 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8771 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8773 this.HashMgr.ToggleHash();
8774 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8776 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8777 this.HashToggleMenuItem.Checked = true;
8778 this.HashTogglePullDownMenuItem.Checked = true;
8782 this.HashStripSplitButton.Text = "#[-]";
8783 this.HashToggleMenuItem.Checked = false;
8784 this.HashTogglePullDownMenuItem.Checked = false;
8786 this.MarkSettingCommonModified();
8787 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8790 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8791 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8793 public void SetPermanentHashtag(string hashtag)
8795 this.HashMgr.SetPermanentHash("#" + hashtag);
8796 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8797 this.HashTogglePullDownMenuItem.Checked = true;
8798 this.HashToggleMenuItem.Checked = true;
8800 this.MarkSettingCommonModified();
8803 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8805 var tab = this.CurrentTab;
8806 var post = this.CurrentPost;
8807 if (!this.ExistCurrentPost)
8809 this.ReplyOpMenuItem.Enabled = false;
8810 this.ReplyAllOpMenuItem.Enabled = false;
8811 this.DmOpMenuItem.Enabled = false;
8812 this.CreateTabRuleOpMenuItem.Enabled = false;
8813 this.CreateIdRuleOpMenuItem.Enabled = false;
8814 this.CreateSourceRuleOpMenuItem.Enabled = false;
8815 this.ReadOpMenuItem.Enabled = false;
8816 this.UnreadOpMenuItem.Enabled = false;
8817 this.AuthorMenuItem.Visible = false;
8818 this.RetweetedByMenuItem.Visible = false;
8822 this.ReplyOpMenuItem.Enabled = true;
8823 this.ReplyAllOpMenuItem.Enabled = true;
8824 this.DmOpMenuItem.Enabled = true;
8825 this.CreateTabRuleOpMenuItem.Enabled = true;
8826 this.CreateIdRuleOpMenuItem.Enabled = true;
8827 this.CreateSourceRuleOpMenuItem.Enabled = true;
8828 this.ReadOpMenuItem.Enabled = true;
8829 this.UnreadOpMenuItem.Enabled = true;
8830 this.AuthorMenuItem.Visible = true;
8831 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8832 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8833 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8836 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8838 this.FavOpMenuItem.Enabled = false;
8839 this.UnFavOpMenuItem.Enabled = false;
8840 this.OpenStatusOpMenuItem.Enabled = false;
8841 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8842 this.RtOpMenuItem.Enabled = false;
8843 this.RtUnOpMenuItem.Enabled = false;
8844 this.QtOpMenuItem.Enabled = false;
8845 this.FavoriteRetweetMenuItem.Enabled = false;
8846 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8850 this.FavOpMenuItem.Enabled = true;
8851 this.UnFavOpMenuItem.Enabled = true;
8852 this.OpenStatusOpMenuItem.Enabled = true;
8853 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8855 if (!post.CanRetweetBy(this.tw.UserId))
8857 this.RtOpMenuItem.Enabled = false;
8858 this.RtUnOpMenuItem.Enabled = false;
8859 this.QtOpMenuItem.Enabled = false;
8860 this.FavoriteRetweetMenuItem.Enabled = false;
8861 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8865 this.RtOpMenuItem.Enabled = true;
8866 this.RtUnOpMenuItem.Enabled = true;
8867 this.QtOpMenuItem.Enabled = true;
8868 this.FavoriteRetweetMenuItem.Enabled = true;
8869 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8873 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8875 this.RefreshPrevOpMenuItem.Enabled = true;
8879 this.RefreshPrevOpMenuItem.Enabled = false;
8881 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8883 this.OpenRepSourceOpMenuItem.Enabled = false;
8887 this.OpenRepSourceOpMenuItem.Enabled = true;
8890 if (this.ExistCurrentPost && post != null)
8892 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8896 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8897 => this.ContextMenuTabProperty_Opening(sender, null!);
8899 public Twitter TwitterInstance
8902 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8904 if (this.initialLayout)
8907 int splitterDistance;
8908 switch (this.WindowState)
8910 case FormWindowState.Normal:
8911 splitterDistance = this.SplitContainer3.SplitterDistance;
8913 case FormWindowState.Maximized:
8914 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8915 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8916 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8917 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8923 this.mySpDis3 = splitterDistance;
8924 this.MarkSettingLocalModified();
8927 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8929 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8931 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8932 this.PublicSearchQueryMenuItem.Enabled = true;
8934 this.PublicSearchQueryMenuItem.Enabled = false;
8936 var post = this.CurrentPost;
8937 if (!this.ExistCurrentPost || post == null)
8939 this.CopySTOTMenuItem.Enabled = false;
8940 this.CopyURLMenuItem.Enabled = false;
8941 this.CopyUserIdStripMenuItem.Enabled = false;
8945 this.CopySTOTMenuItem.Enabled = true;
8946 this.CopyURLMenuItem.Enabled = true;
8947 this.CopyUserIdStripMenuItem.Enabled = true;
8949 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8950 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8954 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8955 => this.SetNotifyIconText();
8957 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8958 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8960 private async Task DoShowUserStatus(string id, bool showInputDialog)
8962 TwitterUser? user = null;
8964 if (showInputDialog)
8966 using var inputName = new InputTabName();
8967 inputName.FormTitle = "Show UserStatus";
8968 inputName.FormDescription = Properties.Resources.FRMessage1;
8969 inputName.TabName = id;
8971 if (inputName.ShowDialog(this) != DialogResult.OK)
8973 if (string.IsNullOrWhiteSpace(inputName.TabName))
8976 id = inputName.TabName.Trim();
8979 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8981 var cancellationToken = dialog.EnableCancellation();
8985 var task = this.tw.GetUserInfo(id);
8986 user = await dialog.WaitForAsync(this, task);
8988 catch (WebApiException ex)
8990 if (!cancellationToken.IsCancellationRequested)
8991 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8995 if (cancellationToken.IsCancellationRequested)
8999 await this.DoShowUserStatus(user);
9002 private async Task DoShowUserStatus(TwitterUser user)
9004 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9005 var showUserTask = userDialog.ShowUserAsync(user);
9006 userDialog.ShowDialog(this);
9009 this.BringToFront();
9011 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9015 internal Task ShowUserStatus(string id, bool showInputDialog)
9016 => this.DoShowUserStatus(id, showInputDialog);
9018 internal Task ShowUserStatus(string id)
9019 => this.DoShowUserStatus(id, true);
9021 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9023 var post = this.CurrentPost;
9026 await this.ShowUserStatus(post.ScreenName, false);
9030 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9032 var retweetedBy = this.CurrentPost?.RetweetedBy;
9033 if (retweetedBy != null)
9035 await this.ShowUserStatus(retweetedBy, false);
9039 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9041 var post = this.CurrentPost;
9042 if (!this.ExistCurrentPost || post == null)
9045 var statusId = post.RetweetedId ?? post.StatusId;
9046 TwitterStatus status;
9048 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9050 var cancellationToken = dialog.EnableCancellation();
9054 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9055 status = await dialog.WaitForAsync(this, task);
9057 catch (WebApiException ex)
9059 if (!cancellationToken.IsCancellationRequested)
9060 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9064 if (cancellationToken.IsCancellationRequested)
9068 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9071 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9073 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9076 this.Visible = false;
9078 else if (Form.ActiveForm == null)
9080 this.Visible = true;
9081 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9083 this.BringToFront();
9084 this.StatusText.Focus();
9088 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9089 => this.MultiLinePullDownMenuItem.PerformClick();
9092 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9094 if (this.ImageSelector.Visible)
9095 this.ImageSelector.EndSelection();
9097 this.ImageSelector.BeginSelection();
9100 private void SelectMedia_DragEnter(DragEventArgs e)
9102 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9104 e.Effect = DragDropEffects.Copy;
9107 e.Effect = DragDropEffects.None;
9110 private void SelectMedia_DragDrop(DragEventArgs e)
9113 this.BringToFront();
9115 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9116 this.ImageSelector.BeginSelection();
9117 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9118 this.StatusText.Focus();
9121 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9123 this.TimelinePanel.Visible = false;
9124 this.TimelinePanel.Enabled = false;
9127 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9129 this.TimelinePanel.Visible = true;
9130 this.TimelinePanel.Enabled = true;
9131 this.CurrentListView.Focus();
9134 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9135 => this.AllowDrop = false;
9137 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9138 => this.AllowDrop = true;
9140 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9142 if (this.ImageSelector.Visible)
9144 this.MarkSettingCommonModified();
9145 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9149 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9150 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9153 /// StatusTextでCtrl+Vが押下された時の処理
9155 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9159 if (Clipboard.ContainsText())
9161 // clipboardにテキストがある場合は貼り付け処理
9162 this.StatusText.Paste(Clipboard.GetText());
9164 else if (Clipboard.ContainsImage())
9167 using var image = Clipboard.GetImage();
9168 this.ImageSelector.BeginSelection();
9169 this.ImageSelector.Model.AddMediaItemFromImage(image);
9171 else if (Clipboard.ContainsFileDropList())
9173 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9174 this.ImageSelector.BeginSelection();
9175 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9178 catch (ExternalException ex)
9180 MessageBox.Show(ex.Message);
9185 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9187 using var form = new ListManage(this.tw);
9188 form.ShowDialog(this);
9191 private bool ModifySettingCommon { get; set; }
9193 private bool ModifySettingLocal { get; set; }
9195 private bool ModifySettingAtId { get; set; }
9197 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9199 var post = this.CurrentPost;
9200 if (this.ExistCurrentPost && post != null && !post.IsDm)
9201 this.RtCountMenuItem.Enabled = true;
9203 this.RtCountMenuItem.Enabled = false;
9206 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9207 => this.CopyUserId();
9209 private void CopyUserId()
9211 var post = this.CurrentPost;
9212 if (post == null) return;
9213 var clstr = post.ScreenName;
9216 Clipboard.SetDataObject(clstr, false, 5, 100);
9218 catch (Exception ex)
9220 MessageBox.Show(ex.Message);
9224 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9226 var post = this.CurrentPost;
9227 if (this.ExistCurrentPost && post != null && !post.IsDm)
9231 await this.OpenRelatedTab(post);
9233 catch (TabException ex)
9235 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9241 /// 指定されたツイートに対する関連発言タブを開きます
9243 /// <param name="statusId">表示するツイートのID</param>
9244 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9245 public async Task OpenRelatedTab(PostId statusId)
9247 var post = this.statuses[statusId];
9252 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9254 catch (WebApiException ex)
9256 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9261 await this.OpenRelatedTab(post);
9265 /// 指定されたツイートに対する関連発言タブを開きます
9267 /// <param name="post">表示する対象となるツイート</param>
9268 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9269 private async Task OpenRelatedTab(PostClass post)
9271 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9272 if (tabRelated != null)
9274 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9277 var tabName = this.statuses.MakeTabName("Related Tweets");
9279 tabRelated = new RelatedPostsTabModel(tabName, post)
9281 UnreadManage = false,
9285 this.statuses.AddTab(tabRelated);
9286 this.AddNewTab(tabRelated, startup: false);
9288 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9290 await this.RefreshTabAsync(tabRelated);
9292 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9296 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9298 var tabPage = this.ListTab.TabPages[tabIndex];
9299 var listView = (DetailsListView)tabPage.Tag;
9300 var targetPost = tabRelated.TargetPost;
9301 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9303 if (index != -1 && index < listView.Items.Count)
9305 listView.SelectedIndices.Add(index);
9306 listView.Items[index].Focused = true;
9311 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9313 var buf = new StringBuilder();
9314 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9315 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9316 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9319 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9321 MyCommon.EndingFlag = true;
9325 Application.Restart();
9329 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9333 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9334 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9336 private bool ExistCurrentPost
9340 var post = this.CurrentPost;
9341 return post != null && !post.IsDeleted;
9345 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9346 => await this.ShowUserTimeline();
9348 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9349 => await this.ShowRetweeterTimeline();
9351 private string GetUserIdFromCurPostOrInput(string caption)
9353 var id = this.CurrentPost?.ScreenName ?? "";
9355 using var inputName = new InputTabName();
9356 inputName.FormTitle = caption;
9357 inputName.FormDescription = Properties.Resources.FRMessage1;
9358 inputName.TabName = id;
9360 if (inputName.ShowDialog() == DialogResult.OK &&
9361 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9363 id = inputName.TabName.Trim();
9372 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9374 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9375 if (!MyCommon.IsNullOrEmpty(id))
9377 await this.AddNewTabForUserTimeline(id);
9381 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9383 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9384 this.timelineScheduler.SystemResumed();
9387 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9389 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9391 TimeZoneInfo.ClearCachedData();
9393 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9395 if (curTimeOffset != prevTimeOffset)
9398 this.listCache?.PurgeCache();
9399 this.CurrentListView.Refresh();
9401 this.DispSelectedPost(forceupdate: true);
9404 this.timelineScheduler.Reset();
9407 private void TimelineRefreshEnableChange(bool isEnable)
9409 this.timelineScheduler.Enabled = isEnable;
9412 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9413 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9415 private async Task OpenUserAppointUrl()
9417 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9419 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9421 var post = this.CurrentPost;
9424 var xUrl = this.settings.Common.UserAppointUrl;
9425 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9427 var statusId = post.RetweetedId ?? post.StatusId;
9428 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9430 await MyCommon.OpenInBrowserAsync(this, xUrl);
9435 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9440 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9441 => await this.OpenUserAppointUrl();
9443 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9445 if (Form.ActiveForm == null)
9447 await this.InvokeAsync(() =>
9449 this.Visible = true;
9450 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9452 this.BringToFront();
9453 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9455 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9459 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9465 private void ReplaceAppName()
9467 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9468 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9471 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9472 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9474 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9476 if (e.KeyCode == Keys.Space)
9478 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9480 e.SuppressKeyPress = true;
9484 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9486 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9487 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9488 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9489 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9490 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9492 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9495 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9496 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9498 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9499 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9501 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9502 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9504 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9505 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9507 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9508 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9510 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9512 if (this.settings.Common.IconSize == iconSize) return;
9514 var oldIconCol = this.Use2ColumnsMode;
9516 this.settings.Common.IconSize = iconSize;
9517 this.ApplyListViewIconSize(iconSize);
9519 if (this.Use2ColumnsMode != oldIconCol)
9521 foreach (TabPage tp in this.ListTab.TabPages)
9523 this.ResetColumns((DetailsListView)tp.Tag);
9527 this.CurrentListView.Refresh();
9528 this.MarkSettingCommonModified();
9531 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9533 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9534 if (this.settings.Common.SortOrderLock == state) return;
9536 this.settings.Common.SortOrderLock = state;
9537 this.MarkSettingCommonModified();
9540 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9542 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9544 this.StatusLabelUrl.Text = e.StatusText;
9548 this.SetStatusLabelUrl();