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%\", 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();
1782 if (this.settings.Common.PostAndGet)
1784 await this.RefreshTabAsync<HomeTabModel>();
1790 this.statuses.AddPost(post);
1791 this.statuses.DistributePosts();
1793 this.RefreshTimeline();
1797 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
1799 await this.workerSemaphore.WaitAsync();
1803 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1805 this.RefreshTasktrayIcon();
1806 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1808 catch (WebApiException ex)
1810 this.myStatusError = true;
1811 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1815 this.workerSemaphore.Release();
1819 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
1821 if (ct.IsCancellationRequested)
1824 if (!CheckAccountValid())
1825 throw new WebApiException("Auth error. Check your account");
1828 if (!this.settings.Common.UnreadManage)
1831 read = this.initial && this.settings.Common.Read;
1833 p.Report("Posting...");
1835 var posts = new List<PostClass>();
1837 await Task.Run(async () =>
1839 foreach (var statusId in statusIds)
1841 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1842 if (post != null) posts.Add(post);
1846 if (ct.IsCancellationRequested)
1849 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1851 this.postTimestamps.Add(DateTimeUtc.Now);
1853 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1854 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1856 if (this.postTimestamps[i] < oneHour)
1857 this.postTimestamps.RemoveAt(i);
1860 // 自分のRTはTLの更新では取得できない場合があるので、
1861 // 投稿時取得の有無に関わらず追加しておく
1862 posts.ForEach(post => this.statuses.AddPost(post));
1864 if (this.settings.Common.PostAndGet)
1866 await this.RefreshTabAsync<HomeTabModel>();
1870 this.statuses.DistributePosts();
1871 this.RefreshTimeline();
1875 private async Task RefreshFollowerIdsAsync()
1877 await this.workerSemaphore.WaitAsync();
1881 this.RefreshTasktrayIcon();
1882 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1884 await this.tw.RefreshFollowerIds();
1886 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1888 this.RefreshTimeline();
1889 this.listCache?.PurgeCache();
1890 this.CurrentListView.Refresh();
1892 catch (WebApiException ex)
1894 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1898 this.workerSemaphore.Release();
1902 private async Task RefreshNoRetweetIdsAsync()
1904 await this.workerSemaphore.WaitAsync();
1908 this.RefreshTasktrayIcon();
1909 await this.tw.RefreshNoRetweetIds();
1911 this.StatusLabel.Text = "NoRetweetIds refreshed";
1913 catch (WebApiException ex)
1915 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1919 this.workerSemaphore.Release();
1923 private async Task RefreshBlockIdsAsync()
1925 await this.workerSemaphore.WaitAsync();
1929 this.RefreshTasktrayIcon();
1930 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1932 await this.tw.RefreshBlockIds();
1934 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1936 catch (WebApiException ex)
1938 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1942 this.workerSemaphore.Release();
1946 private async Task RefreshTwitterConfigurationAsync()
1948 await this.workerSemaphore.WaitAsync();
1952 this.RefreshTasktrayIcon();
1953 await this.tw.RefreshConfiguration();
1955 if (this.tw.Configuration.PhotoSizeLimit != 0)
1957 foreach (var service in this.ImageSelector.GetServices())
1959 service.UpdateTwitterConfiguration(this.tw.Configuration);
1963 this.listCache?.PurgeCache();
1964 this.CurrentListView.Refresh();
1966 catch (WebApiException ex)
1968 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1972 this.workerSemaphore.Release();
1976 private async Task RefreshMuteUserIdsAsync()
1978 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1982 await this.tw.RefreshMuteUserIdsAsync();
1984 catch (WebApiException ex)
1986 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1990 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1993 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1995 if (e.Button == MouseButtons.Left)
1997 this.Visible = true;
1998 if (this.WindowState == FormWindowState.Minimized)
2000 this.WindowState = this.formWindowState;
2003 this.BringToFront();
2007 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2008 => await this.ListItemDoubleClickAction();
2010 private async Task ListItemDoubleClickAction()
2012 switch (this.settings.Common.ListDoubleClickAction)
2014 case MyCommon.ListItemDoubleClickActionType.Reply:
2015 this.MakeReplyText();
2017 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2018 this.MakeReplyText(atAll: true);
2020 case MyCommon.ListItemDoubleClickActionType.Favorite:
2021 await this.FavoriteChange(true);
2023 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2024 var post = this.CurrentPost;
2026 await this.ShowUserStatus(post.ScreenName, false);
2028 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2029 await this.ShowUserTimeline();
2031 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2032 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2034 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2035 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2037 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2038 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2040 case MyCommon.ListItemDoubleClickActionType.None:
2047 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2048 => await this.FavoriteChange(true);
2050 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2051 => await this.FavoriteChange(false);
2053 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2054 => await this.FavoritesRetweetOfficial();
2056 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2057 => await this.FavoritesRetweetUnofficial();
2059 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2061 var tab = this.CurrentTab;
2062 var posts = tab.SelectedPosts;
2064 // trueでFavAdd,falseでFavRemove
2065 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2066 || !this.ExistCurrentPost) return;
2068 if (posts.Length > 1)
2073 // https://support.twitter.com/articles/76915#favoriting
2074 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2075 this.doFavRetweetFlags = false;
2080 if (multiFavoriteChangeDialogEnable)
2082 var confirm = MessageBox.Show(
2083 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2084 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2085 MessageBoxButtons.OKCancel,
2086 MessageBoxIcon.Question);
2088 if (confirm == DialogResult.Cancel)
2096 var selectedPost = posts.Single();
2097 if (selectedPost.IsFav)
2099 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2103 await this.FavAddAsync(selectedPost.StatusId, tab);
2107 var selectedPosts = posts.Where(x => x.IsFav);
2108 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2109 if (statusIds.Length == 0)
2111 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2115 await this.FavRemoveAsync(statusIds, tab);
2119 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2121 var post = this.CurrentPost;
2123 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2125 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2128 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2130 if ((!this.initialLayout) && this.Visible)
2132 if (this.WindowState == FormWindowState.Normal)
2134 this.mySize = this.ClientSize;
2135 this.mySpDis = this.SplitContainer1.SplitterDistance;
2136 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2137 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2138 this.MarkSettingLocalModified();
2143 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2145 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2146 if (comparerMode == null)
2149 this.SetSortColumn(comparerMode.Value);
2153 /// 列インデックスからソートを行う ComparerMode を求める
2155 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2156 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2157 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2159 if (this.Use2ColumnsMode)
2160 return ComparerMode.Id;
2162 return columnIndex switch
2164 1 => ComparerMode.Nickname, // ニックネーム
2165 2 => ComparerMode.Data, // 本文
2166 3 => ComparerMode.Id, // 時刻=発言Id
2167 4 => ComparerMode.Name, // 名前
2168 7 => ComparerMode.Source, // Source
2169 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2174 /// 発言一覧の指定した位置の列でソートする
2176 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2177 private void SetSortColumnByDisplayIndex(int columnIndex)
2179 // 表示上の列の位置から ColumnHeader を求める
2180 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2181 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2186 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2187 if (comparerMode == null)
2190 this.SetSortColumn(comparerMode.Value);
2194 /// 発言一覧の最後列の項目でソートする
2196 private void SetSortLastColumn()
2198 // 表示上の最後列にある ColumnHeader を求める
2199 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2200 .OrderByDescending(x => x.DisplayIndex)
2203 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2204 if (comparerMode == null)
2207 this.SetSortColumn(comparerMode.Value);
2211 /// 発言一覧を指定された ComparerMode に基づいてソートする
2213 private void SetSortColumn(ComparerMode sortColumn)
2215 if (this.settings.Common.SortOrderLock)
2218 this.statuses.ToggleSortOrder(sortColumn);
2219 this.InitColumnText();
2221 var list = this.CurrentListView;
2222 if (this.Use2ColumnsMode)
2224 list.Columns[0].Text = this.columnText[0];
2225 list.Columns[1].Text = this.columnText[2];
2229 for (var i = 0; i <= 7; i++)
2231 list.Columns[i].Text = this.columnText[i];
2235 this.listCache?.PurgeCache();
2237 var tab = this.CurrentTab;
2238 var post = this.CurrentPost;
2239 if (tab.AllCount > 0 && post != null)
2241 var idx = tab.IndexOf(post.StatusId);
2244 this.SelectListItem(list, idx);
2245 list.EnsureVisible(idx);
2250 this.MarkSettingCommonModified();
2253 private void TweenMain_LocationChanged(object sender, EventArgs e)
2255 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2257 this.myLoc = this.DesktopLocation;
2258 this.MarkSettingLocalModified();
2262 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2264 var post = this.CurrentPost;
2265 if (!this.ExistCurrentPost)
2267 this.ReplyStripMenuItem.Enabled = false;
2268 this.ReplyAllStripMenuItem.Enabled = false;
2269 this.DMStripMenuItem.Enabled = false;
2270 this.TabMenuItem.Enabled = false;
2271 this.IDRuleMenuItem.Enabled = false;
2272 this.SourceRuleMenuItem.Enabled = false;
2273 this.ReadedStripMenuItem.Enabled = false;
2274 this.UnreadStripMenuItem.Enabled = false;
2275 this.AuthorContextMenuItem.Visible = false;
2276 this.RetweetedByContextMenuItem.Visible = false;
2280 this.ReplyStripMenuItem.Enabled = true;
2281 this.ReplyAllStripMenuItem.Enabled = true;
2282 this.DMStripMenuItem.Enabled = true;
2283 this.TabMenuItem.Enabled = true;
2284 this.IDRuleMenuItem.Enabled = true;
2285 this.SourceRuleMenuItem.Enabled = true;
2286 this.ReadedStripMenuItem.Enabled = true;
2287 this.UnreadStripMenuItem.Enabled = true;
2288 this.AuthorContextMenuItem.Visible = true;
2289 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2290 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2291 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2293 var tab = this.CurrentTab;
2294 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2296 this.FavAddToolStripMenuItem.Enabled = false;
2297 this.FavRemoveToolStripMenuItem.Enabled = false;
2298 this.StatusOpenMenuItem.Enabled = false;
2299 this.ShowRelatedStatusesMenuItem.Enabled = false;
2301 this.ReTweetStripMenuItem.Enabled = false;
2302 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2303 this.QuoteStripMenuItem.Enabled = false;
2304 this.FavoriteRetweetContextMenu.Enabled = false;
2305 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2309 this.FavAddToolStripMenuItem.Enabled = true;
2310 this.FavRemoveToolStripMenuItem.Enabled = true;
2311 this.StatusOpenMenuItem.Enabled = true;
2312 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2314 if (!post.CanRetweetBy(this.tw.UserId))
2316 this.ReTweetStripMenuItem.Enabled = false;
2317 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2318 this.QuoteStripMenuItem.Enabled = false;
2319 this.FavoriteRetweetContextMenu.Enabled = false;
2320 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2324 this.ReTweetStripMenuItem.Enabled = true;
2325 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2326 this.QuoteStripMenuItem.Enabled = true;
2327 this.FavoriteRetweetContextMenu.Enabled = true;
2328 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2332 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2334 this.RepliedStatusOpenMenuItem.Enabled = false;
2338 this.RepliedStatusOpenMenuItem.Enabled = true;
2341 if (this.ExistCurrentPost && post != null)
2343 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2344 if (post.RetweetedByUserId == this.tw.UserId)
2345 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2347 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2351 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2352 => this.MakeReplyText();
2354 private void DMStripMenuItem_Click(object sender, EventArgs e)
2355 => this.MakeDirectMessageText();
2357 private async Task DoStatusDelete()
2359 var posts = this.CurrentTab.SelectedPosts;
2360 if (posts.Length == 0)
2363 // 選択されたツイートの中に削除可能なものが一つでもあるか
2364 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2367 var ret = MessageBox.Show(
2369 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2370 Properties.Resources.DeleteStripMenuItem_ClickText2,
2371 MessageBoxButtons.OKCancel,
2372 MessageBoxIcon.Question);
2374 if (ret != DialogResult.OK)
2377 var currentListView = this.CurrentListView;
2378 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2380 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2382 Exception? lastException = null;
2383 foreach (var post in posts)
2385 if (!post.CanDeleteBy(this.tw.UserId))
2392 await this.tw.Api.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
2396 if (post.RetweetedByUserId == this.tw.UserId)
2398 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2400 await this.tw.Api.StatusesDestroy(post.StatusId)
2405 if (post.UserId == this.tw.UserId)
2407 if (post.RetweetedId != null)
2409 // 他人に RT された自分のツイート
2410 // => RT 元の自分のツイートを削除
2411 await this.tw.Api.StatusesDestroy(post.RetweetedId.Value)
2418 await this.tw.Api.StatusesDestroy(post.StatusId)
2425 catch (WebApiException ex)
2431 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2434 if (lastException == null)
2435 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2437 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2439 using (ControlTransaction.Update(currentListView))
2441 this.listCache?.PurgeCache();
2442 this.listCache?.UpdateListSize();
2444 currentListView.SelectedIndices.Clear();
2446 var currentTab = this.CurrentTab;
2447 if (currentTab.AllCount != 0)
2450 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2451 selectedIndex = focusedIndex;
2453 selectedIndex = currentTab.AllCount - 1;
2455 currentListView.SelectedIndices.Add(selectedIndex);
2456 currentListView.EnsureVisible(selectedIndex);
2457 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2461 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2463 var tabPage = this.ListTab.TabPages[index];
2464 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2466 if (tabPage.ImageIndex == 0)
2467 tabPage.ImageIndex = -1; // タブアイコン
2471 if (!this.settings.Common.TabIconDisp)
2472 this.ListTab.Refresh();
2476 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2477 => await this.DoStatusDelete();
2479 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2481 using (ControlTransaction.Update(this.CurrentListView))
2483 var tab = this.CurrentTab;
2484 foreach (var statusId in tab.SelectedStatusIds)
2486 this.statuses.SetReadAllTab(statusId, read: true);
2487 var idx = tab.IndexOf(statusId);
2488 this.listCache?.RefreshStyle(idx);
2491 if (this.settings.Common.TabIconDisp)
2493 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2495 if (tab.UnreadCount == 0)
2497 var tabPage = this.ListTab.TabPages[index];
2498 if (tabPage.ImageIndex == 0)
2499 tabPage.ImageIndex = -1; // タブアイコン
2503 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2506 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2508 using (ControlTransaction.Update(this.CurrentListView))
2510 var tab = this.CurrentTab;
2511 foreach (var statusId in tab.SelectedStatusIds)
2513 this.statuses.SetReadAllTab(statusId, read: false);
2514 var idx = tab.IndexOf(statusId);
2515 this.listCache?.RefreshStyle(idx);
2518 if (this.settings.Common.TabIconDisp)
2520 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2522 if (tab.UnreadCount > 0)
2524 var tabPage = this.ListTab.TabPages[index];
2525 if (tabPage.ImageIndex == -1)
2526 tabPage.ImageIndex = 0; // タブアイコン
2530 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2533 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2534 => await this.DoRefresh();
2536 private async Task DoRefresh()
2537 => await this.RefreshTabAsync(this.CurrentTab);
2539 private async Task DoRefreshMore()
2540 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2542 private DialogResult ShowSettingDialog()
2544 using var settingDialog = new AppendSettingDialog();
2545 settingDialog.Icon = this.iconAssets.IconMain;
2546 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2548 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2550 DialogResult result;
2553 result = settingDialog.ShowDialog(this);
2557 return DialogResult.Abort;
2560 if (result == DialogResult.OK)
2562 lock (this.syncObject)
2564 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2571 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2574 var previousUserId = this.settings.Common.UserId;
2575 var oldIconCol = this.Use2ColumnsMode;
2577 if (this.ShowSettingDialog() == DialogResult.OK)
2579 lock (this.syncObject)
2581 this.settings.ApplySettings();
2583 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2584 this.tw.ClearAuthInfo();
2586 this.tw.Initialize(this.settings.Common.Token, this.settings.Common.TokenSecret, this.settings.Common.UserName, this.settings.Common.UserId);
2587 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2588 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2590 this.ImageSelector.Reset(this.tw, this.tw.Configuration);
2594 if (this.settings.Common.TabIconDisp)
2596 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2597 this.ListTab.DrawMode = TabDrawMode.Normal;
2598 this.ListTab.ImageList = this.TabImage;
2602 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2603 this.ListTab.DrawItem += this.ListTab_DrawItem;
2604 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2605 this.ListTab.ImageList = null;
2608 catch (Exception ex)
2610 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2611 ex.Data["IsTerminatePermission"] = false;
2617 if (!this.settings.Common.UnreadManage)
2619 this.ReadedStripMenuItem.Enabled = false;
2620 this.UnreadStripMenuItem.Enabled = false;
2621 if (this.settings.Common.TabIconDisp)
2623 foreach (TabPage myTab in this.ListTab.TabPages)
2625 myTab.ImageIndex = -1;
2631 this.ReadedStripMenuItem.Enabled = true;
2632 this.UnreadStripMenuItem.Enabled = true;
2635 catch (Exception ex)
2637 ex.Data["Instance"] = "ListTab(UnreadManage)";
2638 ex.Data["IsTerminatePermission"] = false;
2643 this.SetTabAlignment();
2645 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2647 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2648 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2649 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2651 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2652 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2653 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2654 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2656 var newTheme = new ThemeManager(this.settings.Local);
2657 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2658 this.tweetDetailsView.Theme = this.themeManager;
2659 if (this.listDrawer != null)
2660 this.listDrawer.Theme = this.themeManager;
2665 if (this.StatusText.Focused)
2666 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2668 this.StatusText.Font = this.themeManager.FontInputFont;
2669 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2671 catch (Exception ex)
2673 MessageBox.Show(ex.Message);
2678 this.InitDetailHtmlFormat();
2680 catch (Exception ex)
2682 ex.Data["Instance"] = "Font";
2683 ex.Data["IsTerminatePermission"] = false;
2689 if (this.settings.Common.TabIconDisp)
2691 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2693 var tabPage = this.ListTab.TabPages[index];
2694 if (tab.UnreadCount == 0)
2695 tabPage.ImageIndex = -1;
2697 tabPage.ImageIndex = 0;
2701 catch (Exception ex)
2703 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2704 ex.Data["IsTerminatePermission"] = false;
2710 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2712 foreach (TabPage tp in this.ListTab.TabPages)
2714 var lst = (DetailsListView)tp.Tag;
2716 using (ControlTransaction.Update(lst))
2718 lst.GridLines = this.settings.Common.ShowGrid;
2720 if (this.Use2ColumnsMode != oldIconCol)
2721 this.ResetColumns(lst);
2725 catch (Exception ex)
2727 ex.Data["Instance"] = "ListView(IconSize)";
2728 ex.Data["IsTerminatePermission"] = false;
2732 this.SetMainWindowTitle();
2733 this.SetNotifyIconText();
2735 this.listCache?.PurgeCache();
2736 this.CurrentListView.Refresh();
2737 this.ListTab.Refresh();
2739 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2740 if (this.settings.Common.HotkeyEnabled)
2742 // グローバルホットキーの登録。設定で変更可能にするかも
2743 var modKey = HookGlobalHotkey.ModKeys.None;
2744 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2745 modKey |= HookGlobalHotkey.ModKeys.Alt;
2746 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2747 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2748 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2749 modKey |= HookGlobalHotkey.ModKeys.Shift;
2750 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2751 modKey |= HookGlobalHotkey.ModKeys.Win;
2753 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2756 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2759 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2767 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2769 this.TopMost = this.settings.Common.AlwaysTop;
2770 this.SaveConfigsAll(false);
2772 if (this.tw.UserId != previousUserId)
2773 await this.DoGetFollowersMenu();
2779 private void SetTabAlignment()
2781 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2782 if (this.ListTab.Alignment == newAlignment) return;
2785 var currentListViewState = this.listViewState[this.CurrentTabName];
2786 currentListViewState.Save(this.ListLockMenuItem.Checked);
2788 this.ListTab.Alignment = newAlignment;
2790 currentListViewState.Restore();
2793 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2796 if (this.listDrawer != null)
2797 this.listDrawer.IconSize = iconSz;
2799 this.listCache?.PurgeCache();
2802 private void ResetColumns(DetailsListView list)
2804 using (ControlTransaction.Update(list))
2805 using (ControlTransaction.Layout(list, false))
2808 list.ColumnClick -= this.MyList_ColumnClick;
2809 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2810 list.ColumnReordered -= this.MyList_ColumnReordered;
2811 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2813 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2814 list.Columns.Clear();
2815 cols.ForEach(col => col.Dispose());
2818 this.InitColumns(list, true);
2820 list.ColumnClick += this.MyList_ColumnClick;
2821 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2822 list.ColumnReordered += this.MyList_ColumnReordered;
2823 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2827 public void AddNewTabForSearch(string searchWord)
2829 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2830 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2832 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2834 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2835 this.ListTab.SelectedIndex = tabIndex;
2840 var tabName = searchWord;
2841 for (var i = 0; i <= 100; i++)
2843 if (this.statuses.ContainsTab(tabName))
2849 var tab = new PublicSearchTabModel(tabName);
2850 this.statuses.AddTab(tab);
2851 this.AddNewTab(tab, startup: false);
2853 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2855 var tabPage = this.CurrentTabPage;
2856 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2857 cmb.Items.Add(searchWord);
2858 cmb.Text = searchWord;
2859 this.SaveConfigsTabs();
2861 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2864 private async Task ShowUserTimeline()
2866 var post = this.CurrentPost;
2867 if (post == null || !this.ExistCurrentPost) return;
2868 await this.AddNewTabForUserTimeline(post.ScreenName);
2871 private async Task ShowRetweeterTimeline()
2873 var retweetedBy = this.CurrentPost?.RetweetedBy;
2874 if (retweetedBy == null || !this.ExistCurrentPost) return;
2875 await this.AddNewTabForUserTimeline(retweetedBy);
2878 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2880 if (e.KeyCode == Keys.Escape)
2882 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2883 this.SaveConfigsTabs();
2884 e.SuppressKeyPress = true;
2888 public async Task AddNewTabForUserTimeline(string user)
2890 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2891 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2893 if (tb.ScreenName == user)
2895 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2896 this.ListTab.SelectedIndex = tabIndex;
2901 var tabName = "user:" + user;
2902 while (this.statuses.ContainsTab(tabName))
2907 var tab = new UserTimelineTabModel(tabName, user);
2908 this.statuses.AddTab(tab);
2909 this.AddNewTab(tab, startup: false);
2911 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2912 this.SaveConfigsTabs();
2914 await this.RefreshTabAsync(tab);
2917 public bool AddNewTab(TabModel tab, bool startup)
2920 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2924 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2926 var tabPage = new TabPage();
2927 var listCustom = new DetailsListView();
2929 var cnt = this.statuses.Tabs.Count;
2931 // ToDo:Create and set controls follow tabtypes
2933 using (ControlTransaction.Update(listCustom))
2934 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2935 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2936 using (ControlTransaction.Layout(this.SplitContainer1, false))
2937 using (ControlTransaction.Layout(this.ListTab, false))
2938 using (ControlTransaction.Layout(this))
2939 using (ControlTransaction.Layout(tabPage, false))
2941 tabPage.Controls.Add(listCustom);
2944 var userTab = tab as UserTimelineTabModel;
2945 var listTab = tab as ListTimelineTabModel;
2946 var searchTab = tab as PublicSearchTabModel;
2948 if (userTab != null || listTab != null)
2950 var label = new Label
2952 Dock = DockStyle.Top,
2957 if (listTab != null)
2959 label.Text = listTab.ListInfo.ToString();
2961 else if (userTab != null)
2963 label.Text = userTab.ScreenName + "'s Timeline";
2965 label.TextAlign = ContentAlignment.MiddleLeft;
2966 using (var tmpComboBox = new ComboBox())
2968 label.Height = tmpComboBox.Height;
2970 tabPage.Controls.Add(label);
2973 else if (searchTab != null)
2975 var pnl = new Panel();
2977 var lbl = new Label();
2978 var cmb = new ComboBox();
2979 var btn = new Button();
2980 var cmbLang = new ComboBox();
2982 using (ControlTransaction.Layout(pnl, false))
2984 pnl.Controls.Add(cmb);
2985 pnl.Controls.Add(cmbLang);
2986 pnl.Controls.Add(btn);
2987 pnl.Controls.Add(lbl);
2988 pnl.Name = "panelSearch";
2990 pnl.Dock = DockStyle.Top;
2991 pnl.Height = cmb.Height;
2992 pnl.Enter += this.SearchControls_Enter;
2993 pnl.Leave += this.SearchControls_Leave;
2996 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2997 cmb.Dock = DockStyle.Fill;
2998 cmb.Name = "comboSearch";
2999 cmb.DropDownStyle = ComboBoxStyle.DropDown;
3000 cmb.ImeMode = ImeMode.NoControl;
3001 cmb.TabStop = false;
3003 cmb.AutoCompleteMode = AutoCompleteMode.None;
3004 cmb.KeyDown += this.SearchComboBox_KeyDown;
3007 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3008 cmbLang.Dock = DockStyle.Right;
3010 cmbLang.Name = "comboLang";
3011 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3012 cmbLang.TabStop = false;
3013 cmbLang.TabIndex = 2;
3014 cmbLang.Items.Add("");
3015 cmbLang.Items.Add("ja");
3016 cmbLang.Items.Add("en");
3017 cmbLang.Items.Add("ar");
3018 cmbLang.Items.Add("da");
3019 cmbLang.Items.Add("nl");
3020 cmbLang.Items.Add("fa");
3021 cmbLang.Items.Add("fi");
3022 cmbLang.Items.Add("fr");
3023 cmbLang.Items.Add("de");
3024 cmbLang.Items.Add("hu");
3025 cmbLang.Items.Add("is");
3026 cmbLang.Items.Add("it");
3027 cmbLang.Items.Add("no");
3028 cmbLang.Items.Add("pl");
3029 cmbLang.Items.Add("pt");
3030 cmbLang.Items.Add("ru");
3031 cmbLang.Items.Add("es");
3032 cmbLang.Items.Add("sv");
3033 cmbLang.Items.Add("th");
3035 lbl.Text = "Search(C-S-f)";
3036 lbl.Name = "label1";
3037 lbl.Dock = DockStyle.Left;
3039 lbl.Height = cmb.Height;
3040 lbl.TextAlign = ContentAlignment.MiddleLeft;
3043 btn.Text = "Search";
3044 btn.Name = "buttonSearch";
3045 btn.UseVisualStyleBackColor = true;
3046 btn.Dock = DockStyle.Right;
3047 btn.TabStop = false;
3049 btn.Click += this.SearchButton_Click;
3051 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3053 cmb.Items.Add(searchTab.SearchWords);
3054 cmb.Text = searchTab.SearchWords;
3057 cmbLang.Text = searchTab.SearchLang;
3059 tabPage.Controls.Add(pnl);
3063 tabPage.Tag = listCustom;
3064 this.ListTab.Controls.Add(tabPage);
3066 tabPage.Location = new Point(4, 4);
3067 tabPage.Name = "CTab" + cnt;
3068 tabPage.Size = new Size(380, 260);
3069 tabPage.TabIndex = 2 + cnt;
3070 tabPage.Text = tab.TabName;
3071 tabPage.UseVisualStyleBackColor = true;
3072 tabPage.AccessibleRole = AccessibleRole.PageTab;
3074 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3075 listCustom.TabIndex = 1;
3076 listCustom.AllowColumnReorder = true;
3077 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3078 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3079 listCustom.Dock = DockStyle.Fill;
3080 listCustom.FullRowSelect = true;
3081 listCustom.HideSelection = false;
3082 listCustom.Location = new Point(0, 0);
3083 listCustom.Margin = new Padding(0);
3084 listCustom.Name = "CList" + Environment.TickCount;
3085 listCustom.ShowItemToolTips = true;
3086 listCustom.Size = new Size(380, 260);
3087 listCustom.UseCompatibleStateImageBehavior = false;
3088 listCustom.View = View.Details;
3089 listCustom.OwnerDraw = true;
3090 listCustom.VirtualMode = true;
3092 listCustom.GridLines = this.settings.Common.ShowGrid;
3093 listCustom.AllowDrop = true;
3095 this.InitColumns(listCustom, startup);
3097 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3098 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3099 listCustom.ColumnClick += this.MyList_ColumnClick;
3100 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3101 listCustom.DragDrop += this.TweenMain_DragDrop;
3102 listCustom.DragEnter += this.TweenMain_DragEnter;
3103 listCustom.DragOver += this.TweenMain_DragOver;
3104 listCustom.MouseClick += this.MyList_MouseClick;
3105 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3106 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3107 listCustom.HScrolled += this.MyList_HScrolled;
3110 var state = new TimelineListViewState(listCustom, tab);
3111 this.listViewState[tab.TabName] = state;
3116 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3118 var tabInfo = this.statuses.GetTabByName(tabName);
3119 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3124 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3125 var result = MessageBox.Show(
3127 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3128 MessageBoxButtons.OKCancel,
3129 MessageBoxIcon.Question,
3130 MessageBoxDefaultButton.Button2);
3131 if (result == DialogResult.Cancel)
3137 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3141 var tabPage = this.ListTab.TabPages[tabIndex];
3143 this.SetListProperty(); // 他のタブに列幅等を反映
3145 this.listViewState.Remove(tabName);
3148 var listCustom = (DetailsListView)tabPage.Tag;
3151 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3152 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3153 using (ControlTransaction.Layout(this.SplitContainer1, false))
3154 using (ControlTransaction.Layout(this.ListTab, false))
3155 using (ControlTransaction.Layout(this))
3156 using (ControlTransaction.Layout(tabPage, false))
3158 if (this.CurrentTabName == tabName)
3160 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3161 this.beforeSelectedTab = null;
3163 this.ListTab.Controls.Remove(tabPage);
3166 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3168 using var label = tabPage.Controls["labelUser"];
3169 tabPage.Controls.Remove(label);
3171 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3173 using var pnl = tabPage.Controls["panelSearch"];
3175 pnl.Enter -= this.SearchControls_Enter;
3176 pnl.Leave -= this.SearchControls_Leave;
3177 tabPage.Controls.Remove(pnl);
3179 foreach (Control ctrl in pnl.Controls)
3181 if (ctrl.Name == "buttonSearch")
3183 ctrl.Click -= this.SearchButton_Click;
3185 else if (ctrl.Name == "comboSearch")
3187 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3189 pnl.Controls.Remove(ctrl);
3194 tabPage.Controls.Remove(listCustom);
3196 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3197 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3198 listCustom.ColumnClick -= this.MyList_ColumnClick;
3199 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3200 listCustom.DragDrop -= this.TweenMain_DragDrop;
3201 listCustom.DragEnter -= this.TweenMain_DragEnter;
3202 listCustom.DragOver -= this.TweenMain_DragOver;
3203 listCustom.MouseClick -= this.MyList_MouseClick;
3204 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3205 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3206 listCustom.HScrolled -= this.MyList_HScrolled;
3208 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3209 listCustom.Columns.Clear();
3210 cols.ForEach(col => col.Dispose());
3213 listCustom.ContextMenuStrip = null;
3214 listCustom.ColumnHeaderContextMenuStrip = null;
3215 listCustom.Font = null;
3217 listCustom.SmallImageList = null;
3218 listCustom.ListViewItemSorter = null;
3221 this.listCache?.PurgeCache();
3225 listCustom.Dispose();
3226 this.statuses.RemoveTab(tabName);
3231 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3233 this.listCache?.PurgeCache();
3234 this.beforeSelectedTab = e.TabPage;
3237 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3241 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3244 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3245 if (!dragEnableRectangle.Contains(e.Location))
3247 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3248 tn = this.CurrentTabName;
3251 if (MyCommon.IsNullOrEmpty(tn)) return;
3253 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3256 var tabPage = this.ListTab.TabPages[tabIndex];
3257 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3262 this.tabDrag = false;
3265 var cpos = new Point(e.X, e.Y);
3266 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3268 var rect = this.ListTab.GetTabRect(index);
3269 if (rect.Contains(cpos))
3271 this.rclickTabName = tab.TabName;
3277 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3279 this.SetMainWindowTitle();
3280 this.SetStatusLabelUrl();
3281 this.SetApiStatusLabel();
3282 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3283 this.Tag = this.ListTab.Tag;
3284 this.TabMenuControl(this.CurrentTabName);
3285 this.PushSelectPostChain();
3286 this.DispSelectedPost();
3289 private void SetListProperty()
3291 if (!this.isColumnChanged) return;
3293 var currentListView = this.CurrentListView;
3295 var dispOrder = new int[currentListView.Columns.Count];
3296 for (var i = 0; i < currentListView.Columns.Count; i++)
3298 for (var j = 0; j < currentListView.Columns.Count; j++)
3300 if (currentListView.Columns[j].DisplayIndex == i)
3309 foreach (TabPage tb in this.ListTab.TabPages)
3311 if (tb.Text == this.CurrentTabName)
3314 if (tb.Tag != null && tb.Controls.Count > 0)
3316 var lst = (DetailsListView)tb.Tag;
3317 for (var i = 0; i < lst.Columns.Count; i++)
3319 lst.Columns[dispOrder[i]].DisplayIndex = i;
3320 lst.Columns[i].Width = currentListView.Columns[i].Width;
3325 this.isColumnChanged = false;
3328 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3330 if (e.KeyChar == '@')
3332 if (!this.settings.Common.UseAtIdSupplement) return;
3334 var cnt = this.AtIdSupl.ItemCount;
3335 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3336 if (cnt != this.AtIdSupl.ItemCount)
3337 this.MarkSettingAtIdModified();
3340 else if (e.KeyChar == '#')
3342 if (!this.settings.Common.UseHashSupplement) return;
3343 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3348 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3349 => this.ShowSuplDialog(owner, dialog, 0, "");
3351 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3352 => this.ShowSuplDialog(owner, dialog, offset, "");
3354 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3356 dialog.StartsWith = startswith;
3363 dialog.ShowDialog();
3365 this.TopMost = this.settings.Common.AlwaysTop;
3366 var selStart = owner.SelectionStart;
3369 if (dialog.DialogResult == DialogResult.OK)
3371 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3375 fHalf = owner.Text.Substring(0, selStart - offset);
3377 if (selStart < owner.Text.Length)
3379 eHalf = owner.Text.Substring(selStart);
3381 owner.Text = fHalf + dialog.InputText + eHalf;
3382 owner.SelectionStart = selStart + dialog.InputText.Length;
3389 fHalf = owner.Text.Substring(0, selStart);
3391 if (selStart < owner.Text.Length)
3393 eHalf = owner.Text.Substring(selStart);
3395 owner.Text = fHalf + eHalf;
3398 owner.SelectionStart = selStart;
3404 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3407 if (!e.Alt && !e.Control && !e.Shift)
3409 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3411 var isSpace = false;
3412 foreach (var c in this.StatusText.Text)
3414 if (c == ' ' || c == ' ')
3427 this.StatusText.Text = "";
3428 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3432 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3435 private void StatusText_TextChanged(object sender, EventArgs e)
3438 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3439 this.lblLen.Text = pLen.ToString();
3442 this.StatusText.ForeColor = Color.Red;
3446 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3449 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3451 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3453 this.inReplyTo = null;
3458 /// メンション以外の文字列が含まれていないテキストであるか判定します
3460 internal static bool TextContainsOnlyMentions(string text)
3462 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3465 foreach (var mention in mentions)
3467 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3469 if (!string.IsNullOrWhiteSpace(textPart))
3472 startIndex = mention.Indices[1];
3475 var textPartLast = text.Substring(startIndex);
3477 if (!string.IsNullOrWhiteSpace(textPartLast))
3484 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3486 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3488 var autoPopulatedUserIdList = new List<long>();
3490 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3491 if (replyToPost != null)
3493 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3495 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3496 autoPopulatedUserIdList.Add(replyToPost.UserId);
3498 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3500 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3502 statusText = statusText.Substring(screenName.Length + 2);
3503 autoPopulatedUserIdList.Add(userId);
3509 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3515 /// attachment_url に指定可能な URL が含まれていれば除去
3517 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3519 attachmentUrl = null;
3521 // attachment_url は media_id と同時に使用できない
3522 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
3525 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3529 attachmentUrl = match.Value;
3532 statusText = statusText.Substring(0, match.Index);
3534 // テキストと URL の間にスペースが含まれていれば除去
3535 return statusText.TrimEnd(' ');
3538 private string FormatStatusTextExtended(string statusText)
3539 => this.FormatStatusTextExtended(statusText, out _, out _);
3542 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3544 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3546 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3548 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3550 return this.FormatStatusText(statusText);
3554 /// ツイート投稿前のフッター付与などの前処理を行います
3556 private string FormatStatusText(string statusText)
3558 statusText = statusText.Replace("\r\n", "\n");
3560 if (this.urlMultibyteSplit)
3563 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3566 if (this.settings.Common.WideSpaceConvert)
3568 // 文中の全角スペースを半角スペース1個にする
3569 statusText = statusText.Replace(" ", " ");
3572 // DM の場合はこれ以降の処理を行わない
3573 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3577 if (this.settings.Common.PostShiftEnter)
3579 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3583 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3584 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3586 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3589 if (statusText.Contains("RT @"))
3590 disableFooter = true;
3592 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3593 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3595 var mentionSelf = $"@{this.tw.Username} ";
3596 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3598 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3599 statusText = statusText.Substring(mentionSelf.Length);
3606 var hashtag = this.HashMgr.UseHash;
3607 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3609 if (this.HashMgr.IsHead)
3610 header = this.HashMgr.UseHash + " ";
3612 footer = " " + this.HashMgr.UseHash;
3617 if (this.settings.Local.UseRecommendStatus)
3620 footer += this.recommendedStatusFooter;
3622 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3624 // テキストボックスに入力されている文字列を使用する
3625 footer += " " + this.settings.Local.StatusText.Trim();
3629 statusText = header + statusText + footer;
3631 if (this.preventSmsCommand)
3633 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3634 // 参照: https://support.twitter.com/articles/14020
3636 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3637 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3639 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3640 statusText = '\u200b' + statusText;
3648 /// 投稿欄に表示する入力可能な文字数を計算します
3650 private int GetRestStatusCount(string statusText)
3652 var remainCount = this.tw.GetTextLengthRemain(statusText);
3654 var uploadService = this.GetSelectedImageService();
3655 if (uploadService != null)
3657 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3658 remainCount -= uploadService.GetReservedTextLength(1);
3664 private IMediaUploadService? GetSelectedImageService()
3665 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
3668 /// 全てのタブの振り分けルールを反映し直します
3670 private void ApplyPostFilters()
3672 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3674 this.statuses.FilterAll();
3676 var listView = this.CurrentListView;
3677 using (ControlTransaction.Update(listView))
3679 this.listCache?.PurgeCache();
3680 this.listCache?.UpdateListSize();
3683 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3685 var tabPage = this.ListTab.TabPages[index];
3687 if (this.settings.Common.TabIconDisp)
3689 if (tab.UnreadCount > 0)
3690 tabPage.ImageIndex = 0;
3692 tabPage.ImageIndex = -1;
3696 if (!this.settings.Common.TabIconDisp)
3697 this.ListTab.Refresh();
3699 this.SetMainWindowTitle();
3700 this.SetStatusLabelUrl();
3704 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3705 => e.DrawDefault = true;
3707 private void MyList_HScrolled(object sender, EventArgs e)
3708 => ((DetailsListView)sender).Refresh();
3710 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3712 base.ScaleControl(factor, specified);
3714 ScaleChildControl(this.TabImage, factor);
3716 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3717 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3719 foreach (var listview in listviews)
3721 ScaleChildControl(listview, factor);
3725 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3727 var tab = this.CurrentTab;
3729 if (tab.AllCount == 0)
3731 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3735 var selectedIndex = tab.SelectedIndex;
3740 case SEARCHTYPE.NextSearch: // 次を検索
3741 if (selectedIndex != -1)
3742 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3746 case SEARCHTYPE.PrevSearch: // 前を検索
3747 if (selectedIndex != -1)
3748 startIndex = Math.Max(selectedIndex - 1, 0);
3750 startIndex = tab.AllCount - 1;
3752 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3754 if (selectedIndex != -1)
3755 startIndex = selectedIndex;
3761 Func<string, bool> stringComparer;
3764 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3766 catch (ArgumentException)
3768 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3772 var reverse = searchType == SEARCHTYPE.PrevSearch;
3773 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3774 .DefaultIfEmpty(-1).First();
3776 if (foundIndex == -1)
3778 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3782 var listView = this.CurrentListView;
3783 this.SelectListItem(listView, foundIndex);
3784 listView.EnsureVisible(foundIndex);
3787 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3788 => this.ShowSearchDialog(); // 検索メニュー
3790 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3792 var previousSearch = this.SearchDialog.ResultOptions;
3793 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3795 this.SearchDialog.Reset();
3796 this.ShowSearchDialog();
3802 previousSearch.Query,
3803 previousSearch.CaseSensitive,
3804 previousSearch.UseRegex,
3805 SEARCHTYPE.NextSearch);
3808 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3810 var previousSearch = this.SearchDialog.ResultOptions;
3811 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3813 this.SearchDialog.Reset();
3814 this.ShowSearchDialog();
3820 previousSearch.Query,
3821 previousSearch.CaseSensitive,
3822 previousSearch.UseRegex,
3823 SEARCHTYPE.PrevSearch);
3827 /// 検索ダイアログを表示し、検索を実行します
3829 private void ShowSearchDialog()
3831 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3833 this.TopMost = this.settings.Common.AlwaysTop;
3836 this.TopMost = this.settings.Common.AlwaysTop;
3838 var searchOptions = this.SearchDialog.ResultOptions!;
3839 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3841 if (searchOptions.NewTab)
3843 var tabName = Properties.Resources.SearchResults_TabName;
3847 tabName = this.statuses.MakeTabName(tabName);
3849 catch (TabException ex)
3851 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3854 var resultTab = new LocalSearchTabModel(tabName);
3855 this.AddNewTab(resultTab, startup: false);
3856 this.statuses.AddTab(resultTab);
3858 var targetTab = this.CurrentTab;
3860 Func<string, bool> stringComparer;
3863 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3865 catch (ArgumentException)
3867 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3871 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3872 if (foundIndices.Length == 0)
3874 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3878 var foundPosts = foundIndices.Select(x => targetTab[x]);
3879 foreach (var post in foundPosts)
3881 resultTab.AddPostQueue(post);
3884 this.statuses.DistributePosts();
3885 this.RefreshTimeline();
3887 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3888 this.ListTab.SelectedIndex = tabIndex;
3893 searchOptions.Query,
3894 searchOptions.CaseSensitive,
3895 searchOptions.UseRegex,
3896 SEARCHTYPE.DialogSearch);
3899 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3901 this.AddNewTabForSearch(searchOptions.Query);
3905 /// <summary>発言検索に使用するメソッドを生成します</summary>
3906 /// <exception cref="ArgumentException">
3907 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3909 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3913 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3914 var regex = new Regex(query, regexOption);
3916 return x => regex.IsMatch(x);
3920 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3922 return x => x.IndexOf(query, comparisonType) != -1;
3926 private void AboutMenuItem_Click(object sender, EventArgs e)
3928 using (var about = new TweenAboutBox())
3930 about.ShowDialog(this);
3932 this.TopMost = this.settings.Common.AlwaysTop;
3935 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3937 var bgnIdx = this.statuses.SelectedTabIndex;
3939 if (this.ImageSelector.Enabled)
3942 TabModel? foundTab = null;
3946 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3948 var unreadIndex = tab.NextUnreadIndex;
3949 if (unreadIndex != -1)
3951 this.ListTab.SelectedIndex = index;
3953 foundIndex = unreadIndex;
3958 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3959 if (foundTab == null && bgnIdx > 0)
3961 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3963 var unreadIndex = tab.NextUnreadIndex;
3964 if (unreadIndex != -1)
3966 this.ListTab.SelectedIndex = index;
3968 foundIndex = unreadIndex;
3974 DetailsListView lst;
3976 if (foundTab == null)
3978 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3979 this.ListTab.SelectedIndex = 0;
3980 var tabPage = this.ListTab.TabPages[0];
3981 var tab = this.statuses.Tabs[0];
3983 if (tab.AllCount == 0)
3986 if (this.statuses.SortOrder == SortOrder.Ascending)
3987 foundIndex = tab.AllCount - 1;
3991 lst = (DetailsListView)tabPage.Tag;
3995 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3996 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3999 this.SelectListItem(lst, foundIndex);
4001 if (this.statuses.SortMode == ComparerMode.Id)
4003 var rowHeight = lst.SmallImageList.ImageSize.Height;
4004 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4005 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4011 lst.EnsureVisible(foundIndex);
4016 lst.EnsureVisible(foundIndex);
4022 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4024 var tab = this.CurrentTab;
4025 var post = this.CurrentPost;
4026 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4027 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4030 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4031 => await this.CheckNewVersion(false);
4033 private void RunTweenUp()
4035 var pinfo = new ProcessStartInfo
4037 UseShellExecute = true,
4038 WorkingDirectory = this.settings.SettingsPath,
4039 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4040 Arguments = "\"" + Application.StartupPath + "\"",
4045 Process.Start(pinfo);
4049 MessageBox.Show("Failed to execute TweenUp3.exe.");
4053 public readonly record struct VersionInfo(
4060 /// OpenTween の最新バージョンの情報を取得します
4062 public async Task<VersionInfo> GetVersionInfoAsync()
4064 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4065 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4067 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4068 .ConfigureAwait(false);
4070 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4071 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4073 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4074 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4076 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4078 return new VersionInfo
4080 Version = Version.Parse(msgHeader[0]),
4081 DownloadUri = new Uri(msgHeader[1]),
4082 ReleaseNote = msgBody,
4086 private async Task CheckNewVersion(bool startup = false)
4088 if (ApplicationSettings.VersionInfoUrl == null)
4089 return; // 更新チェック無効化
4093 var versionInfo = await this.GetVersionInfoAsync();
4095 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4100 var msgtext = string.Format(
4101 Properties.Resources.CheckNewVersionText7,
4102 MyCommon.GetReadableVersion(),
4103 MyCommon.GetReadableVersion(versionInfo.Version));
4104 msgtext = MyCommon.ReplaceAppName(msgtext);
4108 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4109 MessageBoxButtons.OK,
4110 MessageBoxIcon.Information);
4115 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4118 using var dialog = new UpdateDialog();
4120 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4121 MyCommon.GetReadableVersion(versionInfo.Version));
4122 dialog.DetailsText = versionInfo.ReleaseNote;
4124 if (dialog.ShowDialog(this) == DialogResult.Yes)
4126 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri.OriginalString);
4128 else if (dialog.SkipButtonPressed)
4130 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4131 this.MarkSettingCommonModified();
4136 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4140 Properties.Resources.CheckNewVersionText10,
4141 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4142 MessageBoxButtons.OK,
4143 MessageBoxIcon.Exclamation,
4144 MessageBoxDefaultButton.Button2);
4149 private void UpdateSelectedPost()
4151 // 件数関連の場合、タイトル即時書き換え
4152 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4153 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4154 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4155 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4157 this.SetMainWindowTitle();
4159 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4160 this.SetStatusLabelUrl();
4162 if (this.settings.Common.TabIconDisp)
4164 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4166 if (tab.UnreadCount == 0)
4168 var tabPage = this.ListTab.TabPages[index];
4169 if (tabPage.ImageIndex == 0)
4170 tabPage.ImageIndex = -1;
4176 this.ListTab.Refresh();
4179 this.DispSelectedPost();
4182 public string CreateDetailHtml(string orgdata)
4183 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4185 private void DispSelectedPost()
4186 => this.DispSelectedPost(false);
4188 private PostClass displayPost = new();
4191 /// サムネイル表示に使用する CancellationToken の生成元
4193 private CancellationTokenSource? thumbnailTokenSource = null;
4195 private void DispSelectedPost(bool forceupdate)
4197 var currentPost = this.CurrentPost;
4198 if (currentPost == null)
4201 var oldDisplayPost = this.displayPost;
4202 this.displayPost = currentPost;
4204 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4207 var loadTasks = new List<Task>
4209 this.tweetDetailsView.ShowPostDetails(currentPost),
4212 this.SplitContainer3.Panel2Collapsed = true;
4214 if (this.settings.Common.PreviewEnable)
4216 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4217 oldTokenSource?.Cancel();
4219 var token = this.thumbnailTokenSource!.Token;
4220 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
4223 async Task DelayedTasks()
4227 await Task.WhenAll(loadTasks);
4229 catch (OperationCanceledException)
4234 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4238 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4239 => await this.OpenApplicationWebsite();
4241 private async Task OpenApplicationWebsite()
4242 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4244 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4245 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4247 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4249 var tab = this.CurrentTab;
4250 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4252 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4253 if (pnl.Controls["comboSearch"].Focused ||
4254 pnl.Controls["comboLang"].Focused ||
4255 pnl.Controls["buttonSearch"].Focused) return;
4258 if (e.Control || e.Shift || e.Alt)
4261 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4264 e.SuppressKeyPress = true;
4267 if (asyncTask != null)
4271 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4273 private void InitializeShortcuts()
4275 this.shortcutCommands = new[]
4277 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4278 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4279 .FocusedOn(FocusedControl.ListTab)
4280 .Do(() => SendKeys.Send("{DOWN}")),
4282 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4283 .FocusedOn(FocusedControl.ListTab)
4284 .Do(() => SendKeys.Send("{UP}")),
4286 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4287 .FocusedOn(FocusedControl.ListTab)
4288 .Do(() => SendKeys.Send("{PGDN}")),
4290 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4291 .FocusedOn(FocusedControl.ListTab)
4292 .Do(() => SendKeys.Send("{PGUP}")),
4294 ShortcutCommand.Create(Keys.F1)
4295 .Do(() => this.OpenApplicationWebsite()),
4297 ShortcutCommand.Create(Keys.F3)
4298 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4300 ShortcutCommand.Create(Keys.F5)
4301 .Do(() => this.DoRefresh()),
4303 ShortcutCommand.Create(Keys.F6)
4304 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4306 ShortcutCommand.Create(Keys.F7)
4307 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4309 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4310 .NotFocusedOn(FocusedControl.StatusText)
4313 this.CurrentTab.ClearAnchor();
4314 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4317 ShortcutCommand.Create(Keys.G)
4318 .NotFocusedOn(FocusedControl.StatusText)
4321 this.CurrentTab.ClearAnchor();
4322 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4325 ShortcutCommand.Create(Keys.Right, Keys.N)
4326 .FocusedOn(FocusedControl.ListTab)
4327 .Do(() => this.GoRelPost(forward: true)),
4329 ShortcutCommand.Create(Keys.Left, Keys.P)
4330 .FocusedOn(FocusedControl.ListTab)
4331 .Do(() => this.GoRelPost(forward: false)),
4333 ShortcutCommand.Create(Keys.OemPeriod)
4334 .FocusedOn(FocusedControl.ListTab)
4335 .Do(() => this.GoAnchor()),
4337 ShortcutCommand.Create(Keys.I)
4338 .FocusedOn(FocusedControl.ListTab)
4339 .OnlyWhen(() => this.StatusText.Enabled)
4340 .Do(() => this.StatusText.Focus()),
4342 ShortcutCommand.Create(Keys.Enter)
4343 .FocusedOn(FocusedControl.ListTab)
4344 .Do(() => this.ListItemDoubleClickAction()),
4346 ShortcutCommand.Create(Keys.R)
4347 .FocusedOn(FocusedControl.ListTab)
4348 .Do(() => this.DoRefresh()),
4350 ShortcutCommand.Create(Keys.L)
4351 .FocusedOn(FocusedControl.ListTab)
4354 this.CurrentTab.ClearAnchor();
4355 this.GoPost(forward: true);
4358 ShortcutCommand.Create(Keys.H)
4359 .FocusedOn(FocusedControl.ListTab)
4362 this.CurrentTab.ClearAnchor();
4363 this.GoPost(forward: false);
4366 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4367 .FocusedOn(FocusedControl.ListTab)
4370 this.CurrentTab.ClearAnchor();
4374 ShortcutCommand.Create(Keys.S)
4375 .FocusedOn(FocusedControl.ListTab)
4378 this.CurrentTab.ClearAnchor();
4379 this.GoNextTab(forward: true);
4382 ShortcutCommand.Create(Keys.A)
4383 .FocusedOn(FocusedControl.ListTab)
4386 this.CurrentTab.ClearAnchor();
4387 this.GoNextTab(forward: false);
4390 // ] in_reply_to参照元へ戻る
4391 ShortcutCommand.Create(Keys.Oem4)
4392 .FocusedOn(FocusedControl.ListTab)
4395 this.CurrentTab.ClearAnchor();
4396 return this.GoInReplyToPostTree();
4399 // [ in_reply_toへジャンプ
4400 ShortcutCommand.Create(Keys.Oem6)
4401 .FocusedOn(FocusedControl.ListTab)
4404 this.CurrentTab.ClearAnchor();
4405 this.GoBackInReplyToPostTree();
4408 ShortcutCommand.Create(Keys.Escape)
4409 .FocusedOn(FocusedControl.ListTab)
4412 this.CurrentTab.ClearAnchor();
4413 var tab = this.CurrentTab;
4414 var tabtype = tab.TabType;
4415 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4417 this.RemoveSpecifiedTab(tab.TabName, false);
4418 this.SaveConfigsTabs();
4422 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4423 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4424 .FocusedOn(FocusedControl.ListTab)
4425 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4427 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4428 ShortcutCommand.Create(Keys.Up, Keys.Down)
4429 .FocusedOn(FocusedControl.PostBrowser)
4432 ShortcutCommand.Create(Keys.Control | Keys.R)
4433 .Do(() => this.MakeReplyText()),
4435 ShortcutCommand.Create(Keys.Control | Keys.D)
4436 .Do(() => this.DoStatusDelete()),
4438 ShortcutCommand.Create(Keys.Control | Keys.M)
4439 .Do(() => this.MakeDirectMessageText()),
4441 ShortcutCommand.Create(Keys.Control | Keys.S)
4442 .Do(() => this.FavoriteChange(favAdd: true)),
4444 ShortcutCommand.Create(Keys.Control | Keys.I)
4445 .Do(() => this.DoRepliedStatusOpen()),
4447 ShortcutCommand.Create(Keys.Control | Keys.Q)
4448 .Do(() => this.DoQuoteOfficial()),
4450 ShortcutCommand.Create(Keys.Control | Keys.B)
4451 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4453 ShortcutCommand.Create(Keys.Control | Keys.T)
4454 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4456 ShortcutCommand.Create(Keys.Control | Keys.L)
4457 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4459 ShortcutCommand.Create(Keys.Control | Keys.Y)
4460 .NotFocusedOn(FocusedControl.PostBrowser)
4461 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4463 ShortcutCommand.Create(Keys.Control | Keys.F)
4464 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4466 ShortcutCommand.Create(Keys.Control | Keys.U)
4467 .Do(() => this.ShowUserTimeline()),
4469 ShortcutCommand.Create(Keys.Control | Keys.H)
4470 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4472 ShortcutCommand.Create(Keys.Control | Keys.O)
4473 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4475 ShortcutCommand.Create(Keys.Control | Keys.E)
4476 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4478 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4479 .FocusedOn(FocusedControl.ListTab)
4480 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4482 ShortcutCommand.Create(Keys.Control | Keys.N)
4483 .FocusedOn(FocusedControl.ListTab)
4484 .Do(() => this.GoNextTab(forward: true)),
4486 ShortcutCommand.Create(Keys.Control | Keys.P)
4487 .FocusedOn(FocusedControl.ListTab)
4488 .Do(() => this.GoNextTab(forward: false)),
4490 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4491 .FocusedOn(FocusedControl.ListTab)
4492 .Do(() => this.CopyStot()),
4494 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4495 ShortcutCommand.Create(Keys.Control | Keys.D1)
4496 .FocusedOn(FocusedControl.ListTab)
4497 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4498 .Do(() => this.ListTab.SelectedIndex = 0),
4500 ShortcutCommand.Create(Keys.Control | Keys.D2)
4501 .FocusedOn(FocusedControl.ListTab)
4502 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4503 .Do(() => this.ListTab.SelectedIndex = 1),
4505 ShortcutCommand.Create(Keys.Control | Keys.D3)
4506 .FocusedOn(FocusedControl.ListTab)
4507 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4508 .Do(() => this.ListTab.SelectedIndex = 2),
4510 ShortcutCommand.Create(Keys.Control | Keys.D4)
4511 .FocusedOn(FocusedControl.ListTab)
4512 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4513 .Do(() => this.ListTab.SelectedIndex = 3),
4515 ShortcutCommand.Create(Keys.Control | Keys.D5)
4516 .FocusedOn(FocusedControl.ListTab)
4517 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4518 .Do(() => this.ListTab.SelectedIndex = 4),
4520 ShortcutCommand.Create(Keys.Control | Keys.D6)
4521 .FocusedOn(FocusedControl.ListTab)
4522 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4523 .Do(() => this.ListTab.SelectedIndex = 5),
4525 ShortcutCommand.Create(Keys.Control | Keys.D7)
4526 .FocusedOn(FocusedControl.ListTab)
4527 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4528 .Do(() => this.ListTab.SelectedIndex = 6),
4530 ShortcutCommand.Create(Keys.Control | Keys.D8)
4531 .FocusedOn(FocusedControl.ListTab)
4532 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4533 .Do(() => this.ListTab.SelectedIndex = 7),
4535 ShortcutCommand.Create(Keys.Control | Keys.D9)
4536 .FocusedOn(FocusedControl.ListTab)
4537 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4539 ShortcutCommand.Create(Keys.Control | Keys.A)
4540 .FocusedOn(FocusedControl.StatusText)
4541 .Do(() => this.StatusText.SelectAll()),
4543 ShortcutCommand.Create(Keys.Control | Keys.V)
4544 .FocusedOn(FocusedControl.StatusText)
4545 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4547 ShortcutCommand.Create(Keys.Control | Keys.Up)
4548 .FocusedOn(FocusedControl.StatusText)
4549 .Do(() => this.StatusTextHistoryBack()),
4551 ShortcutCommand.Create(Keys.Control | Keys.Down)
4552 .FocusedOn(FocusedControl.StatusText)
4553 .Do(() => this.StatusTextHistoryForward()),
4555 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4556 .FocusedOn(FocusedControl.StatusText)
4559 if (this.ListTab.SelectedIndex == 0)
4561 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4565 this.ListTab.SelectedIndex -= 1;
4567 this.StatusText.Focus();
4570 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4571 .FocusedOn(FocusedControl.StatusText)
4574 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4576 this.ListTab.SelectedIndex = 0;
4580 this.ListTab.SelectedIndex += 1;
4582 this.StatusText.Focus();
4585 ShortcutCommand.Create(Keys.Control | Keys.Y)
4586 .FocusedOn(FocusedControl.PostBrowser)
4589 var multiline = !this.settings.Local.StatusMultiline;
4590 this.settings.Local.StatusMultiline = multiline;
4591 this.MultiLineMenuItem.Checked = multiline;
4592 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4595 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4596 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4598 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4599 .Do(() => this.DoRefreshMore()),
4601 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4602 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4604 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4605 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4607 ShortcutCommand.Create(Keys.Shift | Keys.R)
4608 .NotFocusedOn(FocusedControl.StatusText)
4609 .Do(() => this.DoRefreshMore()),
4611 ShortcutCommand.Create(Keys.Shift | Keys.H)
4612 .FocusedOn(FocusedControl.ListTab)
4613 .Do(() => this.GoTopEnd(goTop: true)),
4615 ShortcutCommand.Create(Keys.Shift | Keys.L)
4616 .FocusedOn(FocusedControl.ListTab)
4617 .Do(() => this.GoTopEnd(goTop: false)),
4619 ShortcutCommand.Create(Keys.Shift | Keys.M)
4620 .FocusedOn(FocusedControl.ListTab)
4621 .Do(() => this.GoMiddle()),
4623 ShortcutCommand.Create(Keys.Shift | Keys.G)
4624 .FocusedOn(FocusedControl.ListTab)
4625 .Do(() => this.GoLast()),
4627 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4628 .FocusedOn(FocusedControl.ListTab)
4629 .Do(() => this.MoveMiddle()),
4631 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4632 .FocusedOn(FocusedControl.ListTab)
4633 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4635 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4636 .FocusedOn(FocusedControl.ListTab)
4637 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4639 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4640 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4641 .FocusedOn(FocusedControl.ListTab)
4642 .Do(() => this.GoFav(forward: true)),
4644 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4645 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4646 .FocusedOn(FocusedControl.ListTab)
4647 .Do(() => this.GoFav(forward: false)),
4649 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4650 .FocusedOn(FocusedControl.ListTab)
4651 .Do(() => this.GoBackSelectPostChain()),
4653 ShortcutCommand.Create(Keys.Alt | Keys.R)
4654 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4656 ShortcutCommand.Create(Keys.Alt | Keys.P)
4657 .OnlyWhen(() => this.CurrentPost != null)
4658 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4660 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4661 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4663 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4664 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4666 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4667 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4669 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4670 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4672 // 別タブの同じ書き込みへ(ALT+←/→)
4673 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4674 .FocusedOn(FocusedControl.ListTab)
4675 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4677 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4678 .FocusedOn(FocusedControl.ListTab)
4679 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4681 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4682 .Do(() => this.MakeReplyText(atAll: true)),
4684 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4685 .Do(() => this.CopyIdUri()),
4687 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4688 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4689 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4691 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4692 .Do(() => this.FavoriteChange(favAdd: false)),
4694 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4695 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4697 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4698 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4700 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4701 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4703 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4704 .Do(() => this.DoMoveToRTHome()),
4706 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4707 .FocusedOn(FocusedControl.StatusText)
4710 var tab = this.CurrentTab;
4711 var selectedIndex = tab.SelectedIndex;
4712 if (selectedIndex != -1 && selectedIndex > 0)
4714 var listView = this.CurrentListView;
4715 var idx = selectedIndex - 1;
4716 this.SelectListItem(listView, idx);
4717 listView.EnsureVisible(idx);
4721 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4722 .FocusedOn(FocusedControl.StatusText)
4725 var tab = this.CurrentTab;
4726 var selectedIndex = tab.SelectedIndex;
4727 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4729 var listView = this.CurrentListView;
4730 var idx = selectedIndex + 1;
4731 this.SelectListItem(listView, idx);
4732 listView.EnsureVisible(idx);
4736 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4737 .FocusedOn(FocusedControl.StatusText)
4740 if (this.StatusText.SelectionStart > 0)
4742 var endidx = this.StatusText.SelectionStart - 1;
4744 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4746 var c = this.StatusText.Text[i];
4747 if (char.IsLetterOrDigit(c) || c == '_')
4753 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4754 var cnt = this.AtIdSupl.ItemCount;
4755 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4756 if (this.AtIdSupl.ItemCount != cnt)
4757 this.MarkSettingAtIdModified();
4761 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4762 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4772 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4773 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4774 .FocusedOn(FocusedControl.ListTab)
4775 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4777 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4778 .FocusedOn(FocusedControl.ListTab)
4779 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4781 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4782 .FocusedOn(FocusedControl.ListTab)
4783 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4785 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4786 .FocusedOn(FocusedControl.ListTab)
4787 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4789 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4790 .FocusedOn(FocusedControl.ListTab)
4791 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4793 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4794 .FocusedOn(FocusedControl.ListTab)
4795 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4797 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4798 .FocusedOn(FocusedControl.ListTab)
4799 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4801 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4802 .FocusedOn(FocusedControl.ListTab)
4803 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4805 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4806 .FocusedOn(FocusedControl.ListTab)
4807 .Do(() => this.SetSortLastColumn()),
4809 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4810 .FocusedOn(FocusedControl.ListTab)
4811 .Do(() => this.FavoritesRetweetOfficial()),
4813 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4814 .FocusedOn(FocusedControl.ListTab)
4815 .Do(() => this.FavoritesRetweetUnofficial()),
4817 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4818 .FocusedOn(FocusedControl.ListTab)
4819 .Do(() => this.OpenUserAppointUrl()),
4821 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4822 .FocusedOn(FocusedControl.PostBrowser)
4823 .Do(() => this.DoReTweetUnofficial()),
4825 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4826 .OnlyWhen(() => this.ExistCurrentPost)
4827 .Do(() => this.tweetDetailsView.DoTranslation()),
4829 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4830 .Do(() => this.DoReTweetUnofficial()),
4832 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4833 .Do(() => this.CopyUserId()),
4835 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4836 .Do(() => this.tweetThumbnail1.ScrollUp()),
4838 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4839 .Do(() => this.tweetThumbnail1.ScrollDown()),
4841 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4842 .FocusedOn(FocusedControl.ListTab)
4843 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4844 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
4848 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4850 // Task を返す非同期処理があれば asyncTask に代入する
4853 // ShortcutCommand に対応しているコマンドはここで処理される
4854 foreach (var command in this.shortcutCommands)
4856 if (command.IsMatch(keyData, focusedOn))
4858 asyncTask = command.RunCommand();
4859 return command.PreventDefault;
4866 private void GoNextTab(bool forward)
4868 var idx = this.statuses.SelectedTabIndex;
4869 var tabCount = this.statuses.Tabs.Count;
4873 if (idx > tabCount - 1) idx = 0;
4878 if (idx < 0) idx = tabCount - 1;
4880 this.ListTab.SelectedIndex = idx;
4883 private void CopyStot()
4885 var sb = new StringBuilder();
4886 var tab = this.CurrentTab;
4887 var isProtected = false;
4888 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4889 foreach (var post in tab.SelectedPosts)
4891 if (post.IsDeleted) continue;
4894 if (post.RetweetedId != null)
4895 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4897 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4901 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4906 MessageBox.Show(Properties.Resources.CopyStotText1);
4910 var clstr = sb.ToString();
4913 Clipboard.SetDataObject(clstr, false, 5, 100);
4915 catch (Exception ex)
4917 MessageBox.Show(ex.Message);
4922 private void CopyIdUri()
4924 var tab = this.CurrentTab;
4925 if (tab == null || tab is DirectMessagesTabModel)
4928 var copyUrls = new List<string>();
4929 foreach (var post in tab.SelectedPosts)
4930 copyUrls.Add(MyCommon.GetStatusUrl(post));
4932 if (copyUrls.Count == 0)
4937 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4939 catch (ExternalException ex)
4941 MessageBox.Show(ex.Message);
4945 private void GoFav(bool forward)
4947 var tab = this.CurrentTab;
4948 if (tab.AllCount == 0)
4951 var selectedIndex = tab.SelectedIndex;
4959 if (selectedIndex == -1)
4965 fIdx = selectedIndex + 1;
4966 if (fIdx > tab.AllCount - 1)
4969 toIdx = tab.AllCount;
4974 if (selectedIndex == -1)
4976 fIdx = tab.AllCount - 1;
4980 fIdx = selectedIndex - 1;
4988 for (var idx = fIdx; idx != toIdx; idx += stp)
4992 var listView = this.CurrentListView;
4993 this.SelectListItem(listView, idx);
4994 listView.EnsureVisible(idx);
5000 private void GoSamePostToAnotherTab(bool left)
5002 var tab = this.CurrentTab;
5004 // Directタブは対象外(見つかるはずがない)
5005 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5008 var selectedStatusId = tab.SelectedStatusId;
5009 if (selectedStatusId == -1)
5012 int fIdx, toIdx, stp;
5017 if (this.ListTab.SelectedIndex == 0)
5023 fIdx = this.ListTab.SelectedIndex - 1;
5031 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5037 fIdx = this.ListTab.SelectedIndex + 1;
5039 toIdx = this.ListTab.TabCount;
5043 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5045 var targetTab = this.statuses.Tabs[tabidx];
5048 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5051 var foundIndex = targetTab.IndexOf(selectedStatusId);
5052 if (foundIndex != -1)
5054 this.ListTab.SelectedIndex = tabidx;
5055 var listView = this.CurrentListView;
5056 this.SelectListItem(listView, foundIndex);
5057 listView.EnsureVisible(foundIndex);
5063 private void GoPost(bool forward)
5065 var tab = this.CurrentTab;
5066 var currentPost = this.CurrentPost;
5068 if (currentPost == null)
5071 var selectedIndex = tab.SelectedIndex;
5073 int fIdx, toIdx, stp;
5077 fIdx = selectedIndex + 1;
5078 if (fIdx > tab.AllCount - 1) return;
5079 toIdx = tab.AllCount;
5084 fIdx = selectedIndex - 1;
5085 if (fIdx < 0) return;
5091 if (currentPost.RetweetedBy == null)
5093 name = currentPost.ScreenName;
5097 name = currentPost.RetweetedBy;
5099 for (var idx = fIdx; idx != toIdx; idx += stp)
5101 var post = tab[idx];
5102 if (post.RetweetedId == null)
5104 if (post.ScreenName == name)
5106 var listView = this.CurrentListView;
5107 this.SelectListItem(listView, idx);
5108 listView.EnsureVisible(idx);
5114 if (post.RetweetedBy == name)
5116 var listView = this.CurrentListView;
5117 this.SelectListItem(listView, idx);
5118 listView.EnsureVisible(idx);
5125 private void GoRelPost(bool forward)
5127 var tab = this.CurrentTab;
5128 var selectedIndex = tab.SelectedIndex;
5130 if (selectedIndex == -1)
5133 int fIdx, toIdx, stp;
5137 fIdx = selectedIndex + 1;
5138 if (fIdx > tab.AllCount - 1) return;
5139 toIdx = tab.AllCount;
5144 fIdx = selectedIndex - 1;
5145 if (fIdx < 0) return;
5150 var anchorPost = tab.AnchorPost;
5151 if (anchorPost == null)
5153 var currentPost = this.CurrentPost;
5154 if (currentPost == null)
5157 anchorPost = currentPost;
5158 tab.AnchorPost = currentPost;
5161 for (var idx = fIdx; idx != toIdx; idx += stp)
5163 var post = tab[idx];
5164 if (post.ScreenName == anchorPost.ScreenName ||
5165 post.RetweetedBy == anchorPost.ScreenName ||
5166 post.ScreenName == anchorPost.RetweetedBy ||
5167 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5168 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5169 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5170 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5171 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5173 var listView = this.CurrentListView;
5174 this.SelectListItem(listView, idx);
5175 listView.EnsureVisible(idx);
5181 private void GoAnchor()
5183 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5184 if (anchorStatusId == null)
5187 var idx = this.CurrentTab.IndexOf(anchorStatusId.Value);
5191 var listView = this.CurrentListView;
5192 this.SelectListItem(listView, idx);
5193 listView.EnsureVisible(idx);
5196 private void GoTopEnd(bool goTop)
5198 var listView = this.CurrentListView;
5199 if (listView.VirtualListSize == 0)
5207 item = listView.GetItemAt(0, 25);
5215 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5217 idx = listView.VirtualListSize - 1;
5221 this.SelectListItem(listView, idx);
5224 private void GoMiddle()
5226 var listView = this.CurrentListView;
5227 if (listView.VirtualListSize == 0)
5235 item = listView.GetItemAt(0, 0);
5245 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5248 idx2 = listView.VirtualListSize - 1;
5254 idx3 = (idx1 + idx2) / 2;
5256 this.SelectListItem(listView, idx3);
5259 private void GoLast()
5261 var listView = this.CurrentListView;
5262 if (listView.VirtualListSize == 0) return;
5264 if (this.statuses.SortOrder == SortOrder.Ascending)
5266 this.SelectListItem(listView, listView.VirtualListSize - 1);
5267 listView.EnsureVisible(listView.VirtualListSize - 1);
5271 this.SelectListItem(listView, 0);
5272 listView.EnsureVisible(0);
5276 private void MoveTop()
5278 var listView = this.CurrentListView;
5279 if (listView.SelectedIndices.Count == 0) return;
5280 var idx = listView.SelectedIndices[0];
5281 if (this.statuses.SortOrder == SortOrder.Ascending)
5283 listView.EnsureVisible(listView.VirtualListSize - 1);
5287 listView.EnsureVisible(0);
5289 listView.EnsureVisible(idx);
5292 private async Task GoInReplyToPostTree()
5294 var curTabClass = this.CurrentTab;
5295 var currentPost = this.CurrentPost;
5297 if (currentPost == null)
5300 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5304 var post = await this.tw.GetStatusApi(false, currentPost.StatusId);
5306 currentPost.InReplyToStatusId = post.InReplyToStatusId;
5307 currentPost.InReplyToUser = post.InReplyToUser;
5308 currentPost.IsReply = post.IsReply;
5309 this.listCache?.PurgeCache();
5311 var index = curTabClass.SelectedIndex;
5312 this.CurrentListView.RedrawItems(index, index, false);
5314 catch (WebApiException ex)
5316 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5320 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5322 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5324 this.replyChains = new Stack<ReplyChain>();
5326 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
5329 string inReplyToTabName;
5330 var inReplyToId = currentPost.InReplyToStatusId.Value;
5331 var inReplyToUser = currentPost.InReplyToUser;
5333 var inReplyToPosts = from tab in this.statuses.Tabs
5334 orderby tab != curTabClass
5335 from post in tab.Posts.Values
5336 where post.StatusId == inReplyToId
5337 let index = tab.IndexOf(post.StatusId)
5339 select new { Tab = tab, Index = index };
5341 var inReplyPost = inReplyToPosts.FirstOrDefault();
5342 if (inReplyPost == null)
5346 await Task.Run(async () =>
5348 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
5349 .ConfigureAwait(false);
5352 this.statuses.AddPost(post);
5353 this.statuses.DistributePosts();
5356 catch (WebApiException ex)
5358 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5359 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5363 this.RefreshTimeline();
5365 inReplyPost = inReplyToPosts.FirstOrDefault();
5366 if (inReplyPost == null)
5368 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
5372 inReplyToTabName = inReplyPost.Tab.TabName;
5373 inReplyToIndex = inReplyPost.Index;
5375 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5376 var tabPage = this.ListTab.TabPages[tabIndex];
5377 var listView = (DetailsListView)tabPage.Tag;
5379 if (this.CurrentTabName != inReplyToTabName)
5381 this.ListTab.SelectedIndex = tabIndex;
5384 this.SelectListItem(listView, inReplyToIndex);
5385 listView.EnsureVisible(inReplyToIndex);
5388 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5390 var curTabClass = this.CurrentTab;
5391 var currentPost = this.CurrentPost;
5393 if (currentPost == null)
5398 if (currentPost.InReplyToStatusId != null)
5400 var posts = from t in this.statuses.Tabs
5402 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5403 let indexOf = t.IndexOf(p.Value.StatusId)
5405 orderby isForward ? indexOf : indexOf * -1
5406 orderby t != curTabClass
5407 select new { Tab = t, Post = p.Value, Index = indexOf };
5410 var postList = posts.ToList();
5411 for (var i = postList.Count - 1; i >= 0; i--)
5414 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5416 postList.RemoveAt(index);
5419 var currentIndex = this.CurrentTab.SelectedIndex;
5420 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5421 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5422 if (post == null) post = postList.First();
5423 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5424 this.ListTab.SelectedIndex = tabIndex;
5425 var listView = this.CurrentListView;
5426 this.SelectListItem(listView, post.Index);
5427 listView.EnsureVisible(post.Index);
5429 catch (InvalidOperationException)
5437 if (this.replyChains == null || this.replyChains.Count < 1)
5439 var posts = from t in this.statuses.Tabs
5441 where p.Value.InReplyToStatusId == currentPost.StatusId
5442 let indexOf = t.IndexOf(p.Value.StatusId)
5445 orderby t != curTabClass
5446 select new { Tab = t, Index = indexOf };
5449 var post = posts.First();
5450 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5451 this.ListTab.SelectedIndex = tabIndex;
5452 var listView = this.CurrentListView;
5453 this.SelectListItem(listView, post.Index);
5454 listView.EnsureVisible(post.Index);
5456 catch (InvalidOperationException)
5463 var chainHead = this.replyChains.Pop();
5464 if (chainHead.InReplyToId == currentPost.StatusId)
5466 var tab = chainHead.OriginalTab;
5467 if (!this.statuses.Tabs.Contains(tab))
5469 this.replyChains = null;
5473 var idx = tab.IndexOf(chainHead.OriginalId);
5476 this.replyChains = null;
5480 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5483 this.ListTab.SelectedIndex = tabIndex;
5487 this.replyChains = null;
5489 var listView = this.CurrentListView;
5490 this.SelectListItem(listView, idx);
5491 listView.EnsureVisible(idx);
5497 this.replyChains = null;
5498 this.GoBackInReplyToPostTree(parallel);
5504 private void GoBackSelectPostChain()
5506 if (this.selectPostChains.Count > 1)
5509 TabModel? foundTab = null;
5515 this.selectPostChains.Pop();
5516 var (tab, post) = this.selectPostChains.Peek();
5518 if (!this.statuses.Tabs.Contains(tab))
5519 continue; // 該当タブが存在しないので無視
5523 idx = tab.IndexOf(post.StatusId);
5524 if (idx == -1) continue; // 該当ポストが存在しないので無視
5529 this.selectPostChains.Pop();
5531 catch (InvalidOperationException)
5537 while (this.selectPostChains.Count > 1);
5539 if (foundTab == null)
5542 // 履歴が残り1つであればクリアしておく
5543 if (this.selectPostChains.Count == 1)
5544 this.selectPostChains.Clear();
5548 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5549 var tabPage = this.ListTab.TabPages[tabIndex];
5550 var lst = (DetailsListView)tabPage.Tag;
5551 this.ListTab.SelectedIndex = tabIndex;
5555 this.SelectListItem(lst, idx);
5556 lst.EnsureVisible(idx);
5562 private void PushSelectPostChain()
5564 var currentTab = this.CurrentTab;
5565 var currentPost = this.CurrentPost;
5567 var count = this.selectPostChains.Count;
5570 var (tab, post) = this.selectPostChains.Peek();
5571 if (tab == currentTab)
5573 if (post == currentPost) return; // 最新の履歴と同一
5574 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5577 if (count >= 2500) this.TrimPostChain();
5578 this.selectPostChains.Push((currentTab, currentPost));
5581 private void TrimPostChain()
5583 if (this.selectPostChains.Count <= 2000) return;
5584 var p = new Stack<(TabModel, PostClass?)>(2000);
5585 for (var i = 0; i < 2000; i++)
5587 p.Push(this.selectPostChains.Pop());
5589 this.selectPostChains.Clear();
5590 for (var i = 0; i < 2000; i++)
5592 this.selectPostChains.Push(p.Pop());
5596 private bool GoStatus(long statusId)
5598 if (statusId == 0) return false;
5600 var tab = this.statuses.Tabs
5601 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5602 .Where(x => x.Contains(statusId))
5608 var index = tab.IndexOf(statusId);
5610 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5611 this.ListTab.SelectedIndex = tabIndex;
5613 var listView = this.CurrentListView;
5614 this.SelectListItem(listView, index);
5615 listView.EnsureVisible(index);
5620 private bool GoDirectMessage(long statusId)
5622 if (statusId == 0) return false;
5624 var tab = this.statuses.DirectMessageTab;
5625 var index = tab.IndexOf(statusId);
5630 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5631 this.ListTab.SelectedIndex = tabIndex;
5633 var listView = this.CurrentListView;
5634 this.SelectListItem(listView, index);
5635 listView.EnsureVisible(index);
5640 private void MyList_MouseClick(object sender, MouseEventArgs e)
5641 => this.CurrentTab.ClearAnchor();
5643 private void StatusText_Enter(object sender, EventArgs e)
5645 // フォーカスの戻り先を StatusText に設定
5646 this.Tag = this.StatusText;
5647 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5650 public Color InputBackColor
5651 => this.themeManager.ColorInputBackcolor;
5653 private void StatusText_Leave(object sender, EventArgs e)
5655 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5656 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5657 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5660 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5662 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5665 e.SuppressKeyPress = true;
5668 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5670 if (asyncTask != null)
5674 private void SaveConfigsAll(bool ifModified)
5678 this.SaveConfigsCommon();
5679 this.SaveConfigsLocal();
5680 this.SaveConfigsTabs();
5681 this.SaveConfigsAtId();
5685 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5686 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5687 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5691 private void SaveConfigsAtId()
5693 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5695 this.ModifySettingAtId = false;
5696 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5697 this.settings.SaveAtIdList();
5700 private void SaveConfigsCommon()
5702 if (this.ignoreConfigSave) return;
5704 this.ModifySettingCommon = false;
5705 lock (this.syncObject)
5707 this.settings.Common.UserName = this.tw.Username;
5708 this.settings.Common.UserId = this.tw.UserId;
5709 this.settings.Common.Token = this.tw.AccessToken;
5710 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5711 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5712 this.settings.Common.SortColumn = this.statuses.SortMode switch
5714 ComparerMode.Nickname => 1, // ニックネーム
5715 ComparerMode.Data => 2, // 本文
5716 ComparerMode.Id => 3, // 時刻=発言Id
5717 ComparerMode.Name => 4, // 名前
5718 ComparerMode.Source => 7, // Source
5719 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5721 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5722 if (this.HashMgr.IsPermanent)
5724 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5728 this.settings.Common.HashSelected = "";
5730 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5731 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5732 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5733 this.settings.Common.UseImageService = this.ImageSelector.ServiceIndex;
5734 this.settings.Common.UseImageServiceName = this.ImageSelector.ServiceName;
5736 this.settings.SaveCommon();
5740 private void SaveConfigsLocal()
5742 if (this.ignoreConfigSave) return;
5743 lock (this.syncObject)
5745 this.ModifySettingLocal = false;
5746 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5747 this.settings.Local.FormSize = this.mySize;
5748 this.settings.Local.FormLocation = this.myLoc;
5749 this.settings.Local.SplitterDistance = this.mySpDis;
5750 this.settings.Local.PreviewDistance = this.mySpDis3;
5751 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5752 this.settings.Local.StatusTextHeight = this.mySpDis2;
5754 if (this.ignoreConfigSave) return;
5755 this.settings.SaveLocal();
5759 private void SaveConfigsTabs()
5761 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5763 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5765 foreach (var tab in tabs)
5767 if (!tab.IsPermanentTabType)
5770 var tabSetting = new SettingTabs.SettingTabItem
5772 TabName = tab.TabName,
5773 TabType = tab.TabType,
5774 UnreadManage = tab.UnreadManage,
5775 Protected = tab.Protected,
5776 Notify = tab.Notify,
5777 SoundFile = tab.SoundFile,
5782 case FilterTabModel filterTab:
5783 tabSetting.FilterArray = filterTab.FilterArray;
5785 case UserTimelineTabModel userTab:
5786 tabSetting.User = userTab.ScreenName;
5788 case PublicSearchTabModel searchTab:
5789 tabSetting.SearchWords = searchTab.SearchWords;
5790 tabSetting.SearchLang = searchTab.SearchLang;
5792 case ListTimelineTabModel listTab:
5793 tabSetting.ListInfo = listTab.ListInfo;
5797 tabSettingList.Add(tabSetting);
5800 this.settings.Tabs.Tabs = tabSettingList;
5801 this.settings.SaveTabs();
5804 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5806 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5807 if (ret != DialogResult.OK)
5810 var match = Twitter.StatusUrlRegex.Match(inputText);
5815 Properties.Resources.OpenURL_InvalidFormat,
5816 Properties.Resources.OpenURL_Caption,
5817 MessageBoxButtons.OK,
5818 MessageBoxIcon.Error);
5824 var statusId = long.Parse(match.Groups["StatusId"].Value);
5825 await this.OpenRelatedTab(statusId);
5827 catch (TabException ex)
5829 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5833 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5835 var tab = this.CurrentTab;
5837 var rslt = MessageBox.Show(
5838 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5839 Properties.Resources.SaveLogMenuItem_ClickText2,
5840 MessageBoxButtons.YesNoCancel,
5841 MessageBoxIcon.Question);
5842 if (rslt == DialogResult.Cancel) return;
5844 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5845 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5846 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5847 this.SaveFileDialog1.FilterIndex = 0;
5848 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5849 this.SaveFileDialog1.RestoreDirectory = true;
5851 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5853 if (!this.SaveFileDialog1.ValidateNames) return;
5854 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5855 if (rslt == DialogResult.Yes)
5858 for (var idx = 0; idx < tab.AllCount; idx++)
5860 var post = tab[idx];
5863 protect = "Protect";
5864 sw.WriteLine(post.Nickname + "\t" +
5865 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5866 post.CreatedAt.ToLocalTimeString() + "\t" +
5867 post.ScreenName + "\t" +
5868 post.StatusId + "\t" +
5869 post.ImageUrl + "\t" +
5870 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5876 foreach (var post in this.CurrentTab.SelectedPosts)
5880 protect = "Protect";
5881 sw.WriteLine(post.Nickname + "\t" +
5882 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5883 post.CreatedAt.ToLocalTimeString() + "\t" +
5884 post.ScreenName + "\t" +
5885 post.StatusId + "\t" +
5886 post.ImageUrl + "\t" +
5887 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5892 this.TopMost = this.settings.Common.AlwaysTop;
5895 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5899 using (var inputName = new InputTabName())
5901 inputName.TabName = origTabName;
5902 inputName.ShowDialog();
5903 if (inputName.DialogResult == DialogResult.Cancel) return false;
5904 newTabName = inputName.TabName;
5906 this.TopMost = this.settings.Common.AlwaysTop;
5907 if (!MyCommon.IsNullOrEmpty(newTabName))
5910 if (this.statuses.ContainsTab(newTabName))
5912 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5913 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5917 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5918 var tabPage = this.ListTab.TabPages[tabIndex];
5921 if (tabPage != null)
5922 tabPage.Text = newTabName;
5924 this.statuses.RenameTab(origTabName, newTabName);
5926 this.SaveConfigsCommon();
5927 this.SaveConfigsTabs();
5928 this.rclickTabName = newTabName;
5937 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5939 if (e.Button == MouseButtons.Middle)
5941 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5943 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5945 this.RemoveSpecifiedTab(tab.TabName, true);
5946 this.SaveConfigsTabs();
5953 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5954 => this.TabRename(this.CurrentTabName, out _);
5956 private void ListTab_MouseDown(object sender, MouseEventArgs e)
5958 if (this.settings.Common.TabMouseLock) return;
5959 if (e.Button == MouseButtons.Left)
5961 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5963 if (this.ListTab.GetTabRect(i).Contains(e.Location))
5965 this.tabDrag = true;
5966 this.tabMouseDownPoint = e.Location;
5973 this.tabDrag = false;
5977 private void ListTab_DragEnter(object sender, DragEventArgs e)
5979 if (e.Data.GetDataPresent(typeof(TabPage)))
5980 e.Effect = DragDropEffects.Move;
5982 e.Effect = DragDropEffects.None;
5985 private void ListTab_DragDrop(object sender, DragEventArgs e)
5987 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5989 this.tabDrag = false;
5992 var cpos = new Point(e.X, e.Y);
5993 var spos = this.ListTab.PointToClient(cpos);
5994 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5996 var rect = this.ListTab.GetTabRect(index);
5997 if (rect.Contains(spos))
6000 if (spos.X <= (rect.Left + rect.Right) / 2)
6009 // タブのないところにドロップ->最後尾へ移動
6010 if (MyCommon.IsNullOrEmpty(tn))
6012 var lastTab = this.statuses.Tabs.Last();
6013 tn = lastTab.TabName;
6017 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6018 if (tp.Text == tn) return;
6020 this.ReOrderTab(tp.Text, tn, bef);
6023 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6025 var baseIndex = this.GetTabPageIndex(baseTabText);
6026 if (baseIndex == -1)
6029 var targetIndex = this.GetTabPageIndex(targetTabText);
6030 if (targetIndex == -1)
6033 using (ControlTransaction.Layout(this.ListTab))
6035 var tab = this.statuses.Tabs[targetIndex];
6036 var tabPage = this.ListTab.TabPages[targetIndex];
6038 this.ListTab.TabPages.Remove(tabPage);
6040 if (targetIndex < baseIndex)
6043 if (!isBeforeBaseTab)
6046 this.statuses.MoveTab(baseIndex, tab);
6048 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6051 this.SaveConfigsTabs();
6054 private void MakeDirectMessageText()
6056 var selectedPosts = this.CurrentTab.SelectedPosts;
6057 if (selectedPosts.Length > 1)
6060 var post = selectedPosts.Single();
6061 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6063 this.inReplyTo = null;
6064 this.StatusText.Text = text;
6065 this.StatusText.SelectionStart = text.Length;
6066 this.StatusText.Focus();
6069 private void MakeReplyText(bool atAll = false)
6071 var selectedPosts = this.CurrentTab.SelectedPosts;
6072 if (selectedPosts.Any(x => x.IsDm))
6074 this.MakeDirectMessageText();
6078 if (selectedPosts.Length == 1)
6080 var post = selectedPosts.Single();
6081 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6082 var inReplyToScreenName = post.ScreenName;
6083 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6087 this.inReplyTo = null;
6090 var selfScreenName = this.tw.Username;
6091 var targetScreenNames = new List<string>();
6092 foreach (var post in selectedPosts)
6094 if (post.ScreenName != selfScreenName)
6095 targetScreenNames.Add(post.ScreenName);
6099 foreach (var (_, screenName) in post.ReplyToList)
6101 if (screenName != selfScreenName)
6102 targetScreenNames.Add(screenName);
6107 if (this.inReplyTo != null)
6109 var (_, screenName) = this.inReplyTo.Value;
6110 if (screenName == selfScreenName)
6111 targetScreenNames.Insert(0, screenName);
6114 var text = this.StatusText.Text;
6115 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6117 var atText = $"@{screenName} ";
6118 if (!text.Contains(atText))
6119 text = atText + text;
6122 this.StatusText.Text = text;
6123 this.StatusText.SelectionStart = text.Length;
6124 this.StatusText.Focus();
6127 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6128 => this.tabDrag = false;
6130 private int iconCnt = 0;
6131 private int blinkCnt = 0;
6132 private bool blink = false;
6134 private void RefreshTasktrayIcon()
6136 void EnableTasktrayAnimation()
6137 => this.TimerRefreshIcon.Enabled = true;
6139 void DisableTasktrayAnimation()
6140 => this.TimerRefreshIcon.Enabled = false;
6142 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6146 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6149 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6150 this.myStatusError = false;
6151 EnableTasktrayAnimation();
6155 var replyIconType = this.settings.Common.ReplyIconState;
6157 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6159 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6160 if (replyTab != null && replyTab.UnreadCount > 0)
6164 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6167 if (this.blinkCnt > 10)
6170 if (this.blinkCnt == 0)
6171 this.blink = !this.blink;
6173 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6174 EnableTasktrayAnimation();
6178 DisableTasktrayAnimation();
6184 // 優先度:リプライ→エラー→オフライン→アイドル
6185 // エラーは更新アイコンでクリアされる
6186 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6187 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6188 else if (this.myStatusError)
6189 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6190 else if (this.myStatusOnline)
6191 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6193 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6196 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6197 => this.RefreshTasktrayIcon(); // 200ms
6199 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6201 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6202 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6203 this.rclickTabName = this.CurrentTabName;
6205 if (this.statuses == null) return;
6206 if (this.statuses.Tabs == null) return;
6208 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6211 this.NotifyDispMenuItem.Checked = tb.Notify;
6212 this.NotifyTbMenuItem.Checked = tb.Notify;
6214 this.soundfileListup = true;
6215 this.SoundFileComboBox.Items.Clear();
6216 this.SoundFileTbComboBox.Items.Clear();
6217 this.SoundFileComboBox.Items.Add("");
6218 this.SoundFileTbComboBox.Items.Add("");
6219 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6220 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6222 oDir = oDir.GetDirectories("Sounds")[0];
6224 foreach (var oFile in oDir.GetFiles("*.wav"))
6226 this.SoundFileComboBox.Items.Add(oFile.Name);
6227 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6229 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6230 if (idx == -1) idx = 0;
6231 this.SoundFileComboBox.SelectedIndex = idx;
6232 this.SoundFileTbComboBox.SelectedIndex = idx;
6233 this.soundfileListup = false;
6234 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6235 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6237 this.TabMenuControl(this.rclickTabName);
6240 private void TabMenuControl(string tabName)
6242 var tabInfo = this.statuses.GetTabByName(tabName)!;
6244 this.FilterEditMenuItem.Enabled = true;
6245 this.EditRuleTbMenuItem.Enabled = true;
6247 if (tabInfo.IsDefaultTabType)
6249 this.ProtectTabMenuItem.Enabled = false;
6250 this.ProtectTbMenuItem.Enabled = false;
6254 this.ProtectTabMenuItem.Enabled = true;
6255 this.ProtectTbMenuItem.Enabled = true;
6258 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6260 this.ProtectTabMenuItem.Checked = true;
6261 this.ProtectTbMenuItem.Checked = true;
6262 this.DeleteTabMenuItem.Enabled = false;
6263 this.DeleteTbMenuItem.Enabled = false;
6267 this.ProtectTabMenuItem.Checked = false;
6268 this.ProtectTbMenuItem.Checked = false;
6269 this.DeleteTabMenuItem.Enabled = true;
6270 this.DeleteTbMenuItem.Enabled = true;
6274 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6276 var checkState = ((ToolStripMenuItem)sender).Checked;
6279 this.ProtectTbMenuItem.Checked = checkState;
6280 this.ProtectTabMenuItem.Checked = checkState;
6283 this.DeleteTabMenuItem.Enabled = !checkState;
6284 this.DeleteTbMenuItem.Enabled = !checkState;
6286 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6287 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6289 this.SaveConfigsTabs();
6292 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6294 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6295 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6297 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6298 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6300 this.SaveConfigsTabs();
6303 public void ChangeTabUnreadManage(string tabName, bool isManage)
6305 var idx = this.GetTabPageIndex(tabName);
6309 var tab = this.statuses.Tabs[tabName];
6310 tab.UnreadManage = isManage;
6312 if (this.settings.Common.TabIconDisp)
6314 var tabPage = this.ListTab.TabPages[idx];
6315 if (tab.UnreadCount > 0)
6316 tabPage.ImageIndex = 0;
6318 tabPage.ImageIndex = -1;
6321 if (this.CurrentTabName == tabName)
6323 this.listCache?.PurgeCache();
6324 this.CurrentListView.Refresh();
6327 this.SetMainWindowTitle();
6328 this.SetStatusLabelUrl();
6329 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6332 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6334 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6335 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6337 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6339 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6341 this.SaveConfigsTabs();
6344 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6346 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6348 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6350 this.SaveConfigsTabs();
6353 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6355 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6356 this.rclickTabName = this.CurrentTabName;
6358 this.RemoveSpecifiedTab(this.rclickTabName, true);
6359 this.SaveConfigsTabs();
6362 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6364 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6366 using (var fltDialog = new FilterDialog())
6368 fltDialog.Owner = this;
6369 fltDialog.SetCurrent(this.rclickTabName);
6370 fltDialog.ShowDialog(this);
6372 this.TopMost = this.settings.Common.AlwaysTop;
6374 this.ApplyPostFilters();
6375 this.SaveConfigsTabs();
6378 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6380 string? tabName = null;
6381 MyCommon.TabUsageType tabUsage;
6382 using (var inputName = new InputTabName())
6384 inputName.TabName = this.statuses.MakeTabName("MyTab");
6385 inputName.IsShowUsage = true;
6386 inputName.ShowDialog();
6387 if (inputName.DialogResult == DialogResult.Cancel) return;
6388 tabName = inputName.TabName;
6389 tabUsage = inputName.Usage;
6391 this.TopMost = this.settings.Common.AlwaysTop;
6392 if (!MyCommon.IsNullOrEmpty(tabName))
6395 ListElement? list = null;
6396 if (tabUsage == MyCommon.TabUsageType.Lists)
6398 using var listAvail = new ListAvailable();
6399 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6401 if (listAvail.SelectedList == null)
6403 list = listAvail.SelectedList;
6409 case MyCommon.TabUsageType.UserDefined:
6410 tab = new FilterTabModel(tabName);
6412 case MyCommon.TabUsageType.PublicSearch:
6413 tab = new PublicSearchTabModel(tabName);
6415 case MyCommon.TabUsageType.Lists:
6416 tab = new ListTimelineTabModel(tabName, list!);
6422 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6424 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6425 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6430 this.SaveConfigsTabs();
6432 var tabIndex = this.statuses.Tabs.Count - 1;
6434 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6436 this.ListTab.SelectedIndex = tabIndex;
6437 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6439 if (tabUsage == MyCommon.TabUsageType.Lists)
6441 this.ListTab.SelectedIndex = tabIndex;
6442 await this.RefreshTabAsync(this.CurrentTab);
6448 private void TabMenuItem_Click(object sender, EventArgs e)
6451 foreach (var post in this.CurrentTab.SelectedPosts)
6454 if (!this.SelectTab(out var tab))
6457 using (var fltDialog = new FilterDialog())
6459 fltDialog.Owner = this;
6460 fltDialog.SetCurrent(tab.TabName);
6462 if (post.RetweetedBy == null)
6464 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6468 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6470 fltDialog.ShowDialog(this);
6473 this.TopMost = this.settings.Common.AlwaysTop;
6476 this.ApplyPostFilters();
6477 this.SaveConfigsTabs();
6480 protected override bool ProcessDialogKey(Keys keyData)
6482 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6483 if ((keyData & Keys.KeyCode) == Keys.Enter)
6485 if (this.StatusText.Focused)
6487 var newLine = false;
6490 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6492 if (this.StatusText.Multiline)
6494 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6496 if ((keyData & Keys.Control) == Keys.Control) post = true;
6500 if ((keyData & Keys.Control) == Keys.Control) post = true;
6503 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6505 if (this.StatusText.Multiline)
6507 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6509 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6513 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6518 if (this.StatusText.Multiline)
6520 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6522 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6523 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6527 if (((keyData & Keys.Shift) == Keys.Shift) ||
6528 (((keyData & Keys.Control) != Keys.Control) &&
6529 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6535 var pos1 = this.StatusText.SelectionStart;
6536 if (this.StatusText.SelectionLength > 0)
6538 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6540 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6541 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6546 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6552 var tab = this.CurrentTab;
6553 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6555 var tabPage = this.CurrentTabPage;
6556 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6557 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6559 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6566 return base.ProcessDialogKey(keyData);
6569 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6570 => this.MakeReplyText(atAll: true);
6572 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6574 var tab = this.CurrentTab;
6575 var selectedPosts = tab.SelectedPosts;
6578 if (selectedPosts.Length == 0)
6581 var screenNameArray = selectedPosts
6582 .Select(x => x.RetweetedBy ?? x.ScreenName)
6585 this.AddFilterRuleByScreenName(screenNameArray);
6587 if (screenNameArray.Length != 0)
6589 var atids = new List<string>();
6590 foreach (var screenName in screenNameArray)
6592 atids.Add("@" + screenName);
6594 var cnt = this.AtIdSupl.ItemCount;
6595 this.AtIdSupl.AddRangeItem(atids.ToArray());
6596 if (this.AtIdSupl.ItemCount != cnt)
6597 this.MarkSettingAtIdModified();
6601 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6603 var tab = this.CurrentTab;
6604 var selectedPosts = tab.SelectedPosts;
6606 if (selectedPosts.Length == 0)
6609 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6611 this.AddFilterRuleBySource(sourceArray);
6614 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6617 if (!this.SelectTab(out var tab)) return;
6621 if (tab.TabType != MyCommon.TabUsageType.Mute)
6623 this.MoveOrCopy(out mv, out mk);
6627 // ミュートタブでは常に MoveMatches を true にする
6632 foreach (var screenName in screenNameArray)
6634 tab.AddFilter(new PostFilterRule
6636 FilterName = screenName,
6637 UseNameField = true,
6641 FilterByUrl = false,
6645 this.ApplyPostFilters();
6646 this.SaveConfigsTabs();
6649 public void AddFilterRuleBySource(params string[] sourceArray)
6651 // タブ選択ダイアログを表示(or追加)
6652 if (!this.SelectTab(out var filterTab))
6657 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6659 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6660 this.MoveOrCopy(out mv, out mk);
6664 // ミュートタブでは常に MoveMatches を true にする
6669 // 振り分けルールに追加するSource
6670 foreach (var source in sourceArray)
6672 filterTab.AddFilter(new PostFilterRule
6674 FilterSource = source,
6678 FilterByUrl = false,
6682 this.ApplyPostFilters();
6683 this.SaveConfigsTabs();
6686 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6693 using (var dialog = new TabsDialog(this.statuses))
6695 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6697 tab = dialog.SelectedTab;
6700 this.CurrentTabPage.Focus();
6705 using (var inputName = new InputTabName())
6707 inputName.TabName = this.statuses.MakeTabName("MyTab");
6708 inputName.ShowDialog();
6709 if (inputName.DialogResult == DialogResult.Cancel) return false;
6710 tabName = inputName.TabName;
6712 this.TopMost = this.settings.Common.AlwaysTop;
6713 if (!MyCommon.IsNullOrEmpty(tabName))
6715 var newTab = new FilterTabModel(tabName);
6716 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6718 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6719 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6738 private void MoveOrCopy(out bool move, out bool mark)
6742 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6743 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6751 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6752 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6763 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6766 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6767 => this.CopyIdUri();
6769 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6771 if (this.StatusText.Focused)
6774 this.StatusText.SelectAll();
6778 // ListView上でのCtrl+A
6779 NativeMethods.SelectAllItems(this.CurrentListView);
6783 private void MoveMiddle()
6789 var listView = this.CurrentListView;
6790 if (listView.SelectedIndices.Count == 0) return;
6792 var idx = listView.SelectedIndices[0];
6794 item = listView.GetItemAt(0, 25);
6800 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6802 idx2 = listView.VirtualListSize - 1;
6806 idx -= Math.Abs(idx1 - idx2) / 2;
6807 if (idx < 0) idx = 0;
6809 listView.EnsureVisible(listView.VirtualListSize - 1);
6810 listView.EnsureVisible(idx);
6813 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6815 var linkElements = this.tweetDetailsView.GetLinkElements();
6817 if (linkElements.Length == 0)
6820 var links = new List<OpenUrlItem>(linkElements.Length);
6822 foreach (var linkElm in linkElements)
6824 var displayUrl = linkElm.GetAttribute("title");
6825 var href = linkElm.GetAttribute("href");
6826 var linkedText = linkElm.InnerText;
6828 if (MyCommon.IsNullOrEmpty(displayUrl))
6831 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6835 bool isReverseSettings;
6837 if (links.Count == 1)
6839 // ツイートに含まれる URL が 1 つのみの場合
6840 // => OpenURL ダイアログを表示せずにリンクを開く
6841 selectedUrl = links[0].Href;
6843 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6844 isReverseSettings = false;
6848 // ツイートに含まれる URL が複数ある場合
6849 // => OpenURL を表示しユーザーが選択したリンクを開く
6850 this.urlDialog.ClearUrl();
6852 foreach (var link in links)
6853 this.urlDialog.AddUrl(link);
6855 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6858 this.TopMost = this.settings.Common.AlwaysTop;
6860 selectedUrl = this.urlDialog.SelectedUrl;
6862 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6863 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6866 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6869 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6871 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6872 this.ClearTab(this.rclickTabName, true);
6875 private void ClearTab(string tabName, bool showWarning)
6879 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6880 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6886 this.statuses.ClearTabIds(tabName);
6887 if (this.CurrentTabName == tabName)
6889 this.CurrentTab.ClearAnchor();
6890 this.listCache?.PurgeCache();
6891 this.listCache?.UpdateListSize();
6894 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6895 var tabPage = this.ListTab.TabPages[tabIndex];
6896 tabPage.ImageIndex = -1;
6898 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6900 this.SetMainWindowTitle();
6901 this.SetStatusLabelUrl();
6904 private static long followers = 0;
6906 private void SetMainWindowTitle()
6908 // メインウインドウタイトルの書き換え
6909 var ttl = new StringBuilder(256);
6912 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6913 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6914 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6915 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6917 foreach (var tab in this.statuses.Tabs)
6919 ur += tab.UnreadCount;
6924 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6925 ttl.Append(ApplicationSettings.ApplicationName);
6927 switch (this.settings.Common.DispLatestPost)
6929 case MyCommon.DispTitleEnum.Ver:
6930 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6932 case MyCommon.DispTitleEnum.Post:
6933 if (this.history != null && this.history.Count > 1)
6934 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6936 case MyCommon.DispTitleEnum.UnreadRepCount:
6937 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6939 case MyCommon.DispTitleEnum.UnreadAllCount:
6940 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6942 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6943 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6945 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6946 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6948 case MyCommon.DispTitleEnum.OwnStatus:
6949 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6950 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6956 this.Text = ttl.ToString();
6958 catch (AccessViolationException)
6960 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6964 private string GetStatusLabelText()
6967 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6968 if (this.statuses == null) return "";
6969 var tbRep = this.statuses.MentionTab;
6970 var tbDm = this.statuses.DirectMessageTab;
6971 if (tbRep == null || tbDm == null) return "";
6972 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6977 var slbl = new StringBuilder(256);
6980 foreach (var tab in this.statuses.Tabs)
6982 ur += tab.UnreadCount;
6984 if (tab.TabName == this.CurrentTabName)
6986 tur = tab.UnreadCount;
6996 this.unreadCounter = ur;
6997 this.unreadAtCounter = urat;
6999 var homeTab = this.statuses.HomeTab;
7001 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7002 if (this.settings.Common.TimelinePeriod == 0)
7004 slbl.Append(Properties.Resources.SetStatusLabelText2);
7008 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7010 return slbl.ToString();
7013 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7017 if (this.InvokeRequired && !this.IsDisposed)
7019 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7023 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7024 this.SetApiStatusLabel(endpointName);
7027 catch (ObjectDisposedException)
7031 catch (InvalidOperationException)
7037 private void SetApiStatusLabel(string? endpointName = null)
7039 var tabType = this.CurrentTab.TabType;
7041 if (endpointName == null)
7044 endpointName = tabType switch
7046 MyCommon.TabUsageType.Home => GetTimelineRequest.EndpointName,
7047 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7048 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7049 MyCommon.TabUsageType.Favorites => "/favorites/list",
7050 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7051 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7052 MyCommon.TabUsageType.Lists => "/lists/statuses",
7053 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7054 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7057 this.toolStripApiGauge.ApiEndpoint = endpointName;
7061 // 表示中のタブに関連する endpoint であれば更新
7063 if (endpointName == GetTimelineRequest.EndpointName)
7065 update = tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined;
7069 update = endpointName switch
7071 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7072 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7073 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7074 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7075 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7076 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7077 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7084 this.toolStripApiGauge.ApiEndpoint = endpointName;
7089 private void SetStatusLabelUrl()
7090 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7092 public void SetStatusLabel(string text)
7093 => this.StatusLabel.Text = text;
7095 private void SetNotifyIconText()
7097 var ur = new StringBuilder(64);
7099 // タスクトレイアイコンのツールチップテキスト書き換え
7101 ur.Remove(0, ur.Length);
7102 if (this.settings.Common.DispUsername)
7104 ur.Append(this.tw.Username);
7107 ur.Append(ApplicationSettings.ApplicationName);
7109 ur.Append("(Debug Build)");
7111 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7114 ur.Append(this.unreadCounter);
7116 ur.Append(this.unreadAtCounter);
7119 this.NotifyIcon1.Text = ur.ToString();
7122 internal void CheckReplyTo(string statusText)
7126 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7128 foreach (Match hm in m)
7130 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7132 hstr += "#" + hm.Result("$3") + " ";
7133 this.HashSupl.AddItem("#" + hm.Result("$3"));
7136 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7138 hstr += this.HashMgr.UseHash;
7140 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7142 // 本当にリプライ先指定すべきかどうかの判定
7143 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7145 if (this.settings.Common.UseAtIdSupplement)
7147 var bCnt = this.AtIdSupl.ItemCount;
7148 foreach (Match mid in m)
7150 this.AtIdSupl.AddItem(mid.Result("${id}"));
7152 if (bCnt != this.AtIdSupl.ItemCount)
7153 this.MarkSettingAtIdModified();
7156 // リプライ先ステータスIDの指定がない場合は指定しない
7157 if (this.inReplyTo == null)
7161 // 次の条件を満たす場合に in_reply_to_status_id 指定
7162 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7163 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7164 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7168 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7169 if (statusText.StartsWith("@", StringComparison.Ordinal))
7171 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7175 foreach (Match mid in m)
7177 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7182 this.inReplyTo = null;
7185 private void TweenMain_Resize(object sender, EventArgs e)
7187 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7189 this.Visible = false;
7191 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7193 // 現在の DPI と設定保存時の DPI との比を取得する
7194 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7196 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7199 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7200 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7201 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7203 this.SplitContainer1.SplitterDistance = splitterDistance;
7207 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7208 if (this.StatusText.Multiline)
7210 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7211 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7212 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7214 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7216 this.StatusText.Height = statusTextHeight;
7220 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7222 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7226 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7227 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7229 this.SplitContainer3.SplitterDistance = previewDistance;
7232 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7233 this.SplitContainer3.Panel2Collapsed = true;
7235 this.initialLayout = false;
7237 if (this.WindowState != FormWindowState.Minimized)
7239 this.formWindowState = this.WindowState;
7243 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7245 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7246 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7247 if (this.PlaySoundMenuItem.Checked)
7249 this.settings.Common.PlaySound = true;
7253 this.settings.Common.PlaySound = false;
7255 this.MarkSettingCommonModified();
7258 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7260 if (this.initialLayout)
7263 int splitterDistance;
7264 switch (this.WindowState)
7266 case FormWindowState.Normal:
7267 splitterDistance = this.SplitContainer1.SplitterDistance;
7269 case FormWindowState.Maximized:
7270 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7271 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7272 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7273 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7279 this.mySpDis = splitterDistance;
7280 this.MarkSettingLocalModified();
7283 private async Task DoRepliedStatusOpen()
7285 var currentPost = this.CurrentPost;
7286 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7288 if (MyCommon.IsKeyDown(Keys.Shift))
7290 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7293 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
7295 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7299 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7301 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
7302 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
7303 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7306 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
7311 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7312 => await this.DoRepliedStatusOpen();
7314 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7316 if (this.initialLayout)
7317 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7319 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7320 if (multiline != this.StatusText.Multiline)
7322 this.StatusText.Multiline = multiline;
7323 this.settings.Local.StatusMultiline = multiline;
7324 this.MarkSettingLocalModified();
7328 private void StatusText_MultilineChanged(object sender, EventArgs e)
7330 if (this.StatusText.Multiline)
7331 this.StatusText.ScrollBars = ScrollBars.Vertical;
7333 this.StatusText.ScrollBars = ScrollBars.None;
7335 if (!this.initialLayout)
7336 this.MarkSettingLocalModified();
7339 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7342 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7343 this.StatusText.Multiline = menuItemChecked;
7344 this.settings.Local.StatusMultiline = menuItemChecked;
7345 if (menuItemChecked)
7347 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7348 this.SplitContainer2.SplitterDistance = 0;
7350 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7354 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7356 this.MarkSettingLocalModified();
7359 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7361 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7363 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7364 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7365 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7367 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7372 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7373 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7374 // Appendix A. Collected ABNF for URI
7375 // http://www.ietf.org/rfc/rfc3986.txt
7377 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7380 if (this.StatusText.SelectionLength > 0)
7382 var tmp = this.StatusText.SelectedText;
7383 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7384 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7386 // 文字列が選択されている場合はその文字列について処理
7388 // nico.ms使用、nicovideoにマッチしたら変換
7389 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7391 result = Nicoms.Shorten(tmp);
7393 else if (converterType != MyCommon.UrlConverter.Nicoms)
7398 var srcUri = new Uri(tmp);
7399 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7400 result = resultUri.AbsoluteUri;
7402 catch (WebApiException e)
7404 this.StatusLabel.Text = converterType + ":" + e.Message;
7407 catch (UriFormatException e)
7409 this.StatusLabel.Text = converterType + ":" + e.Message;
7418 if (!MyCommon.IsNullOrEmpty(result))
7420 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7421 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7422 if (origUrlIndex == -1)
7425 this.StatusText.Select(origUrlIndex, tmp.Length);
7426 this.StatusText.SelectedText = result;
7429 var undo = new UrlUndo
7435 if (this.urlUndoBuffer == null)
7437 this.urlUndoBuffer = new List<UrlUndo>();
7438 this.UrlUndoToolStripMenuItem.Enabled = true;
7441 this.urlUndoBuffer.Add(undo);
7447 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7448 @"(?<url>(?<protocol>https?://)" +
7449 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7450 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7451 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7452 // 正規表現にマッチしたURL文字列をtinyurl化
7453 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7455 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7457 var tmp = mt.Result("${url}");
7458 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7459 tmp = "http://" + tmp;
7462 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7464 // nico.ms使用、nicovideoにマッチしたら変換
7465 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7467 result = Nicoms.Shorten(tmp);
7469 else if (converterType != MyCommon.UrlConverter.Nicoms)
7474 var srcUri = new Uri(tmp);
7475 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7476 result = resultUri.AbsoluteUri;
7478 catch (HttpRequestException e)
7480 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7481 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7482 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7484 this.StatusLabel.Text = converterType + ":" + message;
7487 catch (WebApiException e)
7489 this.StatusLabel.Text = converterType + ":" + e.Message;
7492 catch (UriFormatException e)
7494 this.StatusLabel.Text = converterType + ":" + e.Message;
7503 if (!MyCommon.IsNullOrEmpty(result))
7505 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7506 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7507 if (origUrlIndex == -1)
7510 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7511 this.StatusText.SelectedText = result;
7513 var undo = new UrlUndo
7515 Before = mt.Result("${url}"),
7519 if (this.urlUndoBuffer == null)
7521 this.urlUndoBuffer = new List<UrlUndo>();
7522 this.UrlUndoToolStripMenuItem.Enabled = true;
7525 this.urlUndoBuffer.Add(undo);
7533 private void DoUrlUndo()
7535 if (this.urlUndoBuffer != null)
7537 var tmp = this.StatusText.Text;
7538 foreach (var data in this.urlUndoBuffer)
7540 tmp = tmp.Replace(data.After, data.Before);
7542 this.StatusText.Text = tmp;
7543 this.urlUndoBuffer = null;
7544 this.UrlUndoToolStripMenuItem.Enabled = false;
7545 this.StatusText.SelectionStart = 0;
7546 this.StatusText.SelectionLength = 0;
7550 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7551 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7553 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7554 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7556 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7557 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7559 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7561 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7563 var rnd = new Random();
7565 MyCommon.UrlConverter svc;
7566 // 前回使用した短縮URLサービス以外を選択する
7569 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7571 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7572 await this.UrlConvertAsync(svc);
7576 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7577 => this.DoUrlUndo();
7579 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7581 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7582 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7583 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7584 this.MarkSettingCommonModified();
7587 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7589 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7590 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7591 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7592 this.MarkSettingCommonModified();
7595 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7597 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7598 this.MenuStrip1.Tag = new object();
7599 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7602 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7604 var currentTabPage = this.CurrentTabPage;
7605 if (this.Tag != null) // 設定された戻り先へ遷移
7607 if (this.Tag == currentTabPage)
7608 ((Control)currentTabPage.Tag).Select();
7610 ((Control)this.Tag).Select();
7612 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7614 this.Tag = currentTabPage.Tag;
7615 ((Control)this.Tag).Select();
7617 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7618 this.MenuStrip1.Tag = null;
7621 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7623 if (this.Use2ColumnsMode)
7629 var lst = (DetailsListView)sender;
7630 var columnsCount = lst.Columns.Count;
7632 var darr = new int[columnsCount];
7633 for (var i = 0; i < columnsCount; i++)
7634 darr[lst.Columns[i].DisplayIndex] = i;
7636 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7638 for (var i = 0; i < columnsCount; i++)
7639 this.settings.Local.ColumnsOrder[darr[i]] = i;
7641 this.MarkSettingLocalModified();
7642 this.isColumnChanged = true;
7645 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7647 var lst = (DetailsListView)sender;
7648 if (this.settings.Local == null) return;
7650 var modified = false;
7651 if (this.Use2ColumnsMode)
7653 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7655 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7658 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7660 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7666 var columnsCount = lst.Columns.Count;
7667 for (var i = 0; i < columnsCount; i++)
7669 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7672 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7678 this.MarkSettingLocalModified();
7679 this.isColumnChanged = true;
7683 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7685 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7686 this.MarkSettingLocalModified();
7689 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7691 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7693 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7695 this.SelectMedia_DragDrop(e);
7698 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7700 var (url, title) = GetUrlFromDataObject(e.Data);
7706 appendText = title + " " + url;
7708 if (this.StatusText.TextLength == 0)
7709 this.StatusText.Text = appendText;
7711 this.StatusText.Text += " " + appendText;
7713 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7715 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7717 this.StatusText.Text += text;
7719 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7721 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7722 if (data != null) this.StatusText.Text += data;
7727 /// IDataObject から URL とタイトルの対を取得します
7730 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7732 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7733 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7734 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7736 if (data.GetDataPresent("text/x-moz-url"))
7738 // Firefox, Google Chrome で利用可能
7739 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7741 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7742 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7743 if (lines.Length < 2)
7744 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7746 return (lines[0], lines[1]);
7748 else if (data.GetDataPresent("IESiteModeToUrl"))
7750 // Internet Exproler 用
7751 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7753 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7754 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7755 if (lines.Length < 2)
7756 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7758 return (lines[0], lines[1]);
7760 else if (data.GetDataPresent("UniformResourceLocatorW"))
7764 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7765 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7769 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7772 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7774 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7776 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7778 this.SelectMedia_DragEnter(e);
7782 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7784 e.Effect = DragDropEffects.Copy;
7787 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7789 e.Effect = DragDropEffects.Copy;
7792 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7794 e.Effect = DragDropEffects.Copy;
7798 e.Effect = DragDropEffects.None;
7801 private void TweenMain_DragOver(object sender, DragEventArgs e)
7805 public bool IsNetworkAvailable()
7807 var nw = MyCommon.IsNetworkAvailable();
7808 this.myStatusOnline = nw;
7812 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7814 var uriStr = uri.AbsoluteUri;
7816 // OpenTween 内部で使用する URL
7817 if (uri.Authority == "opentween")
7819 await this.OpenInternalUriAsync(uri);
7823 // ハッシュタグを含む Twitter 検索
7824 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7827 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7828 var pos = unescapedQuery.IndexOf('#');
7829 if (pos == -1) return;
7831 var hash = unescapedQuery.Substring(pos);
7832 this.HashSupl.AddItem(hash);
7833 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7834 this.AddNewTabForSearch(hash);
7839 // フラグが立っている場合は設定と逆の動作をする
7840 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7841 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7843 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7844 if (userUriMatch.Success)
7846 var screenName = userUriMatch.Groups["ScreenName"].Value;
7847 if (this.IsTwitterId(screenName))
7849 await this.AddNewTabForUserTimeline(screenName);
7856 await MyCommon.OpenInBrowserAsync(this, uriStr);
7860 /// OpenTween 内部の機能を呼び出すための URL を開きます
7862 private async Task OpenInternalUriAsync(Uri uri)
7864 // ツイートを開く (//opentween/status/:status_id)
7865 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7868 var statusId = long.Parse(match.Groups[1].Value);
7869 await this.OpenRelatedTab(statusId);
7874 private void ListTabSelect(TabPage tabPage)
7876 this.SetListProperty();
7878 var previousTabName = this.CurrentTabName;
7879 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7880 previousListViewState.Save(this.ListLockMenuItem.Checked);
7882 this.listCache?.PurgeCache();
7884 this.statuses.SelectTab(tabPage.Text);
7886 this.InitializeTimelineListView();
7888 var tab = this.CurrentTab;
7891 var listView = this.CurrentListView;
7893 var currentListViewState = this.listViewState[tab.TabName];
7894 currentListViewState.Restore();
7896 if (this.Use2ColumnsMode)
7898 listView.Columns[1].Text = this.columnText[2];
7902 for (var i = 0; i < listView.Columns.Count; i++)
7904 listView.Columns[i].Text = this.columnText[i];
7909 private void InitializeTimelineListView()
7911 var listView = this.CurrentListView;
7912 var tab = this.CurrentTab;
7914 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7915 (this.listCache, var oldCache) = (newCache, this.listCache);
7916 oldCache?.Dispose();
7918 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager)
7920 IconSize = this.settings.Common.IconSize,
7922 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7923 oldDrawer?.Dispose();
7926 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7927 => this.ListTabSelect(e.TabPage);
7929 private void SelectListItem(DetailsListView lView, int index)
7932 var bnd = new Rectangle();
7934 var item = lView.FocusedItem;
7943 lView.SelectedIndices.Clear();
7945 while (lView.SelectedIndices.Count > 0);
7946 item = lView.Items[index];
7947 item.Selected = true;
7948 item.Focused = true;
7950 if (flg) lView.Invalidate(bnd);
7953 private async void TweenMain_Shown(object sender, EventArgs e)
7955 this.NotifyIcon1.Visible = true;
7957 if (this.IsNetworkAvailable())
7959 var loadTasks = new List<Task>
7961 this.RefreshMuteUserIdsAsync(),
7962 this.RefreshBlockIdsAsync(),
7963 this.RefreshNoRetweetIdsAsync(),
7964 this.RefreshTwitterConfigurationAsync(),
7965 this.RefreshTabAsync<HomeTabModel>(),
7966 this.RefreshTabAsync<MentionsTabModel>(),
7967 this.RefreshTabAsync<DirectMessagesTabModel>(),
7968 this.RefreshTabAsync<PublicSearchTabModel>(),
7969 this.RefreshTabAsync<UserTimelineTabModel>(),
7970 this.RefreshTabAsync<ListTimelineTabModel>(),
7973 if (this.settings.Common.StartupFollowers)
7974 loadTasks.Add(this.RefreshFollowerIdsAsync());
7976 if (this.settings.Common.GetFav)
7977 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
7979 var allTasks = Task.WhenAll(loadTasks);
7984 var timeout = Task.Delay(5000);
7985 if (await Task.WhenAny(allTasks, timeout) != timeout)
7989 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7991 if (MyCommon.EndingFlag)
7995 if (MyCommon.EndingFlag) return;
7997 if (ApplicationSettings.VersionInfoUrl != null)
7999 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8000 if (this.settings.Common.StartupVersion)
8001 await this.CheckNewVersion(true);
8005 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8006 this.VerUpMenuItem.Enabled = false;
8007 this.VerUpMenuItem.Available = false;
8008 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8011 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8012 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8014 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8015 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8019 var reloadTasks = new List<Task>();
8021 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8022 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8024 if (!this.tw.GetNoRetweetSuccess)
8025 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8027 if (this.tw.Configuration.PhotoSizeLimit == 0)
8028 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8030 await Task.WhenAll(reloadTasks);
8033 this.initial = false;
8035 this.timelineScheduler.Enabled = true;
8038 private async Task DoGetFollowersMenu()
8040 await this.RefreshFollowerIdsAsync();
8041 this.DispSelectedPost(true);
8044 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8045 => await this.DoGetFollowersMenu();
8047 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8048 => this.DoReTweetUnofficial();
8050 private async Task DoReTweetOfficial(bool isConfirm)
8053 if (this.ExistCurrentPost)
8055 var selectedPosts = this.CurrentTab.SelectedPosts;
8057 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8059 if (selectedPosts.Any(x => x.IsProtect))
8060 MessageBox.Show("Protected.");
8062 this.doFavRetweetFlags = false;
8066 if (selectedPosts.Length > 15)
8068 MessageBox.Show(Properties.Resources.RetweetLimitText);
8069 this.doFavRetweetFlags = false;
8072 else if (selectedPosts.Length > 1)
8074 var questionText = Properties.Resources.RetweetQuestion2;
8075 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8076 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8078 case DialogResult.Cancel:
8079 case DialogResult.No:
8080 this.doFavRetweetFlags = false;
8086 if (!this.settings.Common.RetweetNoConfirm)
8088 var questiontext = Properties.Resources.RetweetQuestion1;
8089 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8090 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8092 this.doFavRetweetFlags = false;
8098 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8100 await this.RetweetAsync(statusIds);
8104 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8105 => await this.DoReTweetOfficial(true);
8107 private async Task FavoritesRetweetOfficial()
8109 if (!this.ExistCurrentPost) return;
8110 this.doFavRetweetFlags = true;
8111 var retweetTask = this.DoReTweetOfficial(true);
8112 if (this.doFavRetweetFlags)
8114 this.doFavRetweetFlags = false;
8115 var favoriteTask = this.FavoriteChange(true, false);
8117 await Task.WhenAll(retweetTask, favoriteTask);
8125 private async Task FavoritesRetweetUnofficial()
8127 var post = this.CurrentPost;
8128 if (this.ExistCurrentPost && post != null && !post.IsDm)
8130 this.doFavRetweetFlags = true;
8131 var favoriteTask = this.FavoriteChange(true);
8132 if (!post.IsProtect && this.doFavRetweetFlags)
8134 this.doFavRetweetFlags = false;
8135 this.DoReTweetUnofficial();
8143 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8145 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8146 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8147 /// <returns>復元されたツイート本文</returns>
8148 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8150 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8153 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
8155 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8157 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
8159 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
8163 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8165 statusHtml = statusHtml.Replace("<br>", " ");
8167 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8168 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8169 statusHtml = statusHtml.Replace(" ", " ");
8171 return WebUtility.HtmlDecode(statusHtml);
8174 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8176 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8178 if (this.CurrentPost != null)
8179 this.DispSelectedPost(true);
8182 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8184 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8185 this.DebugModeToolStripMenuItem.Visible = true;
8187 this.DebugModeToolStripMenuItem.Visible = false;
8190 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8191 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8193 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8194 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8196 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8197 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8199 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8201 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8202 this.MarkSettingCommonModified();
8205 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8207 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8208 this.MarkSettingCommonModified();
8211 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8213 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8214 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8215 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8216 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8217 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8218 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8221 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8223 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8224 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8225 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8226 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8227 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8228 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8231 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8233 if (this.TraceOutToolStripMenuItem.Checked)
8234 MyCommon.TraceFlag = true;
8236 MyCommon.TraceFlag = false;
8239 private void TweenMain_Deactivate(object sender, EventArgs e)
8240 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8242 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8244 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8246 _ = this.TabRename(this.rclickTabName, out _);
8249 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8250 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8252 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8253 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8255 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8257 TwitterApiStatus? apiStatus;
8259 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8261 var cancellationToken = dialog.EnableCancellation();
8265 var task = this.tw.GetInfoApi();
8266 apiStatus = await dialog.WaitForAsync(this, task);
8268 catch (WebApiException)
8273 if (cancellationToken.IsCancellationRequested)
8276 if (apiStatus == null)
8278 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8283 using var apiDlg = new ApiInfoDialog();
8284 apiDlg.ShowDialog(this);
8287 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8289 var id = this.CurrentPost?.ScreenName ?? "";
8291 await this.FollowCommand(id);
8294 internal async Task FollowCommand(string id)
8296 using (var inputName = new InputTabName())
8298 inputName.FormTitle = "Follow";
8299 inputName.FormDescription = Properties.Resources.FRMessage1;
8300 inputName.TabName = id;
8302 if (inputName.ShowDialog(this) != DialogResult.OK)
8304 if (string.IsNullOrWhiteSpace(inputName.TabName))
8307 id = inputName.TabName.Trim();
8310 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8314 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8315 await dialog.WaitForAsync(this, task);
8317 catch (WebApiException ex)
8319 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8324 MessageBox.Show(Properties.Resources.FRMessage3);
8327 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8329 var id = this.CurrentPost?.ScreenName ?? "";
8331 await this.RemoveCommand(id, false);
8334 internal async Task RemoveCommand(string id, bool skipInput)
8338 using var inputName = new InputTabName();
8339 inputName.FormTitle = "Unfollow";
8340 inputName.FormDescription = Properties.Resources.FRMessage1;
8341 inputName.TabName = id;
8343 if (inputName.ShowDialog(this) != DialogResult.OK)
8345 if (string.IsNullOrWhiteSpace(inputName.TabName))
8348 id = inputName.TabName.Trim();
8351 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8355 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8356 await dialog.WaitForAsync(this, task);
8358 catch (WebApiException ex)
8360 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8365 MessageBox.Show(Properties.Resources.FRMessage3);
8368 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8370 var id = this.CurrentPost?.ScreenName ?? "";
8372 await this.ShowFriendship(id);
8375 internal async Task ShowFriendship(string id)
8377 using (var inputName = new InputTabName())
8379 inputName.FormTitle = "Show Friendships";
8380 inputName.FormDescription = Properties.Resources.FRMessage1;
8381 inputName.TabName = id;
8383 if (inputName.ShowDialog(this) != DialogResult.OK)
8385 if (string.IsNullOrWhiteSpace(inputName.TabName))
8388 id = inputName.TabName.Trim();
8391 bool isFollowing, isFollowed;
8393 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8395 var cancellationToken = dialog.EnableCancellation();
8399 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8400 var friendship = await dialog.WaitForAsync(this, task);
8402 isFollowing = friendship.Relationship.Source.Following;
8403 isFollowed = friendship.Relationship.Source.FollowedBy;
8405 catch (WebApiException ex)
8407 if (!cancellationToken.IsCancellationRequested)
8408 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8412 if (cancellationToken.IsCancellationRequested)
8419 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8423 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8427 result += Properties.Resources.GetFriendshipInfo3;
8431 result += Properties.Resources.GetFriendshipInfo4;
8433 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8434 MessageBox.Show(result);
8437 internal async Task ShowFriendship(string[] ids)
8439 foreach (var id in ids)
8441 bool isFollowing, isFollowed;
8443 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8445 var cancellationToken = dialog.EnableCancellation();
8449 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8450 var friendship = await dialog.WaitForAsync(this, task);
8452 isFollowing = friendship.Relationship.Source.Following;
8453 isFollowed = friendship.Relationship.Source.FollowedBy;
8455 catch (WebApiException ex)
8457 if (!cancellationToken.IsCancellationRequested)
8458 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8462 if (cancellationToken.IsCancellationRequested)
8472 ff += Properties.Resources.GetFriendshipInfo1;
8476 ff += Properties.Resources.GetFriendshipInfo2;
8479 ff += System.Environment.NewLine + " ";
8482 ff += Properties.Resources.GetFriendshipInfo3;
8486 ff += Properties.Resources.GetFriendshipInfo4;
8488 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8491 if (MessageBox.Show(
8492 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8493 Properties.Resources.GetFriendshipInfo8,
8494 MessageBoxButtons.YesNo,
8495 MessageBoxIcon.Question,
8496 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8498 await this.RemoveCommand(id, true);
8503 MessageBox.Show(result);
8508 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8509 => await this.DoShowUserStatus(this.tw.Username, false);
8511 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8514 public bool IsTwitterId(string name)
8516 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8517 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8519 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8522 private void DoQuoteOfficial()
8524 var post = this.CurrentPost;
8525 if (this.ExistCurrentPost && post != null)
8527 if (post.IsDm || !this.StatusText.Enabled)
8532 MessageBox.Show("Protected.");
8536 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8538 this.inReplyTo = null;
8540 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8542 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8543 this.StatusText.Focus();
8547 private void DoReTweetUnofficial()
8550 var post = this.CurrentPost;
8551 if (this.ExistCurrentPost && post != null)
8553 if (post.IsDm || !this.StatusText.Enabled)
8558 MessageBox.Show("Protected.");
8561 var rtdata = post.Text;
8562 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8564 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8566 // 投稿時に in_reply_to_status_id を付加する
8567 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8568 var inReplyToScreenName = post.ScreenName;
8569 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8571 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8573 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8574 this.StatusText.Focus();
8578 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8579 => this.DoQuoteOfficial();
8581 private async void SearchButton_Click(object sender, EventArgs e)
8584 var pnl = ((Control)sender).Parent;
8585 if (pnl == null) return;
8586 var tbName = pnl.Parent.Text;
8587 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8588 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8589 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8590 cmb.Text = cmb.Text.Trim();
8591 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8593 var buf = new StringBuilder();
8594 var c = cmb.Text.ToCharArray();
8595 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8597 if (cnt > cmb.Text.Length - 4)
8599 buf.Append(cmb.Text.Substring(cnt));
8608 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8617 cmb.Text = buf.ToString();
8619 var listView = (DetailsListView)pnl.Parent.Tag;
8621 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8623 tb.SearchWords = cmb.Text;
8624 tb.SearchLang = cmbLang.Text;
8625 if (MyCommon.IsNullOrEmpty(cmb.Text))
8628 this.SaveConfigsTabs();
8633 var idx = cmb.Items.IndexOf(tb.SearchWords);
8634 if (idx > -1) cmb.Items.RemoveAt(idx);
8635 cmb.Items.Insert(0, tb.SearchWords);
8636 cmb.Text = tb.SearchWords;
8638 this.statuses.ClearTabIds(tbName);
8639 this.listCache?.PurgeCache();
8640 this.listCache?.UpdateListSize();
8641 this.SaveConfigsTabs(); // 検索条件の保存
8645 await this.RefreshTabAsync(tb);
8648 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8649 => await this.DoRefreshMore(); // もっと前を取得
8652 /// 指定されたタブのListTabにおける位置を返します
8655 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8657 public int GetTabPageIndex(string tabName)
8658 => this.statuses.Tabs.IndexOf(tabName);
8660 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8662 if (this.statuses.RemovedTab.Count == 0)
8664 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
8669 var tb = this.statuses.RemovedTab.Pop();
8670 if (tb.TabType == MyCommon.TabUsageType.Related)
8672 var relatedTab = this.statuses.GetTabByType(MyCommon.TabUsageType.Related);
8673 if (relatedTab != null)
8675 // 関連発言なら既存のタブを置き換える
8676 tb.TabName = relatedTab.TabName;
8677 this.ClearTab(tb.TabName, false);
8679 this.statuses.ReplaceTab(tb);
8681 var tabIndex = this.statuses.Tabs.IndexOf(tb);
8682 this.ListTab.SelectedIndex = tabIndex;
8686 const string TabName = "Related Tweets";
8687 var renamed = TabName;
8688 for (var i = 2; i <= 100; i++)
8690 if (!this.statuses.ContainsTab(renamed))
8692 renamed = TabName + i;
8694 tb.TabName = renamed;
8696 this.statuses.AddTab(tb);
8697 this.AddNewTab(tb, startup: false);
8699 var tabIndex = this.statuses.Tabs.Count - 1;
8700 this.ListTab.SelectedIndex = tabIndex;
8705 var renamed = tb.TabName;
8706 for (var i = 1; i < int.MaxValue; i++)
8708 if (!this.statuses.ContainsTab(renamed))
8710 renamed = tb.TabName + "(" + i + ")";
8712 tb.TabName = renamed;
8714 this.statuses.AddTab(tb);
8715 this.AddNewTab(tb, startup: false);
8717 var tabIndex = this.statuses.Tabs.Count - 1;
8718 this.ListTab.SelectedIndex = tabIndex;
8720 this.SaveConfigsTabs();
8724 private async Task DoMoveToRTHome()
8726 var post = this.CurrentPost;
8727 if (post != null && post.RetweetedId != null)
8728 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8731 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8732 => await this.DoMoveToRTHome();
8734 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8736 var screenName = this.CurrentPost?.ScreenName;
8737 if (screenName != null)
8738 this.ListManageUserContext(screenName);
8741 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8743 var screenName = this.CurrentPost?.RetweetedBy;
8744 if (screenName != null)
8745 this.ListManageUserContext(screenName);
8748 public void ListManageUserContext(string screenName)
8750 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8751 listSelectForm.ShowDialog(this);
8754 private void SearchControls_Enter(object sender, EventArgs e)
8756 var pnl = (Control)sender;
8757 foreach (Control ctl in pnl.Controls)
8763 private void SearchControls_Leave(object sender, EventArgs e)
8765 var pnl = (Control)sender;
8766 foreach (Control ctl in pnl.Controls)
8768 ctl.TabStop = false;
8772 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8774 var tab = this.CurrentTab;
8775 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8776 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8779 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8780 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8782 private void HashManageMenuItem_Click(object sender, EventArgs e)
8787 rslt = this.HashMgr.ShowDialog();
8793 this.TopMost = this.settings.Common.AlwaysTop;
8794 if (rslt == DialogResult.Cancel) return;
8795 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8797 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8798 this.HashTogglePullDownMenuItem.Checked = true;
8799 this.HashToggleMenuItem.Checked = true;
8803 this.HashStripSplitButton.Text = "#[-]";
8804 this.HashTogglePullDownMenuItem.Checked = false;
8805 this.HashToggleMenuItem.Checked = false;
8808 this.MarkSettingCommonModified();
8809 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8812 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8814 this.HashMgr.ToggleHash();
8815 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8817 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8818 this.HashToggleMenuItem.Checked = true;
8819 this.HashTogglePullDownMenuItem.Checked = true;
8823 this.HashStripSplitButton.Text = "#[-]";
8824 this.HashToggleMenuItem.Checked = false;
8825 this.HashTogglePullDownMenuItem.Checked = false;
8827 this.MarkSettingCommonModified();
8828 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8831 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8832 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8834 public void SetPermanentHashtag(string hashtag)
8836 this.HashMgr.SetPermanentHash("#" + hashtag);
8837 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8838 this.HashTogglePullDownMenuItem.Checked = true;
8839 this.HashToggleMenuItem.Checked = true;
8841 this.MarkSettingCommonModified();
8844 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8846 var tab = this.CurrentTab;
8847 var post = this.CurrentPost;
8848 if (!this.ExistCurrentPost)
8850 this.ReplyOpMenuItem.Enabled = false;
8851 this.ReplyAllOpMenuItem.Enabled = false;
8852 this.DmOpMenuItem.Enabled = false;
8853 this.CreateTabRuleOpMenuItem.Enabled = false;
8854 this.CreateIdRuleOpMenuItem.Enabled = false;
8855 this.CreateSourceRuleOpMenuItem.Enabled = false;
8856 this.ReadOpMenuItem.Enabled = false;
8857 this.UnreadOpMenuItem.Enabled = false;
8858 this.AuthorMenuItem.Visible = false;
8859 this.RetweetedByMenuItem.Visible = false;
8863 this.ReplyOpMenuItem.Enabled = true;
8864 this.ReplyAllOpMenuItem.Enabled = true;
8865 this.DmOpMenuItem.Enabled = true;
8866 this.CreateTabRuleOpMenuItem.Enabled = true;
8867 this.CreateIdRuleOpMenuItem.Enabled = true;
8868 this.CreateSourceRuleOpMenuItem.Enabled = true;
8869 this.ReadOpMenuItem.Enabled = true;
8870 this.UnreadOpMenuItem.Enabled = true;
8871 this.AuthorMenuItem.Visible = true;
8872 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8873 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8874 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8877 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8879 this.FavOpMenuItem.Enabled = false;
8880 this.UnFavOpMenuItem.Enabled = false;
8881 this.OpenStatusOpMenuItem.Enabled = false;
8882 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8883 this.RtOpMenuItem.Enabled = false;
8884 this.RtUnOpMenuItem.Enabled = false;
8885 this.QtOpMenuItem.Enabled = false;
8886 this.FavoriteRetweetMenuItem.Enabled = false;
8887 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8891 this.FavOpMenuItem.Enabled = true;
8892 this.UnFavOpMenuItem.Enabled = true;
8893 this.OpenStatusOpMenuItem.Enabled = true;
8894 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8896 if (!post.CanRetweetBy(this.tw.UserId))
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.RtOpMenuItem.Enabled = true;
8907 this.RtUnOpMenuItem.Enabled = true;
8908 this.QtOpMenuItem.Enabled = true;
8909 this.FavoriteRetweetMenuItem.Enabled = true;
8910 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8914 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8916 this.RefreshPrevOpMenuItem.Enabled = true;
8920 this.RefreshPrevOpMenuItem.Enabled = false;
8922 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8924 this.OpenRepSourceOpMenuItem.Enabled = false;
8928 this.OpenRepSourceOpMenuItem.Enabled = true;
8931 if (this.ExistCurrentPost && post != null)
8933 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8937 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8938 => this.ContextMenuTabProperty_Opening(sender, null!);
8940 public Twitter TwitterInstance
8943 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8945 if (this.initialLayout)
8948 int splitterDistance;
8949 switch (this.WindowState)
8951 case FormWindowState.Normal:
8952 splitterDistance = this.SplitContainer3.SplitterDistance;
8954 case FormWindowState.Maximized:
8955 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8956 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8957 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8958 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8964 this.mySpDis3 = splitterDistance;
8965 this.MarkSettingLocalModified();
8968 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8970 if (this.statuses.RemovedTab.Count == 0)
8972 this.UndoRemoveTabMenuItem.Enabled = false;
8976 this.UndoRemoveTabMenuItem.Enabled = true;
8979 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8980 this.PublicSearchQueryMenuItem.Enabled = true;
8982 this.PublicSearchQueryMenuItem.Enabled = false;
8984 var post = this.CurrentPost;
8985 if (!this.ExistCurrentPost || post == null)
8987 this.CopySTOTMenuItem.Enabled = false;
8988 this.CopyURLMenuItem.Enabled = false;
8989 this.CopyUserIdStripMenuItem.Enabled = false;
8993 this.CopySTOTMenuItem.Enabled = true;
8994 this.CopyURLMenuItem.Enabled = true;
8995 this.CopyUserIdStripMenuItem.Enabled = true;
8997 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8998 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
9002 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
9003 => this.SetNotifyIconText();
9005 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
9006 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
9008 private async Task DoShowUserStatus(string id, bool showInputDialog)
9010 TwitterUser? user = null;
9012 if (showInputDialog)
9014 using var inputName = new InputTabName();
9015 inputName.FormTitle = "Show UserStatus";
9016 inputName.FormDescription = Properties.Resources.FRMessage1;
9017 inputName.TabName = id;
9019 if (inputName.ShowDialog(this) != DialogResult.OK)
9021 if (string.IsNullOrWhiteSpace(inputName.TabName))
9024 id = inputName.TabName.Trim();
9027 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9029 var cancellationToken = dialog.EnableCancellation();
9033 var task = this.tw.Api.UsersShow(id);
9034 user = await dialog.WaitForAsync(this, task);
9036 catch (WebApiException ex)
9038 if (!cancellationToken.IsCancellationRequested)
9039 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9043 if (cancellationToken.IsCancellationRequested)
9047 await this.DoShowUserStatus(user);
9050 private async Task DoShowUserStatus(TwitterUser user)
9052 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9053 var showUserTask = userDialog.ShowUserAsync(user);
9054 userDialog.ShowDialog(this);
9057 this.BringToFront();
9059 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9063 internal Task ShowUserStatus(string id, bool showInputDialog)
9064 => this.DoShowUserStatus(id, showInputDialog);
9066 internal Task ShowUserStatus(string id)
9067 => this.DoShowUserStatus(id, true);
9069 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9071 var post = this.CurrentPost;
9074 await this.ShowUserStatus(post.ScreenName, false);
9078 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9080 var retweetedBy = this.CurrentPost?.RetweetedBy;
9081 if (retweetedBy != null)
9083 await this.ShowUserStatus(retweetedBy, false);
9087 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9089 var post = this.CurrentPost;
9090 if (!this.ExistCurrentPost || post == null)
9093 var statusId = post.RetweetedId ?? post.StatusId;
9094 TwitterStatus status;
9096 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9098 var cancellationToken = dialog.EnableCancellation();
9102 var task = this.tw.Api.StatusesShow(statusId);
9103 status = await dialog.WaitForAsync(this, task);
9105 catch (WebApiException ex)
9107 if (!cancellationToken.IsCancellationRequested)
9108 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9112 if (cancellationToken.IsCancellationRequested)
9116 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9119 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9121 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9124 this.Visible = false;
9126 else if (Form.ActiveForm == null)
9128 this.Visible = true;
9129 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9131 this.BringToFront();
9132 this.StatusText.Focus();
9136 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9137 => this.MultiLinePullDownMenuItem.PerformClick();
9140 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9142 if (this.ImageSelector.Visible)
9143 this.ImageSelector.EndSelection();
9145 this.ImageSelector.BeginSelection();
9148 private void SelectMedia_DragEnter(DragEventArgs e)
9150 if (this.ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9152 e.Effect = DragDropEffects.Copy;
9155 e.Effect = DragDropEffects.None;
9158 private void SelectMedia_DragDrop(DragEventArgs e)
9161 this.BringToFront();
9162 this.ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
9163 this.StatusText.Focus();
9166 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9168 this.TimelinePanel.Visible = false;
9169 this.TimelinePanel.Enabled = false;
9172 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9174 this.TimelinePanel.Visible = true;
9175 this.TimelinePanel.Enabled = true;
9176 this.CurrentListView.Focus();
9179 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9180 => this.AllowDrop = false;
9182 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9183 => this.AllowDrop = true;
9185 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9187 if (this.ImageSelector.Visible)
9189 this.MarkSettingCommonModified();
9190 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9194 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9195 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9198 /// StatusTextでCtrl+Vが押下された時の処理
9200 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9204 if (Clipboard.ContainsText())
9206 // clipboardにテキストがある場合は貼り付け処理
9207 this.StatusText.Paste(Clipboard.GetText());
9209 else if (Clipboard.ContainsImage())
9212 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
9213 Properties.Resources.PostPictureWarn4,
9214 MessageBoxButtons.OKCancel,
9215 MessageBoxIcon.Question,
9216 MessageBoxDefaultButton.Button2)
9220 using var image = Clipboard.GetImage();
9221 this.ImageSelector.BeginSelection(image);
9224 else if (Clipboard.ContainsFileDropList())
9226 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9227 this.ImageSelector.BeginSelection(files);
9230 catch (ExternalException ex)
9232 MessageBox.Show(ex.Message);
9237 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9239 using var form = new ListManage(this.tw);
9240 form.ShowDialog(this);
9243 private bool ModifySettingCommon { get; set; }
9245 private bool ModifySettingLocal { get; set; }
9247 private bool ModifySettingAtId { get; set; }
9249 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9251 var post = this.CurrentPost;
9252 if (this.ExistCurrentPost && post != null && !post.IsDm)
9253 this.RtCountMenuItem.Enabled = true;
9255 this.RtCountMenuItem.Enabled = false;
9258 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9259 => this.CopyUserId();
9261 private void CopyUserId()
9263 var post = this.CurrentPost;
9264 if (post == null) return;
9265 var clstr = post.ScreenName;
9268 Clipboard.SetDataObject(clstr, false, 5, 100);
9270 catch (Exception ex)
9272 MessageBox.Show(ex.Message);
9276 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9278 var post = this.CurrentPost;
9279 if (this.ExistCurrentPost && post != null && !post.IsDm)
9283 await this.OpenRelatedTab(post);
9285 catch (TabException ex)
9287 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9293 /// 指定されたツイートに対する関連発言タブを開きます
9295 /// <param name="statusId">表示するツイートのID</param>
9296 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9297 public async Task OpenRelatedTab(long statusId)
9299 var post = this.statuses[statusId];
9304 post = await this.tw.GetStatusApi(false, statusId);
9306 catch (WebApiException ex)
9308 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9313 await this.OpenRelatedTab(post);
9317 /// 指定されたツイートに対する関連発言タブを開きます
9319 /// <param name="post">表示する対象となるツイート</param>
9320 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9321 private async Task OpenRelatedTab(PostClass post)
9323 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9324 if (tabRelated != null)
9326 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9329 var tabName = this.statuses.MakeTabName("Related Tweets");
9331 tabRelated = new RelatedPostsTabModel(tabName, post)
9333 UnreadManage = false,
9337 this.statuses.AddTab(tabRelated);
9338 this.AddNewTab(tabRelated, startup: false);
9340 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9342 await this.RefreshTabAsync(tabRelated);
9344 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9348 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9350 var tabPage = this.ListTab.TabPages[tabIndex];
9351 var listView = (DetailsListView)tabPage.Tag;
9352 var targetPost = tabRelated.TargetPost;
9353 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9355 if (index != -1 && index < listView.Items.Count)
9357 listView.SelectedIndices.Add(index);
9358 listView.Items[index].Focused = true;
9363 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9365 var buf = new StringBuilder();
9366 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9367 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9368 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9371 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9373 MyCommon.EndingFlag = true;
9377 Application.Restart();
9381 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9385 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9386 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9388 private bool ExistCurrentPost
9392 var post = this.CurrentPost;
9393 return post != null && !post.IsDeleted;
9397 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9398 => await this.ShowUserTimeline();
9400 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9401 => await this.ShowRetweeterTimeline();
9403 private string GetUserIdFromCurPostOrInput(string caption)
9405 var id = this.CurrentPost?.ScreenName ?? "";
9407 using var inputName = new InputTabName();
9408 inputName.FormTitle = caption;
9409 inputName.FormDescription = Properties.Resources.FRMessage1;
9410 inputName.TabName = id;
9412 if (inputName.ShowDialog() == DialogResult.OK &&
9413 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9415 id = inputName.TabName.Trim();
9424 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9426 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9427 if (!MyCommon.IsNullOrEmpty(id))
9429 await this.AddNewTabForUserTimeline(id);
9433 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9435 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9436 this.timelineScheduler.SystemResumed();
9439 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9441 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9443 TimeZoneInfo.ClearCachedData();
9445 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9447 if (curTimeOffset != prevTimeOffset)
9450 this.listCache?.PurgeCache();
9451 this.CurrentListView.Refresh();
9453 this.DispSelectedPost(forceupdate: true);
9456 this.timelineScheduler.Reset();
9459 private void TimelineRefreshEnableChange(bool isEnable)
9461 this.timelineScheduler.Enabled = isEnable;
9464 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9465 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9467 private async Task OpenUserAppointUrl()
9469 if (this.settings.Common.UserAppointUrl != null)
9471 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9473 var post = this.CurrentPost;
9476 var xUrl = this.settings.Common.UserAppointUrl;
9477 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9479 var statusId = post.RetweetedId ?? post.StatusId;
9480 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
9482 await MyCommon.OpenInBrowserAsync(this, xUrl);
9487 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9492 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9493 => await this.OpenUserAppointUrl();
9495 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9497 if (Form.ActiveForm == null)
9499 await this.InvokeAsync(() =>
9501 this.Visible = true;
9502 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9504 this.BringToFront();
9505 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9507 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
9511 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
9517 private void ReplaceAppName()
9519 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9520 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9523 private void TweetThumbnail_ThumbnailLoading(object sender, EventArgs e)
9524 => this.SplitContainer3.Panel2Collapsed = false;
9526 private async void TweetThumbnail_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
9527 => await this.OpenThumbnailPicture(e.Thumbnail);
9529 private async void TweetThumbnail_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
9530 => await MyCommon.OpenInBrowserAsync(this, e.ImageUrl);
9532 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
9534 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
9536 await MyCommon.OpenInBrowserAsync(this, url);
9539 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9540 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9542 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9544 if (e.KeyCode == Keys.Space)
9546 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9548 e.SuppressKeyPress = true;
9552 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9554 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9555 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9556 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9557 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9558 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9560 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9563 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9564 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9566 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9567 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9569 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9570 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9572 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9573 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9575 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9576 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9578 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9580 if (this.settings.Common.IconSize == iconSize) return;
9582 var oldIconCol = this.Use2ColumnsMode;
9584 this.settings.Common.IconSize = iconSize;
9585 this.ApplyListViewIconSize(iconSize);
9587 if (this.Use2ColumnsMode != oldIconCol)
9589 foreach (TabPage tp in this.ListTab.TabPages)
9591 this.ResetColumns((DetailsListView)tp.Tag);
9595 this.CurrentListView.Refresh();
9596 this.MarkSettingCommonModified();
9599 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9601 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9602 if (this.settings.Common.SortOrderLock == state) return;
9604 this.settings.Common.SortOrderLock = state;
9605 this.MarkSettingCommonModified();
9608 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9610 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9612 this.StatusLabelUrl.Text = e.StatusText;
9616 this.SetStatusLabelUrl();