1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.TwitterV2;
56 using OpenTween.Connection;
57 using OpenTween.MediaUploadServices;
58 using OpenTween.Models;
59 using OpenTween.OpenTweenCustomControl;
60 using OpenTween.Setting;
61 using OpenTween.Thumbnail;
65 public partial class TweenMain : OTBaseForm
69 /// <summary>画面サイズ</summary>
72 /// <summary>画面位置</summary>
75 /// <summary>区切り位置</summary>
78 /// <summary>発言欄区切り位置</summary>
81 /// <summary>プレビュー区切り位置</summary>
85 private bool initial; // true:起動時処理中
86 private bool initialLayout = true;
87 private bool ignoreConfigSave; // true:起動時処理中
89 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
92 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
93 private Point tabMouseDownPoint;
95 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
96 private string? rclickTabName;
98 private readonly object syncObject = new(); // ロック用
100 private const string DetailHtmlFormatHead =
101 "<head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
102 + "<style type=\"text/css\"><!-- "
103 + "body, p, pre {margin: 0;} "
104 + "body {font-family: \"%FONT_FAMILY%\", \"Segoe UI Emoji\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
105 + "pre {font-family: inherit;} "
106 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
107 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
108 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
109 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
110 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
114 private const string DetailHtmlFormatTemplateMono =
115 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
117 private const string DetailHtmlFormatTemplateNormal =
118 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
120 private string detailHtmlFormatPreparedTemplate = null!;
122 private bool myStatusError = false;
123 private bool myStatusOnline = false;
124 private bool soundfileListup = false;
125 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
128 private readonly SettingManager settings;
131 private readonly Twitter tw;
134 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
138 /// <summary>検索画面インスタンス</summary>
139 internal SearchWordDialog SearchDialog = new();
141 private readonly OpenURL urlDialog = new();
143 /// <summary>@id補助</summary>
144 public AtIdSupplement AtIdSupl = null!;
146 /// <summary>Hashtag補助</summary>
147 public AtIdSupplement HashSupl = null!;
149 public HashtagManage HashMgr = null!;
152 private ThemeManager themeManager;
154 /// <summary>アイコン画像リスト</summary>
155 private readonly ImageCache iconCache;
157 private readonly IconAssetsManager iconAssets;
159 private readonly ThumbnailGenerator thumbGenerator;
161 /// <summary>発言履歴</summary>
162 private readonly List<StatusTextHistory> history = new();
164 /// <summary>発言履歴カレントインデックス</summary>
167 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169 /// <summary>リプライ先のステータスID・スクリーン名</summary>
170 private (long StatusId, string ScreenName)? inReplyTo = null;
173 private readonly List<DateTimeUtc> postTimestamps = new();
174 private readonly List<DateTimeUtc> favTimestamps = new();
177 private readonly StringFormat sfTab = new();
179 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 /// <summary>発言保持クラス</summary>
182 private readonly TabInformations statuses;
184 private TimelineListViewCache? listCache;
185 private TimelineListViewDrawer? listDrawer;
186 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
188 private bool isColumnChanged = false;
190 private const int MaxWorderThreads = 20;
191 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
192 private readonly CancellationTokenSource workerCts = new();
193 private readonly IProgress<string> workerProgress = null!;
195 private int unreadCounter = -1;
196 private int unreadAtCounter = -1;
198 private readonly string[] columnOrgText = new string[9];
199 private readonly string[] columnText = new string[9];
201 private bool doFavRetweetFlags = false;
203 //////////////////////////////////////////////////////////////////////////////////////////////////////////
205 private readonly TimelineScheduler timelineScheduler = new();
206 private readonly DebounceTimer selectionDebouncer;
207 private readonly DebounceTimer saveConfigDebouncer;
209 private readonly string recommendedStatusFooter;
210 private bool urlMultibyteSplit = false;
211 private bool preventSmsCommand = true;
214 private readonly record struct UrlUndo(
219 private List<UrlUndo>? urlUndoBuffer = null;
221 private readonly record struct ReplyChain(
227 /// <summary>[, ]でのリプライ移動の履歴</summary>
228 private Stack<ReplyChain>? replyChains;
230 /// <summary>ポスト選択履歴</summary>
231 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
233 public TabModel CurrentTab
234 => this.statuses.SelectedTab;
236 public string CurrentTabName
237 => this.statuses.SelectedTabName;
239 public TabPage CurrentTabPage
240 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
242 public DetailsListView CurrentListView
243 => (DetailsListView)this.CurrentTabPage.Tag;
245 public PostClass? CurrentPost
246 => this.CurrentTab.SelectedPost;
248 public bool Use2ColumnsMode
249 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
251 /// <summary>検索処理タイプ</summary>
252 internal enum SEARCHTYPE
259 private readonly record struct StatusTextHistory(
261 (long StatusId, string ScreenName)? InReplyTo = null
264 private readonly HookGlobalHotkey hookGlobalHotkey;
266 private void TweenMain_Activated(object sender, EventArgs e)
268 // 画面がアクティブになったら、発言欄の背景色戻す
269 if (this.StatusText.Focused)
271 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
275 private bool disposed = false;
278 /// 使用中のリソースをすべてクリーンアップします。
280 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
281 protected override void Dispose(bool disposing)
283 base.Dispose(disposing);
290 this.components?.Dispose();
293 this.SearchDialog.Dispose();
294 this.urlDialog.Dispose();
295 this.themeManager.Dispose();
296 this.sfTab.Dispose();
298 this.timelineScheduler.Dispose();
299 this.workerCts.Cancel();
300 this.thumbnailTokenSource?.Dispose();
302 this.hookGlobalHotkey.Dispose();
305 // 終了時にRemoveHandlerしておかないとメモリリークする
306 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
307 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
308 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
310 this.disposed = true;
313 private void InitColumns(ListView list, bool startup)
315 this.InitColumnText();
317 ColumnHeader[]? columns = null;
320 if (this.Use2ColumnsMode)
324 new ColumnHeader(), // アイコン
325 new ColumnHeader(), // 本文
328 columns[0].Text = this.columnText[0];
329 columns[1].Text = this.columnText[2];
333 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
335 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
336 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
337 columns[0].DisplayIndex = 0;
338 columns[1].DisplayIndex = 1;
343 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
345 columns[idx].Width = curListColumn.Width;
346 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
355 new ColumnHeader(), // アイコン
356 new ColumnHeader(), // ニックネーム
357 new ColumnHeader(), // 本文
358 new ColumnHeader(), // 日付
359 new ColumnHeader(), // ユーザID
360 new ColumnHeader(), // 未読
361 new ColumnHeader(), // マーク&プロテクト
362 new ColumnHeader(), // ソース
365 foreach (var i in Enumerable.Range(0, columns.Length))
366 columns[i].Text = this.columnText[i];
370 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
372 foreach (var (column, index) in columns.WithIndex())
374 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
375 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
381 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
383 columns[idx].Width = curListColumn.Width;
384 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
390 list.Columns.AddRange(columns);
398 foreach (var column in columns)
404 private void InitColumnText()
406 this.columnText[0] = "";
407 this.columnText[1] = Properties.Resources.AddNewTabText2;
408 this.columnText[2] = Properties.Resources.AddNewTabText3;
409 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
410 this.columnText[4] = Properties.Resources.AddNewTabText5;
411 this.columnText[5] = "";
412 this.columnText[6] = "";
413 this.columnText[7] = "Source";
415 this.columnOrgText[0] = "";
416 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
417 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
418 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
419 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
420 this.columnOrgText[5] = "";
421 this.columnOrgText[6] = "";
422 this.columnOrgText[7] = "Source";
424 var c = this.statuses.SortMode switch
426 ComparerMode.Nickname => 1, // ニックネーム
427 ComparerMode.Data => 2, // 本文
428 ComparerMode.Id => 3, // 時刻=発言Id
429 ComparerMode.Name => 4, // 名前
430 ComparerMode.Source => 7, // Source
434 if (this.Use2ColumnsMode)
436 if (this.statuses.SortOrder == SortOrder.Descending)
438 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
439 this.columnText[2] = this.columnOrgText[2] + "▾";
443 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
444 this.columnText[2] = this.columnOrgText[2] + "▴";
449 if (this.statuses.SortOrder == SortOrder.Descending)
451 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
452 this.columnText[c] = this.columnOrgText[c] + "▾";
456 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
457 this.columnText[c] = this.columnOrgText[c] + "▴";
463 SettingManager settingManager,
464 TabInformations tabInfo,
466 ImageCache imageCache,
467 IconAssetsManager iconAssets,
468 ThumbnailGenerator thumbGenerator
471 this.settings = settingManager;
472 this.statuses = tabInfo;
474 this.iconCache = imageCache;
475 this.iconAssets = iconAssets;
476 this.thumbGenerator = thumbGenerator;
478 this.InitializeComponent();
480 if (!this.DesignMode)
482 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
483 this.StatusText.Dock = DockStyle.Fill;
486 this.hookGlobalHotkey = new HookGlobalHotkey(this);
488 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
489 this.gh.NotifyClicked += this.GrowlHelper_Callback;
491 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
492 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
494 this.ImageSelector.Visible = false;
495 this.ImageSelector.Enabled = false;
496 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
498 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
500 this.ReplaceAppName();
501 this.InitializeShortcuts();
503 this.ignoreConfigSave = true;
504 this.Visible = false;
506 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
508 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
510 Regex.CacheSize = 100;
513 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
514 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
515 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
517 // <<<<<<<<<設定関連>>>>>>>>>
521 // 現在の DPI と設定保存時の DPI との比を取得する
522 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
525 this.tw.Initialize(this.settings.Common.Token, this.settings.Common.TokenSecret, this.settings.Common.UserName, this.settings.Common.UserId);
529 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
530 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
532 // アクセストークンが有効であるか確認する
533 // ここが Twitter API への最初のアクセスになるようにすること
536 this.tw.VerifyCredentials();
538 catch (WebApiException ex)
542 string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
543 ApplicationSettings.ApplicationName,
544 MessageBoxButtons.OK,
545 MessageBoxIcon.Warning);
549 // プロキシ設定等の通信まわりの初期化が済んでから処理する
550 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
551 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
552 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
553 imgazyobizinet.AutoUpdate = true;
555 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
558 this.ImageSelector.Initialize(this.tw, this.tw.Configuration, this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
560 this.tweetThumbnail1.Initialize(this.thumbGenerator);
563 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
564 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
565 this.HashMgr = new HashtagManage(this.HashSupl,
566 this.settings.Common.HashTags.ToArray(),
567 this.settings.Common.HashSelected,
568 this.settings.Common.HashIsPermanent,
569 this.settings.Common.HashIsHead,
570 this.settings.Common.HashIsNotAddToAtReply);
571 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
574 this.themeManager = new(this.settings.Local);
575 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
577 // StringFormatオブジェクトへの事前設定
578 this.sfTab.Alignment = StringAlignment.Center;
579 this.sfTab.LineAlignment = StringAlignment.Center;
581 this.InitDetailHtmlFormat();
582 this.tweetDetailsView.ClearPostBrowser();
584 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
586 this.history.Add(new StatusTextHistory(""));
588 this.inReplyTo = null;
591 this.SearchDialog.Owner = this;
592 this.urlDialog.Owner = this;
595 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
596 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
598 // 新着取得時のリストスクロールをするか。trueならスクロールしない
599 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
600 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
602 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
603 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
606 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
607 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
608 this.myLoc = this.settings.Local.FormLocation;
610 if (this.WindowState != FormWindowState.Minimized)
612 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
613 var outOfScreen = true;
614 if (Screen.AllScreens.Length == 1) // ハングするとの報告
616 foreach (var scr in Screen.AllScreens)
618 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
626 this.myLoc = new Point(0, 0);
628 this.DesktopLocation = this.myLoc;
630 this.TopMost = this.settings.Common.AlwaysTop;
631 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
632 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
633 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
635 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
636 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
638 this.StatusText.Font = this.themeManager.FontInputFont;
639 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
641 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
642 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
643 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
645 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
646 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
648 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
649 if (this.settings.Common.UnreadManage == false)
651 this.ReadedStripMenuItem.Enabled = false;
652 this.UnreadStripMenuItem.Enabled = false;
655 // リンク先URL表示部の初期化(画面左下)
656 this.StatusLabelUrl.Text = "";
658 this.StatusLabel.Text = "";
659 this.StatusLabel.AutoToolTip = false;
660 this.StatusLabel.ToolTipText = "";
662 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
664 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
665 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
666 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
667 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
669 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
670 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
671 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
672 this.SplitContainer2.Panel2.AccessibleName = "";
674 ////////////////////////////////////////////////////////////////////////////////
675 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
676 var mode = this.settings.Common.SortColumn switch
678 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
679 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
680 1 => ComparerMode.Nickname, // ニックネーム
681 2 => ComparerMode.Data, // 本文
682 3 => ComparerMode.Id, // 時刻=発言Id
683 4 => ComparerMode.Name, // 名前
684 7 => ComparerMode.Source, // Source
685 _ => ComparerMode.Id,
687 this.statuses.SetSortMode(mode, sortOrder);
688 ////////////////////////////////////////////////////////////////////////////////
690 this.ApplyListViewIconSize(this.settings.Common.IconSize);
692 // <<<<<<<<タブ関連>>>>>>>
693 foreach (var tab in this.statuses.Tabs)
695 if (!this.AddNewTab(tab, startup: true))
696 throw new TabException(Properties.Resources.TweenMain_LoadText1);
699 this.ListTabSelect(this.ListTab.SelectedTab);
702 this.SetTabAlignment();
704 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
705 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
707 if (this.settings.Common.TabIconDisp)
709 this.ListTab.DrawMode = TabDrawMode.Normal;
713 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
714 this.ListTab.DrawItem += this.ListTab_DrawItem;
715 this.ListTab.ImageList = null;
718 if (this.settings.Common.HotkeyEnabled)
721 var modKey = HookGlobalHotkey.ModKeys.None;
722 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
723 modKey |= HookGlobalHotkey.ModKeys.Alt;
724 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
725 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
726 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
727 modKey |= HookGlobalHotkey.ModKeys.Shift;
728 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
729 modKey |= HookGlobalHotkey.ModKeys.Win;
731 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
734 if (this.settings.Common.IsUseNotifyGrowl)
735 this.gh.RegisterGrowl();
737 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
739 this.SetMainWindowTitle();
740 this.SetNotifyIconText();
742 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
749 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
750 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
751 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
752 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
753 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
754 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
755 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
757 this.DoGetFollowersMenu(),
758 this.RefreshBlockIdsAsync(),
759 this.RefreshMuteUserIdsAsync(),
760 this.RefreshNoRetweetIdsAsync(),
761 this.RefreshTwitterConfigurationAsync(),
763 this.RefreshTimelineScheduler();
765 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
766 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
769 this.TimerRefreshIcon.Interval = 200;
770 this.TimerRefreshIcon.Enabled = false;
772 this.ignoreConfigSave = false;
773 this.TweenMain_Resize(this, EventArgs.Empty);
775 if (this.settings.IsFirstRun)
777 // 初回起動時だけ右下のメニューを目立たせる
778 this.HashStripSplitButton.ShowDropDown();
782 private void InitDetailHtmlFormat()
784 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
786 static string ColorToRGBString(Color color)
787 => $"{color.R},{color.G},{color.B}";
789 this.detailHtmlFormatPreparedTemplate = htmlTemplate
790 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
791 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
792 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
793 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
794 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
795 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
798 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
803 txt = this.statuses.Tabs[e.Index].TabName;
810 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
811 if (e.State == DrawItemState.Selected)
813 e.DrawFocusRectangle();
818 if (this.statuses.Tabs[txt].UnreadCount > 0)
821 fore = System.Drawing.SystemBrushes.ControlText;
825 fore = System.Drawing.SystemBrushes.ControlText;
827 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
830 private void LoadConfig()
832 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
833 this.statuses.AddDefaultTabs();
836 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
838 this.RefreshTimelineScheduler();
841 private void RefreshTimelineScheduler()
843 static TimeSpan IntervalSecondsOrDisabled(int seconds)
844 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
846 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
847 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
848 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
849 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
850 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
851 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
852 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
853 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
855 this.timelineScheduler.RefreshSchedule();
858 private void MarkSettingCommonModified()
860 if (this.saveConfigDebouncer == null)
863 this.ModifySettingCommon = true;
864 _ = this.saveConfigDebouncer.Call();
867 private void MarkSettingLocalModified()
869 if (this.saveConfigDebouncer == null)
872 this.ModifySettingLocal = true;
873 _ = this.saveConfigDebouncer.Call();
876 internal void MarkSettingAtIdModified()
878 if (this.saveConfigDebouncer == null)
881 this.ModifySettingAtId = true;
882 _ = this.saveConfigDebouncer.Call();
885 private void RefreshTimeline()
887 var curListView = this.CurrentListView;
889 // 現在表示中のタブのスクロール位置を退避
890 var currentListViewState = this.listViewState[this.CurrentTabName];
891 currentListViewState.Save(this.ListLockMenuItem.Checked);
895 addCount = this.statuses.SubmitUpdate(
898 out var newMentionOrDm,
901 if (MyCommon.EndingFlag) return;
904 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
906 using (ControlTransaction.Update(curListView))
908 this.listCache.PurgeCache();
909 this.listCache.UpdateListSize();
912 currentListViewState.RestoreSelection();
918 if (this.settings.Common.TabIconDisp)
920 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
922 var tabPage = this.ListTab.TabPages[index];
923 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
924 tabPage.ImageIndex = 0; // 未読アイコン
929 this.ListTab.Refresh();
934 currentListViewState.RestoreScroll();
937 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
939 this.SetMainWindowTitle();
940 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
942 this.HashSupl.AddRangeItem(this.tw.GetHashList());
945 private bool BalloonRequired()
950 if (NativeMethods.IsScreenSaverRunning())
954 if (!this.NewPostPopMenuItem.Checked)
957 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
958 if (this.settings.Common.LimitBalloon)
960 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
967 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
969 if (this.settings.Common.ReadOwnPost)
971 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
976 if (this.BalloonRequired())
978 if (notifyPosts != null && notifyPosts.Length > 0)
980 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
981 if (this.settings.Common.IsUseNotifyGrowl)
983 var sb = new StringBuilder();
987 foreach (var post in notifyPosts)
989 if (!(notifyPosts.Length > 3))
995 if (post.IsReply && !post.IsExcludeReply) reply = true;
996 if (post.IsDm) dm = true;
997 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
998 switch (this.settings.Common.NameBalloon)
1000 case MyCommon.NameBalloonEnum.UserID:
1001 sb.Append(post.ScreenName).Append(" : ");
1003 case MyCommon.NameBalloonEnum.NickName:
1004 sb.Append(post.Nickname).Append(" : ");
1007 sb.Append(post.TextFromApi);
1008 if (notifyPosts.Length > 3)
1010 if (notifyPosts.Last() != post) continue;
1013 var title = new StringBuilder();
1014 GrowlHelper.NotifyType nt;
1015 if (this.settings.Common.DispUsername)
1017 title.Append(this.tw.Username);
1018 title.Append(" - ");
1023 title.Append(ApplicationSettings.ApplicationName);
1024 title.Append(" [DM] ");
1025 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1026 nt = GrowlHelper.NotifyType.DirectMessage;
1030 title.Append(ApplicationSettings.ApplicationName);
1031 title.Append(" [Reply!] ");
1032 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1033 nt = GrowlHelper.NotifyType.Reply;
1037 title.Append(ApplicationSettings.ApplicationName);
1039 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1040 nt = GrowlHelper.NotifyType.Notify;
1042 var bText = sb.ToString();
1043 if (MyCommon.IsNullOrEmpty(bText)) return;
1045 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1046 this.gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1051 var sb = new StringBuilder();
1054 foreach (var post in notifyPosts)
1056 if (post.IsReply && !post.IsExcludeReply) reply = true;
1057 if (post.IsDm) dm = true;
1058 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1059 switch (this.settings.Common.NameBalloon)
1061 case MyCommon.NameBalloonEnum.UserID:
1062 sb.Append(post.ScreenName).Append(" : ");
1064 case MyCommon.NameBalloonEnum.NickName:
1065 sb.Append(post.Nickname).Append(" : ");
1068 sb.Append(post.TextFromApi);
1071 var title = new StringBuilder();
1073 if (this.settings.Common.DispUsername)
1075 title.Append(this.tw.Username);
1076 title.Append(" - ");
1081 ntIcon = ToolTipIcon.Warning;
1082 title.Append(ApplicationSettings.ApplicationName);
1083 title.Append(" [DM] ");
1084 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1088 ntIcon = ToolTipIcon.Warning;
1089 title.Append(ApplicationSettings.ApplicationName);
1090 title.Append(" [Reply!] ");
1091 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1095 ntIcon = ToolTipIcon.Info;
1096 title.Append(ApplicationSettings.ApplicationName);
1098 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1100 var bText = sb.ToString();
1101 if (MyCommon.IsNullOrEmpty(bText)) return;
1103 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1104 this.NotifyIcon1.BalloonTipText = bText;
1105 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1106 this.NotifyIcon1.ShowBalloonTip(500);
1112 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1116 var dir = Application.StartupPath;
1117 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1119 dir = Path.Combine(dir, "Sounds");
1121 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1129 // mentions新着時に画面ブリンク
1130 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1132 NativeMethods.FlashMyWindow(this.Handle, 3);
1136 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1138 var listView = this.CurrentListView;
1139 if (listView != sender)
1142 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1143 this.CurrentTab.SelectPosts(indices);
1145 if (indices.Length != 1)
1148 var index = indices[0];
1149 if (index > listView.VirtualListSize - 1) return;
1151 this.PushSelectPostChain();
1153 var post = this.CurrentPost!;
1154 this.statuses.SetReadAllTab(post.StatusId, read: true);
1156 this.listCache?.RefreshStyle();
1157 await this.selectionDebouncer.Call();
1160 private void StatusTextHistoryBack()
1162 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1163 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1166 if (this.hisIdx < 0)
1169 var historyItem = this.history[this.hisIdx];
1170 this.inReplyTo = historyItem.InReplyTo;
1171 this.StatusText.Text = historyItem.Status;
1172 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1175 private void StatusTextHistoryForward()
1177 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1178 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1181 if (this.hisIdx > this.history.Count - 1)
1182 this.hisIdx = this.history.Count - 1;
1184 var historyItem = this.history[this.hisIdx];
1185 this.inReplyTo = historyItem.InReplyTo;
1186 this.StatusText.Text = historyItem.Status;
1187 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1190 private async void PostButton_Click(object sender, EventArgs e)
1192 if (this.StatusText.Text.Trim().Length == 0)
1194 if (!this.ImageSelector.Enabled)
1196 await this.DoRefresh();
1201 var currentPost = this.CurrentPost;
1202 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1204 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1206 MessageBoxButtons.YesNoCancel,
1207 MessageBoxIcon.Question);
1210 case DialogResult.Yes:
1211 this.StatusText.Text = "";
1212 await this.DoReTweetOfficial(false);
1214 case DialogResult.Cancel:
1219 if (TextContainsOnlyMentions(this.StatusText.Text))
1221 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1222 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1224 if (ret != DialogResult.OK)
1228 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1230 if (this.settings.Common.Nicoms)
1232 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1233 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1236 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1237 this.CheckReplyTo(this.StatusText.Text);
1239 var status = new PostStatusParams();
1241 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1242 if (this.GetRestStatusCount(statusTextCompat) >= 0)
1244 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1245 // 収まる場合はこれらのオプションを使用せずに投稿する
1246 status.Text = statusTextCompat;
1247 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1251 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1252 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1254 status.AttachmentUrl = attachmentUrl;
1256 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1258 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1259 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1261 status.AutoPopulateReplyMetadata = true;
1263 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1264 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1269 if (this.GetRestStatusCount(status.Text) < 0)
1271 // 文字数制限を超えているが強制的に投稿するか
1272 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1273 if (ret != DialogResult.OK)
1277 IMediaUploadService? uploadService = null;
1278 IMediaItem[]? uploadItems = null;
1279 if (this.ImageSelector.Visible)
1282 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1285 uploadService = this.ImageSelector.GetService(serviceName);
1288 this.inReplyTo = null;
1289 this.StatusText.Text = "";
1290 this.history.Add(new StatusTextHistory(""));
1291 this.hisIdx = this.history.Count - 1;
1292 if (!this.settings.Common.FocusLockToStatusText)
1293 this.CurrentListView.Focus();
1294 this.urlUndoBuffer = null;
1295 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1298 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1300 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1301 await MyCommon.OpenInBrowserAsync(this, tmp);
1304 await this.PostMessageAsync(status, uploadService, uploadItems);
1307 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1309 MyCommon.EndingFlag = true;
1313 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1315 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1317 // _endingFlag=false:フォームの×ボタン
1319 this.Visible = false;
1323 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1324 this.ignoreConfigSave = true;
1325 MyCommon.EndingFlag = true;
1326 this.timelineScheduler.Enabled = false;
1327 this.TimerRefreshIcon.Enabled = false;
1331 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1333 this.Visible = true;
1334 if (this.WindowState == FormWindowState.Minimized)
1336 this.WindowState = FormWindowState.Normal;
1339 this.BringToFront();
1342 private static int errorCount = 0;
1344 private static bool CheckAccountValid()
1346 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1352 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1361 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1362 private Task RefreshTabAsync<T>()
1364 => this.RefreshTabAsync<T>(backward: false);
1366 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1367 private Task RefreshTabAsync<T>(bool backward)
1371 from tab in this.statuses.GetTabsByType<T>()
1372 select this.RefreshTabAsync(tab, backward);
1374 return Task.WhenAll(loadTasks);
1377 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1378 private Task RefreshTabAsync(TabModel tab)
1379 => this.RefreshTabAsync(tab, backward: false);
1381 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1382 private async Task RefreshTabAsync(TabModel tab, bool backward)
1384 await this.workerSemaphore.WaitAsync();
1388 this.RefreshTasktrayIcon();
1389 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1391 catch (WebApiException ex)
1393 this.myStatusError = true;
1394 var tabType = tab switch
1396 HomeTabModel => "GetTimeline",
1397 MentionsTabModel => "GetTimeline",
1398 DirectMessagesTabModel => "GetDirectMessage",
1399 FavoritesTabModel => "GetFavorites",
1400 PublicSearchTabModel => "GetSearch",
1401 UserTimelineTabModel => "GetUserTimeline",
1402 ListTimelineTabModel => "GetListStatus",
1403 RelatedPostsTabModel => "GetRelatedTweets",
1404 _ => tab.GetType().Name.Replace("Model", ""),
1406 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1410 this.RefreshTimeline();
1411 this.workerSemaphore.Release();
1415 private async Task FavAddAsync(long statusId, TabModel tab)
1417 await this.workerSemaphore.WaitAsync();
1421 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1423 this.RefreshTasktrayIcon();
1424 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1426 catch (WebApiException ex)
1428 this.myStatusError = true;
1429 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1433 this.workerSemaphore.Release();
1437 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
1439 if (ct.IsCancellationRequested)
1442 if (!CheckAccountValid())
1443 throw new WebApiException("Auth error. Check your account");
1445 if (!tab.Posts.TryGetValue(statusId, out var post))
1451 await Task.Run(async () =>
1453 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1459 await this.tw.Api.FavoritesCreate(post.RetweetedId ?? post.StatusId)
1461 .ConfigureAwait(false);
1463 catch (TwitterApiException ex)
1464 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1466 // エラーコード 139 のみの場合は成功と見なす
1469 if (this.settings.Common.RestrictFavCheck)
1471 var status = await this.tw.Api.StatusesShow(post.RetweetedId ?? post.StatusId)
1472 .ConfigureAwait(false);
1474 if (status.Favorited != true)
1475 throw new WebApiException("NG(Restricted?)");
1478 this.favTimestamps.Add(DateTimeUtc.Now);
1481 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1483 postTl.IsFav = true;
1485 var favTab = this.statuses.FavoriteTab;
1486 favTab.AddPostQueue(postTl);
1489 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1490 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1492 if (tb.Contains(statusId))
1493 tb.Posts[statusId].IsFav = true;
1496 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1498 catch (WebApiException)
1500 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1505 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1506 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1508 if (this.favTimestamps[i] < oneHour)
1509 this.favTimestamps.RemoveAt(i);
1512 this.statuses.DistributePosts();
1515 if (ct.IsCancellationRequested)
1518 this.RefreshTimeline();
1520 if (this.CurrentTabName == tab.TabName)
1522 using (ControlTransaction.Update(this.CurrentListView))
1524 var idx = tab.IndexOf(statusId);
1526 this.listCache?.RefreshStyle(idx);
1529 var currentPost = this.CurrentPost;
1530 if (currentPost != null && statusId == currentPost.StatusId)
1531 this.DispSelectedPost(true); // 選択アイテム再表示
1535 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
1537 await this.workerSemaphore.WaitAsync();
1541 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1543 this.RefreshTasktrayIcon();
1544 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1546 catch (WebApiException ex)
1548 this.myStatusError = true;
1549 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1553 this.workerSemaphore.Release();
1557 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
1559 if (ct.IsCancellationRequested)
1562 if (!CheckAccountValid())
1563 throw new WebApiException("Auth error. Check your account");
1565 var successIds = new List<long>();
1567 await Task.Run(async () =>
1571 var failedCount = 0;
1572 foreach (var statusId in statusIds)
1576 var post = tab.Posts[statusId];
1578 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1585 await this.tw.Api.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
1587 .ConfigureAwait(false);
1589 catch (WebApiException)
1595 successIds.Add(statusId);
1596 post.IsFav = false; // リスト再描画必要
1598 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1599 tabinfoPost.IsFav = false;
1601 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1602 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1604 if (tb.Contains(statusId))
1605 tb.Posts[statusId].IsFav = false;
1610 if (ct.IsCancellationRequested)
1613 var favTab = this.statuses.FavoriteTab;
1614 foreach (var statusId in successIds)
1616 // ツイートが削除された訳ではないので IsDeleted はセットしない
1617 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1620 this.RefreshTimeline();
1622 if (this.CurrentTabName == tab.TabName)
1624 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1630 using (ControlTransaction.Update(this.CurrentListView))
1632 foreach (var statusId in successIds)
1634 var idx = tab.IndexOf(statusId);
1636 this.listCache?.RefreshStyle(idx);
1640 var currentPost = this.CurrentPost;
1641 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1642 this.DispSelectedPost(true); // 選択アイテム再表示
1647 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1649 await this.workerSemaphore.WaitAsync();
1653 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1655 this.RefreshTasktrayIcon();
1656 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1658 catch (WebApiException ex)
1660 this.myStatusError = true;
1661 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1665 this.workerSemaphore.Release();
1669 private async Task PostMessageAsyncInternal(
1670 IProgress<string> p,
1671 CancellationToken ct,
1672 PostStatusParams postParams,
1673 IMediaUploadService? uploadService,
1674 IMediaItem[]? uploadItems)
1676 if (ct.IsCancellationRequested)
1679 if (!CheckAccountValid())
1680 throw new WebApiException("Auth error. Check your account");
1682 p.Report("Posting...");
1684 PostClass? post = null;
1689 await Task.Run(async () =>
1691 var postParamsWithMedia = postParams;
1693 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1695 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1696 .ConfigureAwait(false);
1699 post = await this.tw.PostStatus(postParamsWithMedia)
1700 .ConfigureAwait(false);
1703 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1705 catch (WebApiException ex)
1707 // 処理は中断せずエラーの表示のみ行う
1708 errMsg = $"Err:{ex.Message}(PostMessage)";
1710 this.myStatusError = true;
1712 catch (UnauthorizedAccessException ex)
1714 // アップロード対象のファイルが開けなかった場合など
1715 errMsg = $"Err:{ex.Message}(PostMessage)";
1717 this.myStatusError = true;
1721 // 使い終わった MediaItem は破棄する
1722 if (uploadItems != null)
1724 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1726 disposableItem.Dispose();
1731 if (ct.IsCancellationRequested)
1734 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1735 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1736 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1738 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1740 var ret = MessageBox.Show(
1742 "Failed to update status",
1743 MessageBoxButtons.RetryCancel,
1744 MessageBoxIcon.Question);
1746 if (ret == DialogResult.Retry)
1748 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1752 this.StatusTextHistoryBack();
1753 this.StatusText.Focus();
1755 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1756 if (this.settings.Common.FocusLockToStatusText)
1757 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1762 this.postTimestamps.Add(DateTimeUtc.Now);
1764 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1765 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1767 if (this.postTimestamps[i] < oneHour)
1768 this.postTimestamps.RemoveAt(i);
1771 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1773 this.HashMgr.ClearHashtag();
1774 this.HashStripSplitButton.Text = "#[-]";
1775 this.HashTogglePullDownMenuItem.Checked = false;
1776 this.HashToggleMenuItem.Checked = false;
1779 this.SetMainWindowTitle();
1784 this.statuses.AddPost(post);
1785 this.statuses.DistributePosts();
1786 this.RefreshTimeline();
1789 if (this.settings.Common.PostAndGet)
1790 await this.RefreshTabAsync<HomeTabModel>();
1793 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
1795 await this.workerSemaphore.WaitAsync();
1799 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1801 this.RefreshTasktrayIcon();
1802 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1804 catch (WebApiException ex)
1806 this.myStatusError = true;
1807 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1811 this.workerSemaphore.Release();
1815 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
1817 if (ct.IsCancellationRequested)
1820 if (!CheckAccountValid())
1821 throw new WebApiException("Auth error. Check your account");
1824 if (!this.settings.Common.UnreadManage)
1827 read = this.initial && this.settings.Common.Read;
1829 p.Report("Posting...");
1831 var posts = new List<PostClass>();
1833 await Task.Run(async () =>
1835 foreach (var statusId in statusIds)
1837 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1838 if (post != null) posts.Add(post);
1842 if (ct.IsCancellationRequested)
1845 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1847 this.postTimestamps.Add(DateTimeUtc.Now);
1849 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1850 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1852 if (this.postTimestamps[i] < oneHour)
1853 this.postTimestamps.RemoveAt(i);
1856 // 自分のRTはTLの更新では取得できない場合があるので、
1857 // 投稿時取得の有無に関わらず追加しておく
1858 posts.ForEach(post => this.statuses.AddPost(post));
1860 if (this.settings.Common.PostAndGet)
1862 await this.RefreshTabAsync<HomeTabModel>();
1866 this.statuses.DistributePosts();
1867 this.RefreshTimeline();
1871 private async Task RefreshFollowerIdsAsync()
1873 await this.workerSemaphore.WaitAsync();
1877 this.RefreshTasktrayIcon();
1878 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1880 await this.tw.RefreshFollowerIds();
1882 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1884 this.RefreshTimeline();
1885 this.listCache?.PurgeCache();
1886 this.CurrentListView.Refresh();
1888 catch (WebApiException ex)
1890 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1894 this.workerSemaphore.Release();
1898 private async Task RefreshNoRetweetIdsAsync()
1900 await this.workerSemaphore.WaitAsync();
1904 this.RefreshTasktrayIcon();
1905 await this.tw.RefreshNoRetweetIds();
1907 this.StatusLabel.Text = "NoRetweetIds refreshed";
1909 catch (WebApiException ex)
1911 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1915 this.workerSemaphore.Release();
1919 private async Task RefreshBlockIdsAsync()
1921 await this.workerSemaphore.WaitAsync();
1925 this.RefreshTasktrayIcon();
1926 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1928 await this.tw.RefreshBlockIds();
1930 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1932 catch (WebApiException ex)
1934 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1938 this.workerSemaphore.Release();
1942 private async Task RefreshTwitterConfigurationAsync()
1944 await this.workerSemaphore.WaitAsync();
1948 this.RefreshTasktrayIcon();
1949 await this.tw.RefreshConfiguration();
1951 if (this.tw.Configuration.PhotoSizeLimit != 0)
1953 foreach (var service in this.ImageSelector.GetServices())
1955 service.UpdateTwitterConfiguration(this.tw.Configuration);
1959 this.listCache?.PurgeCache();
1960 this.CurrentListView.Refresh();
1962 catch (WebApiException ex)
1964 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1968 this.workerSemaphore.Release();
1972 private async Task RefreshMuteUserIdsAsync()
1974 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1978 await this.tw.RefreshMuteUserIdsAsync();
1980 catch (WebApiException ex)
1982 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1986 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1989 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1991 if (e.Button == MouseButtons.Left)
1993 this.Visible = true;
1994 if (this.WindowState == FormWindowState.Minimized)
1996 this.WindowState = this.formWindowState;
1999 this.BringToFront();
2003 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2004 => await this.ListItemDoubleClickAction();
2006 private async Task ListItemDoubleClickAction()
2008 switch (this.settings.Common.ListDoubleClickAction)
2010 case MyCommon.ListItemDoubleClickActionType.Reply:
2011 this.MakeReplyText();
2013 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2014 this.MakeReplyText(atAll: true);
2016 case MyCommon.ListItemDoubleClickActionType.Favorite:
2017 await this.FavoriteChange(true);
2019 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2020 var post = this.CurrentPost;
2022 await this.ShowUserStatus(post.ScreenName, false);
2024 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2025 await this.ShowUserTimeline();
2027 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2028 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2030 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2031 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2033 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2034 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2036 case MyCommon.ListItemDoubleClickActionType.None:
2043 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2044 => await this.FavoriteChange(true);
2046 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2047 => await this.FavoriteChange(false);
2049 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2050 => await this.FavoritesRetweetOfficial();
2052 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2053 => await this.FavoritesRetweetUnofficial();
2055 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2057 var tab = this.CurrentTab;
2058 var posts = tab.SelectedPosts;
2060 // trueでFavAdd,falseでFavRemove
2061 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2062 || !this.ExistCurrentPost) return;
2064 if (posts.Length > 1)
2069 // https://support.twitter.com/articles/76915#favoriting
2070 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2071 this.doFavRetweetFlags = false;
2076 if (multiFavoriteChangeDialogEnable)
2078 var confirm = MessageBox.Show(
2079 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2080 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2081 MessageBoxButtons.OKCancel,
2082 MessageBoxIcon.Question);
2084 if (confirm == DialogResult.Cancel)
2092 var selectedPost = posts.Single();
2093 if (selectedPost.IsFav)
2095 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2099 await this.FavAddAsync(selectedPost.StatusId, tab);
2103 var selectedPosts = posts.Where(x => x.IsFav);
2104 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2105 if (statusIds.Length == 0)
2107 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2111 await this.FavRemoveAsync(statusIds, tab);
2115 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2117 var post = this.CurrentPost;
2119 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2121 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2124 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2126 if ((!this.initialLayout) && this.Visible)
2128 if (this.WindowState == FormWindowState.Normal)
2130 this.mySize = this.ClientSize;
2131 this.mySpDis = this.SplitContainer1.SplitterDistance;
2132 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2133 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2134 this.MarkSettingLocalModified();
2139 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2141 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2142 if (comparerMode == null)
2145 this.SetSortColumn(comparerMode.Value);
2149 /// 列インデックスからソートを行う ComparerMode を求める
2151 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2152 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2153 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2155 if (this.Use2ColumnsMode)
2156 return ComparerMode.Id;
2158 return columnIndex switch
2160 1 => ComparerMode.Nickname, // ニックネーム
2161 2 => ComparerMode.Data, // 本文
2162 3 => ComparerMode.Id, // 時刻=発言Id
2163 4 => ComparerMode.Name, // 名前
2164 7 => ComparerMode.Source, // Source
2165 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2170 /// 発言一覧の指定した位置の列でソートする
2172 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2173 private void SetSortColumnByDisplayIndex(int columnIndex)
2175 // 表示上の列の位置から ColumnHeader を求める
2176 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2177 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2182 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2183 if (comparerMode == null)
2186 this.SetSortColumn(comparerMode.Value);
2190 /// 発言一覧の最後列の項目でソートする
2192 private void SetSortLastColumn()
2194 // 表示上の最後列にある ColumnHeader を求める
2195 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2196 .OrderByDescending(x => x.DisplayIndex)
2199 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2200 if (comparerMode == null)
2203 this.SetSortColumn(comparerMode.Value);
2207 /// 発言一覧を指定された ComparerMode に基づいてソートする
2209 private void SetSortColumn(ComparerMode sortColumn)
2211 if (this.settings.Common.SortOrderLock)
2214 this.statuses.ToggleSortOrder(sortColumn);
2215 this.InitColumnText();
2217 var list = this.CurrentListView;
2218 if (this.Use2ColumnsMode)
2220 list.Columns[0].Text = this.columnText[0];
2221 list.Columns[1].Text = this.columnText[2];
2225 for (var i = 0; i <= 7; i++)
2227 list.Columns[i].Text = this.columnText[i];
2231 this.listCache?.PurgeCache();
2233 var tab = this.CurrentTab;
2234 var post = this.CurrentPost;
2235 if (tab.AllCount > 0 && post != null)
2237 var idx = tab.IndexOf(post.StatusId);
2240 this.SelectListItem(list, idx);
2241 list.EnsureVisible(idx);
2246 this.MarkSettingCommonModified();
2249 private void TweenMain_LocationChanged(object sender, EventArgs e)
2251 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2253 this.myLoc = this.DesktopLocation;
2254 this.MarkSettingLocalModified();
2258 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2260 var post = this.CurrentPost;
2261 if (!this.ExistCurrentPost)
2263 this.ReplyStripMenuItem.Enabled = false;
2264 this.ReplyAllStripMenuItem.Enabled = false;
2265 this.DMStripMenuItem.Enabled = false;
2266 this.TabMenuItem.Enabled = false;
2267 this.IDRuleMenuItem.Enabled = false;
2268 this.SourceRuleMenuItem.Enabled = false;
2269 this.ReadedStripMenuItem.Enabled = false;
2270 this.UnreadStripMenuItem.Enabled = false;
2271 this.AuthorContextMenuItem.Visible = false;
2272 this.RetweetedByContextMenuItem.Visible = false;
2276 this.ReplyStripMenuItem.Enabled = true;
2277 this.ReplyAllStripMenuItem.Enabled = true;
2278 this.DMStripMenuItem.Enabled = true;
2279 this.TabMenuItem.Enabled = true;
2280 this.IDRuleMenuItem.Enabled = true;
2281 this.SourceRuleMenuItem.Enabled = true;
2282 this.ReadedStripMenuItem.Enabled = true;
2283 this.UnreadStripMenuItem.Enabled = true;
2284 this.AuthorContextMenuItem.Visible = true;
2285 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2286 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2287 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2289 var tab = this.CurrentTab;
2290 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2292 this.FavAddToolStripMenuItem.Enabled = false;
2293 this.FavRemoveToolStripMenuItem.Enabled = false;
2294 this.StatusOpenMenuItem.Enabled = false;
2295 this.ShowRelatedStatusesMenuItem.Enabled = false;
2297 this.ReTweetStripMenuItem.Enabled = false;
2298 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2299 this.QuoteStripMenuItem.Enabled = false;
2300 this.FavoriteRetweetContextMenu.Enabled = false;
2301 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2305 this.FavAddToolStripMenuItem.Enabled = true;
2306 this.FavRemoveToolStripMenuItem.Enabled = true;
2307 this.StatusOpenMenuItem.Enabled = true;
2308 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2310 if (!post.CanRetweetBy(this.tw.UserId))
2312 this.ReTweetStripMenuItem.Enabled = false;
2313 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2314 this.QuoteStripMenuItem.Enabled = false;
2315 this.FavoriteRetweetContextMenu.Enabled = false;
2316 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2320 this.ReTweetStripMenuItem.Enabled = true;
2321 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2322 this.QuoteStripMenuItem.Enabled = true;
2323 this.FavoriteRetweetContextMenu.Enabled = true;
2324 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2328 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2330 this.RepliedStatusOpenMenuItem.Enabled = false;
2334 this.RepliedStatusOpenMenuItem.Enabled = true;
2337 if (this.ExistCurrentPost && post != null)
2339 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2340 if (post.RetweetedByUserId == this.tw.UserId)
2341 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2343 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2347 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2348 => this.MakeReplyText();
2350 private void DMStripMenuItem_Click(object sender, EventArgs e)
2351 => this.MakeDirectMessageText();
2353 private async Task DoStatusDelete()
2355 var posts = this.CurrentTab.SelectedPosts;
2356 if (posts.Length == 0)
2359 // 選択されたツイートの中に削除可能なものが一つでもあるか
2360 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2363 var ret = MessageBox.Show(
2365 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2366 Properties.Resources.DeleteStripMenuItem_ClickText2,
2367 MessageBoxButtons.OKCancel,
2368 MessageBoxIcon.Question);
2370 if (ret != DialogResult.OK)
2373 var currentListView = this.CurrentListView;
2374 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2376 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2378 Exception? lastException = null;
2379 foreach (var post in posts)
2381 if (!post.CanDeleteBy(this.tw.UserId))
2388 await this.tw.Api.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
2392 if (post.RetweetedByUserId == this.tw.UserId)
2394 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2396 await this.tw.Api.StatusesDestroy(post.StatusId)
2401 if (post.UserId == this.tw.UserId)
2403 if (post.RetweetedId != null)
2405 // 他人に RT された自分のツイート
2406 // => RT 元の自分のツイートを削除
2407 await this.tw.Api.StatusesDestroy(post.RetweetedId.Value)
2414 await this.tw.Api.StatusesDestroy(post.StatusId)
2421 catch (WebApiException ex)
2427 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2430 if (lastException == null)
2431 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2433 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2435 using (ControlTransaction.Update(currentListView))
2437 this.listCache?.PurgeCache();
2438 this.listCache?.UpdateListSize();
2440 currentListView.SelectedIndices.Clear();
2442 var currentTab = this.CurrentTab;
2443 if (currentTab.AllCount != 0)
2446 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2447 selectedIndex = focusedIndex;
2449 selectedIndex = currentTab.AllCount - 1;
2451 currentListView.SelectedIndices.Add(selectedIndex);
2452 currentListView.EnsureVisible(selectedIndex);
2453 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2457 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2459 var tabPage = this.ListTab.TabPages[index];
2460 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2462 if (tabPage.ImageIndex == 0)
2463 tabPage.ImageIndex = -1; // タブアイコン
2467 if (!this.settings.Common.TabIconDisp)
2468 this.ListTab.Refresh();
2472 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2473 => await this.DoStatusDelete();
2475 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2477 using (ControlTransaction.Update(this.CurrentListView))
2479 var tab = this.CurrentTab;
2480 foreach (var statusId in tab.SelectedStatusIds)
2482 this.statuses.SetReadAllTab(statusId, read: true);
2483 var idx = tab.IndexOf(statusId);
2484 this.listCache?.RefreshStyle(idx);
2487 if (this.settings.Common.TabIconDisp)
2489 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2491 if (tab.UnreadCount == 0)
2493 var tabPage = this.ListTab.TabPages[index];
2494 if (tabPage.ImageIndex == 0)
2495 tabPage.ImageIndex = -1; // タブアイコン
2499 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2502 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2504 using (ControlTransaction.Update(this.CurrentListView))
2506 var tab = this.CurrentTab;
2507 foreach (var statusId in tab.SelectedStatusIds)
2509 this.statuses.SetReadAllTab(statusId, read: false);
2510 var idx = tab.IndexOf(statusId);
2511 this.listCache?.RefreshStyle(idx);
2514 if (this.settings.Common.TabIconDisp)
2516 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2518 if (tab.UnreadCount > 0)
2520 var tabPage = this.ListTab.TabPages[index];
2521 if (tabPage.ImageIndex == -1)
2522 tabPage.ImageIndex = 0; // タブアイコン
2526 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2529 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2530 => await this.DoRefresh();
2532 private async Task DoRefresh()
2533 => await this.RefreshTabAsync(this.CurrentTab);
2535 private async Task DoRefreshMore()
2536 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2538 private DialogResult ShowSettingDialog()
2540 using var settingDialog = new AppendSettingDialog();
2541 settingDialog.Icon = this.iconAssets.IconMain;
2542 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2544 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2546 DialogResult result;
2549 result = settingDialog.ShowDialog(this);
2553 return DialogResult.Abort;
2556 if (result == DialogResult.OK)
2558 lock (this.syncObject)
2560 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2567 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2570 var previousUserId = this.settings.Common.UserId;
2571 var oldIconCol = this.Use2ColumnsMode;
2573 if (this.ShowSettingDialog() == DialogResult.OK)
2575 lock (this.syncObject)
2577 this.settings.ApplySettings();
2579 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2580 this.tw.ClearAuthInfo();
2582 this.tw.Initialize(this.settings.Common.Token, this.settings.Common.TokenSecret, this.settings.Common.UserName, this.settings.Common.UserId);
2583 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2584 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2586 this.ImageSelector.Reset(this.tw, this.tw.Configuration);
2590 if (this.settings.Common.TabIconDisp)
2592 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2593 this.ListTab.DrawMode = TabDrawMode.Normal;
2594 this.ListTab.ImageList = this.TabImage;
2598 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2599 this.ListTab.DrawItem += this.ListTab_DrawItem;
2600 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2601 this.ListTab.ImageList = null;
2604 catch (Exception ex)
2606 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2607 ex.Data["IsTerminatePermission"] = false;
2613 if (!this.settings.Common.UnreadManage)
2615 this.ReadedStripMenuItem.Enabled = false;
2616 this.UnreadStripMenuItem.Enabled = false;
2617 if (this.settings.Common.TabIconDisp)
2619 foreach (TabPage myTab in this.ListTab.TabPages)
2621 myTab.ImageIndex = -1;
2627 this.ReadedStripMenuItem.Enabled = true;
2628 this.UnreadStripMenuItem.Enabled = true;
2631 catch (Exception ex)
2633 ex.Data["Instance"] = "ListTab(UnreadManage)";
2634 ex.Data["IsTerminatePermission"] = false;
2639 this.SetTabAlignment();
2641 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2643 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2644 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2645 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2647 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2648 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2649 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2650 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2652 var newTheme = new ThemeManager(this.settings.Local);
2653 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2654 this.tweetDetailsView.Theme = this.themeManager;
2655 if (this.listDrawer != null)
2656 this.listDrawer.Theme = this.themeManager;
2661 if (this.StatusText.Focused)
2662 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2664 this.StatusText.Font = this.themeManager.FontInputFont;
2665 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2667 catch (Exception ex)
2669 MessageBox.Show(ex.Message);
2674 this.InitDetailHtmlFormat();
2676 catch (Exception ex)
2678 ex.Data["Instance"] = "Font";
2679 ex.Data["IsTerminatePermission"] = false;
2685 if (this.settings.Common.TabIconDisp)
2687 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2689 var tabPage = this.ListTab.TabPages[index];
2690 if (tab.UnreadCount == 0)
2691 tabPage.ImageIndex = -1;
2693 tabPage.ImageIndex = 0;
2697 catch (Exception ex)
2699 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2700 ex.Data["IsTerminatePermission"] = false;
2706 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2708 foreach (TabPage tp in this.ListTab.TabPages)
2710 var lst = (DetailsListView)tp.Tag;
2712 using (ControlTransaction.Update(lst))
2714 lst.GridLines = this.settings.Common.ShowGrid;
2716 if (this.Use2ColumnsMode != oldIconCol)
2717 this.ResetColumns(lst);
2721 catch (Exception ex)
2723 ex.Data["Instance"] = "ListView(IconSize)";
2724 ex.Data["IsTerminatePermission"] = false;
2728 this.SetMainWindowTitle();
2729 this.SetNotifyIconText();
2731 this.listCache?.PurgeCache();
2732 this.CurrentListView.Refresh();
2733 this.ListTab.Refresh();
2735 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2736 if (this.settings.Common.HotkeyEnabled)
2738 // グローバルホットキーの登録。設定で変更可能にするかも
2739 var modKey = HookGlobalHotkey.ModKeys.None;
2740 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2741 modKey |= HookGlobalHotkey.ModKeys.Alt;
2742 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2743 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2744 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2745 modKey |= HookGlobalHotkey.ModKeys.Shift;
2746 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2747 modKey |= HookGlobalHotkey.ModKeys.Win;
2749 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2752 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2755 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2763 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2765 this.TopMost = this.settings.Common.AlwaysTop;
2766 this.SaveConfigsAll(false);
2768 if (this.tw.UserId != previousUserId)
2769 await this.DoGetFollowersMenu();
2775 private void SetTabAlignment()
2777 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2778 if (this.ListTab.Alignment == newAlignment) return;
2781 var currentListViewState = this.listViewState[this.CurrentTabName];
2782 currentListViewState.Save(this.ListLockMenuItem.Checked);
2784 this.ListTab.Alignment = newAlignment;
2786 currentListViewState.Restore();
2789 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2792 if (this.listDrawer != null)
2793 this.listDrawer.IconSize = iconSz;
2795 this.listCache?.PurgeCache();
2798 private void ResetColumns(DetailsListView list)
2800 using (ControlTransaction.Update(list))
2801 using (ControlTransaction.Layout(list, false))
2804 list.ColumnClick -= this.MyList_ColumnClick;
2805 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2806 list.ColumnReordered -= this.MyList_ColumnReordered;
2807 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2809 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2810 list.Columns.Clear();
2811 cols.ForEach(col => col.Dispose());
2814 this.InitColumns(list, true);
2816 list.ColumnClick += this.MyList_ColumnClick;
2817 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2818 list.ColumnReordered += this.MyList_ColumnReordered;
2819 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2823 public void AddNewTabForSearch(string searchWord)
2825 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2826 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2828 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2830 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2831 this.ListTab.SelectedIndex = tabIndex;
2836 var tabName = searchWord;
2837 for (var i = 0; i <= 100; i++)
2839 if (this.statuses.ContainsTab(tabName))
2845 var tab = new PublicSearchTabModel(tabName);
2846 this.statuses.AddTab(tab);
2847 this.AddNewTab(tab, startup: false);
2849 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2851 var tabPage = this.CurrentTabPage;
2852 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2853 cmb.Items.Add(searchWord);
2854 cmb.Text = searchWord;
2855 this.SaveConfigsTabs();
2857 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2860 private async Task ShowUserTimeline()
2862 var post = this.CurrentPost;
2863 if (post == null || !this.ExistCurrentPost) return;
2864 await this.AddNewTabForUserTimeline(post.ScreenName);
2867 private async Task ShowRetweeterTimeline()
2869 var retweetedBy = this.CurrentPost?.RetweetedBy;
2870 if (retweetedBy == null || !this.ExistCurrentPost) return;
2871 await this.AddNewTabForUserTimeline(retweetedBy);
2874 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2876 if (e.KeyCode == Keys.Escape)
2878 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2879 this.SaveConfigsTabs();
2880 e.SuppressKeyPress = true;
2884 public async Task AddNewTabForUserTimeline(string user)
2886 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2887 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2889 if (tb.ScreenName == user)
2891 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2892 this.ListTab.SelectedIndex = tabIndex;
2897 var tabName = "user:" + user;
2898 while (this.statuses.ContainsTab(tabName))
2903 var tab = new UserTimelineTabModel(tabName, user);
2904 this.statuses.AddTab(tab);
2905 this.AddNewTab(tab, startup: false);
2907 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2908 this.SaveConfigsTabs();
2910 await this.RefreshTabAsync(tab);
2913 public bool AddNewTab(TabModel tab, bool startup)
2916 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2920 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2922 var tabPage = new TabPage();
2923 var listCustom = new DetailsListView();
2925 var cnt = this.statuses.Tabs.Count;
2927 // ToDo:Create and set controls follow tabtypes
2929 using (ControlTransaction.Update(listCustom))
2930 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2931 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2932 using (ControlTransaction.Layout(this.SplitContainer1, false))
2933 using (ControlTransaction.Layout(this.ListTab, false))
2934 using (ControlTransaction.Layout(this))
2935 using (ControlTransaction.Layout(tabPage, false))
2937 tabPage.Controls.Add(listCustom);
2940 var userTab = tab as UserTimelineTabModel;
2941 var listTab = tab as ListTimelineTabModel;
2942 var searchTab = tab as PublicSearchTabModel;
2944 if (userTab != null || listTab != null)
2946 var label = new Label
2948 Dock = DockStyle.Top,
2953 if (listTab != null)
2955 label.Text = listTab.ListInfo.ToString();
2957 else if (userTab != null)
2959 label.Text = userTab.ScreenName + "'s Timeline";
2961 label.TextAlign = ContentAlignment.MiddleLeft;
2962 using (var tmpComboBox = new ComboBox())
2964 label.Height = tmpComboBox.Height;
2966 tabPage.Controls.Add(label);
2969 else if (searchTab != null)
2971 var pnl = new Panel();
2973 var lbl = new Label();
2974 var cmb = new ComboBox();
2975 var btn = new Button();
2976 var cmbLang = new ComboBox();
2978 using (ControlTransaction.Layout(pnl, false))
2980 pnl.Controls.Add(cmb);
2981 pnl.Controls.Add(cmbLang);
2982 pnl.Controls.Add(btn);
2983 pnl.Controls.Add(lbl);
2984 pnl.Name = "panelSearch";
2986 pnl.Dock = DockStyle.Top;
2987 pnl.Height = cmb.Height;
2988 pnl.Enter += this.SearchControls_Enter;
2989 pnl.Leave += this.SearchControls_Leave;
2992 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2993 cmb.Dock = DockStyle.Fill;
2994 cmb.Name = "comboSearch";
2995 cmb.DropDownStyle = ComboBoxStyle.DropDown;
2996 cmb.ImeMode = ImeMode.NoControl;
2997 cmb.TabStop = false;
2999 cmb.AutoCompleteMode = AutoCompleteMode.None;
3000 cmb.KeyDown += this.SearchComboBox_KeyDown;
3003 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3004 cmbLang.Dock = DockStyle.Right;
3006 cmbLang.Name = "comboLang";
3007 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3008 cmbLang.TabStop = false;
3009 cmbLang.TabIndex = 2;
3010 cmbLang.Items.Add("");
3011 cmbLang.Items.Add("ja");
3012 cmbLang.Items.Add("en");
3013 cmbLang.Items.Add("ar");
3014 cmbLang.Items.Add("da");
3015 cmbLang.Items.Add("nl");
3016 cmbLang.Items.Add("fa");
3017 cmbLang.Items.Add("fi");
3018 cmbLang.Items.Add("fr");
3019 cmbLang.Items.Add("de");
3020 cmbLang.Items.Add("hu");
3021 cmbLang.Items.Add("is");
3022 cmbLang.Items.Add("it");
3023 cmbLang.Items.Add("no");
3024 cmbLang.Items.Add("pl");
3025 cmbLang.Items.Add("pt");
3026 cmbLang.Items.Add("ru");
3027 cmbLang.Items.Add("es");
3028 cmbLang.Items.Add("sv");
3029 cmbLang.Items.Add("th");
3031 lbl.Text = "Search(C-S-f)";
3032 lbl.Name = "label1";
3033 lbl.Dock = DockStyle.Left;
3035 lbl.Height = cmb.Height;
3036 lbl.TextAlign = ContentAlignment.MiddleLeft;
3039 btn.Text = "Search";
3040 btn.Name = "buttonSearch";
3041 btn.UseVisualStyleBackColor = true;
3042 btn.Dock = DockStyle.Right;
3043 btn.TabStop = false;
3045 btn.Click += this.SearchButton_Click;
3047 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3049 cmb.Items.Add(searchTab.SearchWords);
3050 cmb.Text = searchTab.SearchWords;
3053 cmbLang.Text = searchTab.SearchLang;
3055 tabPage.Controls.Add(pnl);
3059 tabPage.Tag = listCustom;
3060 this.ListTab.Controls.Add(tabPage);
3062 tabPage.Location = new Point(4, 4);
3063 tabPage.Name = "CTab" + cnt;
3064 tabPage.Size = new Size(380, 260);
3065 tabPage.TabIndex = 2 + cnt;
3066 tabPage.Text = tab.TabName;
3067 tabPage.UseVisualStyleBackColor = true;
3068 tabPage.AccessibleRole = AccessibleRole.PageTab;
3070 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3071 listCustom.TabIndex = 1;
3072 listCustom.AllowColumnReorder = true;
3073 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3074 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3075 listCustom.Dock = DockStyle.Fill;
3076 listCustom.FullRowSelect = true;
3077 listCustom.HideSelection = false;
3078 listCustom.Location = new Point(0, 0);
3079 listCustom.Margin = new Padding(0);
3080 listCustom.Name = "CList" + Environment.TickCount;
3081 listCustom.ShowItemToolTips = true;
3082 listCustom.Size = new Size(380, 260);
3083 listCustom.UseCompatibleStateImageBehavior = false;
3084 listCustom.View = View.Details;
3085 listCustom.OwnerDraw = true;
3086 listCustom.VirtualMode = true;
3088 listCustom.GridLines = this.settings.Common.ShowGrid;
3089 listCustom.AllowDrop = true;
3091 this.InitColumns(listCustom, startup);
3093 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3094 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3095 listCustom.ColumnClick += this.MyList_ColumnClick;
3096 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3097 listCustom.DragDrop += this.TweenMain_DragDrop;
3098 listCustom.DragEnter += this.TweenMain_DragEnter;
3099 listCustom.DragOver += this.TweenMain_DragOver;
3100 listCustom.MouseClick += this.MyList_MouseClick;
3101 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3102 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3103 listCustom.HScrolled += this.MyList_HScrolled;
3106 var state = new TimelineListViewState(listCustom, tab);
3107 this.listViewState[tab.TabName] = state;
3112 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3114 var tabInfo = this.statuses.GetTabByName(tabName);
3115 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3120 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3121 var result = MessageBox.Show(
3123 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3124 MessageBoxButtons.OKCancel,
3125 MessageBoxIcon.Question,
3126 MessageBoxDefaultButton.Button2);
3127 if (result == DialogResult.Cancel)
3133 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3137 var tabPage = this.ListTab.TabPages[tabIndex];
3139 this.SetListProperty(); // 他のタブに列幅等を反映
3141 this.listViewState.Remove(tabName);
3144 var listCustom = (DetailsListView)tabPage.Tag;
3147 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3148 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3149 using (ControlTransaction.Layout(this.SplitContainer1, false))
3150 using (ControlTransaction.Layout(this.ListTab, false))
3151 using (ControlTransaction.Layout(this))
3152 using (ControlTransaction.Layout(tabPage, false))
3154 if (this.CurrentTabName == tabName)
3156 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3157 this.beforeSelectedTab = null;
3159 this.ListTab.Controls.Remove(tabPage);
3162 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3164 using var label = tabPage.Controls["labelUser"];
3165 tabPage.Controls.Remove(label);
3167 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3169 using var pnl = tabPage.Controls["panelSearch"];
3171 pnl.Enter -= this.SearchControls_Enter;
3172 pnl.Leave -= this.SearchControls_Leave;
3173 tabPage.Controls.Remove(pnl);
3175 foreach (Control ctrl in pnl.Controls)
3177 if (ctrl.Name == "buttonSearch")
3179 ctrl.Click -= this.SearchButton_Click;
3181 else if (ctrl.Name == "comboSearch")
3183 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3185 pnl.Controls.Remove(ctrl);
3190 tabPage.Controls.Remove(listCustom);
3192 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3193 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3194 listCustom.ColumnClick -= this.MyList_ColumnClick;
3195 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3196 listCustom.DragDrop -= this.TweenMain_DragDrop;
3197 listCustom.DragEnter -= this.TweenMain_DragEnter;
3198 listCustom.DragOver -= this.TweenMain_DragOver;
3199 listCustom.MouseClick -= this.MyList_MouseClick;
3200 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3201 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3202 listCustom.HScrolled -= this.MyList_HScrolled;
3204 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3205 listCustom.Columns.Clear();
3206 cols.ForEach(col => col.Dispose());
3209 listCustom.ContextMenuStrip = null;
3210 listCustom.ColumnHeaderContextMenuStrip = null;
3211 listCustom.Font = null;
3213 listCustom.SmallImageList = null;
3214 listCustom.ListViewItemSorter = null;
3217 this.listCache?.PurgeCache();
3221 listCustom.Dispose();
3222 this.statuses.RemoveTab(tabName);
3227 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3229 this.listCache?.PurgeCache();
3230 this.beforeSelectedTab = e.TabPage;
3233 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3237 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3240 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3241 if (!dragEnableRectangle.Contains(e.Location))
3243 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3244 tn = this.CurrentTabName;
3247 if (MyCommon.IsNullOrEmpty(tn)) return;
3249 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3252 var tabPage = this.ListTab.TabPages[tabIndex];
3253 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3258 this.tabDrag = false;
3261 var cpos = new Point(e.X, e.Y);
3262 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3264 var rect = this.ListTab.GetTabRect(index);
3265 if (rect.Contains(cpos))
3267 this.rclickTabName = tab.TabName;
3273 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3275 this.SetMainWindowTitle();
3276 this.SetStatusLabelUrl();
3277 this.SetApiStatusLabel();
3278 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3279 this.Tag = this.ListTab.Tag;
3280 this.TabMenuControl(this.CurrentTabName);
3281 this.PushSelectPostChain();
3282 this.DispSelectedPost();
3285 private void SetListProperty()
3287 if (!this.isColumnChanged) return;
3289 var currentListView = this.CurrentListView;
3291 var dispOrder = new int[currentListView.Columns.Count];
3292 for (var i = 0; i < currentListView.Columns.Count; i++)
3294 for (var j = 0; j < currentListView.Columns.Count; j++)
3296 if (currentListView.Columns[j].DisplayIndex == i)
3305 foreach (TabPage tb in this.ListTab.TabPages)
3307 if (tb.Text == this.CurrentTabName)
3310 if (tb.Tag != null && tb.Controls.Count > 0)
3312 var lst = (DetailsListView)tb.Tag;
3313 for (var i = 0; i < lst.Columns.Count; i++)
3315 lst.Columns[dispOrder[i]].DisplayIndex = i;
3316 lst.Columns[i].Width = currentListView.Columns[i].Width;
3321 this.isColumnChanged = false;
3324 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3326 if (e.KeyChar == '@')
3328 if (!this.settings.Common.UseAtIdSupplement) return;
3330 var cnt = this.AtIdSupl.ItemCount;
3331 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3332 if (cnt != this.AtIdSupl.ItemCount)
3333 this.MarkSettingAtIdModified();
3336 else if (e.KeyChar == '#')
3338 if (!this.settings.Common.UseHashSupplement) return;
3339 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3344 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3345 => this.ShowSuplDialog(owner, dialog, 0, "");
3347 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3348 => this.ShowSuplDialog(owner, dialog, offset, "");
3350 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3352 dialog.StartsWith = startswith;
3359 dialog.ShowDialog();
3361 this.TopMost = this.settings.Common.AlwaysTop;
3362 var selStart = owner.SelectionStart;
3365 if (dialog.DialogResult == DialogResult.OK)
3367 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3371 fHalf = owner.Text.Substring(0, selStart - offset);
3373 if (selStart < owner.Text.Length)
3375 eHalf = owner.Text.Substring(selStart);
3377 owner.Text = fHalf + dialog.InputText + eHalf;
3378 owner.SelectionStart = selStart + dialog.InputText.Length;
3385 fHalf = owner.Text.Substring(0, selStart);
3387 if (selStart < owner.Text.Length)
3389 eHalf = owner.Text.Substring(selStart);
3391 owner.Text = fHalf + eHalf;
3394 owner.SelectionStart = selStart;
3400 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3403 if (!e.Alt && !e.Control && !e.Shift)
3405 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3407 var isSpace = false;
3408 foreach (var c in this.StatusText.Text)
3410 if (c == ' ' || c == ' ')
3423 this.StatusText.Text = "";
3424 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3428 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3431 private void StatusText_TextChanged(object sender, EventArgs e)
3434 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3435 this.lblLen.Text = pLen.ToString();
3438 this.StatusText.ForeColor = Color.Red;
3442 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3445 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3447 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3449 this.inReplyTo = null;
3454 /// メンション以外の文字列が含まれていないテキストであるか判定します
3456 internal static bool TextContainsOnlyMentions(string text)
3458 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3461 foreach (var mention in mentions)
3463 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3465 if (!string.IsNullOrWhiteSpace(textPart))
3468 startIndex = mention.Indices[1];
3471 var textPartLast = text.Substring(startIndex);
3473 if (!string.IsNullOrWhiteSpace(textPartLast))
3480 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3482 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3484 var autoPopulatedUserIdList = new List<long>();
3486 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3487 if (replyToPost != null)
3489 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3491 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3492 autoPopulatedUserIdList.Add(replyToPost.UserId);
3494 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3496 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3498 statusText = statusText.Substring(screenName.Length + 2);
3499 autoPopulatedUserIdList.Add(userId);
3505 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3511 /// attachment_url に指定可能な URL が含まれていれば除去
3513 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3515 attachmentUrl = null;
3517 // attachment_url は media_id と同時に使用できない
3518 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
3521 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3525 attachmentUrl = match.Value;
3528 statusText = statusText.Substring(0, match.Index);
3530 // テキストと URL の間にスペースが含まれていれば除去
3531 return statusText.TrimEnd(' ');
3534 private string FormatStatusTextExtended(string statusText)
3535 => this.FormatStatusTextExtended(statusText, out _, out _);
3538 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3540 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3542 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3544 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3546 return this.FormatStatusText(statusText);
3550 /// ツイート投稿前のフッター付与などの前処理を行います
3552 private string FormatStatusText(string statusText)
3554 statusText = statusText.Replace("\r\n", "\n");
3556 if (this.urlMultibyteSplit)
3559 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3562 if (this.settings.Common.WideSpaceConvert)
3564 // 文中の全角スペースを半角スペース1個にする
3565 statusText = statusText.Replace(" ", " ");
3568 // DM の場合はこれ以降の処理を行わない
3569 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3573 if (this.settings.Common.PostShiftEnter)
3575 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3579 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3580 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3582 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3585 if (statusText.Contains("RT @"))
3586 disableFooter = true;
3588 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3589 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3591 var mentionSelf = $"@{this.tw.Username} ";
3592 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3594 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3595 statusText = statusText.Substring(mentionSelf.Length);
3602 var hashtag = this.HashMgr.UseHash;
3603 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3605 if (this.HashMgr.IsHead)
3606 header = this.HashMgr.UseHash + " ";
3608 footer = " " + this.HashMgr.UseHash;
3613 if (this.settings.Local.UseRecommendStatus)
3616 footer += this.recommendedStatusFooter;
3618 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3620 // テキストボックスに入力されている文字列を使用する
3621 footer += " " + this.settings.Local.StatusText.Trim();
3625 statusText = header + statusText + footer;
3627 if (this.preventSmsCommand)
3629 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3630 // 参照: https://support.twitter.com/articles/14020
3632 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3633 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3635 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3636 statusText = '\u200b' + statusText;
3644 /// 投稿欄に表示する入力可能な文字数を計算します
3646 private int GetRestStatusCount(string statusText)
3648 var remainCount = this.tw.GetTextLengthRemain(statusText);
3650 var uploadService = this.GetSelectedImageService();
3651 if (uploadService != null)
3653 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3654 remainCount -= uploadService.GetReservedTextLength(1);
3660 private IMediaUploadService? GetSelectedImageService()
3661 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
3664 /// 全てのタブの振り分けルールを反映し直します
3666 private void ApplyPostFilters()
3668 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3670 this.statuses.FilterAll();
3672 var listView = this.CurrentListView;
3673 using (ControlTransaction.Update(listView))
3675 this.listCache?.PurgeCache();
3676 this.listCache?.UpdateListSize();
3679 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3681 var tabPage = this.ListTab.TabPages[index];
3683 if (this.settings.Common.TabIconDisp)
3685 if (tab.UnreadCount > 0)
3686 tabPage.ImageIndex = 0;
3688 tabPage.ImageIndex = -1;
3692 if (!this.settings.Common.TabIconDisp)
3693 this.ListTab.Refresh();
3695 this.SetMainWindowTitle();
3696 this.SetStatusLabelUrl();
3700 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3701 => e.DrawDefault = true;
3703 private void MyList_HScrolled(object sender, EventArgs e)
3704 => ((DetailsListView)sender).Refresh();
3706 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3708 base.ScaleControl(factor, specified);
3710 ScaleChildControl(this.TabImage, factor);
3712 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3713 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3715 foreach (var listview in listviews)
3717 ScaleChildControl(listview, factor);
3721 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3723 var tab = this.CurrentTab;
3725 if (tab.AllCount == 0)
3727 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3731 var selectedIndex = tab.SelectedIndex;
3736 case SEARCHTYPE.NextSearch: // 次を検索
3737 if (selectedIndex != -1)
3738 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3742 case SEARCHTYPE.PrevSearch: // 前を検索
3743 if (selectedIndex != -1)
3744 startIndex = Math.Max(selectedIndex - 1, 0);
3746 startIndex = tab.AllCount - 1;
3748 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3750 if (selectedIndex != -1)
3751 startIndex = selectedIndex;
3757 Func<string, bool> stringComparer;
3760 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3762 catch (ArgumentException)
3764 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3768 var reverse = searchType == SEARCHTYPE.PrevSearch;
3769 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3770 .DefaultIfEmpty(-1).First();
3772 if (foundIndex == -1)
3774 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3778 var listView = this.CurrentListView;
3779 this.SelectListItem(listView, foundIndex);
3780 listView.EnsureVisible(foundIndex);
3783 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3784 => this.ShowSearchDialog(); // 検索メニュー
3786 private void MenuItemSearchNext_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.NextSearch);
3804 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3806 var previousSearch = this.SearchDialog.ResultOptions;
3807 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3809 this.SearchDialog.Reset();
3810 this.ShowSearchDialog();
3816 previousSearch.Query,
3817 previousSearch.CaseSensitive,
3818 previousSearch.UseRegex,
3819 SEARCHTYPE.PrevSearch);
3823 /// 検索ダイアログを表示し、検索を実行します
3825 private void ShowSearchDialog()
3827 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3829 this.TopMost = this.settings.Common.AlwaysTop;
3832 this.TopMost = this.settings.Common.AlwaysTop;
3834 var searchOptions = this.SearchDialog.ResultOptions!;
3835 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3837 if (searchOptions.NewTab)
3839 var tabName = Properties.Resources.SearchResults_TabName;
3843 tabName = this.statuses.MakeTabName(tabName);
3845 catch (TabException ex)
3847 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3850 var resultTab = new LocalSearchTabModel(tabName);
3851 this.AddNewTab(resultTab, startup: false);
3852 this.statuses.AddTab(resultTab);
3854 var targetTab = this.CurrentTab;
3856 Func<string, bool> stringComparer;
3859 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3861 catch (ArgumentException)
3863 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3867 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3868 if (foundIndices.Length == 0)
3870 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3874 var foundPosts = foundIndices.Select(x => targetTab[x]);
3875 foreach (var post in foundPosts)
3877 resultTab.AddPostQueue(post);
3880 this.statuses.DistributePosts();
3881 this.RefreshTimeline();
3883 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3884 this.ListTab.SelectedIndex = tabIndex;
3889 searchOptions.Query,
3890 searchOptions.CaseSensitive,
3891 searchOptions.UseRegex,
3892 SEARCHTYPE.DialogSearch);
3895 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3897 this.AddNewTabForSearch(searchOptions.Query);
3901 /// <summary>発言検索に使用するメソッドを生成します</summary>
3902 /// <exception cref="ArgumentException">
3903 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3905 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3909 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3910 var regex = new Regex(query, regexOption);
3912 return x => regex.IsMatch(x);
3916 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3918 return x => x.IndexOf(query, comparisonType) != -1;
3922 private void AboutMenuItem_Click(object sender, EventArgs e)
3924 using (var about = new TweenAboutBox())
3926 about.ShowDialog(this);
3928 this.TopMost = this.settings.Common.AlwaysTop;
3931 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3933 var bgnIdx = this.statuses.SelectedTabIndex;
3935 if (this.ImageSelector.Enabled)
3938 TabModel? foundTab = null;
3942 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3944 var unreadIndex = tab.NextUnreadIndex;
3945 if (unreadIndex != -1)
3947 this.ListTab.SelectedIndex = index;
3949 foundIndex = unreadIndex;
3954 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3955 if (foundTab == null && bgnIdx > 0)
3957 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3959 var unreadIndex = tab.NextUnreadIndex;
3960 if (unreadIndex != -1)
3962 this.ListTab.SelectedIndex = index;
3964 foundIndex = unreadIndex;
3970 DetailsListView lst;
3972 if (foundTab == null)
3974 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3975 this.ListTab.SelectedIndex = 0;
3976 var tabPage = this.ListTab.TabPages[0];
3977 var tab = this.statuses.Tabs[0];
3979 if (tab.AllCount == 0)
3982 if (this.statuses.SortOrder == SortOrder.Ascending)
3983 foundIndex = tab.AllCount - 1;
3987 lst = (DetailsListView)tabPage.Tag;
3991 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3992 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3995 this.SelectListItem(lst, foundIndex);
3997 if (this.statuses.SortMode == ComparerMode.Id)
3999 var rowHeight = lst.SmallImageList.ImageSize.Height;
4000 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4001 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4007 lst.EnsureVisible(foundIndex);
4012 lst.EnsureVisible(foundIndex);
4018 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4020 var tab = this.CurrentTab;
4021 var post = this.CurrentPost;
4022 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4023 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4026 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4027 => await this.CheckNewVersion(false);
4029 private void RunTweenUp()
4031 var pinfo = new ProcessStartInfo
4033 UseShellExecute = true,
4034 WorkingDirectory = this.settings.SettingsPath,
4035 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4036 Arguments = "\"" + Application.StartupPath + "\"",
4041 Process.Start(pinfo);
4045 MessageBox.Show("Failed to execute TweenUp3.exe.");
4049 public readonly record struct VersionInfo(
4056 /// OpenTween の最新バージョンの情報を取得します
4058 public async Task<VersionInfo> GetVersionInfoAsync()
4060 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4061 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4063 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4064 .ConfigureAwait(false);
4066 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4067 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4069 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4070 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4072 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4074 return new VersionInfo
4076 Version = Version.Parse(msgHeader[0]),
4077 DownloadUri = new Uri(msgHeader[1]),
4078 ReleaseNote = msgBody,
4082 private async Task CheckNewVersion(bool startup = false)
4084 if (ApplicationSettings.VersionInfoUrl == null)
4085 return; // 更新チェック無効化
4089 var versionInfo = await this.GetVersionInfoAsync();
4091 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4096 var msgtext = string.Format(
4097 Properties.Resources.CheckNewVersionText7,
4098 MyCommon.GetReadableVersion(),
4099 MyCommon.GetReadableVersion(versionInfo.Version));
4100 msgtext = MyCommon.ReplaceAppName(msgtext);
4104 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4105 MessageBoxButtons.OK,
4106 MessageBoxIcon.Information);
4111 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4114 using var dialog = new UpdateDialog();
4116 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4117 MyCommon.GetReadableVersion(versionInfo.Version));
4118 dialog.DetailsText = versionInfo.ReleaseNote;
4120 if (dialog.ShowDialog(this) == DialogResult.Yes)
4122 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri.OriginalString);
4124 else if (dialog.SkipButtonPressed)
4126 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4127 this.MarkSettingCommonModified();
4132 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4136 Properties.Resources.CheckNewVersionText10,
4137 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4138 MessageBoxButtons.OK,
4139 MessageBoxIcon.Exclamation,
4140 MessageBoxDefaultButton.Button2);
4145 private void UpdateSelectedPost()
4147 // 件数関連の場合、タイトル即時書き換え
4148 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4149 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4150 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4151 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4153 this.SetMainWindowTitle();
4155 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4156 this.SetStatusLabelUrl();
4158 if (this.settings.Common.TabIconDisp)
4160 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4162 if (tab.UnreadCount == 0)
4164 var tabPage = this.ListTab.TabPages[index];
4165 if (tabPage.ImageIndex == 0)
4166 tabPage.ImageIndex = -1;
4172 this.ListTab.Refresh();
4175 this.DispSelectedPost();
4178 public string CreateDetailHtml(string orgdata)
4179 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4181 private void DispSelectedPost()
4182 => this.DispSelectedPost(false);
4184 private PostClass displayPost = new();
4187 /// サムネイル表示に使用する CancellationToken の生成元
4189 private CancellationTokenSource? thumbnailTokenSource = null;
4191 private void DispSelectedPost(bool forceupdate)
4193 var currentPost = this.CurrentPost;
4194 if (currentPost == null)
4197 var oldDisplayPost = this.displayPost;
4198 this.displayPost = currentPost;
4200 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4203 var loadTasks = new List<Task>
4205 this.tweetDetailsView.ShowPostDetails(currentPost),
4208 this.SplitContainer3.Panel2Collapsed = true;
4210 if (this.settings.Common.PreviewEnable)
4212 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4213 oldTokenSource?.Cancel();
4215 var token = this.thumbnailTokenSource!.Token;
4216 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
4219 async Task DelayedTasks()
4223 await Task.WhenAll(loadTasks);
4225 catch (OperationCanceledException)
4230 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4234 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4235 => await this.OpenApplicationWebsite();
4237 private async Task OpenApplicationWebsite()
4238 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4240 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4241 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4243 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4245 var tab = this.CurrentTab;
4246 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4248 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4249 if (pnl.Controls["comboSearch"].Focused ||
4250 pnl.Controls["comboLang"].Focused ||
4251 pnl.Controls["buttonSearch"].Focused) return;
4254 if (e.Control || e.Shift || e.Alt)
4257 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4260 e.SuppressKeyPress = true;
4263 if (asyncTask != null)
4267 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4269 private void InitializeShortcuts()
4271 this.shortcutCommands = new[]
4273 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4274 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4275 .FocusedOn(FocusedControl.ListTab)
4276 .Do(() => SendKeys.Send("{DOWN}")),
4278 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4279 .FocusedOn(FocusedControl.ListTab)
4280 .Do(() => SendKeys.Send("{UP}")),
4282 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4283 .FocusedOn(FocusedControl.ListTab)
4284 .Do(() => SendKeys.Send("{PGDN}")),
4286 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4287 .FocusedOn(FocusedControl.ListTab)
4288 .Do(() => SendKeys.Send("{PGUP}")),
4290 ShortcutCommand.Create(Keys.F1)
4291 .Do(() => this.OpenApplicationWebsite()),
4293 ShortcutCommand.Create(Keys.F3)
4294 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4296 ShortcutCommand.Create(Keys.F5)
4297 .Do(() => this.DoRefresh()),
4299 ShortcutCommand.Create(Keys.F6)
4300 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4302 ShortcutCommand.Create(Keys.F7)
4303 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4305 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4306 .NotFocusedOn(FocusedControl.StatusText)
4309 this.CurrentTab.ClearAnchor();
4310 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4313 ShortcutCommand.Create(Keys.G)
4314 .NotFocusedOn(FocusedControl.StatusText)
4317 this.CurrentTab.ClearAnchor();
4318 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4321 ShortcutCommand.Create(Keys.Right, Keys.N)
4322 .FocusedOn(FocusedControl.ListTab)
4323 .Do(() => this.GoRelPost(forward: true)),
4325 ShortcutCommand.Create(Keys.Left, Keys.P)
4326 .FocusedOn(FocusedControl.ListTab)
4327 .Do(() => this.GoRelPost(forward: false)),
4329 ShortcutCommand.Create(Keys.OemPeriod)
4330 .FocusedOn(FocusedControl.ListTab)
4331 .Do(() => this.GoAnchor()),
4333 ShortcutCommand.Create(Keys.I)
4334 .FocusedOn(FocusedControl.ListTab)
4335 .OnlyWhen(() => this.StatusText.Enabled)
4336 .Do(() => this.StatusText.Focus()),
4338 ShortcutCommand.Create(Keys.Enter)
4339 .FocusedOn(FocusedControl.ListTab)
4340 .Do(() => this.ListItemDoubleClickAction()),
4342 ShortcutCommand.Create(Keys.R)
4343 .FocusedOn(FocusedControl.ListTab)
4344 .Do(() => this.DoRefresh()),
4346 ShortcutCommand.Create(Keys.L)
4347 .FocusedOn(FocusedControl.ListTab)
4350 this.CurrentTab.ClearAnchor();
4351 this.GoPost(forward: true);
4354 ShortcutCommand.Create(Keys.H)
4355 .FocusedOn(FocusedControl.ListTab)
4358 this.CurrentTab.ClearAnchor();
4359 this.GoPost(forward: false);
4362 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4363 .FocusedOn(FocusedControl.ListTab)
4366 this.CurrentTab.ClearAnchor();
4370 ShortcutCommand.Create(Keys.S)
4371 .FocusedOn(FocusedControl.ListTab)
4374 this.CurrentTab.ClearAnchor();
4375 this.GoNextTab(forward: true);
4378 ShortcutCommand.Create(Keys.A)
4379 .FocusedOn(FocusedControl.ListTab)
4382 this.CurrentTab.ClearAnchor();
4383 this.GoNextTab(forward: false);
4386 // ] in_reply_to参照元へ戻る
4387 ShortcutCommand.Create(Keys.Oem4)
4388 .FocusedOn(FocusedControl.ListTab)
4391 this.CurrentTab.ClearAnchor();
4392 return this.GoInReplyToPostTree();
4395 // [ in_reply_toへジャンプ
4396 ShortcutCommand.Create(Keys.Oem6)
4397 .FocusedOn(FocusedControl.ListTab)
4400 this.CurrentTab.ClearAnchor();
4401 this.GoBackInReplyToPostTree();
4404 ShortcutCommand.Create(Keys.Escape)
4405 .FocusedOn(FocusedControl.ListTab)
4408 this.CurrentTab.ClearAnchor();
4409 var tab = this.CurrentTab;
4410 var tabtype = tab.TabType;
4411 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4413 this.RemoveSpecifiedTab(tab.TabName, false);
4414 this.SaveConfigsTabs();
4418 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4419 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4420 .FocusedOn(FocusedControl.ListTab)
4421 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4423 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4424 ShortcutCommand.Create(Keys.Up, Keys.Down)
4425 .FocusedOn(FocusedControl.PostBrowser)
4428 ShortcutCommand.Create(Keys.Control | Keys.R)
4429 .Do(() => this.MakeReplyText()),
4431 ShortcutCommand.Create(Keys.Control | Keys.D)
4432 .Do(() => this.DoStatusDelete()),
4434 ShortcutCommand.Create(Keys.Control | Keys.M)
4435 .Do(() => this.MakeDirectMessageText()),
4437 ShortcutCommand.Create(Keys.Control | Keys.S)
4438 .Do(() => this.FavoriteChange(favAdd: true)),
4440 ShortcutCommand.Create(Keys.Control | Keys.I)
4441 .Do(() => this.DoRepliedStatusOpen()),
4443 ShortcutCommand.Create(Keys.Control | Keys.Q)
4444 .Do(() => this.DoQuoteOfficial()),
4446 ShortcutCommand.Create(Keys.Control | Keys.B)
4447 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4449 ShortcutCommand.Create(Keys.Control | Keys.T)
4450 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4452 ShortcutCommand.Create(Keys.Control | Keys.L)
4453 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4455 ShortcutCommand.Create(Keys.Control | Keys.Y)
4456 .NotFocusedOn(FocusedControl.PostBrowser)
4457 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4459 ShortcutCommand.Create(Keys.Control | Keys.F)
4460 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4462 ShortcutCommand.Create(Keys.Control | Keys.U)
4463 .Do(() => this.ShowUserTimeline()),
4465 ShortcutCommand.Create(Keys.Control | Keys.H)
4466 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4468 ShortcutCommand.Create(Keys.Control | Keys.O)
4469 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4471 ShortcutCommand.Create(Keys.Control | Keys.E)
4472 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4474 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4475 .FocusedOn(FocusedControl.ListTab)
4476 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4478 ShortcutCommand.Create(Keys.Control | Keys.N)
4479 .FocusedOn(FocusedControl.ListTab)
4480 .Do(() => this.GoNextTab(forward: true)),
4482 ShortcutCommand.Create(Keys.Control | Keys.P)
4483 .FocusedOn(FocusedControl.ListTab)
4484 .Do(() => this.GoNextTab(forward: false)),
4486 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4487 .FocusedOn(FocusedControl.ListTab)
4488 .Do(() => this.CopyStot()),
4490 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4491 ShortcutCommand.Create(Keys.Control | Keys.D1)
4492 .FocusedOn(FocusedControl.ListTab)
4493 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4494 .Do(() => this.ListTab.SelectedIndex = 0),
4496 ShortcutCommand.Create(Keys.Control | Keys.D2)
4497 .FocusedOn(FocusedControl.ListTab)
4498 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4499 .Do(() => this.ListTab.SelectedIndex = 1),
4501 ShortcutCommand.Create(Keys.Control | Keys.D3)
4502 .FocusedOn(FocusedControl.ListTab)
4503 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4504 .Do(() => this.ListTab.SelectedIndex = 2),
4506 ShortcutCommand.Create(Keys.Control | Keys.D4)
4507 .FocusedOn(FocusedControl.ListTab)
4508 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4509 .Do(() => this.ListTab.SelectedIndex = 3),
4511 ShortcutCommand.Create(Keys.Control | Keys.D5)
4512 .FocusedOn(FocusedControl.ListTab)
4513 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4514 .Do(() => this.ListTab.SelectedIndex = 4),
4516 ShortcutCommand.Create(Keys.Control | Keys.D6)
4517 .FocusedOn(FocusedControl.ListTab)
4518 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4519 .Do(() => this.ListTab.SelectedIndex = 5),
4521 ShortcutCommand.Create(Keys.Control | Keys.D7)
4522 .FocusedOn(FocusedControl.ListTab)
4523 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4524 .Do(() => this.ListTab.SelectedIndex = 6),
4526 ShortcutCommand.Create(Keys.Control | Keys.D8)
4527 .FocusedOn(FocusedControl.ListTab)
4528 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4529 .Do(() => this.ListTab.SelectedIndex = 7),
4531 ShortcutCommand.Create(Keys.Control | Keys.D9)
4532 .FocusedOn(FocusedControl.ListTab)
4533 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4535 ShortcutCommand.Create(Keys.Control | Keys.A)
4536 .FocusedOn(FocusedControl.StatusText)
4537 .Do(() => this.StatusText.SelectAll()),
4539 ShortcutCommand.Create(Keys.Control | Keys.V)
4540 .FocusedOn(FocusedControl.StatusText)
4541 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4543 ShortcutCommand.Create(Keys.Control | Keys.Up)
4544 .FocusedOn(FocusedControl.StatusText)
4545 .Do(() => this.StatusTextHistoryBack()),
4547 ShortcutCommand.Create(Keys.Control | Keys.Down)
4548 .FocusedOn(FocusedControl.StatusText)
4549 .Do(() => this.StatusTextHistoryForward()),
4551 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4552 .FocusedOn(FocusedControl.StatusText)
4555 if (this.ListTab.SelectedIndex == 0)
4557 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4561 this.ListTab.SelectedIndex -= 1;
4563 this.StatusText.Focus();
4566 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4567 .FocusedOn(FocusedControl.StatusText)
4570 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4572 this.ListTab.SelectedIndex = 0;
4576 this.ListTab.SelectedIndex += 1;
4578 this.StatusText.Focus();
4581 ShortcutCommand.Create(Keys.Control | Keys.Y)
4582 .FocusedOn(FocusedControl.PostBrowser)
4585 var multiline = !this.settings.Local.StatusMultiline;
4586 this.settings.Local.StatusMultiline = multiline;
4587 this.MultiLineMenuItem.Checked = multiline;
4588 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4591 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4592 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4594 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4595 .Do(() => this.DoRefreshMore()),
4597 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4598 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4600 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4601 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4603 ShortcutCommand.Create(Keys.Shift | Keys.R)
4604 .NotFocusedOn(FocusedControl.StatusText)
4605 .Do(() => this.DoRefreshMore()),
4607 ShortcutCommand.Create(Keys.Shift | Keys.H)
4608 .FocusedOn(FocusedControl.ListTab)
4609 .Do(() => this.GoTopEnd(goTop: true)),
4611 ShortcutCommand.Create(Keys.Shift | Keys.L)
4612 .FocusedOn(FocusedControl.ListTab)
4613 .Do(() => this.GoTopEnd(goTop: false)),
4615 ShortcutCommand.Create(Keys.Shift | Keys.M)
4616 .FocusedOn(FocusedControl.ListTab)
4617 .Do(() => this.GoMiddle()),
4619 ShortcutCommand.Create(Keys.Shift | Keys.G)
4620 .FocusedOn(FocusedControl.ListTab)
4621 .Do(() => this.GoLast()),
4623 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4624 .FocusedOn(FocusedControl.ListTab)
4625 .Do(() => this.MoveMiddle()),
4627 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4628 .FocusedOn(FocusedControl.ListTab)
4629 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4631 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4632 .FocusedOn(FocusedControl.ListTab)
4633 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4635 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4636 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4637 .FocusedOn(FocusedControl.ListTab)
4638 .Do(() => this.GoFav(forward: true)),
4640 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4641 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4642 .FocusedOn(FocusedControl.ListTab)
4643 .Do(() => this.GoFav(forward: false)),
4645 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4646 .FocusedOn(FocusedControl.ListTab)
4647 .Do(() => this.GoBackSelectPostChain()),
4649 ShortcutCommand.Create(Keys.Alt | Keys.R)
4650 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4652 ShortcutCommand.Create(Keys.Alt | Keys.P)
4653 .OnlyWhen(() => this.CurrentPost != null)
4654 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4656 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4657 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4659 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4660 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4662 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4663 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4665 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4666 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4668 // 別タブの同じ書き込みへ(ALT+←/→)
4669 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4670 .FocusedOn(FocusedControl.ListTab)
4671 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4673 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4674 .FocusedOn(FocusedControl.ListTab)
4675 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4677 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4678 .Do(() => this.MakeReplyText(atAll: true)),
4680 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4681 .Do(() => this.CopyIdUri()),
4683 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4684 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4685 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4687 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4688 .Do(() => this.FavoriteChange(favAdd: false)),
4690 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4691 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4693 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4694 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4696 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4697 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4699 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4700 .Do(() => this.DoMoveToRTHome()),
4702 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4703 .FocusedOn(FocusedControl.StatusText)
4706 var tab = this.CurrentTab;
4707 var selectedIndex = tab.SelectedIndex;
4708 if (selectedIndex != -1 && selectedIndex > 0)
4710 var listView = this.CurrentListView;
4711 var idx = selectedIndex - 1;
4712 this.SelectListItem(listView, idx);
4713 listView.EnsureVisible(idx);
4717 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4718 .FocusedOn(FocusedControl.StatusText)
4721 var tab = this.CurrentTab;
4722 var selectedIndex = tab.SelectedIndex;
4723 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4725 var listView = this.CurrentListView;
4726 var idx = selectedIndex + 1;
4727 this.SelectListItem(listView, idx);
4728 listView.EnsureVisible(idx);
4732 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4733 .FocusedOn(FocusedControl.StatusText)
4736 if (this.StatusText.SelectionStart > 0)
4738 var endidx = this.StatusText.SelectionStart - 1;
4740 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4742 var c = this.StatusText.Text[i];
4743 if (char.IsLetterOrDigit(c) || c == '_')
4749 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4750 var cnt = this.AtIdSupl.ItemCount;
4751 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4752 if (this.AtIdSupl.ItemCount != cnt)
4753 this.MarkSettingAtIdModified();
4757 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4758 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4768 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4769 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4770 .FocusedOn(FocusedControl.ListTab)
4771 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4773 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4774 .FocusedOn(FocusedControl.ListTab)
4775 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4777 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4778 .FocusedOn(FocusedControl.ListTab)
4779 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4781 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4782 .FocusedOn(FocusedControl.ListTab)
4783 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4785 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4786 .FocusedOn(FocusedControl.ListTab)
4787 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4789 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4790 .FocusedOn(FocusedControl.ListTab)
4791 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4793 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4794 .FocusedOn(FocusedControl.ListTab)
4795 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4797 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4798 .FocusedOn(FocusedControl.ListTab)
4799 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4801 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4802 .FocusedOn(FocusedControl.ListTab)
4803 .Do(() => this.SetSortLastColumn()),
4805 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4806 .FocusedOn(FocusedControl.ListTab)
4807 .Do(() => this.FavoritesRetweetOfficial()),
4809 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4810 .FocusedOn(FocusedControl.ListTab)
4811 .Do(() => this.FavoritesRetweetUnofficial()),
4813 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4814 .FocusedOn(FocusedControl.ListTab)
4815 .Do(() => this.OpenUserAppointUrl()),
4817 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4818 .FocusedOn(FocusedControl.PostBrowser)
4819 .Do(() => this.DoReTweetUnofficial()),
4821 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4822 .OnlyWhen(() => this.ExistCurrentPost)
4823 .Do(() => this.tweetDetailsView.DoTranslation()),
4825 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4826 .Do(() => this.DoReTweetUnofficial()),
4828 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4829 .Do(() => this.CopyUserId()),
4831 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4832 .Do(() => this.tweetThumbnail1.ScrollUp()),
4834 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4835 .Do(() => this.tweetThumbnail1.ScrollDown()),
4837 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4838 .FocusedOn(FocusedControl.ListTab)
4839 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4840 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
4844 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4846 // Task を返す非同期処理があれば asyncTask に代入する
4849 // ShortcutCommand に対応しているコマンドはここで処理される
4850 foreach (var command in this.shortcutCommands)
4852 if (command.IsMatch(keyData, focusedOn))
4854 asyncTask = command.RunCommand();
4855 return command.PreventDefault;
4862 private void GoNextTab(bool forward)
4864 var idx = this.statuses.SelectedTabIndex;
4865 var tabCount = this.statuses.Tabs.Count;
4869 if (idx > tabCount - 1) idx = 0;
4874 if (idx < 0) idx = tabCount - 1;
4876 this.ListTab.SelectedIndex = idx;
4879 private void CopyStot()
4881 var sb = new StringBuilder();
4882 var tab = this.CurrentTab;
4883 var isProtected = false;
4884 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4885 foreach (var post in tab.SelectedPosts)
4887 if (post.IsDeleted) continue;
4890 if (post.RetweetedId != null)
4891 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4893 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4897 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4902 MessageBox.Show(Properties.Resources.CopyStotText1);
4906 var clstr = sb.ToString();
4909 Clipboard.SetDataObject(clstr, false, 5, 100);
4911 catch (Exception ex)
4913 MessageBox.Show(ex.Message);
4918 private void CopyIdUri()
4920 var tab = this.CurrentTab;
4921 if (tab == null || tab is DirectMessagesTabModel)
4924 var copyUrls = new List<string>();
4925 foreach (var post in tab.SelectedPosts)
4926 copyUrls.Add(MyCommon.GetStatusUrl(post));
4928 if (copyUrls.Count == 0)
4933 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4935 catch (ExternalException ex)
4937 MessageBox.Show(ex.Message);
4941 private void GoFav(bool forward)
4943 var tab = this.CurrentTab;
4944 if (tab.AllCount == 0)
4947 var selectedIndex = tab.SelectedIndex;
4955 if (selectedIndex == -1)
4961 fIdx = selectedIndex + 1;
4962 if (fIdx > tab.AllCount - 1)
4965 toIdx = tab.AllCount;
4970 if (selectedIndex == -1)
4972 fIdx = tab.AllCount - 1;
4976 fIdx = selectedIndex - 1;
4984 for (var idx = fIdx; idx != toIdx; idx += stp)
4988 var listView = this.CurrentListView;
4989 this.SelectListItem(listView, idx);
4990 listView.EnsureVisible(idx);
4996 private void GoSamePostToAnotherTab(bool left)
4998 var tab = this.CurrentTab;
5000 // Directタブは対象外(見つかるはずがない)
5001 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5004 var selectedStatusId = tab.SelectedStatusId;
5005 if (selectedStatusId == -1)
5008 int fIdx, toIdx, stp;
5013 if (this.ListTab.SelectedIndex == 0)
5019 fIdx = this.ListTab.SelectedIndex - 1;
5027 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5033 fIdx = this.ListTab.SelectedIndex + 1;
5035 toIdx = this.ListTab.TabCount;
5039 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5041 var targetTab = this.statuses.Tabs[tabidx];
5044 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5047 var foundIndex = targetTab.IndexOf(selectedStatusId);
5048 if (foundIndex != -1)
5050 this.ListTab.SelectedIndex = tabidx;
5051 var listView = this.CurrentListView;
5052 this.SelectListItem(listView, foundIndex);
5053 listView.EnsureVisible(foundIndex);
5059 private void GoPost(bool forward)
5061 var tab = this.CurrentTab;
5062 var currentPost = this.CurrentPost;
5064 if (currentPost == null)
5067 var selectedIndex = tab.SelectedIndex;
5069 int fIdx, toIdx, stp;
5073 fIdx = selectedIndex + 1;
5074 if (fIdx > tab.AllCount - 1) return;
5075 toIdx = tab.AllCount;
5080 fIdx = selectedIndex - 1;
5081 if (fIdx < 0) return;
5087 if (currentPost.RetweetedBy == null)
5089 name = currentPost.ScreenName;
5093 name = currentPost.RetweetedBy;
5095 for (var idx = fIdx; idx != toIdx; idx += stp)
5097 var post = tab[idx];
5098 if (post.RetweetedId == null)
5100 if (post.ScreenName == name)
5102 var listView = this.CurrentListView;
5103 this.SelectListItem(listView, idx);
5104 listView.EnsureVisible(idx);
5110 if (post.RetweetedBy == name)
5112 var listView = this.CurrentListView;
5113 this.SelectListItem(listView, idx);
5114 listView.EnsureVisible(idx);
5121 private void GoRelPost(bool forward)
5123 var tab = this.CurrentTab;
5124 var selectedIndex = tab.SelectedIndex;
5126 if (selectedIndex == -1)
5129 int fIdx, toIdx, stp;
5133 fIdx = selectedIndex + 1;
5134 if (fIdx > tab.AllCount - 1) return;
5135 toIdx = tab.AllCount;
5140 fIdx = selectedIndex - 1;
5141 if (fIdx < 0) return;
5146 var anchorPost = tab.AnchorPost;
5147 if (anchorPost == null)
5149 var currentPost = this.CurrentPost;
5150 if (currentPost == null)
5153 anchorPost = currentPost;
5154 tab.AnchorPost = currentPost;
5157 for (var idx = fIdx; idx != toIdx; idx += stp)
5159 var post = tab[idx];
5160 if (post.ScreenName == anchorPost.ScreenName ||
5161 post.RetweetedBy == anchorPost.ScreenName ||
5162 post.ScreenName == anchorPost.RetweetedBy ||
5163 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5164 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5165 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5166 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5167 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5169 var listView = this.CurrentListView;
5170 this.SelectListItem(listView, idx);
5171 listView.EnsureVisible(idx);
5177 private void GoAnchor()
5179 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5180 if (anchorStatusId == null)
5183 var idx = this.CurrentTab.IndexOf(anchorStatusId.Value);
5187 var listView = this.CurrentListView;
5188 this.SelectListItem(listView, idx);
5189 listView.EnsureVisible(idx);
5192 private void GoTopEnd(bool goTop)
5194 var listView = this.CurrentListView;
5195 if (listView.VirtualListSize == 0)
5203 item = listView.GetItemAt(0, 25);
5211 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5213 idx = listView.VirtualListSize - 1;
5217 this.SelectListItem(listView, idx);
5220 private void GoMiddle()
5222 var listView = this.CurrentListView;
5223 if (listView.VirtualListSize == 0)
5231 item = listView.GetItemAt(0, 0);
5241 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5244 idx2 = listView.VirtualListSize - 1;
5250 idx3 = (idx1 + idx2) / 2;
5252 this.SelectListItem(listView, idx3);
5255 private void GoLast()
5257 var listView = this.CurrentListView;
5258 if (listView.VirtualListSize == 0) return;
5260 if (this.statuses.SortOrder == SortOrder.Ascending)
5262 this.SelectListItem(listView, listView.VirtualListSize - 1);
5263 listView.EnsureVisible(listView.VirtualListSize - 1);
5267 this.SelectListItem(listView, 0);
5268 listView.EnsureVisible(0);
5272 private void MoveTop()
5274 var listView = this.CurrentListView;
5275 if (listView.SelectedIndices.Count == 0) return;
5276 var idx = listView.SelectedIndices[0];
5277 if (this.statuses.SortOrder == SortOrder.Ascending)
5279 listView.EnsureVisible(listView.VirtualListSize - 1);
5283 listView.EnsureVisible(0);
5285 listView.EnsureVisible(idx);
5288 private async Task GoInReplyToPostTree()
5290 var curTabClass = this.CurrentTab;
5291 var currentPost = this.CurrentPost;
5293 if (currentPost == null)
5296 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5300 var post = await this.tw.GetStatusApi(false, currentPost.StatusId);
5302 currentPost.InReplyToStatusId = post.InReplyToStatusId;
5303 currentPost.InReplyToUser = post.InReplyToUser;
5304 currentPost.IsReply = post.IsReply;
5305 this.listCache?.PurgeCache();
5307 var index = curTabClass.SelectedIndex;
5308 this.CurrentListView.RedrawItems(index, index, false);
5310 catch (WebApiException ex)
5312 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5316 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5318 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5320 this.replyChains = new Stack<ReplyChain>();
5322 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
5325 string inReplyToTabName;
5326 var inReplyToId = currentPost.InReplyToStatusId.Value;
5327 var inReplyToUser = currentPost.InReplyToUser;
5329 var inReplyToPosts = from tab in this.statuses.Tabs
5330 orderby tab != curTabClass
5331 from post in tab.Posts.Values
5332 where post.StatusId == inReplyToId
5333 let index = tab.IndexOf(post.StatusId)
5335 select new { Tab = tab, Index = index };
5337 var inReplyPost = inReplyToPosts.FirstOrDefault();
5338 if (inReplyPost == null)
5342 await Task.Run(async () =>
5344 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
5345 .ConfigureAwait(false);
5348 this.statuses.AddPost(post);
5349 this.statuses.DistributePosts();
5352 catch (WebApiException ex)
5354 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5355 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5359 this.RefreshTimeline();
5361 inReplyPost = inReplyToPosts.FirstOrDefault();
5362 if (inReplyPost == null)
5364 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5368 inReplyToTabName = inReplyPost.Tab.TabName;
5369 inReplyToIndex = inReplyPost.Index;
5371 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5372 var tabPage = this.ListTab.TabPages[tabIndex];
5373 var listView = (DetailsListView)tabPage.Tag;
5375 if (this.CurrentTabName != inReplyToTabName)
5377 this.ListTab.SelectedIndex = tabIndex;
5380 this.SelectListItem(listView, inReplyToIndex);
5381 listView.EnsureVisible(inReplyToIndex);
5384 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5386 var curTabClass = this.CurrentTab;
5387 var currentPost = this.CurrentPost;
5389 if (currentPost == null)
5394 if (currentPost.InReplyToStatusId != null)
5396 var posts = from t in this.statuses.Tabs
5398 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5399 let indexOf = t.IndexOf(p.Value.StatusId)
5401 orderby isForward ? indexOf : indexOf * -1
5402 orderby t != curTabClass
5403 select new { Tab = t, Post = p.Value, Index = indexOf };
5406 var postList = posts.ToList();
5407 for (var i = postList.Count - 1; i >= 0; i--)
5410 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5412 postList.RemoveAt(index);
5415 var currentIndex = this.CurrentTab.SelectedIndex;
5416 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5417 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5418 if (post == null) post = postList.First();
5419 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5420 this.ListTab.SelectedIndex = tabIndex;
5421 var listView = this.CurrentListView;
5422 this.SelectListItem(listView, post.Index);
5423 listView.EnsureVisible(post.Index);
5425 catch (InvalidOperationException)
5433 if (this.replyChains == null || this.replyChains.Count < 1)
5435 var posts = from t in this.statuses.Tabs
5437 where p.Value.InReplyToStatusId == currentPost.StatusId
5438 let indexOf = t.IndexOf(p.Value.StatusId)
5441 orderby t != curTabClass
5442 select new { Tab = t, Index = indexOf };
5445 var post = posts.First();
5446 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5447 this.ListTab.SelectedIndex = tabIndex;
5448 var listView = this.CurrentListView;
5449 this.SelectListItem(listView, post.Index);
5450 listView.EnsureVisible(post.Index);
5452 catch (InvalidOperationException)
5459 var chainHead = this.replyChains.Pop();
5460 if (chainHead.InReplyToId == currentPost.StatusId)
5462 var tab = chainHead.OriginalTab;
5463 if (!this.statuses.Tabs.Contains(tab))
5465 this.replyChains = null;
5469 var idx = tab.IndexOf(chainHead.OriginalId);
5472 this.replyChains = null;
5476 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5479 this.ListTab.SelectedIndex = tabIndex;
5483 this.replyChains = null;
5485 var listView = this.CurrentListView;
5486 this.SelectListItem(listView, idx);
5487 listView.EnsureVisible(idx);
5493 this.replyChains = null;
5494 this.GoBackInReplyToPostTree(parallel);
5500 private void GoBackSelectPostChain()
5502 if (this.selectPostChains.Count > 1)
5505 TabModel? foundTab = null;
5511 this.selectPostChains.Pop();
5512 var (tab, post) = this.selectPostChains.Peek();
5514 if (!this.statuses.Tabs.Contains(tab))
5515 continue; // 該当タブが存在しないので無視
5519 idx = tab.IndexOf(post.StatusId);
5520 if (idx == -1) continue; // 該当ポストが存在しないので無視
5525 this.selectPostChains.Pop();
5527 catch (InvalidOperationException)
5533 while (this.selectPostChains.Count > 1);
5535 if (foundTab == null)
5538 // 履歴が残り1つであればクリアしておく
5539 if (this.selectPostChains.Count == 1)
5540 this.selectPostChains.Clear();
5544 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5545 var tabPage = this.ListTab.TabPages[tabIndex];
5546 var lst = (DetailsListView)tabPage.Tag;
5547 this.ListTab.SelectedIndex = tabIndex;
5551 this.SelectListItem(lst, idx);
5552 lst.EnsureVisible(idx);
5558 private void PushSelectPostChain()
5560 var currentTab = this.CurrentTab;
5561 var currentPost = this.CurrentPost;
5563 var count = this.selectPostChains.Count;
5566 var (tab, post) = this.selectPostChains.Peek();
5567 if (tab == currentTab)
5569 if (post == currentPost) return; // 最新の履歴と同一
5570 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5573 if (count >= 2500) this.TrimPostChain();
5574 this.selectPostChains.Push((currentTab, currentPost));
5577 private void TrimPostChain()
5579 if (this.selectPostChains.Count <= 2000) return;
5580 var p = new Stack<(TabModel, PostClass?)>(2000);
5581 for (var i = 0; i < 2000; i++)
5583 p.Push(this.selectPostChains.Pop());
5585 this.selectPostChains.Clear();
5586 for (var i = 0; i < 2000; i++)
5588 this.selectPostChains.Push(p.Pop());
5592 private bool GoStatus(long statusId)
5594 if (statusId == 0) return false;
5596 var tab = this.statuses.Tabs
5597 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5598 .Where(x => x.Contains(statusId))
5604 var index = tab.IndexOf(statusId);
5606 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5607 this.ListTab.SelectedIndex = tabIndex;
5609 var listView = this.CurrentListView;
5610 this.SelectListItem(listView, index);
5611 listView.EnsureVisible(index);
5616 private bool GoDirectMessage(long statusId)
5618 if (statusId == 0) return false;
5620 var tab = this.statuses.DirectMessageTab;
5621 var index = tab.IndexOf(statusId);
5626 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5627 this.ListTab.SelectedIndex = tabIndex;
5629 var listView = this.CurrentListView;
5630 this.SelectListItem(listView, index);
5631 listView.EnsureVisible(index);
5636 private void MyList_MouseClick(object sender, MouseEventArgs e)
5637 => this.CurrentTab.ClearAnchor();
5639 private void StatusText_Enter(object sender, EventArgs e)
5641 // フォーカスの戻り先を StatusText に設定
5642 this.Tag = this.StatusText;
5643 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5646 public Color InputBackColor
5647 => this.themeManager.ColorInputBackcolor;
5649 private void StatusText_Leave(object sender, EventArgs e)
5651 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5652 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5653 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5656 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5658 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5661 e.SuppressKeyPress = true;
5664 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5666 if (asyncTask != null)
5670 private void SaveConfigsAll(bool ifModified)
5674 this.SaveConfigsCommon();
5675 this.SaveConfigsLocal();
5676 this.SaveConfigsTabs();
5677 this.SaveConfigsAtId();
5681 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5682 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5683 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5687 private void SaveConfigsAtId()
5689 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5691 this.ModifySettingAtId = false;
5692 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5693 this.settings.SaveAtIdList();
5696 private void SaveConfigsCommon()
5698 if (this.ignoreConfigSave) return;
5700 this.ModifySettingCommon = false;
5701 lock (this.syncObject)
5703 this.settings.Common.UserName = this.tw.Username;
5704 this.settings.Common.UserId = this.tw.UserId;
5705 this.settings.Common.Token = this.tw.AccessToken;
5706 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5707 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5708 this.settings.Common.SortColumn = this.statuses.SortMode switch
5710 ComparerMode.Nickname => 1, // ニックネーム
5711 ComparerMode.Data => 2, // 本文
5712 ComparerMode.Id => 3, // 時刻=発言Id
5713 ComparerMode.Name => 4, // 名前
5714 ComparerMode.Source => 7, // Source
5715 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5717 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5718 if (this.HashMgr.IsPermanent)
5720 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5724 this.settings.Common.HashSelected = "";
5726 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5727 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5728 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5729 this.settings.Common.UseImageService = this.ImageSelector.ServiceIndex;
5730 this.settings.Common.UseImageServiceName = this.ImageSelector.ServiceName;
5732 this.settings.SaveCommon();
5736 private void SaveConfigsLocal()
5738 if (this.ignoreConfigSave) return;
5739 lock (this.syncObject)
5741 this.ModifySettingLocal = false;
5742 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5743 this.settings.Local.FormSize = this.mySize;
5744 this.settings.Local.FormLocation = this.myLoc;
5745 this.settings.Local.SplitterDistance = this.mySpDis;
5746 this.settings.Local.PreviewDistance = this.mySpDis3;
5747 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5748 this.settings.Local.StatusTextHeight = this.mySpDis2;
5750 if (this.ignoreConfigSave) return;
5751 this.settings.SaveLocal();
5755 private void SaveConfigsTabs()
5757 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5759 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5761 foreach (var tab in tabs)
5763 if (!tab.IsPermanentTabType)
5766 var tabSetting = new SettingTabs.SettingTabItem
5768 TabName = tab.TabName,
5769 TabType = tab.TabType,
5770 UnreadManage = tab.UnreadManage,
5771 Protected = tab.Protected,
5772 Notify = tab.Notify,
5773 SoundFile = tab.SoundFile,
5778 case FilterTabModel filterTab:
5779 tabSetting.FilterArray = filterTab.FilterArray;
5781 case UserTimelineTabModel userTab:
5782 tabSetting.User = userTab.ScreenName;
5784 case PublicSearchTabModel searchTab:
5785 tabSetting.SearchWords = searchTab.SearchWords;
5786 tabSetting.SearchLang = searchTab.SearchLang;
5788 case ListTimelineTabModel listTab:
5789 tabSetting.ListInfo = listTab.ListInfo;
5793 tabSettingList.Add(tabSetting);
5796 this.settings.Tabs.Tabs = tabSettingList;
5797 this.settings.SaveTabs();
5800 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5802 static void ShowFormatErrorDialog(IWin32Window owner)
5806 Properties.Resources.OpenURL_InvalidFormat,
5807 Properties.Resources.OpenURL_Caption,
5808 MessageBoxButtons.OK,
5809 MessageBoxIcon.Error
5813 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5814 if (ret != DialogResult.OK)
5817 var match = Twitter.StatusUrlRegex.Match(inputText);
5820 ShowFormatErrorDialog(this);
5826 var statusId = long.Parse(match.Groups["StatusId"].Value);
5827 await this.OpenRelatedTab(statusId);
5829 catch (OverflowException)
5831 ShowFormatErrorDialog(this);
5833 catch (TabException ex)
5835 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5839 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5841 var tab = this.CurrentTab;
5843 var rslt = MessageBox.Show(
5844 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5845 Properties.Resources.SaveLogMenuItem_ClickText2,
5846 MessageBoxButtons.YesNoCancel,
5847 MessageBoxIcon.Question);
5848 if (rslt == DialogResult.Cancel) return;
5850 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5851 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5852 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5853 this.SaveFileDialog1.FilterIndex = 0;
5854 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5855 this.SaveFileDialog1.RestoreDirectory = true;
5857 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5859 if (!this.SaveFileDialog1.ValidateNames) return;
5860 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5861 if (rslt == DialogResult.Yes)
5864 for (var idx = 0; idx < tab.AllCount; idx++)
5866 var post = tab[idx];
5869 protect = "Protect";
5870 sw.WriteLine(post.Nickname + "\t" +
5871 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5872 post.CreatedAt.ToLocalTimeString() + "\t" +
5873 post.ScreenName + "\t" +
5874 post.StatusId + "\t" +
5875 post.ImageUrl + "\t" +
5876 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5882 foreach (var post in this.CurrentTab.SelectedPosts)
5886 protect = "Protect";
5887 sw.WriteLine(post.Nickname + "\t" +
5888 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5889 post.CreatedAt.ToLocalTimeString() + "\t" +
5890 post.ScreenName + "\t" +
5891 post.StatusId + "\t" +
5892 post.ImageUrl + "\t" +
5893 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5898 this.TopMost = this.settings.Common.AlwaysTop;
5901 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5905 using (var inputName = new InputTabName())
5907 inputName.TabName = origTabName;
5908 inputName.ShowDialog();
5909 if (inputName.DialogResult == DialogResult.Cancel) return false;
5910 newTabName = inputName.TabName;
5912 this.TopMost = this.settings.Common.AlwaysTop;
5913 if (!MyCommon.IsNullOrEmpty(newTabName))
5916 if (this.statuses.ContainsTab(newTabName))
5918 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5919 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5923 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5924 var tabPage = this.ListTab.TabPages[tabIndex];
5927 if (tabPage != null)
5928 tabPage.Text = newTabName;
5930 this.statuses.RenameTab(origTabName, newTabName);
5932 var state = this.listViewState[origTabName];
5933 this.listViewState.Remove(origTabName);
5934 this.listViewState[newTabName] = state;
5936 this.SaveConfigsCommon();
5937 this.SaveConfigsTabs();
5938 this.rclickTabName = newTabName;
5947 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5949 if (e.Button == MouseButtons.Middle)
5951 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5953 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5955 this.RemoveSpecifiedTab(tab.TabName, true);
5956 this.SaveConfigsTabs();
5963 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5964 => this.TabRename(this.CurrentTabName, out _);
5966 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5968 if (this.settings.Common.TabMouseLock) return;
5969 if (e.Button == MouseButtons.Left)
5971 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5973 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5975 this.tabDrag = true;
5976 this.tabMouseDownPoint = e.Location;
5983 this.tabDrag = false;
5987 private void ListTab_DragEnter(object sender, DragEventArgs e)
5989 if (e.Data.GetDataPresent(typeof(TabPage)))
5990 e.Effect = DragDropEffects.Move;
5992 e.Effect = DragDropEffects.None;
5995 private void ListTab_DragDrop(object sender, DragEventArgs e)
5997 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5999 this.tabDrag = false;
6002 var cpos = new Point(e.X, e.Y);
6003 var spos = this.ListTab.PointToClient(cpos);
6004 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6006 var rect = this.ListTab.GetTabRect(index);
6007 if (rect.Contains(spos))
6010 if (spos.X <= (rect.Left + rect.Right) / 2)
6019 // タブのないところにドロップ->最後尾へ移動
6020 if (MyCommon.IsNullOrEmpty(tn))
6022 var lastTab = this.statuses.Tabs.Last();
6023 tn = lastTab.TabName;
6027 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6028 if (tp.Text == tn) return;
6030 this.ReOrderTab(tp.Text, tn, bef);
6033 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6035 var baseIndex = this.GetTabPageIndex(baseTabText);
6036 if (baseIndex == -1)
6039 var targetIndex = this.GetTabPageIndex(targetTabText);
6040 if (targetIndex == -1)
6043 using (ControlTransaction.Layout(this.ListTab))
6045 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6046 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6047 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6048 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6050 var tab = this.statuses.Tabs[targetIndex];
6051 var tabPage = this.ListTab.TabPages[targetIndex];
6053 this.ListTab.TabPages.Remove(tabPage);
6055 if (targetIndex < baseIndex)
6058 if (!isBeforeBaseTab)
6061 this.statuses.MoveTab(baseIndex, tab);
6063 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6066 this.SaveConfigsTabs();
6069 private void MakeDirectMessageText()
6071 var selectedPosts = this.CurrentTab.SelectedPosts;
6072 if (selectedPosts.Length > 1)
6075 var post = selectedPosts.Single();
6076 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6078 this.inReplyTo = null;
6079 this.StatusText.Text = text;
6080 this.StatusText.SelectionStart = text.Length;
6081 this.StatusText.Focus();
6084 private void MakeReplyText(bool atAll = false)
6086 var selectedPosts = this.CurrentTab.SelectedPosts;
6087 if (selectedPosts.Any(x => x.IsDm))
6089 this.MakeDirectMessageText();
6093 if (selectedPosts.Length == 1)
6095 var post = selectedPosts.Single();
6096 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6097 var inReplyToScreenName = post.ScreenName;
6098 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6102 this.inReplyTo = null;
6105 var selfScreenName = this.tw.Username;
6106 var targetScreenNames = new List<string>();
6107 foreach (var post in selectedPosts)
6109 if (post.ScreenName != selfScreenName)
6110 targetScreenNames.Add(post.ScreenName);
6114 foreach (var (_, screenName) in post.ReplyToList)
6116 if (screenName != selfScreenName)
6117 targetScreenNames.Add(screenName);
6122 if (this.inReplyTo != null)
6124 var (_, screenName) = this.inReplyTo.Value;
6125 if (screenName == selfScreenName)
6126 targetScreenNames.Insert(0, screenName);
6129 var text = this.StatusText.Text;
6130 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6132 var atText = $"@{screenName} ";
6133 if (!text.Contains(atText))
6134 text = atText + text;
6137 this.StatusText.Text = text;
6138 this.StatusText.SelectionStart = text.Length;
6139 this.StatusText.Focus();
6142 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6143 => this.tabDrag = false;
6145 private int iconCnt = 0;
6146 private int blinkCnt = 0;
6147 private bool blink = false;
6149 private void RefreshTasktrayIcon()
6151 void EnableTasktrayAnimation()
6152 => this.TimerRefreshIcon.Enabled = true;
6154 void DisableTasktrayAnimation()
6155 => this.TimerRefreshIcon.Enabled = false;
6157 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6161 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6164 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6165 this.myStatusError = false;
6166 EnableTasktrayAnimation();
6170 var replyIconType = this.settings.Common.ReplyIconState;
6172 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6174 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6175 if (replyTab != null && replyTab.UnreadCount > 0)
6179 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6182 if (this.blinkCnt > 10)
6185 if (this.blinkCnt == 0)
6186 this.blink = !this.blink;
6188 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6189 EnableTasktrayAnimation();
6193 DisableTasktrayAnimation();
6199 // 優先度:リプライ→エラー→オフライン→アイドル
6200 // エラーは更新アイコンでクリアされる
6201 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6202 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6203 else if (this.myStatusError)
6204 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6205 else if (this.myStatusOnline)
6206 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6208 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6211 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6212 => this.RefreshTasktrayIcon(); // 200ms
6214 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6216 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6217 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6218 this.rclickTabName = this.CurrentTabName;
6220 if (this.statuses == null) return;
6221 if (this.statuses.Tabs == null) return;
6223 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6226 this.NotifyDispMenuItem.Checked = tb.Notify;
6227 this.NotifyTbMenuItem.Checked = tb.Notify;
6229 this.soundfileListup = true;
6230 this.SoundFileComboBox.Items.Clear();
6231 this.SoundFileTbComboBox.Items.Clear();
6232 this.SoundFileComboBox.Items.Add("");
6233 this.SoundFileTbComboBox.Items.Add("");
6234 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6235 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6237 oDir = oDir.GetDirectories("Sounds")[0];
6239 foreach (var oFile in oDir.GetFiles("*.wav"))
6241 this.SoundFileComboBox.Items.Add(oFile.Name);
6242 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6244 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6245 if (idx == -1) idx = 0;
6246 this.SoundFileComboBox.SelectedIndex = idx;
6247 this.SoundFileTbComboBox.SelectedIndex = idx;
6248 this.soundfileListup = false;
6249 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6250 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6252 this.TabMenuControl(this.rclickTabName);
6255 private void TabMenuControl(string tabName)
6257 var tabInfo = this.statuses.GetTabByName(tabName)!;
6259 this.FilterEditMenuItem.Enabled = true;
6260 this.EditRuleTbMenuItem.Enabled = true;
6262 if (tabInfo.IsDefaultTabType)
6264 this.ProtectTabMenuItem.Enabled = false;
6265 this.ProtectTbMenuItem.Enabled = false;
6269 this.ProtectTabMenuItem.Enabled = true;
6270 this.ProtectTbMenuItem.Enabled = true;
6273 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6275 this.ProtectTabMenuItem.Checked = true;
6276 this.ProtectTbMenuItem.Checked = true;
6277 this.DeleteTabMenuItem.Enabled = false;
6278 this.DeleteTbMenuItem.Enabled = false;
6282 this.ProtectTabMenuItem.Checked = false;
6283 this.ProtectTbMenuItem.Checked = false;
6284 this.DeleteTabMenuItem.Enabled = true;
6285 this.DeleteTbMenuItem.Enabled = true;
6289 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6291 var checkState = ((ToolStripMenuItem)sender).Checked;
6294 this.ProtectTbMenuItem.Checked = checkState;
6295 this.ProtectTabMenuItem.Checked = checkState;
6298 this.DeleteTabMenuItem.Enabled = !checkState;
6299 this.DeleteTbMenuItem.Enabled = !checkState;
6301 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6302 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6304 this.SaveConfigsTabs();
6307 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6309 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6310 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6312 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6313 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6315 this.SaveConfigsTabs();
6318 public void ChangeTabUnreadManage(string tabName, bool isManage)
6320 var idx = this.GetTabPageIndex(tabName);
6324 var tab = this.statuses.Tabs[tabName];
6325 tab.UnreadManage = isManage;
6327 if (this.settings.Common.TabIconDisp)
6329 var tabPage = this.ListTab.TabPages[idx];
6330 if (tab.UnreadCount > 0)
6331 tabPage.ImageIndex = 0;
6333 tabPage.ImageIndex = -1;
6336 if (this.CurrentTabName == tabName)
6338 this.listCache?.PurgeCache();
6339 this.CurrentListView.Refresh();
6342 this.SetMainWindowTitle();
6343 this.SetStatusLabelUrl();
6344 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6347 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6349 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6350 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6352 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6354 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6356 this.SaveConfigsTabs();
6359 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6361 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6363 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6365 this.SaveConfigsTabs();
6368 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6370 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6371 this.rclickTabName = this.CurrentTabName;
6373 this.RemoveSpecifiedTab(this.rclickTabName, true);
6374 this.SaveConfigsTabs();
6377 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6379 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6381 using (var fltDialog = new FilterDialog())
6383 fltDialog.Owner = this;
6384 fltDialog.SetCurrent(this.rclickTabName);
6385 fltDialog.ShowDialog(this);
6387 this.TopMost = this.settings.Common.AlwaysTop;
6389 this.ApplyPostFilters();
6390 this.SaveConfigsTabs();
6393 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6395 string? tabName = null;
6396 MyCommon.TabUsageType tabUsage;
6397 using (var inputName = new InputTabName())
6399 inputName.TabName = this.statuses.MakeTabName("MyTab");
6400 inputName.IsShowUsage = true;
6401 inputName.ShowDialog();
6402 if (inputName.DialogResult == DialogResult.Cancel) return;
6403 tabName = inputName.TabName;
6404 tabUsage = inputName.Usage;
6406 this.TopMost = this.settings.Common.AlwaysTop;
6407 if (!MyCommon.IsNullOrEmpty(tabName))
6410 ListElement? list = null;
6411 if (tabUsage == MyCommon.TabUsageType.Lists)
6413 using var listAvail = new ListAvailable();
6414 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6416 if (listAvail.SelectedList == null)
6418 list = listAvail.SelectedList;
6424 case MyCommon.TabUsageType.UserDefined:
6425 tab = new FilterTabModel(tabName);
6427 case MyCommon.TabUsageType.PublicSearch:
6428 tab = new PublicSearchTabModel(tabName);
6430 case MyCommon.TabUsageType.Lists:
6431 tab = new ListTimelineTabModel(tabName, list!);
6437 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6439 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6440 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6445 this.SaveConfigsTabs();
6447 var tabIndex = this.statuses.Tabs.Count - 1;
6449 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6451 this.ListTab.SelectedIndex = tabIndex;
6452 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6454 if (tabUsage == MyCommon.TabUsageType.Lists)
6456 this.ListTab.SelectedIndex = tabIndex;
6457 await this.RefreshTabAsync(this.CurrentTab);
6463 private void TabMenuItem_Click(object sender, EventArgs e)
6466 foreach (var post in this.CurrentTab.SelectedPosts)
6469 if (!this.SelectTab(out var tab))
6472 using (var fltDialog = new FilterDialog())
6474 fltDialog.Owner = this;
6475 fltDialog.SetCurrent(tab.TabName);
6477 if (post.RetweetedBy == null)
6479 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6483 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6485 fltDialog.ShowDialog(this);
6488 this.TopMost = this.settings.Common.AlwaysTop;
6491 this.ApplyPostFilters();
6492 this.SaveConfigsTabs();
6495 protected override bool ProcessDialogKey(Keys keyData)
6497 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6498 if ((keyData & Keys.KeyCode) == Keys.Enter)
6500 if (this.StatusText.Focused)
6502 var newLine = false;
6505 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6507 if (this.StatusText.Multiline)
6509 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6511 if ((keyData & Keys.Control) == Keys.Control) post = true;
6515 if ((keyData & Keys.Control) == Keys.Control) post = true;
6518 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6520 if (this.StatusText.Multiline)
6522 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6524 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6528 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6533 if (this.StatusText.Multiline)
6535 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6537 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6538 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6542 if (((keyData & Keys.Shift) == Keys.Shift) ||
6543 (((keyData & Keys.Control) != Keys.Control) &&
6544 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6550 var pos1 = this.StatusText.SelectionStart;
6551 if (this.StatusText.SelectionLength > 0)
6553 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6555 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6556 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6561 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6567 var tab = this.CurrentTab;
6568 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6570 var tabPage = this.CurrentTabPage;
6571 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6572 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6574 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6581 return base.ProcessDialogKey(keyData);
6584 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6585 => this.MakeReplyText(atAll: true);
6587 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6589 var tab = this.CurrentTab;
6590 var selectedPosts = tab.SelectedPosts;
6593 if (selectedPosts.Length == 0)
6596 var screenNameArray = selectedPosts
6597 .Select(x => x.RetweetedBy ?? x.ScreenName)
6600 this.AddFilterRuleByScreenName(screenNameArray);
6602 if (screenNameArray.Length != 0)
6604 var atids = new List<string>();
6605 foreach (var screenName in screenNameArray)
6607 atids.Add("@" + screenName);
6609 var cnt = this.AtIdSupl.ItemCount;
6610 this.AtIdSupl.AddRangeItem(atids.ToArray());
6611 if (this.AtIdSupl.ItemCount != cnt)
6612 this.MarkSettingAtIdModified();
6616 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6618 var tab = this.CurrentTab;
6619 var selectedPosts = tab.SelectedPosts;
6621 if (selectedPosts.Length == 0)
6624 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6626 this.AddFilterRuleBySource(sourceArray);
6629 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6632 if (!this.SelectTab(out var tab)) return;
6636 if (tab.TabType != MyCommon.TabUsageType.Mute)
6638 this.MoveOrCopy(out mv, out mk);
6642 // ミュートタブでは常に MoveMatches を true にする
6647 foreach (var screenName in screenNameArray)
6649 tab.AddFilter(new PostFilterRule
6651 FilterName = screenName,
6652 UseNameField = true,
6656 FilterByUrl = false,
6660 this.ApplyPostFilters();
6661 this.SaveConfigsTabs();
6664 public void AddFilterRuleBySource(params string[] sourceArray)
6666 // タブ選択ダイアログを表示(or追加)
6667 if (!this.SelectTab(out var filterTab))
6672 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6674 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6675 this.MoveOrCopy(out mv, out mk);
6679 // ミュートタブでは常に MoveMatches を true にする
6684 // 振り分けルールに追加するSource
6685 foreach (var source in sourceArray)
6687 filterTab.AddFilter(new PostFilterRule
6689 FilterSource = source,
6693 FilterByUrl = false,
6697 this.ApplyPostFilters();
6698 this.SaveConfigsTabs();
6701 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6708 using (var dialog = new TabsDialog(this.statuses))
6710 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6712 tab = dialog.SelectedTab;
6715 this.CurrentTabPage.Focus();
6720 using (var inputName = new InputTabName())
6722 inputName.TabName = this.statuses.MakeTabName("MyTab");
6723 inputName.ShowDialog();
6724 if (inputName.DialogResult == DialogResult.Cancel) return false;
6725 tabName = inputName.TabName;
6727 this.TopMost = this.settings.Common.AlwaysTop;
6728 if (!MyCommon.IsNullOrEmpty(tabName))
6730 var newTab = new FilterTabModel(tabName);
6731 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6733 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6734 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6753 private void MoveOrCopy(out bool move, out bool mark)
6757 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6758 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6766 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6767 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6778 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6781 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6782 => this.CopyIdUri();
6784 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6786 if (this.StatusText.Focused)
6789 this.StatusText.SelectAll();
6793 // ListView上でのCtrl+A
6794 NativeMethods.SelectAllItems(this.CurrentListView);
6798 private void MoveMiddle()
6804 var listView = this.CurrentListView;
6805 if (listView.SelectedIndices.Count == 0) return;
6807 var idx = listView.SelectedIndices[0];
6809 item = listView.GetItemAt(0, 25);
6815 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6817 idx2 = listView.VirtualListSize - 1;
6821 idx -= Math.Abs(idx1 - idx2) / 2;
6822 if (idx < 0) idx = 0;
6824 listView.EnsureVisible(listView.VirtualListSize - 1);
6825 listView.EnsureVisible(idx);
6828 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6830 var linkElements = this.tweetDetailsView.GetLinkElements();
6832 if (linkElements.Length == 0)
6835 var links = new List<OpenUrlItem>(linkElements.Length);
6837 foreach (var linkElm in linkElements)
6839 var displayUrl = linkElm.GetAttribute("title");
6840 var href = linkElm.GetAttribute("href");
6841 var linkedText = linkElm.InnerText;
6843 if (MyCommon.IsNullOrEmpty(displayUrl))
6846 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6850 bool isReverseSettings;
6852 if (links.Count == 1)
6854 // ツイートに含まれる URL が 1 つのみの場合
6855 // => OpenURL ダイアログを表示せずにリンクを開く
6856 selectedUrl = links[0].Href;
6858 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6859 isReverseSettings = false;
6863 // ツイートに含まれる URL が複数ある場合
6864 // => OpenURL を表示しユーザーが選択したリンクを開く
6865 this.urlDialog.ClearUrl();
6867 foreach (var link in links)
6868 this.urlDialog.AddUrl(link);
6870 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6873 this.TopMost = this.settings.Common.AlwaysTop;
6875 selectedUrl = this.urlDialog.SelectedUrl;
6877 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6878 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6881 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6884 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6886 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6887 this.ClearTab(this.rclickTabName, true);
6890 private void ClearTab(string tabName, bool showWarning)
6894 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6895 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6901 this.statuses.ClearTabIds(tabName);
6902 if (this.CurrentTabName == tabName)
6904 this.CurrentTab.ClearAnchor();
6905 this.listCache?.PurgeCache();
6906 this.listCache?.UpdateListSize();
6909 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6910 var tabPage = this.ListTab.TabPages[tabIndex];
6911 tabPage.ImageIndex = -1;
6913 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6915 this.SetMainWindowTitle();
6916 this.SetStatusLabelUrl();
6919 private static long followers = 0;
6921 private void SetMainWindowTitle()
6923 // メインウインドウタイトルの書き換え
6924 var ttl = new StringBuilder(256);
6927 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6928 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6929 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6930 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6932 foreach (var tab in this.statuses.Tabs)
6934 ur += tab.UnreadCount;
6939 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6940 ttl.Append(ApplicationSettings.ApplicationName);
6942 switch (this.settings.Common.DispLatestPost)
6944 case MyCommon.DispTitleEnum.Ver:
6945 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6947 case MyCommon.DispTitleEnum.Post:
6948 if (this.history != null && this.history.Count > 1)
6949 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6951 case MyCommon.DispTitleEnum.UnreadRepCount:
6952 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6954 case MyCommon.DispTitleEnum.UnreadAllCount:
6955 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6957 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6958 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6960 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6961 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6963 case MyCommon.DispTitleEnum.OwnStatus:
6964 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6965 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6971 this.Text = ttl.ToString();
6973 catch (AccessViolationException)
6975 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6979 private string GetStatusLabelText()
6982 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6983 if (this.statuses == null) return "";
6984 var tbRep = this.statuses.MentionTab;
6985 var tbDm = this.statuses.DirectMessageTab;
6986 if (tbRep == null || tbDm == null) return "";
6987 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6992 var slbl = new StringBuilder(256);
6995 foreach (var tab in this.statuses.Tabs)
6997 ur += tab.UnreadCount;
6999 if (tab.TabName == this.CurrentTabName)
7001 tur = tab.UnreadCount;
7011 this.unreadCounter = ur;
7012 this.unreadAtCounter = urat;
7014 var homeTab = this.statuses.HomeTab;
7016 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7017 if (this.settings.Common.TimelinePeriod == 0)
7019 slbl.Append(Properties.Resources.SetStatusLabelText2);
7023 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7025 return slbl.ToString();
7028 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7032 if (this.InvokeRequired && !this.IsDisposed)
7034 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7038 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7039 this.SetApiStatusLabel(endpointName);
7042 catch (ObjectDisposedException)
7046 catch (InvalidOperationException)
7052 private void SetApiStatusLabel(string? endpointName = null)
7054 var tabType = this.CurrentTab.TabType;
7056 if (endpointName == null)
7059 endpointName = tabType switch
7061 MyCommon.TabUsageType.Home => GetTimelineRequest.EndpointName,
7062 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7063 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7064 MyCommon.TabUsageType.Favorites => "/favorites/list",
7065 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7066 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7067 MyCommon.TabUsageType.Lists => "/lists/statuses",
7068 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7069 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7072 this.toolStripApiGauge.ApiEndpoint = endpointName;
7076 // 表示中のタブに関連する endpoint であれば更新
7078 if (endpointName == GetTimelineRequest.EndpointName)
7080 update = tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined;
7084 update = endpointName switch
7086 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7087 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7088 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7089 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7090 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7091 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7092 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7099 this.toolStripApiGauge.ApiEndpoint = endpointName;
7104 private void SetStatusLabelUrl()
7105 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7107 public void SetStatusLabel(string text)
7108 => this.StatusLabel.Text = text;
7110 private void SetNotifyIconText()
7112 var ur = new StringBuilder(64);
7114 // タスクトレイアイコンのツールチップテキスト書き換え
7116 ur.Remove(0, ur.Length);
7117 if (this.settings.Common.DispUsername)
7119 ur.Append(this.tw.Username);
7122 ur.Append(ApplicationSettings.ApplicationName);
7124 ur.Append("(Debug Build)");
7126 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7129 ur.Append(this.unreadCounter);
7131 ur.Append(this.unreadAtCounter);
7134 this.NotifyIcon1.Text = ur.ToString();
7137 internal void CheckReplyTo(string statusText)
7141 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7143 foreach (Match hm in m)
7145 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7147 hstr += "#" + hm.Result("$3") + " ";
7148 this.HashSupl.AddItem("#" + hm.Result("$3"));
7151 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7153 hstr += this.HashMgr.UseHash;
7155 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7157 // 本当にリプライ先指定すべきかどうかの判定
7158 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7160 if (this.settings.Common.UseAtIdSupplement)
7162 var bCnt = this.AtIdSupl.ItemCount;
7163 foreach (Match mid in m)
7165 this.AtIdSupl.AddItem(mid.Result("${id}"));
7167 if (bCnt != this.AtIdSupl.ItemCount)
7168 this.MarkSettingAtIdModified();
7171 // リプライ先ステータスIDの指定がない場合は指定しない
7172 if (this.inReplyTo == null)
7176 // 次の条件を満たす場合に in_reply_to_status_id 指定
7177 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7178 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7179 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7183 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7184 if (statusText.StartsWith("@", StringComparison.Ordinal))
7186 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7190 foreach (Match mid in m)
7192 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7197 this.inReplyTo = null;
7200 private void TweenMain_Resize(object sender, EventArgs e)
7202 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7204 this.Visible = false;
7206 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7208 // 現在の DPI と設定保存時の DPI との比を取得する
7209 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7211 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7214 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7215 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7216 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7218 this.SplitContainer1.SplitterDistance = splitterDistance;
7222 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7223 if (this.StatusText.Multiline)
7225 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7226 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7227 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7229 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7231 this.StatusText.Height = statusTextHeight;
7235 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7237 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7241 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7242 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7244 this.SplitContainer3.SplitterDistance = previewDistance;
7247 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7248 this.SplitContainer3.Panel2Collapsed = true;
7250 this.initialLayout = false;
7252 if (this.WindowState != FormWindowState.Minimized)
7254 this.formWindowState = this.WindowState;
7258 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7260 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7261 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7262 if (this.PlaySoundMenuItem.Checked)
7264 this.settings.Common.PlaySound = true;
7268 this.settings.Common.PlaySound = false;
7270 this.MarkSettingCommonModified();
7273 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7275 if (this.initialLayout)
7278 int splitterDistance;
7279 switch (this.WindowState)
7281 case FormWindowState.Normal:
7282 splitterDistance = this.SplitContainer1.SplitterDistance;
7284 case FormWindowState.Maximized:
7285 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7286 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7287 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7288 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7294 this.mySpDis = splitterDistance;
7295 this.MarkSettingLocalModified();
7298 private async Task DoRepliedStatusOpen()
7300 var currentPost = this.CurrentPost;
7301 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7303 if (MyCommon.IsKeyDown(Keys.Shift))
7305 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7308 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
7310 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7314 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7316 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
7317 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
7318 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7321 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7326 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7327 => await this.DoRepliedStatusOpen();
7329 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7331 if (this.initialLayout)
7332 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7334 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7335 if (multiline != this.StatusText.Multiline)
7337 this.StatusText.Multiline = multiline;
7338 this.settings.Local.StatusMultiline = multiline;
7339 this.MarkSettingLocalModified();
7343 private void StatusText_MultilineChanged(object sender, EventArgs e)
7345 if (this.StatusText.Multiline)
7346 this.StatusText.ScrollBars = ScrollBars.Vertical;
7348 this.StatusText.ScrollBars = ScrollBars.None;
7350 if (!this.initialLayout)
7351 this.MarkSettingLocalModified();
7354 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7357 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7358 this.StatusText.Multiline = menuItemChecked;
7359 this.settings.Local.StatusMultiline = menuItemChecked;
7360 if (menuItemChecked)
7362 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7363 this.SplitContainer2.SplitterDistance = 0;
7365 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7369 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7371 this.MarkSettingLocalModified();
7374 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7376 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7378 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7379 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7380 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7382 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7387 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7388 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7389 // Appendix A. Collected ABNF for URI
7390 // http://www.ietf.org/rfc/rfc3986.txt
7392 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7395 if (this.StatusText.SelectionLength > 0)
7397 var tmp = this.StatusText.SelectedText;
7398 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7399 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7401 // 文字列が選択されている場合はその文字列について処理
7403 // nico.ms使用、nicovideoにマッチしたら変換
7404 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7406 result = Nicoms.Shorten(tmp);
7408 else if (converterType != MyCommon.UrlConverter.Nicoms)
7413 var srcUri = new Uri(tmp);
7414 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7415 result = resultUri.AbsoluteUri;
7417 catch (WebApiException e)
7419 this.StatusLabel.Text = converterType + ":" + e.Message;
7422 catch (UriFormatException e)
7424 this.StatusLabel.Text = converterType + ":" + e.Message;
7433 if (!MyCommon.IsNullOrEmpty(result))
7435 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7436 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7437 if (origUrlIndex == -1)
7440 this.StatusText.Select(origUrlIndex, tmp.Length);
7441 this.StatusText.SelectedText = result;
7444 var undo = new UrlUndo
7450 if (this.urlUndoBuffer == null)
7452 this.urlUndoBuffer = new List<UrlUndo>();
7453 this.UrlUndoToolStripMenuItem.Enabled = true;
7456 this.urlUndoBuffer.Add(undo);
7462 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7463 @"(?<url>(?<protocol>https?://)" +
7464 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7465 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7466 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7467 // 正規表現にマッチしたURL文字列をtinyurl化
7468 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7470 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7472 var tmp = mt.Result("${url}");
7473 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7474 tmp = "http://" + tmp;
7477 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7479 // nico.ms使用、nicovideoにマッチしたら変換
7480 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7482 result = Nicoms.Shorten(tmp);
7484 else if (converterType != MyCommon.UrlConverter.Nicoms)
7489 var srcUri = new Uri(tmp);
7490 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7491 result = resultUri.AbsoluteUri;
7493 catch (HttpRequestException e)
7495 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7496 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7497 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7499 this.StatusLabel.Text = converterType + ":" + message;
7502 catch (WebApiException e)
7504 this.StatusLabel.Text = converterType + ":" + e.Message;
7507 catch (UriFormatException e)
7509 this.StatusLabel.Text = converterType + ":" + e.Message;
7518 if (!MyCommon.IsNullOrEmpty(result))
7520 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7521 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7522 if (origUrlIndex == -1)
7525 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7526 this.StatusText.SelectedText = result;
7528 var undo = new UrlUndo
7530 Before = mt.Result("${url}"),
7534 if (this.urlUndoBuffer == null)
7536 this.urlUndoBuffer = new List<UrlUndo>();
7537 this.UrlUndoToolStripMenuItem.Enabled = true;
7540 this.urlUndoBuffer.Add(undo);
7548 private void DoUrlUndo()
7550 if (this.urlUndoBuffer != null)
7552 var tmp = this.StatusText.Text;
7553 foreach (var data in this.urlUndoBuffer)
7555 tmp = tmp.Replace(data.After, data.Before);
7557 this.StatusText.Text = tmp;
7558 this.urlUndoBuffer = null;
7559 this.UrlUndoToolStripMenuItem.Enabled = false;
7560 this.StatusText.SelectionStart = 0;
7561 this.StatusText.SelectionLength = 0;
7565 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7566 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7568 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7569 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7571 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7572 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7574 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7576 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7578 var rnd = new Random();
7580 MyCommon.UrlConverter svc;
7581 // 前回使用した短縮URLサービス以外を選択する
7584 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7586 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7587 await this.UrlConvertAsync(svc);
7591 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7592 => this.DoUrlUndo();
7594 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7596 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7597 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7598 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7599 this.MarkSettingCommonModified();
7602 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7604 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7605 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7606 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7607 this.MarkSettingCommonModified();
7610 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7612 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7613 this.MenuStrip1.Tag = new object();
7614 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7617 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7619 var currentTabPage = this.CurrentTabPage;
7620 if (this.Tag != null) // 設定された戻り先へ遷移
7622 if (this.Tag == currentTabPage)
7623 ((Control)currentTabPage.Tag).Select();
7625 ((Control)this.Tag).Select();
7627 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7629 this.Tag = currentTabPage.Tag;
7630 ((Control)this.Tag).Select();
7632 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7633 this.MenuStrip1.Tag = null;
7636 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7638 if (this.Use2ColumnsMode)
7644 var lst = (DetailsListView)sender;
7645 var columnsCount = lst.Columns.Count;
7647 var darr = new int[columnsCount];
7648 for (var i = 0; i < columnsCount; i++)
7649 darr[lst.Columns[i].DisplayIndex] = i;
7651 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7653 for (var i = 0; i < columnsCount; i++)
7654 this.settings.Local.ColumnsOrder[darr[i]] = i;
7656 this.MarkSettingLocalModified();
7657 this.isColumnChanged = true;
7660 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7662 var lst = (DetailsListView)sender;
7663 if (this.settings.Local == null) return;
7665 var modified = false;
7666 if (this.Use2ColumnsMode)
7668 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7670 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7673 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7675 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7681 var columnsCount = lst.Columns.Count;
7682 for (var i = 0; i < columnsCount; i++)
7684 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7687 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7693 this.MarkSettingLocalModified();
7694 this.isColumnChanged = true;
7698 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7700 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7701 this.MarkSettingLocalModified();
7704 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7706 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7708 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7710 this.SelectMedia_DragDrop(e);
7713 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7715 var (url, title) = GetUrlFromDataObject(e.Data);
7721 appendText = title + " " + url;
7723 if (this.StatusText.TextLength == 0)
7724 this.StatusText.Text = appendText;
7726 this.StatusText.Text += " " + appendText;
7728 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7730 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7732 this.StatusText.Text += text;
7734 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7736 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7737 if (data != null) this.StatusText.Text += data;
7742 /// IDataObject から URL とタイトルの対を取得します
7745 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7747 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7748 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7749 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7751 if (data.GetDataPresent("text/x-moz-url"))
7753 // Firefox, Google Chrome で利用可能
7754 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7756 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7757 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7758 if (lines.Length < 2)
7759 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7761 return (lines[0], lines[1]);
7763 else if (data.GetDataPresent("IESiteModeToUrl"))
7765 // Internet Exproler 用
7766 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7768 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7769 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7770 if (lines.Length < 2)
7771 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7773 return (lines[0], lines[1]);
7775 else if (data.GetDataPresent("UniformResourceLocatorW"))
7779 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7780 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7784 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7787 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7789 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7791 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7793 this.SelectMedia_DragEnter(e);
7797 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7799 e.Effect = DragDropEffects.Copy;
7802 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7804 e.Effect = DragDropEffects.Copy;
7807 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7809 e.Effect = DragDropEffects.Copy;
7813 e.Effect = DragDropEffects.None;
7816 private void TweenMain_DragOver(object sender, DragEventArgs e)
7820 public bool IsNetworkAvailable()
7822 var nw = MyCommon.IsNetworkAvailable();
7823 this.myStatusOnline = nw;
7827 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7829 var uriStr = uri.AbsoluteUri;
7831 // OpenTween 内部で使用する URL
7832 if (uri.Authority == "opentween")
7834 await this.OpenInternalUriAsync(uri);
7838 // ハッシュタグを含む Twitter 検索
7839 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7842 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7843 var pos = unescapedQuery.IndexOf('#');
7844 if (pos == -1) return;
7846 var hash = unescapedQuery.Substring(pos);
7847 this.HashSupl.AddItem(hash);
7848 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7849 this.AddNewTabForSearch(hash);
7854 // フラグが立っている場合は設定と逆の動作をする
7855 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7856 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7858 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7859 if (userUriMatch.Success)
7861 var screenName = userUriMatch.Groups["ScreenName"].Value;
7862 if (this.IsTwitterId(screenName))
7864 await this.AddNewTabForUserTimeline(screenName);
7871 await MyCommon.OpenInBrowserAsync(this, uriStr);
7875 /// OpenTween 内部の機能を呼び出すための URL を開きます
7877 private async Task OpenInternalUriAsync(Uri uri)
7879 // ツイートを開く (//opentween/status/:status_id)
7880 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7883 var statusId = long.Parse(match.Groups[1].Value);
7884 await this.OpenRelatedTab(statusId);
7889 private void ListTabSelect(TabPage tabPage)
7891 this.SetListProperty();
7893 var previousTabName = this.CurrentTabName;
7894 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7895 previousListViewState.Save(this.ListLockMenuItem.Checked);
7897 this.listCache?.PurgeCache();
7899 this.statuses.SelectTab(tabPage.Text);
7901 this.InitializeTimelineListView();
7903 var tab = this.CurrentTab;
7906 var listView = this.CurrentListView;
7908 var currentListViewState = this.listViewState[tab.TabName];
7909 currentListViewState.Restore();
7911 if (this.Use2ColumnsMode)
7913 listView.Columns[1].Text = this.columnText[2];
7917 for (var i = 0; i < listView.Columns.Count; i++)
7919 listView.Columns[i].Text = this.columnText[i];
7924 private void InitializeTimelineListView()
7926 var listView = this.CurrentListView;
7927 var tab = this.CurrentTab;
7929 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7930 (this.listCache, var oldCache) = (newCache, this.listCache);
7931 oldCache?.Dispose();
7933 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager)
7935 IconSize = this.settings.Common.IconSize,
7937 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7938 oldDrawer?.Dispose();
7941 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7942 => this.ListTabSelect(e.TabPage);
7944 private void SelectListItem(DetailsListView lView, int index)
7947 var bnd = new Rectangle();
7949 var item = lView.FocusedItem;
7958 lView.SelectedIndices.Clear();
7960 while (lView.SelectedIndices.Count > 0);
7961 item = lView.Items[index];
7962 item.Selected = true;
7963 item.Focused = true;
7965 if (flg) lView.Invalidate(bnd);
7968 private async void TweenMain_Shown(object sender, EventArgs e)
7970 this.NotifyIcon1.Visible = true;
7972 if (this.IsNetworkAvailable())
7974 var loadTasks = new List<Task>
7976 this.RefreshMuteUserIdsAsync(),
7977 this.RefreshBlockIdsAsync(),
7978 this.RefreshNoRetweetIdsAsync(),
7979 this.RefreshTwitterConfigurationAsync(),
7980 this.RefreshTabAsync<HomeTabModel>(),
7981 this.RefreshTabAsync<MentionsTabModel>(),
7982 this.RefreshTabAsync<DirectMessagesTabModel>(),
7983 this.RefreshTabAsync<PublicSearchTabModel>(),
7984 this.RefreshTabAsync<UserTimelineTabModel>(),
7985 this.RefreshTabAsync<ListTimelineTabModel>(),
7988 if (this.settings.Common.StartupFollowers)
7989 loadTasks.Add(this.RefreshFollowerIdsAsync());
7991 if (this.settings.Common.GetFav)
7992 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
7994 var allTasks = Task.WhenAll(loadTasks);
7999 var timeout = Task.Delay(5000);
8000 if (await Task.WhenAny(allTasks, timeout) != timeout)
8004 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
8006 if (MyCommon.EndingFlag)
8010 if (MyCommon.EndingFlag) return;
8012 if (ApplicationSettings.VersionInfoUrl != null)
8014 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8015 if (this.settings.Common.StartupVersion)
8016 await this.CheckNewVersion(true);
8020 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8021 this.VerUpMenuItem.Enabled = false;
8022 this.VerUpMenuItem.Available = false;
8023 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8026 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8027 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8029 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8030 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8034 var reloadTasks = new List<Task>();
8036 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8037 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8039 if (!this.tw.GetNoRetweetSuccess)
8040 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8042 if (this.tw.Configuration.PhotoSizeLimit == 0)
8043 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8045 await Task.WhenAll(reloadTasks);
8048 this.initial = false;
8050 this.timelineScheduler.Enabled = true;
8053 private async Task DoGetFollowersMenu()
8055 await this.RefreshFollowerIdsAsync();
8056 this.DispSelectedPost(true);
8059 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8060 => await this.DoGetFollowersMenu();
8062 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8063 => this.DoReTweetUnofficial();
8065 private async Task DoReTweetOfficial(bool isConfirm)
8068 if (this.ExistCurrentPost)
8070 var selectedPosts = this.CurrentTab.SelectedPosts;
8072 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8074 if (selectedPosts.Any(x => x.IsProtect))
8075 MessageBox.Show("Protected.");
8077 this.doFavRetweetFlags = false;
8081 if (selectedPosts.Length > 15)
8083 MessageBox.Show(Properties.Resources.RetweetLimitText);
8084 this.doFavRetweetFlags = false;
8087 else if (selectedPosts.Length > 1)
8089 var questionText = Properties.Resources.RetweetQuestion2;
8090 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8091 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8093 case DialogResult.Cancel:
8094 case DialogResult.No:
8095 this.doFavRetweetFlags = false;
8101 if (!this.settings.Common.RetweetNoConfirm)
8103 var questiontext = Properties.Resources.RetweetQuestion1;
8104 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8105 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8107 this.doFavRetweetFlags = false;
8113 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8115 await this.RetweetAsync(statusIds);
8119 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8120 => await this.DoReTweetOfficial(true);
8122 private async Task FavoritesRetweetOfficial()
8124 if (!this.ExistCurrentPost) return;
8125 this.doFavRetweetFlags = true;
8126 var retweetTask = this.DoReTweetOfficial(true);
8127 if (this.doFavRetweetFlags)
8129 this.doFavRetweetFlags = false;
8130 var favoriteTask = this.FavoriteChange(true, false);
8132 await Task.WhenAll(retweetTask, favoriteTask);
8140 private async Task FavoritesRetweetUnofficial()
8142 var post = this.CurrentPost;
8143 if (this.ExistCurrentPost && post != null && !post.IsDm)
8145 this.doFavRetweetFlags = true;
8146 var favoriteTask = this.FavoriteChange(true);
8147 if (!post.IsProtect && this.doFavRetweetFlags)
8149 this.doFavRetweetFlags = false;
8150 this.DoReTweetUnofficial();
8158 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8160 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8161 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8162 /// <returns>復元されたツイート本文</returns>
8163 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8165 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8168 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
8170 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8172 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8174 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
8178 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8180 statusHtml = statusHtml.Replace("<br>", " ");
8182 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8183 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8184 statusHtml = statusHtml.Replace(" ", " ");
8186 return WebUtility.HtmlDecode(statusHtml);
8189 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8191 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8193 if (this.CurrentPost != null)
8194 this.DispSelectedPost(true);
8197 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8199 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8200 this.DebugModeToolStripMenuItem.Visible = true;
8202 this.DebugModeToolStripMenuItem.Visible = false;
8205 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8206 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8208 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8209 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8211 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8212 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8214 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8216 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8217 this.MarkSettingCommonModified();
8220 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8222 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8223 this.MarkSettingCommonModified();
8226 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8228 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8229 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8230 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8231 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8232 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8233 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8236 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8238 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8239 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8240 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8241 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8242 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8243 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8246 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8248 if (this.TraceOutToolStripMenuItem.Checked)
8249 MyCommon.TraceFlag = true;
8251 MyCommon.TraceFlag = false;
8254 private void TweenMain_Deactivate(object sender, EventArgs e)
8255 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8257 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8259 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8261 _ = this.TabRename(this.rclickTabName, out _);
8264 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8265 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8267 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8268 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8270 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8272 TwitterApiStatus? apiStatus;
8274 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8276 var cancellationToken = dialog.EnableCancellation();
8280 var task = this.tw.GetInfoApi();
8281 apiStatus = await dialog.WaitForAsync(this, task);
8283 catch (WebApiException)
8288 if (cancellationToken.IsCancellationRequested)
8291 if (apiStatus == null)
8293 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8298 using var apiDlg = new ApiInfoDialog();
8299 apiDlg.ShowDialog(this);
8302 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8304 var id = this.CurrentPost?.ScreenName ?? "";
8306 await this.FollowCommand(id);
8309 internal async Task FollowCommand(string id)
8311 using (var inputName = new InputTabName())
8313 inputName.FormTitle = "Follow";
8314 inputName.FormDescription = Properties.Resources.FRMessage1;
8315 inputName.TabName = id;
8317 if (inputName.ShowDialog(this) != DialogResult.OK)
8319 if (string.IsNullOrWhiteSpace(inputName.TabName))
8322 id = inputName.TabName.Trim();
8325 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8329 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8330 await dialog.WaitForAsync(this, task);
8332 catch (WebApiException ex)
8334 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8339 MessageBox.Show(Properties.Resources.FRMessage3);
8342 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8344 var id = this.CurrentPost?.ScreenName ?? "";
8346 await this.RemoveCommand(id, false);
8349 internal async Task RemoveCommand(string id, bool skipInput)
8353 using var inputName = new InputTabName();
8354 inputName.FormTitle = "Unfollow";
8355 inputName.FormDescription = Properties.Resources.FRMessage1;
8356 inputName.TabName = id;
8358 if (inputName.ShowDialog(this) != DialogResult.OK)
8360 if (string.IsNullOrWhiteSpace(inputName.TabName))
8363 id = inputName.TabName.Trim();
8366 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8370 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8371 await dialog.WaitForAsync(this, task);
8373 catch (WebApiException ex)
8375 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8380 MessageBox.Show(Properties.Resources.FRMessage3);
8383 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8385 var id = this.CurrentPost?.ScreenName ?? "";
8387 await this.ShowFriendship(id);
8390 internal async Task ShowFriendship(string id)
8392 using (var inputName = new InputTabName())
8394 inputName.FormTitle = "Show Friendships";
8395 inputName.FormDescription = Properties.Resources.FRMessage1;
8396 inputName.TabName = id;
8398 if (inputName.ShowDialog(this) != DialogResult.OK)
8400 if (string.IsNullOrWhiteSpace(inputName.TabName))
8403 id = inputName.TabName.Trim();
8406 bool isFollowing, isFollowed;
8408 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8410 var cancellationToken = dialog.EnableCancellation();
8414 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8415 var friendship = await dialog.WaitForAsync(this, task);
8417 isFollowing = friendship.Relationship.Source.Following;
8418 isFollowed = friendship.Relationship.Source.FollowedBy;
8420 catch (WebApiException ex)
8422 if (!cancellationToken.IsCancellationRequested)
8423 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8427 if (cancellationToken.IsCancellationRequested)
8434 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8438 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8442 result += Properties.Resources.GetFriendshipInfo3;
8446 result += Properties.Resources.GetFriendshipInfo4;
8448 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8449 MessageBox.Show(result);
8452 internal async Task ShowFriendship(string[] ids)
8454 foreach (var id in ids)
8456 bool isFollowing, isFollowed;
8458 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8460 var cancellationToken = dialog.EnableCancellation();
8464 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8465 var friendship = await dialog.WaitForAsync(this, task);
8467 isFollowing = friendship.Relationship.Source.Following;
8468 isFollowed = friendship.Relationship.Source.FollowedBy;
8470 catch (WebApiException ex)
8472 if (!cancellationToken.IsCancellationRequested)
8473 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8477 if (cancellationToken.IsCancellationRequested)
8487 ff += Properties.Resources.GetFriendshipInfo1;
8491 ff += Properties.Resources.GetFriendshipInfo2;
8494 ff += System.Environment.NewLine + " ";
8497 ff += Properties.Resources.GetFriendshipInfo3;
8501 ff += Properties.Resources.GetFriendshipInfo4;
8503 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8506 if (MessageBox.Show(
8507 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8508 Properties.Resources.GetFriendshipInfo8,
8509 MessageBoxButtons.YesNo,
8510 MessageBoxIcon.Question,
8511 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8513 await this.RemoveCommand(id, true);
8518 MessageBox.Show(result);
8523 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8524 => await this.DoShowUserStatus(this.tw.Username, false);
8526 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8529 public bool IsTwitterId(string name)
8531 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8532 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8534 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8537 private void DoQuoteOfficial()
8539 var post = this.CurrentPost;
8540 if (this.ExistCurrentPost && post != null)
8542 if (post.IsDm || !this.StatusText.Enabled)
8547 MessageBox.Show("Protected.");
8551 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8553 this.inReplyTo = null;
8555 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8557 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8558 this.StatusText.Focus();
8562 private void DoReTweetUnofficial()
8565 var post = this.CurrentPost;
8566 if (this.ExistCurrentPost && post != null)
8568 if (post.IsDm || !this.StatusText.Enabled)
8573 MessageBox.Show("Protected.");
8576 var rtdata = post.Text;
8577 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8579 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8581 // 投稿時に in_reply_to_status_id を付加する
8582 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8583 var inReplyToScreenName = post.ScreenName;
8584 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8586 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8588 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8589 this.StatusText.Focus();
8593 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8594 => this.DoQuoteOfficial();
8596 private async void SearchButton_Click(object sender, EventArgs e)
8599 var pnl = ((Control)sender).Parent;
8600 if (pnl == null) return;
8601 var tbName = pnl.Parent.Text;
8602 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8603 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8604 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8605 cmb.Text = cmb.Text.Trim();
8606 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8608 var buf = new StringBuilder();
8609 var c = cmb.Text.ToCharArray();
8610 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8612 if (cnt > cmb.Text.Length - 4)
8614 buf.Append(cmb.Text.Substring(cnt));
8623 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8632 cmb.Text = buf.ToString();
8634 var listView = (DetailsListView)pnl.Parent.Tag;
8636 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8638 tb.SearchWords = cmb.Text;
8639 tb.SearchLang = cmbLang.Text;
8640 if (MyCommon.IsNullOrEmpty(cmb.Text))
8643 this.SaveConfigsTabs();
8648 var idx = cmb.Items.IndexOf(tb.SearchWords);
8649 if (idx > -1) cmb.Items.RemoveAt(idx);
8650 cmb.Items.Insert(0, tb.SearchWords);
8651 cmb.Text = tb.SearchWords;
8653 this.statuses.ClearTabIds(tbName);
8654 this.listCache?.PurgeCache();
8655 this.listCache?.UpdateListSize();
8656 this.SaveConfigsTabs(); // 検索条件の保存
8660 await this.RefreshTabAsync(tb);
8663 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8664 => await this.DoRefreshMore(); // もっと前を取得
8667 /// 指定されたタブのListTabにおける位置を返します
8670 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8672 public int GetTabPageIndex(string tabName)
8673 => this.statuses.Tabs.IndexOf(tabName);
8675 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8677 if (this.statuses.RemovedTab.Count == 0)
8679 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
8684 var tb = this.statuses.RemovedTab.Pop();
8685 if (tb.TabType == MyCommon.TabUsageType.Related)
8687 var relatedTab = this.statuses.GetTabByType(MyCommon.TabUsageType.Related);
8688 if (relatedTab != null)
8690 // 関連発言なら既存のタブを置き換える
8691 tb.TabName = relatedTab.TabName;
8692 this.ClearTab(tb.TabName, false);
8694 this.statuses.ReplaceTab(tb);
8696 var tabIndex = this.statuses.Tabs.IndexOf(tb);
8697 this.ListTab.SelectedIndex = tabIndex;
8701 const string TabName = "Related Tweets";
8702 var renamed = TabName;
8703 for (var i = 2; i <= 100; i++)
8705 if (!this.statuses.ContainsTab(renamed))
8707 renamed = TabName + i;
8709 tb.TabName = renamed;
8711 this.statuses.AddTab(tb);
8712 this.AddNewTab(tb, startup: false);
8714 var tabIndex = this.statuses.Tabs.Count - 1;
8715 this.ListTab.SelectedIndex = tabIndex;
8720 var renamed = tb.TabName;
8721 for (var i = 1; i < int.MaxValue; i++)
8723 if (!this.statuses.ContainsTab(renamed))
8725 renamed = tb.TabName + "(" + i + ")";
8727 tb.TabName = renamed;
8729 this.statuses.AddTab(tb);
8730 this.AddNewTab(tb, startup: false);
8732 var tabIndex = this.statuses.Tabs.Count - 1;
8733 this.ListTab.SelectedIndex = tabIndex;
8735 this.SaveConfigsTabs();
8739 private async Task DoMoveToRTHome()
8741 var post = this.CurrentPost;
8742 if (post != null && post.RetweetedId != null)
8743 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8746 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8747 => await this.DoMoveToRTHome();
8749 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8751 var screenName = this.CurrentPost?.ScreenName;
8752 if (screenName != null)
8753 this.ListManageUserContext(screenName);
8756 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8758 var screenName = this.CurrentPost?.RetweetedBy;
8759 if (screenName != null)
8760 this.ListManageUserContext(screenName);
8763 public void ListManageUserContext(string screenName)
8765 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8766 listSelectForm.ShowDialog(this);
8769 private void SearchControls_Enter(object sender, EventArgs e)
8771 var pnl = (Control)sender;
8772 foreach (Control ctl in pnl.Controls)
8778 private void SearchControls_Leave(object sender, EventArgs e)
8780 var pnl = (Control)sender;
8781 foreach (Control ctl in pnl.Controls)
8783 ctl.TabStop = false;
8787 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8789 var tab = this.CurrentTab;
8790 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8791 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8794 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8795 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8797 private void HashManageMenuItem_Click(object sender, EventArgs e)
8802 rslt = this.HashMgr.ShowDialog();
8808 this.TopMost = this.settings.Common.AlwaysTop;
8809 if (rslt == DialogResult.Cancel) return;
8810 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8812 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8813 this.HashTogglePullDownMenuItem.Checked = true;
8814 this.HashToggleMenuItem.Checked = true;
8818 this.HashStripSplitButton.Text = "#[-]";
8819 this.HashTogglePullDownMenuItem.Checked = false;
8820 this.HashToggleMenuItem.Checked = false;
8823 this.MarkSettingCommonModified();
8824 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8827 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8829 this.HashMgr.ToggleHash();
8830 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8832 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8833 this.HashToggleMenuItem.Checked = true;
8834 this.HashTogglePullDownMenuItem.Checked = true;
8838 this.HashStripSplitButton.Text = "#[-]";
8839 this.HashToggleMenuItem.Checked = false;
8840 this.HashTogglePullDownMenuItem.Checked = false;
8842 this.MarkSettingCommonModified();
8843 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8846 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8847 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8849 public void SetPermanentHashtag(string hashtag)
8851 this.HashMgr.SetPermanentHash("#" + hashtag);
8852 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8853 this.HashTogglePullDownMenuItem.Checked = true;
8854 this.HashToggleMenuItem.Checked = true;
8856 this.MarkSettingCommonModified();
8859 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8861 var tab = this.CurrentTab;
8862 var post = this.CurrentPost;
8863 if (!this.ExistCurrentPost)
8865 this.ReplyOpMenuItem.Enabled = false;
8866 this.ReplyAllOpMenuItem.Enabled = false;
8867 this.DmOpMenuItem.Enabled = false;
8868 this.CreateTabRuleOpMenuItem.Enabled = false;
8869 this.CreateIdRuleOpMenuItem.Enabled = false;
8870 this.CreateSourceRuleOpMenuItem.Enabled = false;
8871 this.ReadOpMenuItem.Enabled = false;
8872 this.UnreadOpMenuItem.Enabled = false;
8873 this.AuthorMenuItem.Visible = false;
8874 this.RetweetedByMenuItem.Visible = false;
8878 this.ReplyOpMenuItem.Enabled = true;
8879 this.ReplyAllOpMenuItem.Enabled = true;
8880 this.DmOpMenuItem.Enabled = true;
8881 this.CreateTabRuleOpMenuItem.Enabled = true;
8882 this.CreateIdRuleOpMenuItem.Enabled = true;
8883 this.CreateSourceRuleOpMenuItem.Enabled = true;
8884 this.ReadOpMenuItem.Enabled = true;
8885 this.UnreadOpMenuItem.Enabled = true;
8886 this.AuthorMenuItem.Visible = true;
8887 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8888 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8889 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8892 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8894 this.FavOpMenuItem.Enabled = false;
8895 this.UnFavOpMenuItem.Enabled = false;
8896 this.OpenStatusOpMenuItem.Enabled = false;
8897 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8898 this.RtOpMenuItem.Enabled = false;
8899 this.RtUnOpMenuItem.Enabled = false;
8900 this.QtOpMenuItem.Enabled = false;
8901 this.FavoriteRetweetMenuItem.Enabled = false;
8902 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8906 this.FavOpMenuItem.Enabled = true;
8907 this.UnFavOpMenuItem.Enabled = true;
8908 this.OpenStatusOpMenuItem.Enabled = true;
8909 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8911 if (!post.CanRetweetBy(this.tw.UserId))
8913 this.RtOpMenuItem.Enabled = false;
8914 this.RtUnOpMenuItem.Enabled = false;
8915 this.QtOpMenuItem.Enabled = false;
8916 this.FavoriteRetweetMenuItem.Enabled = false;
8917 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8921 this.RtOpMenuItem.Enabled = true;
8922 this.RtUnOpMenuItem.Enabled = true;
8923 this.QtOpMenuItem.Enabled = true;
8924 this.FavoriteRetweetMenuItem.Enabled = true;
8925 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8929 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8931 this.RefreshPrevOpMenuItem.Enabled = true;
8935 this.RefreshPrevOpMenuItem.Enabled = false;
8937 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8939 this.OpenRepSourceOpMenuItem.Enabled = false;
8943 this.OpenRepSourceOpMenuItem.Enabled = true;
8946 if (this.ExistCurrentPost && post != null)
8948 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8952 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8953 => this.ContextMenuTabProperty_Opening(sender, null!);
8955 public Twitter TwitterInstance
8958 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8960 if (this.initialLayout)
8963 int splitterDistance;
8964 switch (this.WindowState)
8966 case FormWindowState.Normal:
8967 splitterDistance = this.SplitContainer3.SplitterDistance;
8969 case FormWindowState.Maximized:
8970 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8971 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8972 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8973 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8979 this.mySpDis3 = splitterDistance;
8980 this.MarkSettingLocalModified();
8983 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8985 if (this.statuses.RemovedTab.Count == 0)
8987 this.UndoRemoveTabMenuItem.Enabled = false;
8991 this.UndoRemoveTabMenuItem.Enabled = true;
8994 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8995 this.PublicSearchQueryMenuItem.Enabled = true;
8997 this.PublicSearchQueryMenuItem.Enabled = false;
8999 var post = this.CurrentPost;
9000 if (!this.ExistCurrentPost || post == null)
9002 this.CopySTOTMenuItem.Enabled = false;
9003 this.CopyURLMenuItem.Enabled = false;
9004 this.CopyUserIdStripMenuItem.Enabled = false;
9008 this.CopySTOTMenuItem.Enabled = true;
9009 this.CopyURLMenuItem.Enabled = true;
9010 this.CopyUserIdStripMenuItem.Enabled = true;
9012 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
9013 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
9017 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
9018 => this.SetNotifyIconText();
9020 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
9021 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
9023 private async Task DoShowUserStatus(string id, bool showInputDialog)
9025 TwitterUser? user = null;
9027 if (showInputDialog)
9029 using var inputName = new InputTabName();
9030 inputName.FormTitle = "Show UserStatus";
9031 inputName.FormDescription = Properties.Resources.FRMessage1;
9032 inputName.TabName = id;
9034 if (inputName.ShowDialog(this) != DialogResult.OK)
9036 if (string.IsNullOrWhiteSpace(inputName.TabName))
9039 id = inputName.TabName.Trim();
9042 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9044 var cancellationToken = dialog.EnableCancellation();
9048 var task = this.tw.Api.UsersShow(id);
9049 user = await dialog.WaitForAsync(this, task);
9051 catch (WebApiException ex)
9053 if (!cancellationToken.IsCancellationRequested)
9054 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9058 if (cancellationToken.IsCancellationRequested)
9062 await this.DoShowUserStatus(user);
9065 private async Task DoShowUserStatus(TwitterUser user)
9067 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9068 var showUserTask = userDialog.ShowUserAsync(user);
9069 userDialog.ShowDialog(this);
9072 this.BringToFront();
9074 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9078 internal Task ShowUserStatus(string id, bool showInputDialog)
9079 => this.DoShowUserStatus(id, showInputDialog);
9081 internal Task ShowUserStatus(string id)
9082 => this.DoShowUserStatus(id, true);
9084 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9086 var post = this.CurrentPost;
9089 await this.ShowUserStatus(post.ScreenName, false);
9093 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9095 var retweetedBy = this.CurrentPost?.RetweetedBy;
9096 if (retweetedBy != null)
9098 await this.ShowUserStatus(retweetedBy, false);
9102 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9104 var post = this.CurrentPost;
9105 if (!this.ExistCurrentPost || post == null)
9108 var statusId = post.RetweetedId ?? post.StatusId;
9109 TwitterStatus status;
9111 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9113 var cancellationToken = dialog.EnableCancellation();
9117 var task = this.tw.Api.StatusesShow(statusId);
9118 status = await dialog.WaitForAsync(this, task);
9120 catch (WebApiException ex)
9122 if (!cancellationToken.IsCancellationRequested)
9123 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9127 if (cancellationToken.IsCancellationRequested)
9131 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9134 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9136 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9139 this.Visible = false;
9141 else if (Form.ActiveForm == null)
9143 this.Visible = true;
9144 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9146 this.BringToFront();
9147 this.StatusText.Focus();
9151 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9152 => this.MultiLinePullDownMenuItem.PerformClick();
9155 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9157 if (this.ImageSelector.Visible)
9158 this.ImageSelector.EndSelection();
9160 this.ImageSelector.BeginSelection();
9163 private void SelectMedia_DragEnter(DragEventArgs e)
9165 if (this.ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9167 e.Effect = DragDropEffects.Copy;
9170 e.Effect = DragDropEffects.None;
9173 private void SelectMedia_DragDrop(DragEventArgs e)
9176 this.BringToFront();
9177 this.ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
9178 this.StatusText.Focus();
9181 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9183 this.TimelinePanel.Visible = false;
9184 this.TimelinePanel.Enabled = false;
9187 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9189 this.TimelinePanel.Visible = true;
9190 this.TimelinePanel.Enabled = true;
9191 this.CurrentListView.Focus();
9194 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9195 => this.AllowDrop = false;
9197 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9198 => this.AllowDrop = true;
9200 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9202 if (this.ImageSelector.Visible)
9204 this.MarkSettingCommonModified();
9205 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9209 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9210 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9213 /// StatusTextでCtrl+Vが押下された時の処理
9215 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9219 if (Clipboard.ContainsText())
9221 // clipboardにテキストがある場合は貼り付け処理
9222 this.StatusText.Paste(Clipboard.GetText());
9224 else if (Clipboard.ContainsImage())
9227 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
9228 Properties.Resources.PostPictureWarn4,
9229 MessageBoxButtons.OKCancel,
9230 MessageBoxIcon.Question,
9231 MessageBoxDefaultButton.Button2)
9235 using var image = Clipboard.GetImage();
9236 this.ImageSelector.BeginSelection(image);
9239 else if (Clipboard.ContainsFileDropList())
9241 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9242 this.ImageSelector.BeginSelection(files);
9245 catch (ExternalException ex)
9247 MessageBox.Show(ex.Message);
9252 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9254 using var form = new ListManage(this.tw);
9255 form.ShowDialog(this);
9258 private bool ModifySettingCommon { get; set; }
9260 private bool ModifySettingLocal { get; set; }
9262 private bool ModifySettingAtId { get; set; }
9264 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9266 var post = this.CurrentPost;
9267 if (this.ExistCurrentPost && post != null && !post.IsDm)
9268 this.RtCountMenuItem.Enabled = true;
9270 this.RtCountMenuItem.Enabled = false;
9273 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9274 => this.CopyUserId();
9276 private void CopyUserId()
9278 var post = this.CurrentPost;
9279 if (post == null) return;
9280 var clstr = post.ScreenName;
9283 Clipboard.SetDataObject(clstr, false, 5, 100);
9285 catch (Exception ex)
9287 MessageBox.Show(ex.Message);
9291 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9293 var post = this.CurrentPost;
9294 if (this.ExistCurrentPost && post != null && !post.IsDm)
9298 await this.OpenRelatedTab(post);
9300 catch (TabException ex)
9302 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9308 /// 指定されたツイートに対する関連発言タブを開きます
9310 /// <param name="statusId">表示するツイートのID</param>
9311 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9312 public async Task OpenRelatedTab(long statusId)
9314 var post = this.statuses[statusId];
9319 post = await this.tw.GetStatusApi(false, statusId);
9321 catch (WebApiException ex)
9323 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9328 await this.OpenRelatedTab(post);
9332 /// 指定されたツイートに対する関連発言タブを開きます
9334 /// <param name="post">表示する対象となるツイート</param>
9335 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9336 private async Task OpenRelatedTab(PostClass post)
9338 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9339 if (tabRelated != null)
9341 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9344 var tabName = this.statuses.MakeTabName("Related Tweets");
9346 tabRelated = new RelatedPostsTabModel(tabName, post)
9348 UnreadManage = false,
9352 this.statuses.AddTab(tabRelated);
9353 this.AddNewTab(tabRelated, startup: false);
9355 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9357 await this.RefreshTabAsync(tabRelated);
9359 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9363 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9365 var tabPage = this.ListTab.TabPages[tabIndex];
9366 var listView = (DetailsListView)tabPage.Tag;
9367 var targetPost = tabRelated.TargetPost;
9368 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9370 if (index != -1 && index < listView.Items.Count)
9372 listView.SelectedIndices.Add(index);
9373 listView.Items[index].Focused = true;
9378 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9380 var buf = new StringBuilder();
9381 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9382 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9383 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9386 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9388 MyCommon.EndingFlag = true;
9392 Application.Restart();
9396 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9400 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9401 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9403 private bool ExistCurrentPost
9407 var post = this.CurrentPost;
9408 return post != null && !post.IsDeleted;
9412 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9413 => await this.ShowUserTimeline();
9415 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9416 => await this.ShowRetweeterTimeline();
9418 private string GetUserIdFromCurPostOrInput(string caption)
9420 var id = this.CurrentPost?.ScreenName ?? "";
9422 using var inputName = new InputTabName();
9423 inputName.FormTitle = caption;
9424 inputName.FormDescription = Properties.Resources.FRMessage1;
9425 inputName.TabName = id;
9427 if (inputName.ShowDialog() == DialogResult.OK &&
9428 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9430 id = inputName.TabName.Trim();
9439 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9441 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9442 if (!MyCommon.IsNullOrEmpty(id))
9444 await this.AddNewTabForUserTimeline(id);
9448 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9450 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9451 this.timelineScheduler.SystemResumed();
9454 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9456 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9458 TimeZoneInfo.ClearCachedData();
9460 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9462 if (curTimeOffset != prevTimeOffset)
9465 this.listCache?.PurgeCache();
9466 this.CurrentListView.Refresh();
9468 this.DispSelectedPost(forceupdate: true);
9471 this.timelineScheduler.Reset();
9474 private void TimelineRefreshEnableChange(bool isEnable)
9476 this.timelineScheduler.Enabled = isEnable;
9479 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9480 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9482 private async Task OpenUserAppointUrl()
9484 if (this.settings.Common.UserAppointUrl != null)
9486 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9488 var post = this.CurrentPost;
9491 var xUrl = this.settings.Common.UserAppointUrl;
9492 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9494 var statusId = post.RetweetedId ?? post.StatusId;
9495 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
9497 await MyCommon.OpenInBrowserAsync(this, xUrl);
9502 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9507 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9508 => await this.OpenUserAppointUrl();
9510 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9512 if (Form.ActiveForm == null)
9514 await this.InvokeAsync(() =>
9516 this.Visible = true;
9517 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9519 this.BringToFront();
9520 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9522 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
9526 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
9532 private void ReplaceAppName()
9534 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9535 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9538 private void TweetThumbnail_ThumbnailLoading(object sender, EventArgs e)
9539 => this.SplitContainer3.Panel2Collapsed = false;
9541 private async void TweetThumbnail_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
9542 => await this.OpenThumbnailPicture(e.Thumbnail);
9544 private async void TweetThumbnail_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
9545 => await MyCommon.OpenInBrowserAsync(this, e.ImageUrl);
9547 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
9549 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
9551 await MyCommon.OpenInBrowserAsync(this, url);
9554 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9555 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9557 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9559 if (e.KeyCode == Keys.Space)
9561 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9563 e.SuppressKeyPress = true;
9567 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9569 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9570 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9571 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9572 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9573 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9575 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9578 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9579 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9581 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9582 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9584 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9585 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9587 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9588 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9590 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9591 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9593 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9595 if (this.settings.Common.IconSize == iconSize) return;
9597 var oldIconCol = this.Use2ColumnsMode;
9599 this.settings.Common.IconSize = iconSize;
9600 this.ApplyListViewIconSize(iconSize);
9602 if (this.Use2ColumnsMode != oldIconCol)
9604 foreach (TabPage tp in this.ListTab.TabPages)
9606 this.ResetColumns((DetailsListView)tp.Tag);
9610 this.CurrentListView.Refresh();
9611 this.MarkSettingCommonModified();
9614 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9616 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9617 if (this.settings.Common.SortOrderLock == state) return;
9619 this.settings.Common.SortOrderLock = state;
9620 this.MarkSettingCommonModified();
9623 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9625 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9627 this.StatusLabelUrl.Text = e.StatusText;
9631 this.SetStatusLabelUrl();