1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
40 using System.Globalization;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.TwitterV2;
56 using OpenTween.Connection;
57 using OpenTween.MediaUploadServices;
58 using OpenTween.Models;
59 using OpenTween.OpenTweenCustomControl;
60 using OpenTween.Setting;
61 using OpenTween.Thumbnail;
65 public partial class TweenMain : OTBaseForm
69 /// <summary>画面サイズ</summary>
72 /// <summary>画面位置</summary>
75 /// <summary>区切り位置</summary>
78 /// <summary>発言欄区切り位置</summary>
81 /// <summary>プレビュー区切り位置</summary>
85 private bool initial; // true:起動時処理中
86 private bool initialLayout = true;
87 private bool ignoreConfigSave; // true:起動時処理中
89 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
92 private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
93 private Point tabMouseDownPoint;
95 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
96 private string? rclickTabName;
98 private readonly object syncObject = new(); // ロック用
100 private const string DetailHtmlFormatHead =
101 """<head><meta http-equiv="X-UA-Compatible" content="IE=8">"""
102 + """<style type="text/css"><!-- """
103 + "body, p, pre {margin: 0;} "
104 + """body {font-family: "%FONT_FAMILY%", "Segoe UI Emoji", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} """
105 + "pre {font-family: inherit;} "
106 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
107 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
108 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
109 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
110 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
114 private const string DetailHtmlFormatTemplateMono =
115 $"<html>{DetailHtmlFormatHead}<body><pre>%CONTENT_HTML%</pre></body></html>";
117 private const string DetailHtmlFormatTemplateNormal =
118 $"<html>{DetailHtmlFormatHead}<body><p>%CONTENT_HTML%</p></body></html>";
120 private string detailHtmlFormatPreparedTemplate = null!;
122 private bool myStatusError = false;
123 private bool myStatusOnline = false;
124 private bool soundfileListup = false;
125 private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
128 private readonly SettingManager settings;
131 private readonly Twitter tw;
134 private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
138 /// <summary>検索画面インスタンス</summary>
139 internal SearchWordDialog SearchDialog = new();
141 private readonly OpenURL urlDialog = new();
143 /// <summary>@id補助</summary>
144 public AtIdSupplement AtIdSupl = null!;
146 /// <summary>Hashtag補助</summary>
147 public AtIdSupplement HashSupl = null!;
149 public HashtagManage HashMgr = null!;
152 private ThemeManager themeManager;
154 /// <summary>アイコン画像リスト</summary>
155 private readonly ImageCache iconCache;
157 private readonly IconAssetsManager iconAssets;
159 private readonly ThumbnailGenerator thumbGenerator;
161 /// <summary>発言履歴</summary>
162 private readonly List<StatusTextHistory> history = new();
164 /// <summary>発言履歴カレントインデックス</summary>
167 // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169 /// <summary>リプライ先のステータスID・スクリーン名</summary>
170 private (PostId StatusId, string ScreenName)? inReplyTo = null;
173 private readonly List<DateTimeUtc> postTimestamps = new();
174 private readonly List<DateTimeUtc> favTimestamps = new();
177 private readonly StringFormat sfTab = new();
179 //////////////////////////////////////////////////////////////////////////////////////////////////////////
181 /// <summary>発言保持クラス</summary>
182 private readonly TabInformations statuses;
184 private TimelineListViewCache? listCache;
185 private TimelineListViewDrawer? listDrawer;
186 private readonly Dictionary<string, TimelineListViewState> listViewState = new();
188 private bool isColumnChanged = false;
190 private const int MaxWorderThreads = 20;
191 private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
192 private readonly CancellationTokenSource workerCts = new();
193 private readonly IProgress<string> workerProgress = null!;
195 private int unreadCounter = -1;
196 private int unreadAtCounter = -1;
198 private readonly string[] columnOrgText = new string[9];
199 private readonly string[] columnText = new string[9];
201 private bool doFavRetweetFlags = false;
203 //////////////////////////////////////////////////////////////////////////////////////////////////////////
205 private readonly TimelineScheduler timelineScheduler = new();
206 private readonly DebounceTimer selectionDebouncer;
207 private readonly DebounceTimer saveConfigDebouncer;
209 private readonly string recommendedStatusFooter;
210 private bool urlMultibyteSplit = false;
211 private bool preventSmsCommand = true;
214 private readonly record struct UrlUndo(
219 private List<UrlUndo>? urlUndoBuffer = null;
221 private readonly record struct ReplyChain(
227 /// <summary>[, ]でのリプライ移動の履歴</summary>
228 private Stack<ReplyChain>? replyChains;
230 /// <summary>ポスト選択履歴</summary>
231 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
233 public TabModel CurrentTab
234 => this.statuses.SelectedTab;
236 public string CurrentTabName
237 => this.statuses.SelectedTabName;
239 public TabPage CurrentTabPage
240 => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
242 public DetailsListView CurrentListView
243 => (DetailsListView)this.CurrentTabPage.Tag;
245 public PostClass? CurrentPost
246 => this.CurrentTab.SelectedPost;
248 public bool Use2ColumnsMode
249 => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
251 /// <summary>検索処理タイプ</summary>
252 internal enum SEARCHTYPE
259 private readonly record struct StatusTextHistory(
261 (PostId StatusId, string ScreenName)? InReplyTo = null
264 private readonly HookGlobalHotkey hookGlobalHotkey;
266 private void TweenMain_Activated(object sender, EventArgs e)
268 // 画面がアクティブになったら、発言欄の背景色戻す
269 if (this.StatusText.Focused)
271 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
275 private bool disposed = false;
278 /// 使用中のリソースをすべてクリーンアップします。
280 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
281 protected override void Dispose(bool disposing)
283 base.Dispose(disposing);
290 this.components?.Dispose();
293 this.SearchDialog.Dispose();
294 this.urlDialog.Dispose();
295 this.themeManager.Dispose();
296 this.sfTab.Dispose();
298 this.timelineScheduler.Dispose();
299 this.workerCts.Cancel();
300 this.thumbnailTokenSource?.Dispose();
302 this.hookGlobalHotkey.Dispose();
305 // 終了時にRemoveHandlerしておかないとメモリリークする
306 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
307 Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
308 Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
310 this.disposed = true;
313 private void InitColumns(ListView list, bool startup)
315 this.InitColumnText();
317 ColumnHeader[]? columns = null;
320 if (this.Use2ColumnsMode)
324 new ColumnHeader(), // アイコン
325 new ColumnHeader(), // 本文
328 columns[0].Text = this.columnText[0];
329 columns[1].Text = this.columnText[2];
333 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
335 columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
336 columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
337 columns[0].DisplayIndex = 0;
338 columns[1].DisplayIndex = 1;
343 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
345 columns[idx].Width = curListColumn.Width;
346 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
355 new ColumnHeader(), // アイコン
356 new ColumnHeader(), // ニックネーム
357 new ColumnHeader(), // 本文
358 new ColumnHeader(), // 日付
359 new ColumnHeader(), // ユーザID
360 new ColumnHeader(), // 未読
361 new ColumnHeader(), // マーク&プロテクト
362 new ColumnHeader(), // ソース
365 foreach (var i in Enumerable.Range(0, columns.Length))
366 columns[i].Text = this.columnText[i];
370 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
372 foreach (var (column, index) in columns.WithIndex())
374 column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
375 column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
381 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
383 columns[idx].Width = curListColumn.Width;
384 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
390 list.Columns.AddRange(columns);
398 foreach (var column in columns)
404 private void InitColumnText()
406 this.columnText[0] = "";
407 this.columnText[1] = Properties.Resources.AddNewTabText2;
408 this.columnText[2] = Properties.Resources.AddNewTabText3;
409 this.columnText[3] = Properties.Resources.AddNewTabText4_2;
410 this.columnText[4] = Properties.Resources.AddNewTabText5;
411 this.columnText[5] = "";
412 this.columnText[6] = "";
413 this.columnText[7] = "Source";
415 this.columnOrgText[0] = "";
416 this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
417 this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
418 this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
419 this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
420 this.columnOrgText[5] = "";
421 this.columnOrgText[6] = "";
422 this.columnOrgText[7] = "Source";
424 var c = this.statuses.SortMode switch
426 ComparerMode.Nickname => 1, // ニックネーム
427 ComparerMode.Data => 2, // 本文
428 ComparerMode.Id => 3, // 時刻=発言Id
429 ComparerMode.Name => 4, // 名前
430 ComparerMode.Source => 7, // Source
434 if (this.Use2ColumnsMode)
436 if (this.statuses.SortOrder == SortOrder.Descending)
438 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
439 this.columnText[2] = this.columnOrgText[2] + "▾";
443 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
444 this.columnText[2] = this.columnOrgText[2] + "▴";
449 if (this.statuses.SortOrder == SortOrder.Descending)
451 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
452 this.columnText[c] = this.columnOrgText[c] + "▾";
456 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
457 this.columnText[c] = this.columnOrgText[c] + "▴";
463 SettingManager settingManager,
464 TabInformations tabInfo,
466 ImageCache imageCache,
467 IconAssetsManager iconAssets,
468 ThumbnailGenerator thumbGenerator
471 this.settings = settingManager;
472 this.statuses = tabInfo;
474 this.iconCache = imageCache;
475 this.iconAssets = iconAssets;
476 this.thumbGenerator = thumbGenerator;
478 this.InitializeComponent();
480 if (!this.DesignMode)
482 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
483 this.StatusText.Dock = DockStyle.Fill;
486 this.hookGlobalHotkey = new HookGlobalHotkey(this);
488 this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
489 this.gh.NotifyClicked += this.GrowlHelper_Callback;
491 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
492 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
494 this.ImageSelector.Visible = false;
495 this.ImageSelector.Enabled = false;
496 this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
498 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
500 this.ReplaceAppName();
501 this.InitializeShortcuts();
503 this.ignoreConfigSave = true;
504 this.Visible = false;
506 this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
508 Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
510 Regex.CacheSize = 100;
513 this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
514 this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
515 this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
517 // <<<<<<<<<設定関連>>>>>>>>>
521 // 現在の DPI と設定保存時の DPI との比を取得する
522 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
525 var account = this.settings.Common.SelectedAccount;
527 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
529 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
533 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
534 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
536 // アクセストークンが有効であるか確認する
537 // ここが Twitter API への最初のアクセスになるようにすること
540 this.tw.VerifyCredentials();
542 catch (WebApiException ex)
546 string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
547 ApplicationSettings.ApplicationName,
548 MessageBoxButtons.OK,
549 MessageBoxIcon.Warning);
553 // プロキシ設定等の通信まわりの初期化が済んでから処理する
554 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
555 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
556 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
557 imgazyobizinet.AutoUpdate = true;
559 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
562 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
563 this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
565 this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
568 this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
569 this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
570 this.HashMgr = new HashtagManage(this.HashSupl,
571 this.settings.Common.HashTags.ToArray(),
572 this.settings.Common.HashSelected,
573 this.settings.Common.HashIsPermanent,
574 this.settings.Common.HashIsHead,
575 this.settings.Common.HashIsNotAddToAtReply);
576 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
579 this.themeManager = new(this.settings.Local);
580 this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
582 // StringFormatオブジェクトへの事前設定
583 this.sfTab.Alignment = StringAlignment.Center;
584 this.sfTab.LineAlignment = StringAlignment.Center;
586 this.InitDetailHtmlFormat();
587 this.tweetDetailsView.ClearPostBrowser();
589 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
591 this.history.Add(new StatusTextHistory(""));
593 this.inReplyTo = null;
596 this.SearchDialog.Owner = this;
597 this.urlDialog.Owner = this;
600 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
601 this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
603 // 新着取得時のリストスクロールをするか。trueならスクロールしない
604 this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
605 this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
607 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
608 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
611 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
612 this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
613 this.myLoc = this.settings.Local.FormLocation;
615 if (this.WindowState != FormWindowState.Minimized)
617 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
618 var outOfScreen = true;
619 if (Screen.AllScreens.Length == 1) // ハングするとの報告
621 foreach (var scr in Screen.AllScreens)
623 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
631 this.myLoc = new Point(0, 0);
633 this.DesktopLocation = this.myLoc;
635 this.TopMost = this.settings.Common.AlwaysTop;
636 this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
637 this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
638 this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
640 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
641 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
643 this.StatusText.Font = this.themeManager.FontInputFont;
644 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
646 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
647 this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
648 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
650 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
651 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
653 // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
654 if (this.settings.Common.UnreadManage == false)
656 this.ReadedStripMenuItem.Enabled = false;
657 this.UnreadStripMenuItem.Enabled = false;
660 // リンク先URL表示部の初期化(画面左下)
661 this.StatusLabelUrl.Text = "";
663 this.StatusLabel.Text = "";
664 this.StatusLabel.AutoToolTip = false;
665 this.StatusLabel.ToolTipText = "";
667 this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
669 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
670 this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
671 this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
672 this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
674 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
675 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
676 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
677 this.SplitContainer2.Panel2.AccessibleName = "";
679 ////////////////////////////////////////////////////////////////////////////////
680 var sortOrder = (SortOrder)this.settings.Common.SortOrder;
681 var mode = this.settings.Common.SortColumn switch
683 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
684 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
685 1 => ComparerMode.Nickname, // ニックネーム
686 2 => ComparerMode.Data, // 本文
687 3 => ComparerMode.Id, // 時刻=発言Id
688 4 => ComparerMode.Name, // 名前
689 7 => ComparerMode.Source, // Source
690 _ => ComparerMode.Id,
692 this.statuses.SetSortMode(mode, sortOrder);
693 ////////////////////////////////////////////////////////////////////////////////
695 this.ApplyListViewIconSize(this.settings.Common.IconSize);
697 // <<<<<<<<タブ関連>>>>>>>
698 foreach (var tab in this.statuses.Tabs)
700 if (!this.AddNewTab(tab, startup: true))
701 throw new TabException(Properties.Resources.TweenMain_LoadText1);
704 this.ListTabSelect(this.ListTab.SelectedTab);
707 this.SetTabAlignment();
709 MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
710 Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
712 if (this.settings.Common.TabIconDisp)
714 this.ListTab.DrawMode = TabDrawMode.Normal;
718 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
719 this.ListTab.DrawItem += this.ListTab_DrawItem;
720 this.ListTab.ImageList = null;
723 if (this.settings.Common.HotkeyEnabled)
726 var modKey = HookGlobalHotkey.ModKeys.None;
727 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
728 modKey |= HookGlobalHotkey.ModKeys.Alt;
729 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
730 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
731 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
732 modKey |= HookGlobalHotkey.ModKeys.Shift;
733 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
734 modKey |= HookGlobalHotkey.ModKeys.Win;
736 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
739 if (this.settings.Common.IsUseNotifyGrowl)
740 this.gh.RegisterGrowl();
742 this.StatusLabel.Text = Properties.Resources.Form1_LoadText1; // 画面右下の状態表示を変更
744 this.SetMainWindowTitle();
745 this.SetNotifyIconText();
747 if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
754 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
755 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
756 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
757 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
758 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
759 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
760 this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
762 this.DoGetFollowersMenu(),
763 this.RefreshBlockIdsAsync(),
764 this.RefreshMuteUserIdsAsync(),
765 this.RefreshNoRetweetIdsAsync(),
766 this.RefreshTwitterConfigurationAsync(),
768 this.RefreshTimelineScheduler();
770 this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
771 this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
774 this.TimerRefreshIcon.Interval = 200;
775 this.TimerRefreshIcon.Enabled = false;
777 this.ignoreConfigSave = false;
778 this.TweenMain_Resize(this, EventArgs.Empty);
780 if (this.settings.IsFirstRun)
782 // 初回起動時だけ右下のメニューを目立たせる
783 this.HashStripSplitButton.ShowDropDown();
787 private void InitDetailHtmlFormat()
789 var htmlTemplate = this.settings.Common.IsMonospace ? DetailHtmlFormatTemplateMono : DetailHtmlFormatTemplateNormal;
791 static string ColorToRGBString(Color color)
792 => $"{color.R},{color.G},{color.B}";
794 this.detailHtmlFormatPreparedTemplate = htmlTemplate
795 .Replace("%FONT_FAMILY%", this.themeManager.FontDetail.Name)
796 .Replace("%FONT_SIZE%", this.themeManager.FontDetail.Size.ToString())
797 .Replace("%FONT_COLOR%", ColorToRGBString(this.themeManager.ColorDetail))
798 .Replace("%LINK_COLOR%", ColorToRGBString(this.themeManager.ColorDetailLink))
799 .Replace("%BG_COLOR%", ColorToRGBString(this.themeManager.ColorDetailBackcolor))
800 .Replace("%BG_REPLY_COLOR%", ColorToRGBString(this.themeManager.ColorAtTo));
803 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
808 txt = this.statuses.Tabs[e.Index].TabName;
815 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
816 if (e.State == DrawItemState.Selected)
818 e.DrawFocusRectangle();
823 if (this.statuses.Tabs[txt].UnreadCount > 0)
826 fore = System.Drawing.SystemBrushes.ControlText;
830 fore = System.Drawing.SystemBrushes.ControlText;
832 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
835 private void LoadConfig()
837 this.statuses.LoadTabsFromSettings(this.settings.Tabs);
838 this.statuses.AddDefaultTabs();
841 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
843 this.RefreshTimelineScheduler();
846 private void RefreshTimelineScheduler()
848 static TimeSpan IntervalSecondsOrDisabled(int seconds)
849 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
851 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
852 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
853 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
854 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
855 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
856 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
857 this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
858 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
860 this.timelineScheduler.RefreshSchedule();
863 private void MarkSettingCommonModified()
865 if (this.saveConfigDebouncer == null)
868 this.ModifySettingCommon = true;
869 _ = this.saveConfigDebouncer.Call();
872 private void MarkSettingLocalModified()
874 if (this.saveConfigDebouncer == null)
877 this.ModifySettingLocal = true;
878 _ = this.saveConfigDebouncer.Call();
881 internal void MarkSettingAtIdModified()
883 if (this.saveConfigDebouncer == null)
886 this.ModifySettingAtId = true;
887 _ = this.saveConfigDebouncer.Call();
890 private void RefreshTimeline()
892 var curListView = this.CurrentListView;
894 // 現在表示中のタブのスクロール位置を退避
895 var currentListViewState = this.listViewState[this.CurrentTabName];
896 currentListViewState.Save(this.ListLockMenuItem.Checked);
900 addCount = this.statuses.SubmitUpdate(
903 out var newMentionOrDm,
906 if (MyCommon.EndingFlag) return;
909 if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
911 using (ControlTransaction.Update(curListView))
913 this.listCache.PurgeCache();
914 this.listCache.UpdateListSize();
917 currentListViewState.RestoreSelection();
923 if (this.settings.Common.TabIconDisp)
925 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
927 var tabPage = this.ListTab.TabPages[index];
928 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
929 tabPage.ImageIndex = 0; // 未読アイコン
934 this.ListTab.Refresh();
939 currentListViewState.RestoreScroll();
942 this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
944 this.SetMainWindowTitle();
945 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
947 this.HashSupl.AddRangeItem(this.tw.GetHashList());
950 private bool BalloonRequired()
955 if (NativeMethods.IsScreenSaverRunning())
959 if (!this.NewPostPopMenuItem.Checked)
962 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
963 if (this.settings.Common.LimitBalloon)
965 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
972 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
974 if (this.settings.Common.ReadOwnPost)
976 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
981 if (this.BalloonRequired())
983 if (notifyPosts != null && notifyPosts.Length > 0)
985 // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
986 if (this.settings.Common.IsUseNotifyGrowl)
988 var sb = new StringBuilder();
992 foreach (var post in notifyPosts)
994 if (!(notifyPosts.Length > 3))
1000 if (post.IsReply && !post.IsExcludeReply) reply = true;
1001 if (post.IsDm) dm = true;
1002 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1003 switch (this.settings.Common.NameBalloon)
1005 case MyCommon.NameBalloonEnum.UserID:
1006 sb.Append(post.ScreenName).Append(" : ");
1008 case MyCommon.NameBalloonEnum.NickName:
1009 sb.Append(post.Nickname).Append(" : ");
1012 sb.Append(post.TextFromApi);
1013 if (notifyPosts.Length > 3)
1015 if (notifyPosts.Last() != post) continue;
1018 var title = new StringBuilder();
1019 GrowlHelper.NotifyType nt;
1020 if (this.settings.Common.DispUsername)
1022 title.Append(this.tw.Username);
1023 title.Append(" - ");
1028 title.Append(ApplicationSettings.ApplicationName);
1029 title.Append(" [DM] ");
1030 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1031 nt = GrowlHelper.NotifyType.DirectMessage;
1035 title.Append(ApplicationSettings.ApplicationName);
1036 title.Append(" [Reply!] ");
1037 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1038 nt = GrowlHelper.NotifyType.Reply;
1042 title.Append(ApplicationSettings.ApplicationName);
1044 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1045 nt = GrowlHelper.NotifyType.Notify;
1047 var bText = sb.ToString();
1048 if (MyCommon.IsNullOrEmpty(bText)) return;
1050 var image = this.iconCache.TryGetFromCache(post.ImageUrl);
1051 this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
1056 var sb = new StringBuilder();
1059 foreach (var post in notifyPosts)
1061 if (post.IsReply && !post.IsExcludeReply) reply = true;
1062 if (post.IsDm) dm = true;
1063 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1064 switch (this.settings.Common.NameBalloon)
1066 case MyCommon.NameBalloonEnum.UserID:
1067 sb.Append(post.ScreenName).Append(" : ");
1069 case MyCommon.NameBalloonEnum.NickName:
1070 sb.Append(post.Nickname).Append(" : ");
1073 sb.Append(post.TextFromApi);
1076 var title = new StringBuilder();
1078 if (this.settings.Common.DispUsername)
1080 title.Append(this.tw.Username);
1081 title.Append(" - ");
1086 ntIcon = ToolTipIcon.Warning;
1087 title.Append(ApplicationSettings.ApplicationName);
1088 title.Append(" [DM] ");
1089 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1093 ntIcon = ToolTipIcon.Warning;
1094 title.Append(ApplicationSettings.ApplicationName);
1095 title.Append(" [Reply!] ");
1096 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1100 ntIcon = ToolTipIcon.Info;
1101 title.Append(ApplicationSettings.ApplicationName);
1103 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1105 var bText = sb.ToString();
1106 if (MyCommon.IsNullOrEmpty(bText)) return;
1108 this.NotifyIcon1.BalloonTipTitle = title.ToString();
1109 this.NotifyIcon1.BalloonTipText = bText;
1110 this.NotifyIcon1.BalloonTipIcon = ntIcon;
1111 this.NotifyIcon1.ShowBalloonTip(500);
1117 if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1121 var dir = Application.StartupPath;
1122 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1124 dir = Path.Combine(dir, "Sounds");
1126 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1134 // mentions新着時に画面ブリンク
1135 if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1137 NativeMethods.FlashMyWindow(this.Handle, 3);
1141 private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1143 var listView = this.CurrentListView;
1144 if (listView != sender)
1147 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1148 this.CurrentTab.SelectPosts(indices);
1150 if (indices.Length != 1)
1153 var index = indices[0];
1154 if (index > listView.VirtualListSize - 1) return;
1156 this.PushSelectPostChain();
1158 var post = this.CurrentPost!;
1159 this.statuses.SetReadAllTab(post.StatusId, read: true);
1161 this.listCache?.RefreshStyle();
1162 await this.selectionDebouncer.Call();
1165 private void StatusTextHistoryBack()
1167 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1168 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1171 if (this.hisIdx < 0)
1174 var historyItem = this.history[this.hisIdx];
1175 this.inReplyTo = historyItem.InReplyTo;
1176 this.StatusText.Text = historyItem.Status;
1177 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1180 private void StatusTextHistoryForward()
1182 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
1183 this.history[this.hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1186 if (this.hisIdx > this.history.Count - 1)
1187 this.hisIdx = this.history.Count - 1;
1189 var historyItem = this.history[this.hisIdx];
1190 this.inReplyTo = historyItem.InReplyTo;
1191 this.StatusText.Text = historyItem.Status;
1192 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1195 private async void PostButton_Click(object sender, EventArgs e)
1197 if (this.StatusText.Text.Trim().Length == 0)
1199 if (!this.ImageSelector.Enabled)
1201 await this.DoRefresh();
1206 var currentPost = this.CurrentPost;
1207 if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1209 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1211 MessageBoxButtons.YesNoCancel,
1212 MessageBoxIcon.Question);
1215 case DialogResult.Yes:
1216 this.StatusText.Text = "";
1217 await this.DoReTweetOfficial(false);
1219 case DialogResult.Cancel:
1224 if (TextContainsOnlyMentions(this.StatusText.Text))
1226 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1227 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1229 if (ret != DialogResult.OK)
1233 this.history[this.history.Count - 1] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
1235 if (this.settings.Common.Nicoms)
1237 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1238 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1241 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1242 this.CheckReplyTo(this.StatusText.Text);
1244 var status = new PostStatusParams();
1246 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1247 if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AppToken.AuthType == APIAuthType.OAuth1)
1249 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1250 // 収まる場合はこれらのオプションを使用せずに投稿する
1251 status.Text = statusTextCompat;
1252 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1256 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1257 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1259 status.AttachmentUrl = attachmentUrl;
1261 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1263 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1264 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1266 status.AutoPopulateReplyMetadata = true;
1268 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1269 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1274 if (this.GetRestStatusCount(status.Text) < 0)
1276 // 文字数制限を超えているが強制的に投稿するか
1277 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1278 if (ret != DialogResult.OK)
1282 IMediaUploadService? uploadService = null;
1283 IMediaItem[]? uploadItems = null;
1284 if (this.ImageSelector.Visible)
1287 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1290 this.ImageSelector.EndSelection();
1291 uploadService = this.ImageSelector.Model.GetService(serviceName);
1294 this.inReplyTo = null;
1295 this.StatusText.Text = "";
1296 this.history.Add(new StatusTextHistory(""));
1297 this.hisIdx = this.history.Count - 1;
1298 if (!this.settings.Common.FocusLockToStatusText)
1299 this.CurrentListView.Focus();
1300 this.urlUndoBuffer = null;
1301 this.UrlUndoToolStripMenuItem.Enabled = false; // Undoをできないように設定
1304 if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1306 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1307 await MyCommon.OpenInBrowserAsync(this, tmp);
1310 await this.PostMessageAsync(status, uploadService, uploadItems);
1313 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1315 MyCommon.EndingFlag = true;
1319 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1321 if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1323 // _endingFlag=false:フォームの×ボタン
1325 this.Visible = false;
1329 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1330 this.ignoreConfigSave = true;
1331 MyCommon.EndingFlag = true;
1332 this.timelineScheduler.Enabled = false;
1333 this.TimerRefreshIcon.Enabled = false;
1337 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1339 this.Visible = true;
1340 if (this.WindowState == FormWindowState.Minimized)
1342 this.WindowState = FormWindowState.Normal;
1345 this.BringToFront();
1348 private static int errorCount = 0;
1350 private static bool CheckAccountValid()
1352 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1358 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1367 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1368 private Task RefreshTabAsync<T>()
1370 => this.RefreshTabAsync<T>(backward: false);
1372 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1373 private Task RefreshTabAsync<T>(bool backward)
1377 from tab in this.statuses.GetTabsByType<T>()
1378 select this.RefreshTabAsync(tab, backward);
1380 return Task.WhenAll(loadTasks);
1383 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1384 private Task RefreshTabAsync(TabModel tab)
1385 => this.RefreshTabAsync(tab, backward: false);
1387 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1388 private async Task RefreshTabAsync(TabModel tab, bool backward)
1390 await this.workerSemaphore.WaitAsync();
1394 this.RefreshTasktrayIcon();
1395 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1397 catch (WebApiException ex)
1399 this.myStatusError = true;
1400 var tabType = tab switch
1402 HomeTabModel => "GetTimeline",
1403 MentionsTabModel => "GetTimeline",
1404 DirectMessagesTabModel => "GetDirectMessage",
1405 FavoritesTabModel => "GetFavorites",
1406 PublicSearchTabModel => "GetSearch",
1407 UserTimelineTabModel => "GetUserTimeline",
1408 ListTimelineTabModel => "GetListStatus",
1409 RelatedPostsTabModel => "GetRelatedTweets",
1410 _ => tab.GetType().Name.Replace("Model", ""),
1412 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1416 this.RefreshTimeline();
1417 this.workerSemaphore.Release();
1421 private async Task FavAddAsync(PostId statusId, TabModel tab)
1423 await this.workerSemaphore.WaitAsync();
1427 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1429 this.RefreshTasktrayIcon();
1430 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1432 catch (WebApiException ex)
1434 this.myStatusError = true;
1435 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1439 this.workerSemaphore.Release();
1443 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1445 if (ct.IsCancellationRequested)
1448 if (!CheckAccountValid())
1449 throw new WebApiException("Auth error. Check your account");
1451 if (!tab.Posts.TryGetValue(statusId, out var post))
1457 await Task.Run(async () =>
1459 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1463 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1466 await this.tw.Api.FavoritesCreate(twitterStatusId)
1468 .ConfigureAwait(false);
1470 catch (TwitterApiException ex)
1471 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1473 // エラーコード 139 のみの場合は成功と見なす
1476 if (this.settings.Common.RestrictFavCheck)
1478 var status = await this.tw.Api.StatusesShow(twitterStatusId)
1479 .ConfigureAwait(false);
1481 if (status.Favorited != true)
1482 throw new WebApiException("NG(Restricted?)");
1485 this.favTimestamps.Add(DateTimeUtc.Now);
1488 if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1490 postTl.IsFav = true;
1492 var favTab = this.statuses.FavoriteTab;
1493 favTab.AddPostQueue(postTl);
1496 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1497 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1499 if (tb.Contains(statusId))
1500 tb.Posts[statusId].IsFav = true;
1503 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1505 catch (WebApiException)
1507 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1512 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1513 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1515 if (this.favTimestamps[i] < oneHour)
1516 this.favTimestamps.RemoveAt(i);
1519 this.statuses.DistributePosts();
1522 if (ct.IsCancellationRequested)
1525 this.RefreshTimeline();
1527 if (this.CurrentTabName == tab.TabName)
1529 using (ControlTransaction.Update(this.CurrentListView))
1531 var idx = tab.IndexOf(statusId);
1533 this.listCache?.RefreshStyle(idx);
1536 var currentPost = this.CurrentPost;
1537 if (currentPost != null && statusId == currentPost.StatusId)
1538 this.DispSelectedPost(true); // 選択アイテム再表示
1542 private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1544 await this.workerSemaphore.WaitAsync();
1548 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1550 this.RefreshTasktrayIcon();
1551 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1553 catch (WebApiException ex)
1555 this.myStatusError = true;
1556 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1560 this.workerSemaphore.Release();
1564 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1566 if (ct.IsCancellationRequested)
1569 if (!CheckAccountValid())
1570 throw new WebApiException("Auth error. Check your account");
1572 var successIds = new List<PostId>();
1574 await Task.Run(async () =>
1578 var failedCount = 0;
1579 foreach (var statusId in statusIds)
1583 var post = tab.Posts[statusId];
1585 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1590 var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1594 await this.tw.Api.FavoritesDestroy(twitterStatusId)
1596 .ConfigureAwait(false);
1598 catch (WebApiException)
1604 successIds.Add(statusId);
1605 post.IsFav = false; // リスト再描画必要
1607 if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1608 tabinfoPost.IsFav = false;
1610 // 検索,リスト,UserTimeline,Relatedの各タブに反映
1611 foreach (var tb in this.statuses.GetTabsInnerStorageType())
1613 if (tb.Contains(statusId))
1614 tb.Posts[statusId].IsFav = false;
1619 if (ct.IsCancellationRequested)
1622 var favTab = this.statuses.FavoriteTab;
1623 foreach (var statusId in successIds)
1625 // ツイートが削除された訳ではないので IsDeleted はセットしない
1626 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1629 this.RefreshTimeline();
1631 if (this.CurrentTabName == tab.TabName)
1633 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1639 using (ControlTransaction.Update(this.CurrentListView))
1641 foreach (var statusId in successIds)
1643 var idx = tab.IndexOf(statusId);
1645 this.listCache?.RefreshStyle(idx);
1649 var currentPost = this.CurrentPost;
1650 if (currentPost != null && successIds.Contains(currentPost.StatusId))
1651 this.DispSelectedPost(true); // 選択アイテム再表示
1656 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1658 await this.workerSemaphore.WaitAsync();
1662 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1664 this.RefreshTasktrayIcon();
1665 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1667 catch (WebApiException ex)
1669 this.myStatusError = true;
1670 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1674 this.workerSemaphore.Release();
1678 private async Task PostMessageAsyncInternal(
1679 IProgress<string> p,
1680 CancellationToken ct,
1681 PostStatusParams postParams,
1682 IMediaUploadService? uploadService,
1683 IMediaItem[]? uploadItems)
1685 if (ct.IsCancellationRequested)
1688 if (!CheckAccountValid())
1689 throw new WebApiException("Auth error. Check your account");
1691 p.Report("Posting...");
1693 PostClass? post = null;
1698 await Task.Run(async () =>
1700 var postParamsWithMedia = postParams;
1702 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1704 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1705 .ConfigureAwait(false);
1708 post = await this.tw.PostStatus(postParamsWithMedia)
1709 .ConfigureAwait(false);
1712 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1714 catch (WebApiException ex)
1716 // 処理は中断せずエラーの表示のみ行う
1717 errMsg = $"Err:{ex.Message}(PostMessage)";
1719 this.myStatusError = true;
1721 catch (UnauthorizedAccessException ex)
1723 // アップロード対象のファイルが開けなかった場合など
1724 errMsg = $"Err:{ex.Message}(PostMessage)";
1726 this.myStatusError = true;
1730 // 使い終わった MediaItem は破棄する
1731 if (uploadItems != null)
1733 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1735 disposableItem.Dispose();
1740 if (ct.IsCancellationRequested)
1743 if (!MyCommon.IsNullOrEmpty(errMsg) &&
1744 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1745 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1747 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1749 var ret = MessageBox.Show(
1751 "Failed to update status",
1752 MessageBoxButtons.RetryCancel,
1753 MessageBoxIcon.Question);
1755 if (ret == DialogResult.Retry)
1757 await this.PostMessageAsync(postParams, uploadService, uploadItems);
1761 this.StatusTextHistoryBack();
1762 this.StatusText.Focus();
1764 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1765 if (this.settings.Common.FocusLockToStatusText)
1766 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1771 this.postTimestamps.Add(DateTimeUtc.Now);
1773 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1774 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1776 if (this.postTimestamps[i] < oneHour)
1777 this.postTimestamps.RemoveAt(i);
1780 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1782 this.HashMgr.ClearHashtag();
1783 this.HashStripSplitButton.Text = "#[-]";
1784 this.HashTogglePullDownMenuItem.Checked = false;
1785 this.HashToggleMenuItem.Checked = false;
1788 this.SetMainWindowTitle();
1793 this.statuses.AddPost(post);
1794 this.statuses.DistributePosts();
1795 this.RefreshTimeline();
1798 if (this.settings.Common.PostAndGet)
1799 await this.RefreshTabAsync<HomeTabModel>();
1802 private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1804 await this.workerSemaphore.WaitAsync();
1808 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1810 this.RefreshTasktrayIcon();
1811 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1813 catch (WebApiException ex)
1815 this.myStatusError = true;
1816 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1820 this.workerSemaphore.Release();
1824 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1826 if (ct.IsCancellationRequested)
1829 if (!CheckAccountValid())
1830 throw new WebApiException("Auth error. Check your account");
1833 if (!this.settings.Common.UnreadManage)
1836 read = this.initial && this.settings.Common.Read;
1838 p.Report("Posting...");
1840 var posts = new List<PostClass>();
1842 await Task.Run(async () =>
1844 foreach (var statusId in statusIds)
1846 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1847 if (post != null) posts.Add(post);
1851 if (ct.IsCancellationRequested)
1854 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1856 this.postTimestamps.Add(DateTimeUtc.Now);
1858 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1859 foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1861 if (this.postTimestamps[i] < oneHour)
1862 this.postTimestamps.RemoveAt(i);
1865 // 自分のRTはTLの更新では取得できない場合があるので、
1866 // 投稿時取得の有無に関わらず追加しておく
1867 posts.ForEach(post => this.statuses.AddPost(post));
1869 if (this.settings.Common.PostAndGet)
1871 await this.RefreshTabAsync<HomeTabModel>();
1875 this.statuses.DistributePosts();
1876 this.RefreshTimeline();
1880 private async Task RefreshFollowerIdsAsync()
1882 await this.workerSemaphore.WaitAsync();
1886 this.RefreshTasktrayIcon();
1887 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1889 await this.tw.RefreshFollowerIds();
1891 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1893 this.RefreshTimeline();
1894 this.listCache?.PurgeCache();
1895 this.CurrentListView.Refresh();
1897 catch (WebApiException ex)
1899 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1903 this.workerSemaphore.Release();
1907 private async Task RefreshNoRetweetIdsAsync()
1909 await this.workerSemaphore.WaitAsync();
1913 this.RefreshTasktrayIcon();
1914 await this.tw.RefreshNoRetweetIds();
1916 this.StatusLabel.Text = "NoRetweetIds refreshed";
1918 catch (WebApiException ex)
1920 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1924 this.workerSemaphore.Release();
1928 private async Task RefreshBlockIdsAsync()
1930 await this.workerSemaphore.WaitAsync();
1934 this.RefreshTasktrayIcon();
1935 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1937 await this.tw.RefreshBlockIds();
1939 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1941 catch (WebApiException ex)
1943 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1947 this.workerSemaphore.Release();
1951 private async Task RefreshTwitterConfigurationAsync()
1953 await this.workerSemaphore.WaitAsync();
1957 this.RefreshTasktrayIcon();
1958 await this.tw.RefreshConfiguration();
1960 if (this.tw.Configuration.PhotoSizeLimit != 0)
1962 foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1964 service.UpdateTwitterConfiguration(this.tw.Configuration);
1968 this.listCache?.PurgeCache();
1969 this.CurrentListView.Refresh();
1971 catch (WebApiException ex)
1973 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1977 this.workerSemaphore.Release();
1981 private async Task RefreshMuteUserIdsAsync()
1983 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1987 await this.tw.RefreshMuteUserIdsAsync();
1989 catch (WebApiException ex)
1991 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1995 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1998 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2000 if (e.Button == MouseButtons.Left)
2002 this.Visible = true;
2003 if (this.WindowState == FormWindowState.Minimized)
2005 this.WindowState = this.formWindowState;
2008 this.BringToFront();
2012 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2013 => await this.ListItemDoubleClickAction();
2015 private async Task ListItemDoubleClickAction()
2017 switch (this.settings.Common.ListDoubleClickAction)
2019 case MyCommon.ListItemDoubleClickActionType.Reply:
2020 this.MakeReplyText();
2022 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
2023 this.MakeReplyText(atAll: true);
2025 case MyCommon.ListItemDoubleClickActionType.Favorite:
2026 await this.FavoriteChange(true);
2028 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
2029 var post = this.CurrentPost;
2031 await this.ShowUserStatus(post.ScreenName, false);
2033 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
2034 await this.ShowUserTimeline();
2036 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
2037 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2039 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
2040 this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
2042 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
2043 this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2045 case MyCommon.ListItemDoubleClickActionType.None:
2052 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2053 => await this.FavoriteChange(true);
2055 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2056 => await this.FavoriteChange(false);
2058 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2059 => await this.FavoritesRetweetOfficial();
2061 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2062 => await this.FavoritesRetweetUnofficial();
2064 private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
2066 var tab = this.CurrentTab;
2067 var posts = tab.SelectedPosts;
2069 // trueでFavAdd,falseでFavRemove
2070 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
2071 || !this.ExistCurrentPost) return;
2073 if (posts.Length > 1)
2078 // https://support.twitter.com/articles/76915#favoriting
2079 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
2080 this.doFavRetweetFlags = false;
2085 if (multiFavoriteChangeDialogEnable)
2087 var confirm = MessageBox.Show(
2088 Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2089 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2090 MessageBoxButtons.OKCancel,
2091 MessageBoxIcon.Question);
2093 if (confirm == DialogResult.Cancel)
2101 var selectedPost = posts.Single();
2102 if (selectedPost.IsFav)
2104 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2108 await this.FavAddAsync(selectedPost.StatusId, tab);
2112 var selectedPosts = posts.Where(x => x.IsFav);
2113 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2114 if (statusIds.Length == 0)
2116 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2120 await this.FavRemoveAsync(statusIds, tab);
2124 private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2126 var post = this.CurrentPost;
2128 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2130 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2133 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2135 if ((!this.initialLayout) && this.Visible)
2137 if (this.WindowState == FormWindowState.Normal)
2139 this.mySize = this.ClientSize;
2140 this.mySpDis = this.SplitContainer1.SplitterDistance;
2141 this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2142 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2143 this.MarkSettingLocalModified();
2148 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2150 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2151 if (comparerMode == null)
2154 this.SetSortColumn(comparerMode.Value);
2158 /// 列インデックスからソートを行う ComparerMode を求める
2160 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2161 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2162 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2164 if (this.Use2ColumnsMode)
2165 return ComparerMode.Id;
2167 return columnIndex switch
2169 1 => ComparerMode.Nickname, // ニックネーム
2170 2 => ComparerMode.Data, // 本文
2171 3 => ComparerMode.Id, // 時刻=発言Id
2172 4 => ComparerMode.Name, // 名前
2173 7 => ComparerMode.Source, // Source
2174 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2179 /// 発言一覧の指定した位置の列でソートする
2181 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2182 private void SetSortColumnByDisplayIndex(int columnIndex)
2184 // 表示上の列の位置から ColumnHeader を求める
2185 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2186 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2191 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2192 if (comparerMode == null)
2195 this.SetSortColumn(comparerMode.Value);
2199 /// 発言一覧の最後列の項目でソートする
2201 private void SetSortLastColumn()
2203 // 表示上の最後列にある ColumnHeader を求める
2204 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2205 .OrderByDescending(x => x.DisplayIndex)
2208 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2209 if (comparerMode == null)
2212 this.SetSortColumn(comparerMode.Value);
2216 /// 発言一覧を指定された ComparerMode に基づいてソートする
2218 private void SetSortColumn(ComparerMode sortColumn)
2220 if (this.settings.Common.SortOrderLock)
2223 this.statuses.ToggleSortOrder(sortColumn);
2224 this.InitColumnText();
2226 var list = this.CurrentListView;
2227 if (this.Use2ColumnsMode)
2229 list.Columns[0].Text = this.columnText[0];
2230 list.Columns[1].Text = this.columnText[2];
2234 for (var i = 0; i <= 7; i++)
2236 list.Columns[i].Text = this.columnText[i];
2240 this.listCache?.PurgeCache();
2242 var tab = this.CurrentTab;
2243 var post = this.CurrentPost;
2244 if (tab.AllCount > 0 && post != null)
2246 var idx = tab.IndexOf(post.StatusId);
2249 this.SelectListItem(list, idx);
2250 list.EnsureVisible(idx);
2255 this.MarkSettingCommonModified();
2258 private void TweenMain_LocationChanged(object sender, EventArgs e)
2260 if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2262 this.myLoc = this.DesktopLocation;
2263 this.MarkSettingLocalModified();
2267 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2269 var post = this.CurrentPost;
2270 if (!this.ExistCurrentPost)
2272 this.ReplyStripMenuItem.Enabled = false;
2273 this.ReplyAllStripMenuItem.Enabled = false;
2274 this.DMStripMenuItem.Enabled = false;
2275 this.TabMenuItem.Enabled = false;
2276 this.IDRuleMenuItem.Enabled = false;
2277 this.SourceRuleMenuItem.Enabled = false;
2278 this.ReadedStripMenuItem.Enabled = false;
2279 this.UnreadStripMenuItem.Enabled = false;
2280 this.AuthorContextMenuItem.Visible = false;
2281 this.RetweetedByContextMenuItem.Visible = false;
2285 this.ReplyStripMenuItem.Enabled = true;
2286 this.ReplyAllStripMenuItem.Enabled = true;
2287 this.DMStripMenuItem.Enabled = true;
2288 this.TabMenuItem.Enabled = true;
2289 this.IDRuleMenuItem.Enabled = true;
2290 this.SourceRuleMenuItem.Enabled = true;
2291 this.ReadedStripMenuItem.Enabled = true;
2292 this.UnreadStripMenuItem.Enabled = true;
2293 this.AuthorContextMenuItem.Visible = true;
2294 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2295 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2296 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2298 var tab = this.CurrentTab;
2299 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2301 this.FavAddToolStripMenuItem.Enabled = false;
2302 this.FavRemoveToolStripMenuItem.Enabled = false;
2303 this.StatusOpenMenuItem.Enabled = false;
2304 this.ShowRelatedStatusesMenuItem.Enabled = false;
2306 this.ReTweetStripMenuItem.Enabled = false;
2307 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2308 this.QuoteStripMenuItem.Enabled = false;
2309 this.FavoriteRetweetContextMenu.Enabled = false;
2310 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2314 this.FavAddToolStripMenuItem.Enabled = true;
2315 this.FavRemoveToolStripMenuItem.Enabled = true;
2316 this.StatusOpenMenuItem.Enabled = true;
2317 this.ShowRelatedStatusesMenuItem.Enabled = true; // PublicSearchの時問題出るかも
2319 if (!post.CanRetweetBy(this.tw.UserId))
2321 this.ReTweetStripMenuItem.Enabled = false;
2322 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2323 this.QuoteStripMenuItem.Enabled = false;
2324 this.FavoriteRetweetContextMenu.Enabled = false;
2325 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2329 this.ReTweetStripMenuItem.Enabled = true;
2330 this.ReTweetUnofficialStripMenuItem.Enabled = true;
2331 this.QuoteStripMenuItem.Enabled = true;
2332 this.FavoriteRetweetContextMenu.Enabled = true;
2333 this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2337 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2339 this.RepliedStatusOpenMenuItem.Enabled = false;
2343 this.RepliedStatusOpenMenuItem.Enabled = true;
2346 if (this.ExistCurrentPost && post != null)
2348 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2349 if (post.RetweetedByUserId == this.tw.UserId)
2350 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2352 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2356 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2357 => this.MakeReplyText();
2359 private void DMStripMenuItem_Click(object sender, EventArgs e)
2360 => this.MakeDirectMessageText();
2362 private async Task DoStatusDelete()
2364 var posts = this.CurrentTab.SelectedPosts;
2365 if (posts.Length == 0)
2368 // 選択されたツイートの中に削除可能なものが一つでもあるか
2369 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2372 var ret = MessageBox.Show(
2374 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2375 Properties.Resources.DeleteStripMenuItem_ClickText2,
2376 MessageBoxButtons.OKCancel,
2377 MessageBoxIcon.Question);
2379 if (ret != DialogResult.OK)
2382 var currentListView = this.CurrentListView;
2383 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2385 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2387 Exception? lastException = null;
2388 foreach (var post in posts)
2390 if (!post.CanDeleteBy(this.tw.UserId))
2395 if (post.StatusId is TwitterDirectMessageId dmId)
2397 await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2401 if (post.RetweetedByUserId == this.tw.UserId)
2403 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2405 await this.tw.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
2410 if (post.UserId == this.tw.UserId)
2412 if (post.RetweetedId != null)
2414 // 他人に RT された自分のツイート
2415 // => RT 元の自分のツイートを削除
2416 await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2422 await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2428 catch (WebApiException ex)
2434 this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2437 if (lastException == null)
2438 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2440 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2442 using (ControlTransaction.Update(currentListView))
2444 this.listCache?.PurgeCache();
2445 this.listCache?.UpdateListSize();
2447 currentListView.SelectedIndices.Clear();
2449 var currentTab = this.CurrentTab;
2450 if (currentTab.AllCount != 0)
2453 if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2454 selectedIndex = focusedIndex;
2456 selectedIndex = currentTab.AllCount - 1;
2458 currentListView.SelectedIndices.Add(selectedIndex);
2459 currentListView.EnsureVisible(selectedIndex);
2460 currentListView.FocusedItem = currentListView.Items[selectedIndex];
2464 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2466 var tabPage = this.ListTab.TabPages[index];
2467 if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2469 if (tabPage.ImageIndex == 0)
2470 tabPage.ImageIndex = -1; // タブアイコン
2474 if (!this.settings.Common.TabIconDisp)
2475 this.ListTab.Refresh();
2479 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2480 => await this.DoStatusDelete();
2482 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2484 using (ControlTransaction.Update(this.CurrentListView))
2486 var tab = this.CurrentTab;
2487 foreach (var statusId in tab.SelectedStatusIds)
2489 this.statuses.SetReadAllTab(statusId, read: true);
2490 var idx = tab.IndexOf(statusId);
2491 this.listCache?.RefreshStyle(idx);
2494 if (this.settings.Common.TabIconDisp)
2496 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2498 if (tab.UnreadCount == 0)
2500 var tabPage = this.ListTab.TabPages[index];
2501 if (tabPage.ImageIndex == 0)
2502 tabPage.ImageIndex = -1; // タブアイコン
2506 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2509 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2511 using (ControlTransaction.Update(this.CurrentListView))
2513 var tab = this.CurrentTab;
2514 foreach (var statusId in tab.SelectedStatusIds)
2516 this.statuses.SetReadAllTab(statusId, read: false);
2517 var idx = tab.IndexOf(statusId);
2518 this.listCache?.RefreshStyle(idx);
2521 if (this.settings.Common.TabIconDisp)
2523 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2525 if (tab.UnreadCount > 0)
2527 var tabPage = this.ListTab.TabPages[index];
2528 if (tabPage.ImageIndex == -1)
2529 tabPage.ImageIndex = 0; // タブアイコン
2533 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2536 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2537 => await this.DoRefresh();
2539 private async Task DoRefresh()
2540 => await this.RefreshTabAsync(this.CurrentTab);
2542 private async Task DoRefreshMore()
2543 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2545 private DialogResult ShowSettingDialog()
2547 using var settingDialog = new AppendSettingDialog();
2548 settingDialog.Icon = this.iconAssets.IconMain;
2549 settingDialog.IntervalChanged += this.TimerInterval_Changed;
2551 settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2553 DialogResult result;
2556 result = settingDialog.ShowDialog(this);
2560 return DialogResult.Abort;
2563 if (result == DialogResult.OK)
2565 lock (this.syncObject)
2567 settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2574 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2577 var previousUserId = this.settings.Common.UserId;
2578 var oldIconCol = this.Use2ColumnsMode;
2580 if (this.ShowSettingDialog() == DialogResult.OK)
2582 lock (this.syncObject)
2584 this.settings.ApplySettings();
2586 if (MyCommon.IsNullOrEmpty(this.settings.Common.Token))
2587 this.tw.ClearAuthInfo();
2589 var account = this.settings.Common.SelectedAccount;
2590 if (account != null)
2591 this.tw.Initialize(account.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
2593 this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 0L);
2595 this.tw.RestrictFavCheck = this.settings.Common.RestrictFavCheck;
2596 this.tw.ReadOwnPost = this.settings.Common.ReadOwnPost;
2598 this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2602 if (this.settings.Common.TabIconDisp)
2604 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2605 this.ListTab.DrawMode = TabDrawMode.Normal;
2606 this.ListTab.ImageList = this.TabImage;
2610 this.ListTab.DrawItem -= this.ListTab_DrawItem;
2611 this.ListTab.DrawItem += this.ListTab_DrawItem;
2612 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2613 this.ListTab.ImageList = null;
2616 catch (Exception ex)
2618 ex.Data["Instance"] = "ListTab(TabIconDisp)";
2619 ex.Data["IsTerminatePermission"] = false;
2625 if (!this.settings.Common.UnreadManage)
2627 this.ReadedStripMenuItem.Enabled = false;
2628 this.UnreadStripMenuItem.Enabled = false;
2629 if (this.settings.Common.TabIconDisp)
2631 foreach (TabPage myTab in this.ListTab.TabPages)
2633 myTab.ImageIndex = -1;
2639 this.ReadedStripMenuItem.Enabled = true;
2640 this.UnreadStripMenuItem.Enabled = true;
2643 catch (Exception ex)
2645 ex.Data["Instance"] = "ListTab(UnreadManage)";
2646 ex.Data["IsTerminatePermission"] = false;
2651 this.SetTabAlignment();
2653 this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2655 var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2656 imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2657 imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2659 this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2660 this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2661 this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2662 this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2664 var newTheme = new ThemeManager(this.settings.Local);
2665 (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2666 this.tweetDetailsView.Theme = this.themeManager;
2667 if (this.listDrawer != null)
2668 this.listDrawer.Theme = this.themeManager;
2673 if (this.StatusText.Focused)
2674 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2676 this.StatusText.Font = this.themeManager.FontInputFont;
2677 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2679 catch (Exception ex)
2681 MessageBox.Show(ex.Message);
2686 this.InitDetailHtmlFormat();
2688 catch (Exception ex)
2690 ex.Data["Instance"] = "Font";
2691 ex.Data["IsTerminatePermission"] = false;
2697 if (this.settings.Common.TabIconDisp)
2699 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2701 var tabPage = this.ListTab.TabPages[index];
2702 if (tab.UnreadCount == 0)
2703 tabPage.ImageIndex = -1;
2705 tabPage.ImageIndex = 0;
2709 catch (Exception ex)
2711 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2712 ex.Data["IsTerminatePermission"] = false;
2718 this.ApplyListViewIconSize(this.settings.Common.IconSize);
2720 foreach (TabPage tp in this.ListTab.TabPages)
2722 var lst = (DetailsListView)tp.Tag;
2724 using (ControlTransaction.Update(lst))
2726 lst.GridLines = this.settings.Common.ShowGrid;
2728 if (this.Use2ColumnsMode != oldIconCol)
2729 this.ResetColumns(lst);
2733 catch (Exception ex)
2735 ex.Data["Instance"] = "ListView(IconSize)";
2736 ex.Data["IsTerminatePermission"] = false;
2740 this.SetMainWindowTitle();
2741 this.SetNotifyIconText();
2743 this.listCache?.PurgeCache();
2744 this.CurrentListView.Refresh();
2745 this.ListTab.Refresh();
2747 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2748 if (this.settings.Common.HotkeyEnabled)
2750 // グローバルホットキーの登録。設定で変更可能にするかも
2751 var modKey = HookGlobalHotkey.ModKeys.None;
2752 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2753 modKey |= HookGlobalHotkey.ModKeys.Alt;
2754 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2755 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2756 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2757 modKey |= HookGlobalHotkey.ModKeys.Shift;
2758 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2759 modKey |= HookGlobalHotkey.ModKeys.Win;
2761 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2764 if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2767 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2775 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2777 this.TopMost = this.settings.Common.AlwaysTop;
2778 this.SaveConfigsAll(false);
2780 if (this.tw.UserId != previousUserId)
2781 await this.DoGetFollowersMenu();
2787 private void SetTabAlignment()
2789 var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2790 if (this.ListTab.Alignment == newAlignment) return;
2793 var currentListViewState = this.listViewState[this.CurrentTabName];
2794 currentListViewState.Save(this.ListLockMenuItem.Checked);
2796 this.ListTab.Alignment = newAlignment;
2798 currentListViewState.Restore(forceScroll: true);
2801 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2804 if (this.listDrawer != null)
2806 this.listDrawer.IconSize = iconSz;
2807 this.listDrawer.UpdateItemHeight();
2810 this.listCache?.PurgeCache();
2813 private void ResetColumns(DetailsListView list)
2815 using (ControlTransaction.Update(list))
2816 using (ControlTransaction.Layout(list, false))
2819 list.ColumnClick -= this.MyList_ColumnClick;
2820 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2821 list.ColumnReordered -= this.MyList_ColumnReordered;
2822 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2824 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2825 list.Columns.Clear();
2826 cols.ForEach(col => col.Dispose());
2829 this.InitColumns(list, true);
2831 list.ColumnClick += this.MyList_ColumnClick;
2832 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2833 list.ColumnReordered += this.MyList_ColumnReordered;
2834 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2838 public void AddNewTabForSearch(string searchWord)
2840 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2841 foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2843 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2845 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2846 this.ListTab.SelectedIndex = tabIndex;
2851 var tabName = searchWord;
2852 for (var i = 0; i <= 100; i++)
2854 if (this.statuses.ContainsTab(tabName))
2860 var tab = new PublicSearchTabModel(tabName);
2861 this.statuses.AddTab(tab);
2862 this.AddNewTab(tab, startup: false);
2864 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2866 var tabPage = this.CurrentTabPage;
2867 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2868 cmb.Items.Add(searchWord);
2869 cmb.Text = searchWord;
2870 this.SaveConfigsTabs();
2872 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2875 private async Task ShowUserTimeline()
2877 var post = this.CurrentPost;
2878 if (post == null || !this.ExistCurrentPost) return;
2879 await this.AddNewTabForUserTimeline(post.ScreenName);
2882 private async Task ShowRetweeterTimeline()
2884 var retweetedBy = this.CurrentPost?.RetweetedBy;
2885 if (retweetedBy == null || !this.ExistCurrentPost) return;
2886 await this.AddNewTabForUserTimeline(retweetedBy);
2889 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2891 if (e.KeyCode == Keys.Escape)
2893 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2894 this.SaveConfigsTabs();
2895 e.SuppressKeyPress = true;
2899 public async Task AddNewTabForUserTimeline(string user)
2901 // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2902 foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2904 if (tb.ScreenName == user)
2906 var tabIndex = this.statuses.Tabs.IndexOf(tb);
2907 this.ListTab.SelectedIndex = tabIndex;
2912 var tabName = "user:" + user;
2913 while (this.statuses.ContainsTab(tabName))
2918 var tab = new UserTimelineTabModel(tabName, user);
2919 this.statuses.AddTab(tab);
2920 this.AddNewTab(tab, startup: false);
2922 this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2923 this.SaveConfigsTabs();
2925 await this.RefreshTabAsync(tab);
2928 public bool AddNewTab(TabModel tab, bool startup)
2931 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2935 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2937 var tabPage = new TabPage();
2938 var listCustom = new DetailsListView();
2940 var cnt = this.statuses.Tabs.Count;
2942 // ToDo:Create and set controls follow tabtypes
2944 using (ControlTransaction.Update(listCustom))
2945 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2946 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2947 using (ControlTransaction.Layout(this.SplitContainer1, false))
2948 using (ControlTransaction.Layout(this.ListTab, false))
2949 using (ControlTransaction.Layout(this))
2950 using (ControlTransaction.Layout(tabPage, false))
2952 tabPage.Controls.Add(listCustom);
2955 var userTab = tab as UserTimelineTabModel;
2956 var listTab = tab as ListTimelineTabModel;
2957 var searchTab = tab as PublicSearchTabModel;
2959 if (userTab != null || listTab != null)
2961 var label = new Label
2963 Dock = DockStyle.Top,
2968 if (listTab != null)
2970 label.Text = listTab.ListInfo.ToString();
2972 else if (userTab != null)
2974 label.Text = userTab.ScreenName + "'s Timeline";
2976 label.TextAlign = ContentAlignment.MiddleLeft;
2977 using (var tmpComboBox = new ComboBox())
2979 label.Height = tmpComboBox.Height;
2981 tabPage.Controls.Add(label);
2984 else if (searchTab != null)
2986 var pnl = new Panel();
2988 var lbl = new Label();
2989 var cmb = new ComboBox();
2990 var btn = new Button();
2991 var cmbLang = new ComboBox();
2993 using (ControlTransaction.Layout(pnl, false))
2995 pnl.Controls.Add(cmb);
2996 pnl.Controls.Add(cmbLang);
2997 pnl.Controls.Add(btn);
2998 pnl.Controls.Add(lbl);
2999 pnl.Name = "panelSearch";
3001 pnl.Dock = DockStyle.Top;
3002 pnl.Height = cmb.Height;
3003 pnl.Enter += this.SearchControls_Enter;
3004 pnl.Leave += this.SearchControls_Leave;
3007 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3008 cmb.Dock = DockStyle.Fill;
3009 cmb.Name = "comboSearch";
3010 cmb.DropDownStyle = ComboBoxStyle.DropDown;
3011 cmb.ImeMode = ImeMode.NoControl;
3012 cmb.TabStop = false;
3014 cmb.AutoCompleteMode = AutoCompleteMode.None;
3015 cmb.KeyDown += this.SearchComboBox_KeyDown;
3018 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
3019 cmbLang.Dock = DockStyle.Right;
3021 cmbLang.Name = "comboLang";
3022 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
3023 cmbLang.TabStop = false;
3024 cmbLang.TabIndex = 2;
3025 cmbLang.Items.Add("");
3026 cmbLang.Items.Add("ja");
3027 cmbLang.Items.Add("en");
3028 cmbLang.Items.Add("ar");
3029 cmbLang.Items.Add("da");
3030 cmbLang.Items.Add("nl");
3031 cmbLang.Items.Add("fa");
3032 cmbLang.Items.Add("fi");
3033 cmbLang.Items.Add("fr");
3034 cmbLang.Items.Add("de");
3035 cmbLang.Items.Add("hu");
3036 cmbLang.Items.Add("is");
3037 cmbLang.Items.Add("it");
3038 cmbLang.Items.Add("no");
3039 cmbLang.Items.Add("pl");
3040 cmbLang.Items.Add("pt");
3041 cmbLang.Items.Add("ru");
3042 cmbLang.Items.Add("es");
3043 cmbLang.Items.Add("sv");
3044 cmbLang.Items.Add("th");
3046 lbl.Text = "Search(C-S-f)";
3047 lbl.Name = "label1";
3048 lbl.Dock = DockStyle.Left;
3050 lbl.Height = cmb.Height;
3051 lbl.TextAlign = ContentAlignment.MiddleLeft;
3054 btn.Text = "Search";
3055 btn.Name = "buttonSearch";
3056 btn.UseVisualStyleBackColor = true;
3057 btn.Dock = DockStyle.Right;
3058 btn.TabStop = false;
3060 btn.Click += this.SearchButton_Click;
3062 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
3064 cmb.Items.Add(searchTab.SearchWords);
3065 cmb.Text = searchTab.SearchWords;
3068 cmbLang.Text = searchTab.SearchLang;
3070 tabPage.Controls.Add(pnl);
3074 tabPage.Tag = listCustom;
3075 this.ListTab.Controls.Add(tabPage);
3077 tabPage.Location = new Point(4, 4);
3078 tabPage.Name = "CTab" + cnt;
3079 tabPage.Size = new Size(380, 260);
3080 tabPage.TabIndex = 2 + cnt;
3081 tabPage.Text = tab.TabName;
3082 tabPage.UseVisualStyleBackColor = true;
3083 tabPage.AccessibleRole = AccessibleRole.PageTab;
3085 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
3086 listCustom.TabIndex = 1;
3087 listCustom.AllowColumnReorder = true;
3088 listCustom.ContextMenuStrip = this.ContextMenuOperate;
3089 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
3090 listCustom.Dock = DockStyle.Fill;
3091 listCustom.FullRowSelect = true;
3092 listCustom.HideSelection = false;
3093 listCustom.Location = new Point(0, 0);
3094 listCustom.Margin = new Padding(0);
3095 listCustom.Name = "CList" + Environment.TickCount;
3096 listCustom.ShowItemToolTips = true;
3097 listCustom.Size = new Size(380, 260);
3098 listCustom.UseCompatibleStateImageBehavior = false;
3099 listCustom.View = View.Details;
3100 listCustom.OwnerDraw = true;
3101 listCustom.VirtualMode = true;
3103 listCustom.GridLines = this.settings.Common.ShowGrid;
3104 listCustom.AllowDrop = true;
3106 this.InitColumns(listCustom, startup);
3108 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3109 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3110 listCustom.ColumnClick += this.MyList_ColumnClick;
3111 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3112 listCustom.DragDrop += this.TweenMain_DragDrop;
3113 listCustom.DragEnter += this.TweenMain_DragEnter;
3114 listCustom.DragOver += this.TweenMain_DragOver;
3115 listCustom.MouseClick += this.MyList_MouseClick;
3116 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3117 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3118 listCustom.HScrolled += this.MyList_HScrolled;
3121 var state = new TimelineListViewState(listCustom, tab);
3122 this.listViewState[tab.TabName] = state;
3127 public bool RemoveSpecifiedTab(string tabName, bool confirm)
3129 var tabInfo = this.statuses.GetTabByName(tabName);
3130 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3135 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3136 var result = MessageBox.Show(
3138 tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3139 MessageBoxButtons.OKCancel,
3140 MessageBoxIcon.Question,
3141 MessageBoxDefaultButton.Button2);
3142 if (result == DialogResult.Cancel)
3148 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3152 var tabPage = this.ListTab.TabPages[tabIndex];
3154 this.SetListProperty(); // 他のタブに列幅等を反映
3156 this.listViewState.Remove(tabName);
3159 var listCustom = (DetailsListView)tabPage.Tag;
3162 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3163 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3164 using (ControlTransaction.Layout(this.SplitContainer1, false))
3165 using (ControlTransaction.Layout(this.ListTab, false))
3166 using (ControlTransaction.Layout(this))
3167 using (ControlTransaction.Layout(tabPage, false))
3169 if (this.CurrentTabName == tabName)
3171 this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3172 this.beforeSelectedTab = null;
3174 this.ListTab.Controls.Remove(tabPage);
3177 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3179 using var label = tabPage.Controls["labelUser"];
3180 tabPage.Controls.Remove(label);
3182 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3184 using var pnl = tabPage.Controls["panelSearch"];
3186 pnl.Enter -= this.SearchControls_Enter;
3187 pnl.Leave -= this.SearchControls_Leave;
3188 tabPage.Controls.Remove(pnl);
3190 foreach (Control ctrl in pnl.Controls)
3192 if (ctrl.Name == "buttonSearch")
3194 ctrl.Click -= this.SearchButton_Click;
3196 else if (ctrl.Name == "comboSearch")
3198 ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3200 pnl.Controls.Remove(ctrl);
3205 tabPage.Controls.Remove(listCustom);
3207 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3208 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3209 listCustom.ColumnClick -= this.MyList_ColumnClick;
3210 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3211 listCustom.DragDrop -= this.TweenMain_DragDrop;
3212 listCustom.DragEnter -= this.TweenMain_DragEnter;
3213 listCustom.DragOver -= this.TweenMain_DragOver;
3214 listCustom.MouseClick -= this.MyList_MouseClick;
3215 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3216 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3217 listCustom.HScrolled -= this.MyList_HScrolled;
3219 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3220 listCustom.Columns.Clear();
3221 cols.ForEach(col => col.Dispose());
3224 listCustom.ContextMenuStrip = null;
3225 listCustom.ColumnHeaderContextMenuStrip = null;
3226 listCustom.Font = null;
3228 listCustom.SmallImageList = null;
3229 listCustom.ListViewItemSorter = null;
3232 this.listCache?.PurgeCache();
3236 listCustom.Dispose();
3237 this.statuses.RemoveTab(tabName);
3242 private void ListTab_Deselected(object sender, TabControlEventArgs e)
3244 this.listCache?.PurgeCache();
3245 this.beforeSelectedTab = e.TabPage;
3248 private void ListTab_MouseMove(object sender, MouseEventArgs e)
3252 if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3255 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3256 if (!dragEnableRectangle.Contains(e.Location))
3258 // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3259 tn = this.CurrentTabName;
3262 if (MyCommon.IsNullOrEmpty(tn)) return;
3264 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3267 var tabPage = this.ListTab.TabPages[tabIndex];
3268 this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3273 this.tabDrag = false;
3276 var cpos = new Point(e.X, e.Y);
3277 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3279 var rect = this.ListTab.GetTabRect(index);
3280 if (rect.Contains(cpos))
3282 this.rclickTabName = tab.TabName;
3288 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3290 this.SetMainWindowTitle();
3291 this.SetStatusLabelUrl();
3292 this.SetApiStatusLabel();
3293 if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3294 this.Tag = this.ListTab.Tag;
3295 this.TabMenuControl(this.CurrentTabName);
3296 this.PushSelectPostChain();
3297 this.DispSelectedPost();
3300 private void SetListProperty()
3302 if (!this.isColumnChanged) return;
3304 var currentListView = this.CurrentListView;
3306 var dispOrder = new int[currentListView.Columns.Count];
3307 for (var i = 0; i < currentListView.Columns.Count; i++)
3309 for (var j = 0; j < currentListView.Columns.Count; j++)
3311 if (currentListView.Columns[j].DisplayIndex == i)
3320 foreach (TabPage tb in this.ListTab.TabPages)
3322 if (tb.Text == this.CurrentTabName)
3325 if (tb.Tag != null && tb.Controls.Count > 0)
3327 var lst = (DetailsListView)tb.Tag;
3328 for (var i = 0; i < lst.Columns.Count; i++)
3330 lst.Columns[dispOrder[i]].DisplayIndex = i;
3331 lst.Columns[i].Width = currentListView.Columns[i].Width;
3336 this.isColumnChanged = false;
3339 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3341 if (e.KeyChar == '@')
3343 if (!this.settings.Common.UseAtIdSupplement) return;
3345 var cnt = this.AtIdSupl.ItemCount;
3346 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3347 if (cnt != this.AtIdSupl.ItemCount)
3348 this.MarkSettingAtIdModified();
3351 else if (e.KeyChar == '#')
3353 if (!this.settings.Common.UseHashSupplement) return;
3354 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3359 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3360 => this.ShowSuplDialog(owner, dialog, 0, "");
3362 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3363 => this.ShowSuplDialog(owner, dialog, offset, "");
3365 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3367 dialog.StartsWith = startswith;
3374 dialog.ShowDialog();
3376 this.TopMost = this.settings.Common.AlwaysTop;
3377 var selStart = owner.SelectionStart;
3380 if (dialog.DialogResult == DialogResult.OK)
3382 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3386 fHalf = owner.Text.Substring(0, selStart - offset);
3388 if (selStart < owner.Text.Length)
3390 eHalf = owner.Text.Substring(selStart);
3392 owner.Text = fHalf + dialog.InputText + eHalf;
3393 owner.SelectionStart = selStart + dialog.InputText.Length;
3400 fHalf = owner.Text.Substring(0, selStart);
3402 if (selStart < owner.Text.Length)
3404 eHalf = owner.Text.Substring(selStart);
3406 owner.Text = fHalf + eHalf;
3409 owner.SelectionStart = selStart;
3415 private void StatusText_KeyUp(object sender, KeyEventArgs e)
3418 if (!e.Alt && !e.Control && !e.Shift)
3420 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3422 var isSpace = false;
3423 foreach (var c in this.StatusText.Text)
3425 if (c == ' ' || c == ' ')
3438 this.StatusText.Text = "";
3439 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3443 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3446 private void StatusText_TextChanged(object sender, EventArgs e)
3449 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3450 this.lblLen.Text = pLen.ToString();
3453 this.StatusText.ForeColor = Color.Red;
3457 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3460 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3462 if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3464 this.inReplyTo = null;
3469 /// メンション以外の文字列が含まれていないテキストであるか判定します
3471 internal static bool TextContainsOnlyMentions(string text)
3473 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3476 foreach (var mention in mentions)
3478 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3480 if (!string.IsNullOrWhiteSpace(textPart))
3483 startIndex = mention.Indices[1];
3486 var textPartLast = text.Substring(startIndex);
3488 if (!string.IsNullOrWhiteSpace(textPartLast))
3495 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3497 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3499 var autoPopulatedUserIdList = new List<long>();
3501 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3502 if (replyToPost != null)
3504 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3506 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3507 autoPopulatedUserIdList.Add(replyToPost.UserId);
3509 foreach (var (userId, screenName) in replyToPost.ReplyToList)
3511 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3513 statusText = statusText.Substring(screenName.Length + 2);
3514 autoPopulatedUserIdList.Add(userId);
3520 autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3526 /// attachment_url に指定可能な URL が含まれていれば除去
3528 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3530 attachmentUrl = null;
3532 // attachment_url は media_id と同時に使用できない
3533 if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3536 var match = Twitter.AttachmentUrlRegex.Match(statusText);
3540 attachmentUrl = match.Value;
3543 statusText = statusText.Substring(0, match.Index);
3545 // テキストと URL の間にスペースが含まれていれば除去
3546 return statusText.TrimEnd(' ');
3549 private string FormatStatusTextExtended(string statusText)
3550 => this.FormatStatusTextExtended(statusText, out _, out _);
3553 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3555 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3557 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3559 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3561 return this.FormatStatusText(statusText);
3565 /// ツイート投稿前のフッター付与などの前処理を行います
3567 private string FormatStatusText(string statusText)
3569 statusText = statusText.Replace("\r\n", "\n");
3571 if (this.urlMultibyteSplit)
3574 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3577 if (this.settings.Common.WideSpaceConvert)
3579 // 文中の全角スペースを半角スペース1個にする
3580 statusText = statusText.Replace(" ", " ");
3583 // DM の場合はこれ以降の処理を行わない
3584 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3588 if (this.settings.Common.PostShiftEnter)
3590 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3594 if (this.StatusText.Multiline && !this.settings.Common.PostCtrlEnter)
3595 disableFooter = MyCommon.IsKeyDown(Keys.Control);
3597 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
3600 if (statusText.Contains("RT @"))
3601 disableFooter = true;
3603 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3604 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3606 var mentionSelf = $"@{this.tw.Username} ";
3607 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3609 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3610 statusText = statusText.Substring(mentionSelf.Length);
3617 var hashtag = this.HashMgr.UseHash;
3618 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3620 if (this.HashMgr.IsHead)
3621 header = this.HashMgr.UseHash + " ";
3623 footer = " " + this.HashMgr.UseHash;
3628 if (this.settings.Local.UseRecommendStatus)
3631 footer += this.recommendedStatusFooter;
3633 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3635 // テキストボックスに入力されている文字列を使用する
3636 footer += " " + this.settings.Local.StatusText.Trim();
3640 statusText = header + statusText + footer;
3642 if (this.preventSmsCommand)
3644 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3645 // 参照: https://support.twitter.com/articles/14020
3647 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3648 && !Twitter.DMSendTextRegex.IsMatch(statusText))
3650 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3651 statusText = '\u200b' + statusText;
3659 /// 投稿欄に表示する入力可能な文字数を計算します
3661 private int GetRestStatusCount(string statusText)
3663 var remainCount = this.tw.GetTextLengthRemain(statusText);
3665 var uploadService = this.GetSelectedImageService();
3666 if (uploadService != null)
3668 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3669 remainCount -= uploadService.GetReservedTextLength(1);
3675 private IMediaUploadService? GetSelectedImageService()
3676 => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3679 /// 全てのタブの振り分けルールを反映し直します
3681 private void ApplyPostFilters()
3683 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3685 this.statuses.FilterAll();
3687 var listView = this.CurrentListView;
3688 using (ControlTransaction.Update(listView))
3690 this.listCache?.PurgeCache();
3691 this.listCache?.UpdateListSize();
3694 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3696 var tabPage = this.ListTab.TabPages[index];
3698 if (this.settings.Common.TabIconDisp)
3700 if (tab.UnreadCount > 0)
3701 tabPage.ImageIndex = 0;
3703 tabPage.ImageIndex = -1;
3707 if (!this.settings.Common.TabIconDisp)
3708 this.ListTab.Refresh();
3710 this.SetMainWindowTitle();
3711 this.SetStatusLabelUrl();
3715 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3716 => e.DrawDefault = true;
3718 private void MyList_HScrolled(object sender, EventArgs e)
3719 => ((DetailsListView)sender).Refresh();
3721 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3723 base.ScaleControl(factor, specified);
3725 ScaleChildControl(this.TabImage, factor);
3727 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3728 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3730 foreach (var listview in listviews)
3732 ScaleChildControl(listview, factor);
3736 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3738 var tab = this.CurrentTab;
3740 if (tab.AllCount == 0)
3742 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3746 var selectedIndex = tab.SelectedIndex;
3751 case SEARCHTYPE.NextSearch: // 次を検索
3752 if (selectedIndex != -1)
3753 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3757 case SEARCHTYPE.PrevSearch: // 前を検索
3758 if (selectedIndex != -1)
3759 startIndex = Math.Max(selectedIndex - 1, 0);
3761 startIndex = tab.AllCount - 1;
3763 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3765 if (selectedIndex != -1)
3766 startIndex = selectedIndex;
3772 Func<string, bool> stringComparer;
3775 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3777 catch (ArgumentException)
3779 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3783 var reverse = searchType == SEARCHTYPE.PrevSearch;
3784 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3785 .DefaultIfEmpty(-1).First();
3787 if (foundIndex == -1)
3789 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3793 var listView = this.CurrentListView;
3794 this.SelectListItem(listView, foundIndex);
3795 listView.EnsureVisible(foundIndex);
3798 private void MenuItemSubSearch_Click(object sender, EventArgs e)
3799 => this.ShowSearchDialog(); // 検索メニュー
3801 private void MenuItemSearchNext_Click(object sender, EventArgs e)
3803 var previousSearch = this.SearchDialog.ResultOptions;
3804 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3806 this.SearchDialog.Reset();
3807 this.ShowSearchDialog();
3813 previousSearch.Query,
3814 previousSearch.CaseSensitive,
3815 previousSearch.UseRegex,
3816 SEARCHTYPE.NextSearch);
3819 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3821 var previousSearch = this.SearchDialog.ResultOptions;
3822 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3824 this.SearchDialog.Reset();
3825 this.ShowSearchDialog();
3831 previousSearch.Query,
3832 previousSearch.CaseSensitive,
3833 previousSearch.UseRegex,
3834 SEARCHTYPE.PrevSearch);
3838 /// 検索ダイアログを表示し、検索を実行します
3840 private void ShowSearchDialog()
3842 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3844 this.TopMost = this.settings.Common.AlwaysTop;
3847 this.TopMost = this.settings.Common.AlwaysTop;
3849 var searchOptions = this.SearchDialog.ResultOptions!;
3850 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3852 if (searchOptions.NewTab)
3854 var tabName = Properties.Resources.SearchResults_TabName;
3858 tabName = this.statuses.MakeTabName(tabName);
3860 catch (TabException ex)
3862 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3865 var resultTab = new LocalSearchTabModel(tabName);
3866 this.AddNewTab(resultTab, startup: false);
3867 this.statuses.AddTab(resultTab);
3869 var targetTab = this.CurrentTab;
3871 Func<string, bool> stringComparer;
3874 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3876 catch (ArgumentException)
3878 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3882 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3883 if (foundIndices.Length == 0)
3885 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3889 var foundPosts = foundIndices.Select(x => targetTab[x]);
3890 foreach (var post in foundPosts)
3892 resultTab.AddPostQueue(post);
3895 this.statuses.DistributePosts();
3896 this.RefreshTimeline();
3898 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3899 this.ListTab.SelectedIndex = tabIndex;
3904 searchOptions.Query,
3905 searchOptions.CaseSensitive,
3906 searchOptions.UseRegex,
3907 SEARCHTYPE.DialogSearch);
3910 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3912 this.AddNewTabForSearch(searchOptions.Query);
3916 /// <summary>発言検索に使用するメソッドを生成します</summary>
3917 /// <exception cref="ArgumentException">
3918 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3920 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3924 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3925 var regex = new Regex(query, regexOption);
3927 return x => regex.IsMatch(x);
3931 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3933 return x => x.IndexOf(query, comparisonType) != -1;
3937 private void AboutMenuItem_Click(object sender, EventArgs e)
3939 using (var about = new TweenAboutBox())
3941 about.ShowDialog(this);
3943 this.TopMost = this.settings.Common.AlwaysTop;
3946 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3948 var bgnIdx = this.statuses.SelectedTabIndex;
3950 if (this.ImageSelector.Enabled)
3953 TabModel? foundTab = null;
3957 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3959 var unreadIndex = tab.NextUnreadIndex;
3960 if (unreadIndex != -1)
3962 this.ListTab.SelectedIndex = index;
3964 foundIndex = unreadIndex;
3969 // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3970 if (foundTab == null && bgnIdx > 0)
3972 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3974 var unreadIndex = tab.NextUnreadIndex;
3975 if (unreadIndex != -1)
3977 this.ListTab.SelectedIndex = index;
3979 foundIndex = unreadIndex;
3985 DetailsListView lst;
3987 if (foundTab == null)
3989 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3990 this.ListTab.SelectedIndex = 0;
3991 var tabPage = this.ListTab.TabPages[0];
3992 var tab = this.statuses.Tabs[0];
3994 if (tab.AllCount == 0)
3997 if (this.statuses.SortOrder == SortOrder.Ascending)
3998 foundIndex = tab.AllCount - 1;
4002 lst = (DetailsListView)tabPage.Tag;
4006 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
4007 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
4010 this.SelectListItem(lst, foundIndex);
4012 if (this.statuses.SortMode == ComparerMode.Id)
4014 var rowHeight = lst.SmallImageList.ImageSize.Height;
4015 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
4016 this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
4022 lst.EnsureVisible(foundIndex);
4027 lst.EnsureVisible(foundIndex);
4033 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
4035 var tab = this.CurrentTab;
4036 var post = this.CurrentPost;
4037 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
4038 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
4041 private async void VerUpMenuItem_Click(object sender, EventArgs e)
4042 => await this.CheckNewVersion(false);
4044 private void RunTweenUp()
4046 var pinfo = new ProcessStartInfo
4048 UseShellExecute = true,
4049 WorkingDirectory = this.settings.SettingsPath,
4050 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
4051 Arguments = "\"" + Application.StartupPath + "\"",
4056 Process.Start(pinfo);
4060 MessageBox.Show("Failed to execute TweenUp3.exe.");
4064 public readonly record struct VersionInfo(
4071 /// OpenTween の最新バージョンの情報を取得します
4073 public async Task<VersionInfo> GetVersionInfoAsync()
4075 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
4076 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
4078 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
4079 .ConfigureAwait(false);
4081 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
4082 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
4084 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
4085 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
4087 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
4089 return new VersionInfo
4091 Version = Version.Parse(msgHeader[0]),
4092 DownloadUri = new Uri(msgHeader[1]),
4093 ReleaseNote = msgBody,
4097 private async Task CheckNewVersion(bool startup = false)
4099 if (ApplicationSettings.VersionInfoUrl == null)
4100 return; // 更新チェック無効化
4104 var versionInfo = await this.GetVersionInfoAsync();
4106 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4111 var msgtext = string.Format(
4112 Properties.Resources.CheckNewVersionText7,
4113 MyCommon.GetReadableVersion(),
4114 MyCommon.GetReadableVersion(versionInfo.Version));
4115 msgtext = MyCommon.ReplaceAppName(msgtext);
4119 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4120 MessageBoxButtons.OK,
4121 MessageBoxIcon.Information);
4126 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4129 using var dialog = new UpdateDialog();
4131 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4132 MyCommon.GetReadableVersion(versionInfo.Version));
4133 dialog.DetailsText = versionInfo.ReleaseNote;
4135 if (dialog.ShowDialog(this) == DialogResult.Yes)
4137 await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4139 else if (dialog.SkipButtonPressed)
4141 this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4142 this.MarkSettingCommonModified();
4147 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4151 Properties.Resources.CheckNewVersionText10,
4152 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4153 MessageBoxButtons.OK,
4154 MessageBoxIcon.Exclamation,
4155 MessageBoxDefaultButton.Button2);
4160 private void UpdateSelectedPost()
4162 // 件数関連の場合、タイトル即時書き換え
4163 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4164 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4165 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4166 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4168 this.SetMainWindowTitle();
4170 if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4171 this.SetStatusLabelUrl();
4173 if (this.settings.Common.TabIconDisp)
4175 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4177 if (tab.UnreadCount == 0)
4179 var tabPage = this.ListTab.TabPages[index];
4180 if (tabPage.ImageIndex == 0)
4181 tabPage.ImageIndex = -1;
4187 this.ListTab.Refresh();
4190 this.DispSelectedPost();
4193 public string CreateDetailHtml(string orgdata)
4194 => this.detailHtmlFormatPreparedTemplate.Replace("%CONTENT_HTML%", orgdata);
4196 private void DispSelectedPost()
4197 => this.DispSelectedPost(false);
4199 private PostClass displayPost = new();
4202 /// サムネイル表示に使用する CancellationToken の生成元
4204 private CancellationTokenSource? thumbnailTokenSource = null;
4206 private void DispSelectedPost(bool forceupdate)
4208 var currentPost = this.CurrentPost;
4209 if (currentPost == null)
4212 var oldDisplayPost = this.displayPost;
4213 this.displayPost = currentPost;
4215 if (!forceupdate && currentPost.Equals(oldDisplayPost))
4218 var loadTasks = new List<Task>
4220 this.tweetDetailsView.ShowPostDetails(currentPost),
4223 if (this.settings.Common.PreviewEnable)
4225 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4226 oldTokenSource?.Cancel();
4228 var token = this.thumbnailTokenSource!.Token;
4229 loadTasks.Add(this.PrepareThumbnailControl(currentPost, token));
4233 this.SplitContainer3.Panel2Collapsed = true;
4236 async Task DelayedTasks()
4240 await Task.WhenAll(loadTasks);
4242 catch (OperationCanceledException)
4247 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4251 private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4253 var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4255 var timeout = Task.Delay(100);
4256 if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4258 token.ThrowIfCancellationRequested();
4260 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4261 this.SplitContainer3.Panel2Collapsed = true;
4265 token.ThrowIfCancellationRequested();
4267 this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4270 private async void MatomeMenuItem_Click(object sender, EventArgs e)
4271 => await this.OpenApplicationWebsite();
4273 private async Task OpenApplicationWebsite()
4274 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4276 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4277 => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4279 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4281 var tab = this.CurrentTab;
4282 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4284 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4285 if (pnl.Controls["comboSearch"].Focused ||
4286 pnl.Controls["comboLang"].Focused ||
4287 pnl.Controls["buttonSearch"].Focused) return;
4290 if (e.Control || e.Shift || e.Alt)
4293 if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4296 e.SuppressKeyPress = true;
4299 if (asyncTask != null)
4303 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4305 private void InitializeShortcuts()
4307 this.shortcutCommands = new[]
4309 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4310 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4311 .FocusedOn(FocusedControl.ListTab)
4312 .Do(() => SendKeys.Send("{DOWN}")),
4314 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4315 .FocusedOn(FocusedControl.ListTab)
4316 .Do(() => SendKeys.Send("{UP}")),
4318 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4319 .FocusedOn(FocusedControl.ListTab)
4320 .Do(() => SendKeys.Send("{PGDN}")),
4322 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4323 .FocusedOn(FocusedControl.ListTab)
4324 .Do(() => SendKeys.Send("{PGUP}")),
4326 ShortcutCommand.Create(Keys.F1)
4327 .Do(() => this.OpenApplicationWebsite()),
4329 ShortcutCommand.Create(Keys.F3)
4330 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4332 ShortcutCommand.Create(Keys.F5)
4333 .Do(() => this.DoRefresh()),
4335 ShortcutCommand.Create(Keys.F6)
4336 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4338 ShortcutCommand.Create(Keys.F7)
4339 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4341 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4342 .NotFocusedOn(FocusedControl.StatusText)
4345 this.CurrentTab.ClearAnchor();
4346 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4349 ShortcutCommand.Create(Keys.G)
4350 .NotFocusedOn(FocusedControl.StatusText)
4353 this.CurrentTab.ClearAnchor();
4354 this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4357 ShortcutCommand.Create(Keys.Right, Keys.N)
4358 .FocusedOn(FocusedControl.ListTab)
4359 .Do(() => this.GoRelPost(forward: true)),
4361 ShortcutCommand.Create(Keys.Left, Keys.P)
4362 .FocusedOn(FocusedControl.ListTab)
4363 .Do(() => this.GoRelPost(forward: false)),
4365 ShortcutCommand.Create(Keys.OemPeriod)
4366 .FocusedOn(FocusedControl.ListTab)
4367 .Do(() => this.GoAnchor()),
4369 ShortcutCommand.Create(Keys.I)
4370 .FocusedOn(FocusedControl.ListTab)
4371 .OnlyWhen(() => this.StatusText.Enabled)
4372 .Do(() => this.StatusText.Focus()),
4374 ShortcutCommand.Create(Keys.Enter)
4375 .FocusedOn(FocusedControl.ListTab)
4376 .Do(() => this.ListItemDoubleClickAction()),
4378 ShortcutCommand.Create(Keys.R)
4379 .FocusedOn(FocusedControl.ListTab)
4380 .Do(() => this.DoRefresh()),
4382 ShortcutCommand.Create(Keys.L)
4383 .FocusedOn(FocusedControl.ListTab)
4386 this.CurrentTab.ClearAnchor();
4387 this.GoPost(forward: true);
4390 ShortcutCommand.Create(Keys.H)
4391 .FocusedOn(FocusedControl.ListTab)
4394 this.CurrentTab.ClearAnchor();
4395 this.GoPost(forward: false);
4398 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4399 .FocusedOn(FocusedControl.ListTab)
4402 this.CurrentTab.ClearAnchor();
4406 ShortcutCommand.Create(Keys.S)
4407 .FocusedOn(FocusedControl.ListTab)
4410 this.CurrentTab.ClearAnchor();
4411 this.GoNextTab(forward: true);
4414 ShortcutCommand.Create(Keys.A)
4415 .FocusedOn(FocusedControl.ListTab)
4418 this.CurrentTab.ClearAnchor();
4419 this.GoNextTab(forward: false);
4422 // ] in_reply_to参照元へ戻る
4423 ShortcutCommand.Create(Keys.Oem4)
4424 .FocusedOn(FocusedControl.ListTab)
4427 this.CurrentTab.ClearAnchor();
4428 return this.GoInReplyToPostTree();
4431 // [ in_reply_toへジャンプ
4432 ShortcutCommand.Create(Keys.Oem6)
4433 .FocusedOn(FocusedControl.ListTab)
4436 this.CurrentTab.ClearAnchor();
4437 this.GoBackInReplyToPostTree();
4440 ShortcutCommand.Create(Keys.Escape)
4441 .FocusedOn(FocusedControl.ListTab)
4444 this.CurrentTab.ClearAnchor();
4445 var tab = this.CurrentTab;
4446 var tabtype = tab.TabType;
4447 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4449 this.RemoveSpecifiedTab(tab.TabName, false);
4450 this.SaveConfigsTabs();
4454 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4455 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4456 .FocusedOn(FocusedControl.ListTab)
4457 .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4459 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4460 ShortcutCommand.Create(Keys.Up, Keys.Down)
4461 .FocusedOn(FocusedControl.PostBrowser)
4464 ShortcutCommand.Create(Keys.Control | Keys.R)
4465 .Do(() => this.MakeReplyText()),
4467 ShortcutCommand.Create(Keys.Control | Keys.D)
4468 .Do(() => this.DoStatusDelete()),
4470 ShortcutCommand.Create(Keys.Control | Keys.M)
4471 .Do(() => this.MakeDirectMessageText()),
4473 ShortcutCommand.Create(Keys.Control | Keys.S)
4474 .Do(() => this.FavoriteChange(favAdd: true)),
4476 ShortcutCommand.Create(Keys.Control | Keys.I)
4477 .Do(() => this.DoRepliedStatusOpen()),
4479 ShortcutCommand.Create(Keys.Control | Keys.Q)
4480 .Do(() => this.DoQuoteOfficial()),
4482 ShortcutCommand.Create(Keys.Control | Keys.B)
4483 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4485 ShortcutCommand.Create(Keys.Control | Keys.T)
4486 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4488 ShortcutCommand.Create(Keys.Control | Keys.L)
4489 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4491 ShortcutCommand.Create(Keys.Control | Keys.Y)
4492 .NotFocusedOn(FocusedControl.PostBrowser)
4493 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4495 ShortcutCommand.Create(Keys.Control | Keys.F)
4496 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4498 ShortcutCommand.Create(Keys.Control | Keys.U)
4499 .Do(() => this.ShowUserTimeline()),
4501 ShortcutCommand.Create(Keys.Control | Keys.H)
4502 .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4504 ShortcutCommand.Create(Keys.Control | Keys.O)
4505 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4507 ShortcutCommand.Create(Keys.Control | Keys.E)
4508 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4510 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4511 .FocusedOn(FocusedControl.ListTab)
4512 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4514 ShortcutCommand.Create(Keys.Control | Keys.N)
4515 .FocusedOn(FocusedControl.ListTab)
4516 .Do(() => this.GoNextTab(forward: true)),
4518 ShortcutCommand.Create(Keys.Control | Keys.P)
4519 .FocusedOn(FocusedControl.ListTab)
4520 .Do(() => this.GoNextTab(forward: false)),
4522 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4523 .FocusedOn(FocusedControl.ListTab)
4524 .Do(() => this.CopyStot()),
4526 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4527 ShortcutCommand.Create(Keys.Control | Keys.D1)
4528 .FocusedOn(FocusedControl.ListTab)
4529 .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4530 .Do(() => this.ListTab.SelectedIndex = 0),
4532 ShortcutCommand.Create(Keys.Control | Keys.D2)
4533 .FocusedOn(FocusedControl.ListTab)
4534 .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4535 .Do(() => this.ListTab.SelectedIndex = 1),
4537 ShortcutCommand.Create(Keys.Control | Keys.D3)
4538 .FocusedOn(FocusedControl.ListTab)
4539 .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4540 .Do(() => this.ListTab.SelectedIndex = 2),
4542 ShortcutCommand.Create(Keys.Control | Keys.D4)
4543 .FocusedOn(FocusedControl.ListTab)
4544 .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4545 .Do(() => this.ListTab.SelectedIndex = 3),
4547 ShortcutCommand.Create(Keys.Control | Keys.D5)
4548 .FocusedOn(FocusedControl.ListTab)
4549 .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4550 .Do(() => this.ListTab.SelectedIndex = 4),
4552 ShortcutCommand.Create(Keys.Control | Keys.D6)
4553 .FocusedOn(FocusedControl.ListTab)
4554 .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4555 .Do(() => this.ListTab.SelectedIndex = 5),
4557 ShortcutCommand.Create(Keys.Control | Keys.D7)
4558 .FocusedOn(FocusedControl.ListTab)
4559 .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4560 .Do(() => this.ListTab.SelectedIndex = 6),
4562 ShortcutCommand.Create(Keys.Control | Keys.D8)
4563 .FocusedOn(FocusedControl.ListTab)
4564 .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4565 .Do(() => this.ListTab.SelectedIndex = 7),
4567 ShortcutCommand.Create(Keys.Control | Keys.D9)
4568 .FocusedOn(FocusedControl.ListTab)
4569 .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4571 ShortcutCommand.Create(Keys.Control | Keys.A)
4572 .FocusedOn(FocusedControl.StatusText)
4573 .Do(() => this.StatusText.SelectAll()),
4575 ShortcutCommand.Create(Keys.Control | Keys.V)
4576 .FocusedOn(FocusedControl.StatusText)
4577 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4579 ShortcutCommand.Create(Keys.Control | Keys.Up)
4580 .FocusedOn(FocusedControl.StatusText)
4581 .Do(() => this.StatusTextHistoryBack()),
4583 ShortcutCommand.Create(Keys.Control | Keys.Down)
4584 .FocusedOn(FocusedControl.StatusText)
4585 .Do(() => this.StatusTextHistoryForward()),
4587 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4588 .FocusedOn(FocusedControl.StatusText)
4591 if (this.ListTab.SelectedIndex == 0)
4593 this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4597 this.ListTab.SelectedIndex -= 1;
4599 this.StatusText.Focus();
4602 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4603 .FocusedOn(FocusedControl.StatusText)
4606 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4608 this.ListTab.SelectedIndex = 0;
4612 this.ListTab.SelectedIndex += 1;
4614 this.StatusText.Focus();
4617 ShortcutCommand.Create(Keys.Control | Keys.Y)
4618 .FocusedOn(FocusedControl.PostBrowser)
4621 var multiline = !this.settings.Local.StatusMultiline;
4622 this.settings.Local.StatusMultiline = multiline;
4623 this.MultiLineMenuItem.Checked = multiline;
4624 this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4627 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4628 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4630 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4631 .Do(() => this.DoRefreshMore()),
4633 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4634 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4636 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4637 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4639 ShortcutCommand.Create(Keys.Shift | Keys.R)
4640 .NotFocusedOn(FocusedControl.StatusText)
4641 .Do(() => this.DoRefreshMore()),
4643 ShortcutCommand.Create(Keys.Shift | Keys.H)
4644 .FocusedOn(FocusedControl.ListTab)
4645 .Do(() => this.GoTopEnd(goTop: true)),
4647 ShortcutCommand.Create(Keys.Shift | Keys.L)
4648 .FocusedOn(FocusedControl.ListTab)
4649 .Do(() => this.GoTopEnd(goTop: false)),
4651 ShortcutCommand.Create(Keys.Shift | Keys.M)
4652 .FocusedOn(FocusedControl.ListTab)
4653 .Do(() => this.GoMiddle()),
4655 ShortcutCommand.Create(Keys.Shift | Keys.G)
4656 .FocusedOn(FocusedControl.ListTab)
4657 .Do(() => this.GoLast()),
4659 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4660 .FocusedOn(FocusedControl.ListTab)
4661 .Do(() => this.MoveMiddle()),
4663 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4664 .FocusedOn(FocusedControl.ListTab)
4665 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4667 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4668 .FocusedOn(FocusedControl.ListTab)
4669 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4671 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4672 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4673 .FocusedOn(FocusedControl.ListTab)
4674 .Do(() => this.GoFav(forward: true)),
4676 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4677 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4678 .FocusedOn(FocusedControl.ListTab)
4679 .Do(() => this.GoFav(forward: false)),
4681 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4682 .FocusedOn(FocusedControl.ListTab)
4683 .Do(() => this.GoBackSelectPostChain()),
4685 ShortcutCommand.Create(Keys.Alt | Keys.R)
4686 .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4688 ShortcutCommand.Create(Keys.Alt | Keys.P)
4689 .OnlyWhen(() => this.CurrentPost != null)
4690 .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4692 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4693 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4695 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4696 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4698 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4699 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4701 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4702 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4704 // 別タブの同じ書き込みへ(ALT+←/→)
4705 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4706 .FocusedOn(FocusedControl.ListTab)
4707 .Do(() => this.GoSamePostToAnotherTab(left: false)),
4709 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4710 .FocusedOn(FocusedControl.ListTab)
4711 .Do(() => this.GoSamePostToAnotherTab(left: true)),
4713 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4714 .Do(() => this.MakeReplyText(atAll: true)),
4716 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4717 .Do(() => this.CopyIdUri()),
4719 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4720 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4721 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4723 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4724 .Do(() => this.DoQuoteOfficial()),
4726 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4727 .Do(() => this.FavoriteChange(favAdd: false)),
4729 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4730 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4732 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4733 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4735 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4736 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4738 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4739 .Do(() => this.DoMoveToRTHome()),
4741 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4742 .FocusedOn(FocusedControl.StatusText)
4745 var tab = this.CurrentTab;
4746 var selectedIndex = tab.SelectedIndex;
4747 if (selectedIndex != -1 && selectedIndex > 0)
4749 var listView = this.CurrentListView;
4750 var idx = selectedIndex - 1;
4751 this.SelectListItem(listView, idx);
4752 listView.EnsureVisible(idx);
4756 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4757 .FocusedOn(FocusedControl.StatusText)
4760 var tab = this.CurrentTab;
4761 var selectedIndex = tab.SelectedIndex;
4762 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4764 var listView = this.CurrentListView;
4765 var idx = selectedIndex + 1;
4766 this.SelectListItem(listView, idx);
4767 listView.EnsureVisible(idx);
4771 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4772 .FocusedOn(FocusedControl.StatusText)
4775 if (this.StatusText.SelectionStart > 0)
4777 var endidx = this.StatusText.SelectionStart - 1;
4779 for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4781 var c = this.StatusText.Text[i];
4782 if (char.IsLetterOrDigit(c) || c == '_')
4788 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4789 var cnt = this.AtIdSupl.ItemCount;
4790 this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4791 if (this.AtIdSupl.ItemCount != cnt)
4792 this.MarkSettingAtIdModified();
4796 startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4797 this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4807 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4808 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4809 .FocusedOn(FocusedControl.ListTab)
4810 .Do(() => this.SetSortColumnByDisplayIndex(0)),
4812 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4813 .FocusedOn(FocusedControl.ListTab)
4814 .Do(() => this.SetSortColumnByDisplayIndex(1)),
4816 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4817 .FocusedOn(FocusedControl.ListTab)
4818 .Do(() => this.SetSortColumnByDisplayIndex(2)),
4820 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4821 .FocusedOn(FocusedControl.ListTab)
4822 .Do(() => this.SetSortColumnByDisplayIndex(3)),
4824 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4825 .FocusedOn(FocusedControl.ListTab)
4826 .Do(() => this.SetSortColumnByDisplayIndex(4)),
4828 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4829 .FocusedOn(FocusedControl.ListTab)
4830 .Do(() => this.SetSortColumnByDisplayIndex(5)),
4832 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4833 .FocusedOn(FocusedControl.ListTab)
4834 .Do(() => this.SetSortColumnByDisplayIndex(6)),
4836 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4837 .FocusedOn(FocusedControl.ListTab)
4838 .Do(() => this.SetSortColumnByDisplayIndex(7)),
4840 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4841 .FocusedOn(FocusedControl.ListTab)
4842 .Do(() => this.SetSortLastColumn()),
4844 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4845 .FocusedOn(FocusedControl.ListTab)
4846 .Do(() => this.FavoritesRetweetOfficial()),
4848 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4849 .FocusedOn(FocusedControl.ListTab)
4850 .Do(() => this.FavoritesRetweetUnofficial()),
4852 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4853 .FocusedOn(FocusedControl.ListTab)
4854 .Do(() => this.OpenUserAppointUrl()),
4856 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4857 .FocusedOn(FocusedControl.PostBrowser)
4858 .Do(() => this.DoReTweetUnofficial()),
4860 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4861 .OnlyWhen(() => this.ExistCurrentPost)
4862 .Do(() => this.tweetDetailsView.DoTranslation()),
4864 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4865 .Do(() => this.DoReTweetUnofficial()),
4867 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4868 .Do(() => this.CopyUserId()),
4870 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4871 .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4873 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4874 .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4876 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4877 .FocusedOn(FocusedControl.ListTab)
4878 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4879 .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4883 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4885 // Task を返す非同期処理があれば asyncTask に代入する
4888 // ShortcutCommand に対応しているコマンドはここで処理される
4889 foreach (var command in this.shortcutCommands)
4891 if (command.IsMatch(keyData, focusedOn))
4893 asyncTask = command.RunCommand();
4894 return command.PreventDefault;
4901 private void GoNextTab(bool forward)
4903 var idx = this.statuses.SelectedTabIndex;
4904 var tabCount = this.statuses.Tabs.Count;
4908 if (idx > tabCount - 1) idx = 0;
4913 if (idx < 0) idx = tabCount - 1;
4915 this.ListTab.SelectedIndex = idx;
4918 private void CopyStot()
4920 var sb = new StringBuilder();
4921 var tab = this.CurrentTab;
4922 var isProtected = false;
4923 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4924 foreach (var post in tab.SelectedPosts)
4926 if (post.IsDeleted) continue;
4929 if (post.RetweetedId != null)
4930 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4932 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4936 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4941 MessageBox.Show(Properties.Resources.CopyStotText1);
4945 var clstr = sb.ToString();
4948 Clipboard.SetDataObject(clstr, false, 5, 100);
4950 catch (Exception ex)
4952 MessageBox.Show(ex.Message);
4957 private void CopyIdUri()
4959 var tab = this.CurrentTab;
4960 if (tab == null || tab is DirectMessagesTabModel)
4963 var copyUrls = new List<string>();
4964 foreach (var post in tab.SelectedPosts)
4965 copyUrls.Add(MyCommon.GetStatusUrl(post));
4967 if (copyUrls.Count == 0)
4972 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4974 catch (ExternalException ex)
4976 MessageBox.Show(ex.Message);
4980 private void GoFav(bool forward)
4982 var tab = this.CurrentTab;
4983 if (tab.AllCount == 0)
4986 var selectedIndex = tab.SelectedIndex;
4994 if (selectedIndex == -1)
5000 fIdx = selectedIndex + 1;
5001 if (fIdx > tab.AllCount - 1)
5004 toIdx = tab.AllCount;
5009 if (selectedIndex == -1)
5011 fIdx = tab.AllCount - 1;
5015 fIdx = selectedIndex - 1;
5023 for (var idx = fIdx; idx != toIdx; idx += stp)
5027 var listView = this.CurrentListView;
5028 this.SelectListItem(listView, idx);
5029 listView.EnsureVisible(idx);
5035 private void GoSamePostToAnotherTab(bool left)
5037 var tab = this.CurrentTab;
5039 // Directタブは対象外(見つかるはずがない)
5040 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
5043 var selectedStatusId = tab.SelectedStatusId;
5044 if (selectedStatusId == null)
5047 int fIdx, toIdx, stp;
5052 if (this.ListTab.SelectedIndex == 0)
5058 fIdx = this.ListTab.SelectedIndex - 1;
5066 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
5072 fIdx = this.ListTab.SelectedIndex + 1;
5074 toIdx = this.ListTab.TabCount;
5078 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
5080 var targetTab = this.statuses.Tabs[tabidx];
5083 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
5086 var foundIndex = targetTab.IndexOf(selectedStatusId);
5087 if (foundIndex != -1)
5089 this.ListTab.SelectedIndex = tabidx;
5090 var listView = this.CurrentListView;
5091 this.SelectListItem(listView, foundIndex);
5092 listView.EnsureVisible(foundIndex);
5098 private void GoPost(bool forward)
5100 var tab = this.CurrentTab;
5101 var currentPost = this.CurrentPost;
5103 if (currentPost == null)
5106 var selectedIndex = tab.SelectedIndex;
5108 int fIdx, toIdx, stp;
5112 fIdx = selectedIndex + 1;
5113 if (fIdx > tab.AllCount - 1) return;
5114 toIdx = tab.AllCount;
5119 fIdx = selectedIndex - 1;
5120 if (fIdx < 0) return;
5126 if (currentPost.RetweetedBy == null)
5128 name = currentPost.ScreenName;
5132 name = currentPost.RetweetedBy;
5134 for (var idx = fIdx; idx != toIdx; idx += stp)
5136 var post = tab[idx];
5137 if (post.RetweetedId == null)
5139 if (post.ScreenName == name)
5141 var listView = this.CurrentListView;
5142 this.SelectListItem(listView, idx);
5143 listView.EnsureVisible(idx);
5149 if (post.RetweetedBy == name)
5151 var listView = this.CurrentListView;
5152 this.SelectListItem(listView, idx);
5153 listView.EnsureVisible(idx);
5160 private void GoRelPost(bool forward)
5162 var tab = this.CurrentTab;
5163 var selectedIndex = tab.SelectedIndex;
5165 if (selectedIndex == -1)
5168 int fIdx, toIdx, stp;
5172 fIdx = selectedIndex + 1;
5173 if (fIdx > tab.AllCount - 1) return;
5174 toIdx = tab.AllCount;
5179 fIdx = selectedIndex - 1;
5180 if (fIdx < 0) return;
5185 var anchorPost = tab.AnchorPost;
5186 if (anchorPost == null)
5188 var currentPost = this.CurrentPost;
5189 if (currentPost == null)
5192 anchorPost = currentPost;
5193 tab.AnchorPost = currentPost;
5196 for (var idx = fIdx; idx != toIdx; idx += stp)
5198 var post = tab[idx];
5199 if (post.ScreenName == anchorPost.ScreenName ||
5200 post.RetweetedBy == anchorPost.ScreenName ||
5201 post.ScreenName == anchorPost.RetweetedBy ||
5202 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5203 anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5204 anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5205 post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5206 post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5208 var listView = this.CurrentListView;
5209 this.SelectListItem(listView, idx);
5210 listView.EnsureVisible(idx);
5216 private void GoAnchor()
5218 var anchorStatusId = this.CurrentTab.AnchorStatusId;
5219 if (anchorStatusId == null)
5222 var idx = this.CurrentTab.IndexOf(anchorStatusId);
5226 var listView = this.CurrentListView;
5227 this.SelectListItem(listView, idx);
5228 listView.EnsureVisible(idx);
5231 private void GoTopEnd(bool goTop)
5233 var listView = this.CurrentListView;
5234 if (listView.VirtualListSize == 0)
5242 item = listView.GetItemAt(0, 25);
5250 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5252 idx = listView.VirtualListSize - 1;
5256 this.SelectListItem(listView, idx);
5259 private void GoMiddle()
5261 var listView = this.CurrentListView;
5262 if (listView.VirtualListSize == 0)
5270 item = listView.GetItemAt(0, 0);
5280 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5283 idx2 = listView.VirtualListSize - 1;
5289 idx3 = (idx1 + idx2) / 2;
5291 this.SelectListItem(listView, idx3);
5294 private void GoLast()
5296 var listView = this.CurrentListView;
5297 if (listView.VirtualListSize == 0) return;
5299 if (this.statuses.SortOrder == SortOrder.Ascending)
5301 this.SelectListItem(listView, listView.VirtualListSize - 1);
5302 listView.EnsureVisible(listView.VirtualListSize - 1);
5306 this.SelectListItem(listView, 0);
5307 listView.EnsureVisible(0);
5311 private void MoveTop()
5313 var listView = this.CurrentListView;
5314 if (listView.SelectedIndices.Count == 0) return;
5315 var idx = listView.SelectedIndices[0];
5316 if (this.statuses.SortOrder == SortOrder.Ascending)
5318 listView.EnsureVisible(listView.VirtualListSize - 1);
5322 listView.EnsureVisible(0);
5324 listView.EnsureVisible(idx);
5327 private async Task GoInReplyToPostTree()
5329 var curTabClass = this.CurrentTab;
5330 var currentPost = this.CurrentPost;
5332 if (currentPost == null)
5335 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5339 var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5341 currentPost = currentPost with
5343 InReplyToStatusId = post.InReplyToStatusId,
5344 InReplyToUser = post.InReplyToUser,
5345 IsReply = post.IsReply,
5347 curTabClass.ReplacePost(currentPost);
5348 this.listCache?.PurgeCache();
5350 var index = curTabClass.SelectedIndex;
5351 this.CurrentListView.RedrawItems(index, index, false);
5353 catch (WebApiException ex)
5355 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5359 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5361 if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5363 this.replyChains = new Stack<ReplyChain>();
5365 this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5368 string inReplyToTabName;
5369 var inReplyToId = currentPost.InReplyToStatusId;
5370 var inReplyToUser = currentPost.InReplyToUser;
5372 var inReplyToPosts = from tab in this.statuses.Tabs
5373 orderby tab != curTabClass
5374 from post in tab.Posts.Values
5375 where post.StatusId == inReplyToId
5376 let index = tab.IndexOf(post.StatusId)
5378 select new { Tab = tab, Index = index };
5380 var inReplyPost = inReplyToPosts.FirstOrDefault();
5381 if (inReplyPost == null)
5385 await Task.Run(async () =>
5387 var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5388 .ConfigureAwait(false);
5391 this.statuses.AddPost(post);
5392 this.statuses.DistributePosts();
5395 catch (WebApiException ex)
5397 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5398 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5402 this.RefreshTimeline();
5404 inReplyPost = inReplyToPosts.FirstOrDefault();
5405 if (inReplyPost == null)
5407 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5411 inReplyToTabName = inReplyPost.Tab.TabName;
5412 inReplyToIndex = inReplyPost.Index;
5414 var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5415 var tabPage = this.ListTab.TabPages[tabIndex];
5416 var listView = (DetailsListView)tabPage.Tag;
5418 if (this.CurrentTabName != inReplyToTabName)
5420 this.ListTab.SelectedIndex = tabIndex;
5423 this.SelectListItem(listView, inReplyToIndex);
5424 listView.EnsureVisible(inReplyToIndex);
5427 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5429 var curTabClass = this.CurrentTab;
5430 var currentPost = this.CurrentPost;
5432 if (currentPost == null)
5437 if (currentPost.InReplyToStatusId != null)
5439 var posts = from t in this.statuses.Tabs
5441 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5442 let indexOf = t.IndexOf(p.Value.StatusId)
5444 orderby isForward ? indexOf : indexOf * -1
5445 orderby t != curTabClass
5446 select new { Tab = t, Post = p.Value, Index = indexOf };
5449 var postList = posts.ToList();
5450 for (var i = postList.Count - 1; i >= 0; i--)
5453 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5455 postList.RemoveAt(index);
5458 var currentIndex = this.CurrentTab.SelectedIndex;
5459 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5460 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5461 if (post == null) post = postList.First();
5462 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5463 this.ListTab.SelectedIndex = tabIndex;
5464 var listView = this.CurrentListView;
5465 this.SelectListItem(listView, post.Index);
5466 listView.EnsureVisible(post.Index);
5468 catch (InvalidOperationException)
5476 if (this.replyChains == null || this.replyChains.Count < 1)
5478 var posts = from t in this.statuses.Tabs
5480 where p.Value.InReplyToStatusId == currentPost.StatusId
5481 let indexOf = t.IndexOf(p.Value.StatusId)
5484 orderby t != curTabClass
5485 select new { Tab = t, Index = indexOf };
5488 var post = posts.First();
5489 var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5490 this.ListTab.SelectedIndex = tabIndex;
5491 var listView = this.CurrentListView;
5492 this.SelectListItem(listView, post.Index);
5493 listView.EnsureVisible(post.Index);
5495 catch (InvalidOperationException)
5502 var chainHead = this.replyChains.Pop();
5503 if (chainHead.InReplyToId == currentPost.StatusId)
5505 var tab = chainHead.OriginalTab;
5506 if (!this.statuses.Tabs.Contains(tab))
5508 this.replyChains = null;
5512 var idx = tab.IndexOf(chainHead.OriginalId);
5515 this.replyChains = null;
5519 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5522 this.ListTab.SelectedIndex = tabIndex;
5526 this.replyChains = null;
5528 var listView = this.CurrentListView;
5529 this.SelectListItem(listView, idx);
5530 listView.EnsureVisible(idx);
5536 this.replyChains = null;
5537 this.GoBackInReplyToPostTree(parallel);
5543 private void GoBackSelectPostChain()
5545 if (this.selectPostChains.Count > 1)
5548 TabModel? foundTab = null;
5554 this.selectPostChains.Pop();
5555 var (tab, post) = this.selectPostChains.Peek();
5557 if (!this.statuses.Tabs.Contains(tab))
5558 continue; // 該当タブが存在しないので無視
5562 idx = tab.IndexOf(post.StatusId);
5563 if (idx == -1) continue; // 該当ポストが存在しないので無視
5568 this.selectPostChains.Pop();
5570 catch (InvalidOperationException)
5576 while (this.selectPostChains.Count > 1);
5578 if (foundTab == null)
5581 // 履歴が残り1つであればクリアしておく
5582 if (this.selectPostChains.Count == 1)
5583 this.selectPostChains.Clear();
5587 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5588 var tabPage = this.ListTab.TabPages[tabIndex];
5589 var lst = (DetailsListView)tabPage.Tag;
5590 this.ListTab.SelectedIndex = tabIndex;
5594 this.SelectListItem(lst, idx);
5595 lst.EnsureVisible(idx);
5601 private void PushSelectPostChain()
5603 var currentTab = this.CurrentTab;
5604 var currentPost = this.CurrentPost;
5606 var count = this.selectPostChains.Count;
5609 var (tab, post) = this.selectPostChains.Peek();
5610 if (tab == currentTab)
5612 if (post == currentPost) return; // 最新の履歴と同一
5613 if (post == null) this.selectPostChains.Pop(); // 置き換えるため削除
5616 if (count >= 2500) this.TrimPostChain();
5617 this.selectPostChains.Push((currentTab, currentPost));
5620 private void TrimPostChain()
5622 if (this.selectPostChains.Count <= 2000) return;
5623 var p = new Stack<(TabModel, PostClass?)>(2000);
5624 for (var i = 0; i < 2000; i++)
5626 p.Push(this.selectPostChains.Pop());
5628 this.selectPostChains.Clear();
5629 for (var i = 0; i < 2000; i++)
5631 this.selectPostChains.Push(p.Pop());
5635 private bool GoStatus(PostId statusId)
5637 var tab = this.statuses.Tabs
5638 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5639 .Where(x => x.Contains(statusId))
5645 var index = tab.IndexOf(statusId);
5647 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5648 this.ListTab.SelectedIndex = tabIndex;
5650 var listView = this.CurrentListView;
5651 this.SelectListItem(listView, index);
5652 listView.EnsureVisible(index);
5657 private bool GoDirectMessage(PostId statusId)
5659 var tab = this.statuses.DirectMessageTab;
5660 var index = tab.IndexOf(statusId);
5665 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5666 this.ListTab.SelectedIndex = tabIndex;
5668 var listView = this.CurrentListView;
5669 this.SelectListItem(listView, index);
5670 listView.EnsureVisible(index);
5675 private void MyList_MouseClick(object sender, MouseEventArgs e)
5676 => this.CurrentTab.ClearAnchor();
5678 private void StatusText_Enter(object sender, EventArgs e)
5680 // フォーカスの戻り先を StatusText に設定
5681 this.Tag = this.StatusText;
5682 this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5685 public Color InputBackColor
5686 => this.themeManager.ColorInputBackcolor;
5688 private void StatusText_Leave(object sender, EventArgs e)
5690 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5691 if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5692 this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5695 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5697 if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5700 e.SuppressKeyPress = true;
5703 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5705 if (asyncTask != null)
5709 private void SaveConfigsAll(bool ifModified)
5713 this.SaveConfigsCommon();
5714 this.SaveConfigsLocal();
5715 this.SaveConfigsTabs();
5716 this.SaveConfigsAtId();
5720 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5721 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5722 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5726 private void SaveConfigsAtId()
5728 if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5730 this.ModifySettingAtId = false;
5731 this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5732 this.settings.SaveAtIdList();
5735 private void SaveConfigsCommon()
5737 if (this.ignoreConfigSave) return;
5739 this.ModifySettingCommon = false;
5740 lock (this.syncObject)
5742 this.settings.Common.UserName = this.tw.Username;
5743 this.settings.Common.UserId = this.tw.UserId;
5744 this.settings.Common.Token = this.tw.AccessToken;
5745 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5746 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5747 this.settings.Common.SortColumn = this.statuses.SortMode switch
5749 ComparerMode.Nickname => 1, // ニックネーム
5750 ComparerMode.Data => 2, // 本文
5751 ComparerMode.Id => 3, // 時刻=発言Id
5752 ComparerMode.Name => 4, // 名前
5753 ComparerMode.Source => 7, // Source
5754 _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5756 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5757 if (this.HashMgr.IsPermanent)
5759 this.settings.Common.HashSelected = this.HashMgr.UseHash;
5763 this.settings.Common.HashSelected = "";
5765 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5766 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5767 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5768 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5769 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5771 this.settings.SaveCommon();
5775 private void SaveConfigsLocal()
5777 if (this.ignoreConfigSave) return;
5778 lock (this.syncObject)
5780 this.ModifySettingLocal = false;
5781 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5782 this.settings.Local.FormSize = this.mySize;
5783 this.settings.Local.FormLocation = this.myLoc;
5784 this.settings.Local.SplitterDistance = this.mySpDis;
5785 this.settings.Local.PreviewDistance = this.mySpDis3;
5786 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5787 this.settings.Local.StatusTextHeight = this.mySpDis2;
5789 if (this.ignoreConfigSave) return;
5790 this.settings.SaveLocal();
5794 private void SaveConfigsTabs()
5796 var tabSettingList = new List<SettingTabs.SettingTabItem>();
5798 var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5800 foreach (var tab in tabs)
5802 if (!tab.IsPermanentTabType)
5805 var tabSetting = new SettingTabs.SettingTabItem
5807 TabName = tab.TabName,
5808 TabType = tab.TabType,
5809 UnreadManage = tab.UnreadManage,
5810 Protected = tab.Protected,
5811 Notify = tab.Notify,
5812 SoundFile = tab.SoundFile,
5817 case FilterTabModel filterTab:
5818 tabSetting.FilterArray = filterTab.FilterArray;
5820 case UserTimelineTabModel userTab:
5821 tabSetting.User = userTab.ScreenName;
5823 case PublicSearchTabModel searchTab:
5824 tabSetting.SearchWords = searchTab.SearchWords;
5825 tabSetting.SearchLang = searchTab.SearchLang;
5827 case ListTimelineTabModel listTab:
5828 tabSetting.ListInfo = listTab.ListInfo;
5832 tabSettingList.Add(tabSetting);
5835 this.settings.Tabs.Tabs = tabSettingList;
5836 this.settings.SaveTabs();
5839 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5841 static void ShowFormatErrorDialog(IWin32Window owner)
5845 Properties.Resources.OpenURL_InvalidFormat,
5846 Properties.Resources.OpenURL_Caption,
5847 MessageBoxButtons.OK,
5848 MessageBoxIcon.Error
5852 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5853 if (ret != DialogResult.OK)
5856 var match = Twitter.StatusUrlRegex.Match(inputText);
5859 ShowFormatErrorDialog(this);
5865 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5866 await this.OpenRelatedTab(statusId);
5868 catch (OverflowException)
5870 ShowFormatErrorDialog(this);
5872 catch (TabException ex)
5874 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5878 private void SaveLogMenuItem_Click(object sender, EventArgs e)
5880 var tab = this.CurrentTab;
5882 var rslt = MessageBox.Show(
5883 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5884 Properties.Resources.SaveLogMenuItem_ClickText2,
5885 MessageBoxButtons.YesNoCancel,
5886 MessageBoxIcon.Question);
5887 if (rslt == DialogResult.Cancel) return;
5889 this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5890 this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5891 this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5892 this.SaveFileDialog1.FilterIndex = 0;
5893 this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5894 this.SaveFileDialog1.RestoreDirectory = true;
5896 if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5898 if (!this.SaveFileDialog1.ValidateNames) return;
5899 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5900 if (rslt == DialogResult.Yes)
5903 for (var idx = 0; idx < tab.AllCount; idx++)
5905 var post = tab[idx];
5908 protect = "Protect";
5909 sw.WriteLine(post.Nickname + "\t" +
5910 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5911 post.CreatedAt.ToLocalTimeString() + "\t" +
5912 post.ScreenName + "\t" +
5913 post.StatusId.Id + "\t" +
5914 post.ImageUrl + "\t" +
5915 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5921 foreach (var post in this.CurrentTab.SelectedPosts)
5925 protect = "Protect";
5926 sw.WriteLine(post.Nickname + "\t" +
5927 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5928 post.CreatedAt.ToLocalTimeString() + "\t" +
5929 post.ScreenName + "\t" +
5930 post.StatusId.Id + "\t" +
5931 post.ImageUrl + "\t" +
5932 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5937 this.TopMost = this.settings.Common.AlwaysTop;
5940 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5944 using (var inputName = new InputTabName())
5946 inputName.TabName = origTabName;
5947 inputName.ShowDialog();
5948 if (inputName.DialogResult == DialogResult.Cancel) return false;
5949 newTabName = inputName.TabName;
5951 this.TopMost = this.settings.Common.AlwaysTop;
5952 if (!MyCommon.IsNullOrEmpty(newTabName))
5955 if (this.statuses.ContainsTab(newTabName))
5957 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5958 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5962 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5963 var tabPage = this.ListTab.TabPages[tabIndex];
5966 if (tabPage != null)
5967 tabPage.Text = newTabName;
5969 this.statuses.RenameTab(origTabName, newTabName);
5971 var state = this.listViewState[origTabName];
5972 this.listViewState.Remove(origTabName);
5973 this.listViewState[newTabName] = state;
5975 this.SaveConfigsCommon();
5976 this.SaveConfigsTabs();
5977 this.rclickTabName = newTabName;
5986 private void ListTab_MouseClick(object sender, MouseEventArgs e)
5988 if (e.Button == MouseButtons.Middle)
5990 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5992 if (this.ListTab.GetTabRect(index).Contains(e.Location))
5994 this.RemoveSpecifiedTab(tab.TabName, true);
5995 this.SaveConfigsTabs();
6002 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
6003 => this.TabRename(this.CurrentTabName, out _);
6005 private void ListTab_MouseDown(object sender, MouseEventArgs e)
6007 if (this.settings.Common.TabMouseLock) return;
6008 if (e.Button == MouseButtons.Left)
6010 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
6012 if (this.ListTab.GetTabRect(i).Contains(e.Location))
6014 this.tabDrag = true;
6015 this.tabMouseDownPoint = e.Location;
6022 this.tabDrag = false;
6026 private void ListTab_DragEnter(object sender, DragEventArgs e)
6028 if (e.Data.GetDataPresent(typeof(TabPage)))
6029 e.Effect = DragDropEffects.Move;
6031 e.Effect = DragDropEffects.None;
6034 private void ListTab_DragDrop(object sender, DragEventArgs e)
6036 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
6038 this.tabDrag = false;
6041 var cpos = new Point(e.X, e.Y);
6042 var spos = this.ListTab.PointToClient(cpos);
6043 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6045 var rect = this.ListTab.GetTabRect(index);
6046 if (rect.Contains(spos))
6049 if (spos.X <= (rect.Left + rect.Right) / 2)
6058 // タブのないところにドロップ->最後尾へ移動
6059 if (MyCommon.IsNullOrEmpty(tn))
6061 var lastTab = this.statuses.Tabs.Last();
6062 tn = lastTab.TabName;
6066 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6067 if (tp.Text == tn) return;
6069 this.ReOrderTab(tp.Text, tn, bef);
6072 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6074 var baseIndex = this.GetTabPageIndex(baseTabText);
6075 if (baseIndex == -1)
6078 var targetIndex = this.GetTabPageIndex(targetTabText);
6079 if (targetIndex == -1)
6082 using (ControlTransaction.Layout(this.ListTab))
6084 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6085 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6086 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6087 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6089 var tab = this.statuses.Tabs[targetIndex];
6090 var tabPage = this.ListTab.TabPages[targetIndex];
6092 this.ListTab.TabPages.Remove(tabPage);
6094 if (targetIndex < baseIndex)
6097 if (!isBeforeBaseTab)
6100 this.statuses.MoveTab(baseIndex, tab);
6102 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6105 this.SaveConfigsTabs();
6108 private void MakeDirectMessageText()
6110 var selectedPosts = this.CurrentTab.SelectedPosts;
6111 if (selectedPosts.Length > 1)
6114 var post = selectedPosts.Single();
6115 var text = $"D {post.ScreenName} {this.StatusText.Text}";
6117 this.inReplyTo = null;
6118 this.StatusText.Text = text;
6119 this.StatusText.SelectionStart = text.Length;
6120 this.StatusText.Focus();
6123 private void MakeReplyText(bool atAll = false)
6125 var selectedPosts = this.CurrentTab.SelectedPosts;
6126 if (selectedPosts.Any(x => x.IsDm))
6128 this.MakeDirectMessageText();
6132 if (selectedPosts.Length == 1)
6134 var post = selectedPosts.Single();
6135 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6136 var inReplyToScreenName = post.ScreenName;
6137 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6141 this.inReplyTo = null;
6144 var selfScreenName = this.tw.Username;
6145 var targetScreenNames = new List<string>();
6146 foreach (var post in selectedPosts)
6148 if (post.ScreenName != selfScreenName)
6149 targetScreenNames.Add(post.ScreenName);
6153 foreach (var (_, screenName) in post.ReplyToList)
6155 if (screenName != selfScreenName)
6156 targetScreenNames.Add(screenName);
6161 if (this.inReplyTo != null)
6163 var (_, screenName) = this.inReplyTo.Value;
6164 if (screenName == selfScreenName)
6165 targetScreenNames.Insert(0, screenName);
6168 var text = this.StatusText.Text;
6169 foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6171 var atText = $"@{screenName} ";
6172 if (!text.Contains(atText))
6173 text = atText + text;
6176 this.StatusText.Text = text;
6177 this.StatusText.SelectionStart = text.Length;
6178 this.StatusText.Focus();
6181 private void ListTab_MouseUp(object sender, MouseEventArgs e)
6182 => this.tabDrag = false;
6184 private int iconCnt = 0;
6185 private int blinkCnt = 0;
6186 private bool blink = false;
6188 private void RefreshTasktrayIcon()
6190 void EnableTasktrayAnimation()
6191 => this.TimerRefreshIcon.Enabled = true;
6193 void DisableTasktrayAnimation()
6194 => this.TimerRefreshIcon.Enabled = false;
6196 var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6200 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6203 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6204 this.myStatusError = false;
6205 EnableTasktrayAnimation();
6209 var replyIconType = this.settings.Common.ReplyIconState;
6211 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6213 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6214 if (replyTab != null && replyTab.UnreadCount > 0)
6218 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6221 if (this.blinkCnt > 10)
6224 if (this.blinkCnt == 0)
6225 this.blink = !this.blink;
6227 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6228 EnableTasktrayAnimation();
6232 DisableTasktrayAnimation();
6238 // 優先度:リプライ→エラー→オフライン→アイドル
6239 // エラーは更新アイコンでクリアされる
6240 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6241 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6242 else if (this.myStatusError)
6243 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6244 else if (this.myStatusOnline)
6245 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6247 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6250 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6251 => this.RefreshTasktrayIcon(); // 200ms
6253 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6255 // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6256 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6257 this.rclickTabName = this.CurrentTabName;
6259 if (this.statuses == null) return;
6260 if (this.statuses.Tabs == null) return;
6262 if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6265 this.NotifyDispMenuItem.Checked = tb.Notify;
6266 this.NotifyTbMenuItem.Checked = tb.Notify;
6268 this.soundfileListup = true;
6269 this.SoundFileComboBox.Items.Clear();
6270 this.SoundFileTbComboBox.Items.Clear();
6271 this.SoundFileComboBox.Items.Add("");
6272 this.SoundFileTbComboBox.Items.Add("");
6273 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6274 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6276 oDir = oDir.GetDirectories("Sounds")[0];
6278 foreach (var oFile in oDir.GetFiles("*.wav"))
6280 this.SoundFileComboBox.Items.Add(oFile.Name);
6281 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6283 var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6284 if (idx == -1) idx = 0;
6285 this.SoundFileComboBox.SelectedIndex = idx;
6286 this.SoundFileTbComboBox.SelectedIndex = idx;
6287 this.soundfileListup = false;
6288 this.UreadManageMenuItem.Checked = tb.UnreadManage;
6289 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6291 this.TabMenuControl(this.rclickTabName);
6294 private void TabMenuControl(string tabName)
6296 var tabInfo = this.statuses.GetTabByName(tabName)!;
6298 this.FilterEditMenuItem.Enabled = true;
6299 this.EditRuleTbMenuItem.Enabled = true;
6301 if (tabInfo.IsDefaultTabType)
6303 this.ProtectTabMenuItem.Enabled = false;
6304 this.ProtectTbMenuItem.Enabled = false;
6308 this.ProtectTabMenuItem.Enabled = true;
6309 this.ProtectTbMenuItem.Enabled = true;
6312 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6314 this.ProtectTabMenuItem.Checked = true;
6315 this.ProtectTbMenuItem.Checked = true;
6316 this.DeleteTabMenuItem.Enabled = false;
6317 this.DeleteTbMenuItem.Enabled = false;
6321 this.ProtectTabMenuItem.Checked = false;
6322 this.ProtectTbMenuItem.Checked = false;
6323 this.DeleteTabMenuItem.Enabled = true;
6324 this.DeleteTbMenuItem.Enabled = true;
6328 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6330 var checkState = ((ToolStripMenuItem)sender).Checked;
6333 this.ProtectTbMenuItem.Checked = checkState;
6334 this.ProtectTabMenuItem.Checked = checkState;
6337 this.DeleteTabMenuItem.Enabled = !checkState;
6338 this.DeleteTbMenuItem.Enabled = !checkState;
6340 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6341 this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6343 this.SaveConfigsTabs();
6346 private void UreadManageMenuItem_Click(object sender, EventArgs e)
6348 this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6349 this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6351 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6352 this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6354 this.SaveConfigsTabs();
6357 public void ChangeTabUnreadManage(string tabName, bool isManage)
6359 var idx = this.GetTabPageIndex(tabName);
6363 var tab = this.statuses.Tabs[tabName];
6364 tab.UnreadManage = isManage;
6366 if (this.settings.Common.TabIconDisp)
6368 var tabPage = this.ListTab.TabPages[idx];
6369 if (tab.UnreadCount > 0)
6370 tabPage.ImageIndex = 0;
6372 tabPage.ImageIndex = -1;
6375 if (this.CurrentTabName == tabName)
6377 this.listCache?.PurgeCache();
6378 this.CurrentListView.Refresh();
6381 this.SetMainWindowTitle();
6382 this.SetStatusLabelUrl();
6383 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6386 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6388 this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6389 this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6391 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6393 this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6395 this.SaveConfigsTabs();
6398 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6400 if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6402 this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6404 this.SaveConfigsTabs();
6407 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6409 if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6410 this.rclickTabName = this.CurrentTabName;
6412 this.RemoveSpecifiedTab(this.rclickTabName, true);
6413 this.SaveConfigsTabs();
6416 private void FilterEditMenuItem_Click(object sender, EventArgs e)
6418 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6420 using (var fltDialog = new FilterDialog())
6422 fltDialog.Owner = this;
6423 fltDialog.SetCurrent(this.rclickTabName);
6424 fltDialog.ShowDialog(this);
6426 this.TopMost = this.settings.Common.AlwaysTop;
6428 this.ApplyPostFilters();
6429 this.SaveConfigsTabs();
6432 private async void AddTabMenuItem_Click(object sender, EventArgs e)
6434 string? tabName = null;
6435 MyCommon.TabUsageType tabUsage;
6436 using (var inputName = new InputTabName())
6438 inputName.TabName = this.statuses.MakeTabName("MyTab");
6439 inputName.IsShowUsage = true;
6440 inputName.ShowDialog();
6441 if (inputName.DialogResult == DialogResult.Cancel) return;
6442 tabName = inputName.TabName;
6443 tabUsage = inputName.Usage;
6445 this.TopMost = this.settings.Common.AlwaysTop;
6446 if (!MyCommon.IsNullOrEmpty(tabName))
6449 ListElement? list = null;
6450 if (tabUsage == MyCommon.TabUsageType.Lists)
6452 using var listAvail = new ListAvailable();
6453 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6455 if (listAvail.SelectedList == null)
6457 list = listAvail.SelectedList;
6463 case MyCommon.TabUsageType.UserDefined:
6464 tab = new FilterTabModel(tabName);
6466 case MyCommon.TabUsageType.PublicSearch:
6467 tab = new PublicSearchTabModel(tabName);
6469 case MyCommon.TabUsageType.Lists:
6470 tab = new ListTimelineTabModel(tabName, list!);
6476 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6478 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6479 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6484 this.SaveConfigsTabs();
6486 var tabIndex = this.statuses.Tabs.Count - 1;
6488 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6490 this.ListTab.SelectedIndex = tabIndex;
6491 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6493 if (tabUsage == MyCommon.TabUsageType.Lists)
6495 this.ListTab.SelectedIndex = tabIndex;
6496 await this.RefreshTabAsync(this.CurrentTab);
6502 private void TabMenuItem_Click(object sender, EventArgs e)
6505 foreach (var post in this.CurrentTab.SelectedPosts)
6508 if (!this.SelectTab(out var tab))
6511 using (var fltDialog = new FilterDialog())
6513 fltDialog.Owner = this;
6514 fltDialog.SetCurrent(tab.TabName);
6516 if (post.RetweetedBy == null)
6518 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6522 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6524 fltDialog.ShowDialog(this);
6527 this.TopMost = this.settings.Common.AlwaysTop;
6530 this.ApplyPostFilters();
6531 this.SaveConfigsTabs();
6534 protected override bool ProcessDialogKey(Keys keyData)
6536 // TextBox1でEnterを押してもビープ音が鳴らないようにする
6537 if ((keyData & Keys.KeyCode) == Keys.Enter)
6539 if (this.StatusText.Focused)
6541 var newLine = false;
6544 if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6546 if (this.StatusText.Multiline)
6548 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6550 if ((keyData & Keys.Control) == Keys.Control) post = true;
6554 if ((keyData & Keys.Control) == Keys.Control) post = true;
6557 else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6559 if (this.StatusText.Multiline)
6561 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6563 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6567 if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6572 if (this.StatusText.Multiline)
6574 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6576 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6577 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6581 if (((keyData & Keys.Shift) == Keys.Shift) ||
6582 (((keyData & Keys.Control) != Keys.Control) &&
6583 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6589 var pos1 = this.StatusText.SelectionStart;
6590 if (this.StatusText.SelectionLength > 0)
6592 this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength); // 選択状態文字列削除
6594 this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine); // 改行挿入
6595 this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length; // カーソルを改行の次の文字へ移動
6600 this.PostButton_Click(this.PostButton, EventArgs.Empty);
6606 var tab = this.CurrentTab;
6607 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6609 var tabPage = this.CurrentTabPage;
6610 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6611 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6613 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6620 return base.ProcessDialogKey(keyData);
6623 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6624 => this.MakeReplyText(atAll: true);
6626 private void IDRuleMenuItem_Click(object sender, EventArgs e)
6628 var tab = this.CurrentTab;
6629 var selectedPosts = tab.SelectedPosts;
6632 if (selectedPosts.Length == 0)
6635 var screenNameArray = selectedPosts
6636 .Select(x => x.RetweetedBy ?? x.ScreenName)
6639 this.AddFilterRuleByScreenName(screenNameArray);
6641 if (screenNameArray.Length != 0)
6643 var atids = new List<string>();
6644 foreach (var screenName in screenNameArray)
6646 atids.Add("@" + screenName);
6648 var cnt = this.AtIdSupl.ItemCount;
6649 this.AtIdSupl.AddRangeItem(atids.ToArray());
6650 if (this.AtIdSupl.ItemCount != cnt)
6651 this.MarkSettingAtIdModified();
6655 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6657 var tab = this.CurrentTab;
6658 var selectedPosts = tab.SelectedPosts;
6660 if (selectedPosts.Length == 0)
6663 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6665 this.AddFilterRuleBySource(sourceArray);
6668 public void AddFilterRuleByScreenName(params string[] screenNameArray)
6671 if (!this.SelectTab(out var tab)) return;
6675 if (tab.TabType != MyCommon.TabUsageType.Mute)
6677 this.MoveOrCopy(out mv, out mk);
6681 // ミュートタブでは常に MoveMatches を true にする
6686 foreach (var screenName in screenNameArray)
6688 tab.AddFilter(new PostFilterRule
6690 FilterName = screenName,
6691 UseNameField = true,
6695 FilterByUrl = false,
6699 this.ApplyPostFilters();
6700 this.SaveConfigsTabs();
6703 public void AddFilterRuleBySource(params string[] sourceArray)
6705 // タブ選択ダイアログを表示(or追加)
6706 if (!this.SelectTab(out var filterTab))
6711 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6713 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6714 this.MoveOrCopy(out mv, out mk);
6718 // ミュートタブでは常に MoveMatches を true にする
6723 // 振り分けルールに追加するSource
6724 foreach (var source in sourceArray)
6726 filterTab.AddFilter(new PostFilterRule
6728 FilterSource = source,
6732 FilterByUrl = false,
6736 this.ApplyPostFilters();
6737 this.SaveConfigsTabs();
6740 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6747 using (var dialog = new TabsDialog(this.statuses))
6749 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6751 tab = dialog.SelectedTab;
6754 this.CurrentTabPage.Focus();
6759 using (var inputName = new InputTabName())
6761 inputName.TabName = this.statuses.MakeTabName("MyTab");
6762 inputName.ShowDialog();
6763 if (inputName.DialogResult == DialogResult.Cancel) return false;
6764 tabName = inputName.TabName;
6766 this.TopMost = this.settings.Common.AlwaysTop;
6767 if (!MyCommon.IsNullOrEmpty(tabName))
6769 var newTab = new FilterTabModel(tabName);
6770 if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6772 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6773 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6792 private void MoveOrCopy(out bool move, out bool mark)
6796 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6797 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6805 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6806 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6817 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6820 private void CopyURLMenuItem_Click(object sender, EventArgs e)
6821 => this.CopyIdUri();
6823 private void SelectAllMenuItem_Click(object sender, EventArgs e)
6825 if (this.StatusText.Focused)
6828 this.StatusText.SelectAll();
6832 // ListView上でのCtrl+A
6833 NativeMethods.SelectAllItems(this.CurrentListView);
6837 private void MoveMiddle()
6843 var listView = this.CurrentListView;
6844 if (listView.SelectedIndices.Count == 0) return;
6846 var idx = listView.SelectedIndices[0];
6848 item = listView.GetItemAt(0, 25);
6854 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6856 idx2 = listView.VirtualListSize - 1;
6860 idx -= Math.Abs(idx1 - idx2) / 2;
6861 if (idx < 0) idx = 0;
6863 listView.EnsureVisible(listView.VirtualListSize - 1);
6864 listView.EnsureVisible(idx);
6867 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6869 var linkElements = this.tweetDetailsView.GetLinkElements();
6871 if (linkElements.Length == 0)
6874 var links = new List<OpenUrlItem>(linkElements.Length);
6876 foreach (var linkElm in linkElements)
6878 var displayUrl = linkElm.GetAttribute("title");
6879 var href = linkElm.GetAttribute("href");
6880 var linkedText = linkElm.InnerText;
6882 if (MyCommon.IsNullOrEmpty(displayUrl))
6885 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6889 bool isReverseSettings;
6891 if (links.Count == 1)
6893 // ツイートに含まれる URL が 1 つのみの場合
6894 // => OpenURL ダイアログを表示せずにリンクを開く
6895 selectedUrl = links[0].Href;
6897 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6898 isReverseSettings = false;
6902 // ツイートに含まれる URL が複数ある場合
6903 // => OpenURL を表示しユーザーが選択したリンクを開く
6904 this.urlDialog.ClearUrl();
6906 foreach (var link in links)
6907 this.urlDialog.AddUrl(link);
6909 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6912 this.TopMost = this.settings.Common.AlwaysTop;
6914 selectedUrl = this.urlDialog.SelectedUrl;
6916 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6917 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6920 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6923 private void ClearTabMenuItem_Click(object sender, EventArgs e)
6925 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6926 this.ClearTab(this.rclickTabName, true);
6929 private void ClearTab(string tabName, bool showWarning)
6933 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6934 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6940 this.statuses.ClearTabIds(tabName);
6941 if (this.CurrentTabName == tabName)
6943 this.CurrentTab.ClearAnchor();
6944 this.listCache?.PurgeCache();
6945 this.listCache?.UpdateListSize();
6948 var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6949 var tabPage = this.ListTab.TabPages[tabIndex];
6950 tabPage.ImageIndex = -1;
6952 if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6954 this.SetMainWindowTitle();
6955 this.SetStatusLabelUrl();
6958 private static long followers = 0;
6960 private void SetMainWindowTitle()
6962 // メインウインドウタイトルの書き換え
6963 var ttl = new StringBuilder(256);
6966 if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6967 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6968 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6969 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6971 foreach (var tab in this.statuses.Tabs)
6973 ur += tab.UnreadCount;
6978 if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6979 ttl.Append(ApplicationSettings.ApplicationName);
6981 switch (this.settings.Common.DispLatestPost)
6983 case MyCommon.DispTitleEnum.Ver:
6984 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6986 case MyCommon.DispTitleEnum.Post:
6987 if (this.history != null && this.history.Count > 1)
6988 ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6990 case MyCommon.DispTitleEnum.UnreadRepCount:
6991 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6993 case MyCommon.DispTitleEnum.UnreadAllCount:
6994 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6996 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6997 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6999 case MyCommon.DispTitleEnum.UnreadCountAllCount:
7000 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
7002 case MyCommon.DispTitleEnum.OwnStatus:
7003 if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
7004 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
7010 this.Text = ttl.ToString();
7012 catch (AccessViolationException)
7014 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
7018 private string GetStatusLabelText()
7021 // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
7022 if (this.statuses == null) return "";
7023 var tbRep = this.statuses.MentionTab;
7024 var tbDm = this.statuses.DirectMessageTab;
7025 if (tbRep == null || tbDm == null) return "";
7026 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
7031 var slbl = new StringBuilder(256);
7034 foreach (var tab in this.statuses.Tabs)
7036 ur += tab.UnreadCount;
7038 if (tab.TabName == this.CurrentTabName)
7040 tur = tab.UnreadCount;
7050 this.unreadCounter = ur;
7051 this.unreadAtCounter = urat;
7053 var homeTab = this.statuses.HomeTab;
7055 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7056 if (this.settings.Common.TimelinePeriod == 0)
7058 slbl.Append(Properties.Resources.SetStatusLabelText2);
7062 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7064 return slbl.ToString();
7067 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7071 if (this.InvokeRequired && !this.IsDisposed)
7073 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7077 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7078 this.SetApiStatusLabel(endpointName);
7081 catch (ObjectDisposedException)
7085 catch (InvalidOperationException)
7091 private void SetApiStatusLabel(string? endpointName = null)
7093 var tabType = this.CurrentTab.TabType;
7095 if (endpointName == null)
7098 endpointName = tabType switch
7100 MyCommon.TabUsageType.Home => GetTimelineRequest.EndpointName,
7101 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7102 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7103 MyCommon.TabUsageType.Favorites => "/favorites/list",
7104 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7105 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
7106 MyCommon.TabUsageType.Lists => "/lists/statuses",
7107 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
7108 MyCommon.TabUsageType.Related => "/statuses/show/:id",
7111 this.toolStripApiGauge.ApiEndpoint = endpointName;
7115 // 表示中のタブに関連する endpoint であれば更新
7117 if (endpointName == GetTimelineRequest.EndpointName)
7119 update = tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined;
7123 update = endpointName switch
7125 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
7126 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
7127 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
7128 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
7129 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
7130 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
7131 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
7138 this.toolStripApiGauge.ApiEndpoint = endpointName;
7143 private void SetStatusLabelUrl()
7144 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7146 public void SetStatusLabel(string text)
7147 => this.StatusLabel.Text = text;
7149 private void SetNotifyIconText()
7151 var ur = new StringBuilder(64);
7153 // タスクトレイアイコンのツールチップテキスト書き換え
7155 ur.Remove(0, ur.Length);
7156 if (this.settings.Common.DispUsername)
7158 ur.Append(this.tw.Username);
7161 ur.Append(ApplicationSettings.ApplicationName);
7163 ur.Append("(Debug Build)");
7165 if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7168 ur.Append(this.unreadCounter);
7170 ur.Append(this.unreadAtCounter);
7173 this.NotifyIcon1.Text = ur.ToString();
7176 internal void CheckReplyTo(string statusText)
7180 m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7182 foreach (Match hm in m)
7184 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7186 hstr += "#" + hm.Result("$3") + " ";
7187 this.HashSupl.AddItem("#" + hm.Result("$3"));
7190 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7192 hstr += this.HashMgr.UseHash;
7194 if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7196 // 本当にリプライ先指定すべきかどうかの判定
7197 m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7199 if (this.settings.Common.UseAtIdSupplement)
7201 var bCnt = this.AtIdSupl.ItemCount;
7202 foreach (Match mid in m)
7204 this.AtIdSupl.AddItem(mid.Result("${id}"));
7206 if (bCnt != this.AtIdSupl.ItemCount)
7207 this.MarkSettingAtIdModified();
7210 // リプライ先ステータスIDの指定がない場合は指定しない
7211 if (this.inReplyTo == null)
7215 // 次の条件を満たす場合に in_reply_to_status_id 指定
7216 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7217 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7218 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7222 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7223 if (statusText.StartsWith("@", StringComparison.Ordinal))
7225 if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7229 foreach (Match mid in m)
7231 if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7236 this.inReplyTo = null;
7239 private void TweenMain_Resize(object sender, EventArgs e)
7241 if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7243 this.Visible = false;
7245 if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7247 // 現在の DPI と設定保存時の DPI との比を取得する
7248 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7250 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7253 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7254 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7255 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7257 this.SplitContainer1.SplitterDistance = splitterDistance;
7261 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7262 if (this.StatusText.Multiline)
7264 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7265 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7266 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7268 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7270 this.StatusText.Height = statusTextHeight;
7274 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7276 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7280 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7281 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7283 this.SplitContainer3.SplitterDistance = previewDistance;
7286 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7287 this.SplitContainer3.Panel2Collapsed = true;
7289 this.initialLayout = false;
7291 if (this.WindowState != FormWindowState.Minimized)
7293 this.formWindowState = this.WindowState;
7297 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7299 this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7300 this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7301 if (this.PlaySoundMenuItem.Checked)
7303 this.settings.Common.PlaySound = true;
7307 this.settings.Common.PlaySound = false;
7309 this.MarkSettingCommonModified();
7312 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7314 if (this.initialLayout)
7317 int splitterDistance;
7318 switch (this.WindowState)
7320 case FormWindowState.Normal:
7321 splitterDistance = this.SplitContainer1.SplitterDistance;
7323 case FormWindowState.Maximized:
7324 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7325 var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7326 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7327 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7333 this.mySpDis = splitterDistance;
7334 this.MarkSettingLocalModified();
7337 private async Task DoRepliedStatusOpen()
7339 var currentPost = this.CurrentPost;
7340 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7342 if (MyCommon.IsKeyDown(Keys.Shift))
7344 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7347 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7349 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7353 foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7355 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7356 repPost = tb.Posts[currentPost.InReplyToStatusId];
7357 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7360 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7365 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7366 => await this.DoRepliedStatusOpen();
7368 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7370 if (this.initialLayout)
7371 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7373 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7374 if (multiline != this.StatusText.Multiline)
7376 this.StatusText.Multiline = multiline;
7377 this.settings.Local.StatusMultiline = multiline;
7378 this.MarkSettingLocalModified();
7382 private void StatusText_MultilineChanged(object sender, EventArgs e)
7384 if (this.StatusText.Multiline)
7385 this.StatusText.ScrollBars = ScrollBars.Vertical;
7387 this.StatusText.ScrollBars = ScrollBars.None;
7389 if (!this.initialLayout)
7390 this.MarkSettingLocalModified();
7393 private void MultiLineMenuItem_Click(object sender, EventArgs e)
7396 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7397 this.StatusText.Multiline = menuItemChecked;
7398 this.settings.Local.StatusMultiline = menuItemChecked;
7399 if (menuItemChecked)
7401 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7402 this.SplitContainer2.SplitterDistance = 0;
7404 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7408 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7410 this.MarkSettingLocalModified();
7413 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7415 if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7417 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7418 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7419 (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7421 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7426 // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7427 // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7428 // Appendix A. Collected ABNF for URI
7429 // http://www.ietf.org/rfc/rfc3986.txt
7431 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7434 if (this.StatusText.SelectionLength > 0)
7436 var tmp = this.StatusText.SelectedText;
7437 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7438 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7440 // 文字列が選択されている場合はその文字列について処理
7442 // nico.ms使用、nicovideoにマッチしたら変換
7443 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7445 result = Nicoms.Shorten(tmp);
7447 else if (converterType != MyCommon.UrlConverter.Nicoms)
7452 var srcUri = new Uri(tmp);
7453 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7454 result = resultUri.AbsoluteUri;
7456 catch (WebApiException e)
7458 this.StatusLabel.Text = converterType + ":" + e.Message;
7461 catch (UriFormatException e)
7463 this.StatusLabel.Text = converterType + ":" + e.Message;
7472 if (!MyCommon.IsNullOrEmpty(result))
7474 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7475 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7476 if (origUrlIndex == -1)
7479 this.StatusText.Select(origUrlIndex, tmp.Length);
7480 this.StatusText.SelectedText = result;
7483 var undo = new UrlUndo
7489 if (this.urlUndoBuffer == null)
7491 this.urlUndoBuffer = new List<UrlUndo>();
7492 this.UrlUndoToolStripMenuItem.Enabled = true;
7495 this.urlUndoBuffer.Add(undo);
7501 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7502 @"(?<url>(?<protocol>https?://)" +
7503 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7504 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7505 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7506 // 正規表現にマッチしたURL文字列をtinyurl化
7507 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7509 if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7511 var tmp = mt.Result("${url}");
7512 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7513 tmp = "http://" + tmp;
7516 this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7518 // nico.ms使用、nicovideoにマッチしたら変換
7519 if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7521 result = Nicoms.Shorten(tmp);
7523 else if (converterType != MyCommon.UrlConverter.Nicoms)
7528 var srcUri = new Uri(tmp);
7529 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7530 result = resultUri.AbsoluteUri;
7532 catch (HttpRequestException e)
7534 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7535 // のように長いので「:」が含まれていればそれ以降のみを抽出する
7536 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7538 this.StatusLabel.Text = converterType + ":" + message;
7541 catch (WebApiException e)
7543 this.StatusLabel.Text = converterType + ":" + e.Message;
7546 catch (UriFormatException e)
7548 this.StatusLabel.Text = converterType + ":" + e.Message;
7557 if (!MyCommon.IsNullOrEmpty(result))
7559 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7560 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7561 if (origUrlIndex == -1)
7564 this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7565 this.StatusText.SelectedText = result;
7567 var undo = new UrlUndo
7569 Before = mt.Result("${url}"),
7573 if (this.urlUndoBuffer == null)
7575 this.urlUndoBuffer = new List<UrlUndo>();
7576 this.UrlUndoToolStripMenuItem.Enabled = true;
7579 this.urlUndoBuffer.Add(undo);
7587 private void DoUrlUndo()
7589 if (this.urlUndoBuffer != null)
7591 var tmp = this.StatusText.Text;
7592 foreach (var data in this.urlUndoBuffer)
7594 tmp = tmp.Replace(data.After, data.Before);
7596 this.StatusText.Text = tmp;
7597 this.urlUndoBuffer = null;
7598 this.UrlUndoToolStripMenuItem.Enabled = false;
7599 this.StatusText.SelectionStart = 0;
7600 this.StatusText.SelectionLength = 0;
7604 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7605 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7607 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7608 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7610 private async void UxnuMenuItem_Click(object sender, EventArgs e)
7611 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7613 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7615 if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7617 var rnd = new Random();
7619 MyCommon.UrlConverter svc;
7620 // 前回使用した短縮URLサービス以外を選択する
7623 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7625 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7626 await this.UrlConvertAsync(svc);
7630 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7631 => this.DoUrlUndo();
7633 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7635 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7636 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7637 this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7638 this.MarkSettingCommonModified();
7641 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7643 this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7644 this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7645 this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7646 this.MarkSettingCommonModified();
7649 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7651 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7652 this.MenuStrip1.Tag = new object();
7653 this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7656 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7658 var currentTabPage = this.CurrentTabPage;
7659 if (this.Tag != null) // 設定された戻り先へ遷移
7661 if (this.Tag == currentTabPage)
7662 ((Control)currentTabPage.Tag).Select();
7664 ((Control)this.Tag).Select();
7666 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7668 this.Tag = currentTabPage.Tag;
7669 ((Control)this.Tag).Select();
7671 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7672 this.MenuStrip1.Tag = null;
7675 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7677 if (this.Use2ColumnsMode)
7683 var lst = (DetailsListView)sender;
7684 var columnsCount = lst.Columns.Count;
7686 var darr = new int[columnsCount];
7687 for (var i = 0; i < columnsCount; i++)
7688 darr[lst.Columns[i].DisplayIndex] = i;
7690 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7692 for (var i = 0; i < columnsCount; i++)
7693 this.settings.Local.ColumnsOrder[darr[i]] = i;
7695 this.MarkSettingLocalModified();
7696 this.isColumnChanged = true;
7699 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7701 var lst = (DetailsListView)sender;
7702 if (this.settings.Local == null) return;
7704 var modified = false;
7705 if (this.Use2ColumnsMode)
7707 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7709 this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7712 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7714 this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7720 var columnsCount = lst.Columns.Count;
7721 for (var i = 0; i < columnsCount; i++)
7723 if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7726 this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7732 this.MarkSettingLocalModified();
7733 this.isColumnChanged = true;
7737 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7739 if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7740 this.MarkSettingLocalModified();
7743 private void TweenMain_DragDrop(object sender, DragEventArgs e)
7745 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7747 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7749 this.SelectMedia_DragDrop(e);
7752 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7754 var (url, title) = GetUrlFromDataObject(e.Data);
7760 appendText = title + " " + url;
7762 if (this.StatusText.TextLength == 0)
7763 this.StatusText.Text = appendText;
7765 this.StatusText.Text += " " + appendText;
7767 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7769 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7771 this.StatusText.Text += text;
7773 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7775 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7776 if (data != null) this.StatusText.Text += data;
7781 /// IDataObject から URL とタイトルの対を取得します
7784 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7786 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7787 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7788 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7790 if (data.GetDataPresent("text/x-moz-url"))
7792 // Firefox, Google Chrome で利用可能
7793 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7795 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7796 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7797 if (lines.Length < 2)
7798 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7800 return (lines[0], lines[1]);
7802 else if (data.GetDataPresent("IESiteModeToUrl"))
7804 // Internet Exproler 用
7805 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7807 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7808 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7809 if (lines.Length < 2)
7810 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7812 return (lines[0], lines[1]);
7814 else if (data.GetDataPresent("UniformResourceLocatorW"))
7818 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7819 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7823 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7826 private void TweenMain_DragEnter(object sender, DragEventArgs e)
7828 if (e.Data.GetDataPresent(DataFormats.FileDrop))
7830 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7832 this.SelectMedia_DragEnter(e);
7836 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7838 e.Effect = DragDropEffects.Copy;
7841 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7843 e.Effect = DragDropEffects.Copy;
7846 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7848 e.Effect = DragDropEffects.Copy;
7852 e.Effect = DragDropEffects.None;
7855 private void TweenMain_DragOver(object sender, DragEventArgs e)
7859 public bool IsNetworkAvailable()
7861 var nw = MyCommon.IsNetworkAvailable();
7862 this.myStatusOnline = nw;
7866 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7868 var uriStr = uri.AbsoluteUri;
7870 // OpenTween 内部で使用する URL
7871 if (uri.Authority == "opentween")
7873 await this.OpenInternalUriAsync(uri);
7877 // ハッシュタグを含む Twitter 検索
7878 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7881 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7882 var pos = unescapedQuery.IndexOf('#');
7883 if (pos == -1) return;
7885 var hash = unescapedQuery.Substring(pos);
7886 this.HashSupl.AddItem(hash);
7887 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7888 this.AddNewTabForSearch(hash);
7893 // フラグが立っている場合は設定と逆の動作をする
7894 if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7895 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7897 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7898 if (userUriMatch.Success)
7900 var screenName = userUriMatch.Groups["ScreenName"].Value;
7901 if (this.IsTwitterId(screenName))
7903 await this.AddNewTabForUserTimeline(screenName);
7910 await MyCommon.OpenInBrowserAsync(this, uriStr);
7914 /// OpenTween 内部の機能を呼び出すための URL を開きます
7916 private async Task OpenInternalUriAsync(Uri uri)
7918 // ツイートを開く (//opentween/status/:status_id)
7919 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7922 var statusId = new TwitterStatusId(match.Groups[1].Value);
7923 await this.OpenRelatedTab(statusId);
7928 private void ListTabSelect(TabPage tabPage)
7930 this.SetListProperty();
7932 var previousTabName = this.CurrentTabName;
7933 if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7934 previousListViewState.Save(this.ListLockMenuItem.Checked);
7936 this.listCache?.PurgeCache();
7938 this.statuses.SelectTab(tabPage.Text);
7940 this.InitializeTimelineListView();
7942 var tab = this.CurrentTab;
7945 var listView = this.CurrentListView;
7947 var currentListViewState = this.listViewState[tab.TabName];
7948 currentListViewState.Restore(forceScroll: true);
7950 if (this.Use2ColumnsMode)
7952 listView.Columns[1].Text = this.columnText[2];
7956 for (var i = 0; i < listView.Columns.Count; i++)
7958 listView.Columns[i].Text = this.columnText[i];
7963 private void InitializeTimelineListView()
7965 var listView = this.CurrentListView;
7966 var tab = this.CurrentTab;
7968 var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7969 (this.listCache, var oldCache) = (newCache, this.listCache);
7970 oldCache?.Dispose();
7972 var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7973 (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7974 oldDrawer?.Dispose();
7976 newDrawer.IconSize = this.settings.Common.IconSize;
7977 newDrawer.UpdateItemHeight();
7980 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7981 => this.ListTabSelect(e.TabPage);
7983 private void SelectListItem(DetailsListView lView, int index)
7986 var bnd = new Rectangle();
7988 var item = lView.FocusedItem;
7997 lView.SelectedIndices.Clear();
7999 while (lView.SelectedIndices.Count > 0);
8000 item = lView.Items[index];
8001 item.Selected = true;
8002 item.Focused = true;
8004 if (flg) lView.Invalidate(bnd);
8007 private async void TweenMain_Shown(object sender, EventArgs e)
8009 this.NotifyIcon1.Visible = true;
8011 if (this.IsNetworkAvailable())
8013 var loadTasks = new List<Task>
8015 this.RefreshMuteUserIdsAsync(),
8016 this.RefreshBlockIdsAsync(),
8017 this.RefreshNoRetweetIdsAsync(),
8018 this.RefreshTwitterConfigurationAsync(),
8019 this.RefreshTabAsync<HomeTabModel>(),
8020 this.RefreshTabAsync<MentionsTabModel>(),
8021 this.RefreshTabAsync<DirectMessagesTabModel>(),
8022 this.RefreshTabAsync<PublicSearchTabModel>(),
8023 this.RefreshTabAsync<UserTimelineTabModel>(),
8024 this.RefreshTabAsync<ListTimelineTabModel>(),
8027 if (this.settings.Common.StartupFollowers)
8028 loadTasks.Add(this.RefreshFollowerIdsAsync());
8030 if (this.settings.Common.GetFav)
8031 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
8033 var allTasks = Task.WhenAll(loadTasks);
8038 var timeout = Task.Delay(5000);
8039 if (await Task.WhenAny(allTasks, timeout) != timeout)
8043 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
8045 if (MyCommon.EndingFlag)
8049 if (MyCommon.EndingFlag) return;
8051 if (ApplicationSettings.VersionInfoUrl != null)
8053 // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8054 if (this.settings.Common.StartupVersion)
8055 await this.CheckNewVersion(true);
8059 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8060 this.VerUpMenuItem.Enabled = false;
8061 this.VerUpMenuItem.Available = false;
8062 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8065 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8066 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8068 MessageBox.Show(Properties.Resources.ReAuthorizeText);
8069 this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8073 var reloadTasks = new List<Task>();
8075 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8076 reloadTasks.Add(this.RefreshFollowerIdsAsync());
8078 if (!this.tw.GetNoRetweetSuccess)
8079 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
8081 if (this.tw.Configuration.PhotoSizeLimit == 0)
8082 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
8084 await Task.WhenAll(reloadTasks);
8087 this.initial = false;
8089 this.timelineScheduler.Enabled = true;
8092 private async Task DoGetFollowersMenu()
8094 await this.RefreshFollowerIdsAsync();
8095 this.DispSelectedPost(true);
8098 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8099 => await this.DoGetFollowersMenu();
8101 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8102 => this.DoReTweetUnofficial();
8104 private async Task DoReTweetOfficial(bool isConfirm)
8107 if (this.ExistCurrentPost)
8109 var selectedPosts = this.CurrentTab.SelectedPosts;
8111 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8113 if (selectedPosts.Any(x => x.IsProtect))
8114 MessageBox.Show("Protected.");
8116 this.doFavRetweetFlags = false;
8120 if (selectedPosts.Length > 15)
8122 MessageBox.Show(Properties.Resources.RetweetLimitText);
8123 this.doFavRetweetFlags = false;
8126 else if (selectedPosts.Length > 1)
8128 var questionText = Properties.Resources.RetweetQuestion2;
8129 if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8130 switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8132 case DialogResult.Cancel:
8133 case DialogResult.No:
8134 this.doFavRetweetFlags = false;
8140 if (!this.settings.Common.RetweetNoConfirm)
8142 var questiontext = Properties.Resources.RetweetQuestion1;
8143 if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8144 if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8146 this.doFavRetweetFlags = false;
8152 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8154 await this.RetweetAsync(statusIds);
8158 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8159 => await this.DoReTweetOfficial(true);
8161 private async Task FavoritesRetweetOfficial()
8163 if (!this.ExistCurrentPost) return;
8164 this.doFavRetweetFlags = true;
8165 var retweetTask = this.DoReTweetOfficial(true);
8166 if (this.doFavRetweetFlags)
8168 this.doFavRetweetFlags = false;
8169 var favoriteTask = this.FavoriteChange(true, false);
8171 await Task.WhenAll(retweetTask, favoriteTask);
8179 private async Task FavoritesRetweetUnofficial()
8181 var post = this.CurrentPost;
8182 if (this.ExistCurrentPost && post != null && !post.IsDm)
8184 this.doFavRetweetFlags = true;
8185 var favoriteTask = this.FavoriteChange(true);
8186 if (!post.IsProtect && this.doFavRetweetFlags)
8188 this.doFavRetweetFlags = false;
8189 this.DoReTweetUnofficial();
8197 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8199 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8200 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8201 /// <returns>復元されたツイート本文</returns>
8202 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8204 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8207 statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8209 statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8211 statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8213 statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8217 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8219 statusHtml = statusHtml.Replace("<br>", " ");
8221 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8222 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
8223 statusHtml = statusHtml.Replace(" ", " ");
8225 return WebUtility.HtmlDecode(statusHtml);
8228 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8230 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8232 if (this.CurrentPost != null)
8233 this.DispSelectedPost(true);
8236 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8238 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8239 this.DebugModeToolStripMenuItem.Visible = true;
8241 this.DebugModeToolStripMenuItem.Visible = false;
8244 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8245 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8247 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8248 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8250 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8251 => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8253 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8255 this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8256 this.MarkSettingCommonModified();
8259 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8261 this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8262 this.MarkSettingCommonModified();
8265 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8267 this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8268 this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8269 this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8270 this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8271 this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8272 this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8275 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8277 this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8278 this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8279 this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8280 this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8281 this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8282 this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8285 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8287 if (this.TraceOutToolStripMenuItem.Checked)
8288 MyCommon.TraceFlag = true;
8290 MyCommon.TraceFlag = false;
8293 private void TweenMain_Deactivate(object sender, EventArgs e)
8294 => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8296 private void TabRenameMenuItem_Click(object sender, EventArgs e)
8298 if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8300 _ = this.TabRename(this.rclickTabName, out _);
8303 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8304 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8306 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8307 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8309 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8311 TwitterApiStatus? apiStatus;
8313 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8315 var cancellationToken = dialog.EnableCancellation();
8319 var task = this.tw.GetInfoApi();
8320 apiStatus = await dialog.WaitForAsync(this, task);
8322 catch (WebApiException)
8327 if (cancellationToken.IsCancellationRequested)
8330 if (apiStatus == null)
8332 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8337 using var apiDlg = new ApiInfoDialog();
8338 apiDlg.ShowDialog(this);
8341 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8343 var id = this.CurrentPost?.ScreenName ?? "";
8345 await this.FollowCommand(id);
8348 internal async Task FollowCommand(string id)
8350 using (var inputName = new InputTabName())
8352 inputName.FormTitle = "Follow";
8353 inputName.FormDescription = Properties.Resources.FRMessage1;
8354 inputName.TabName = id;
8356 if (inputName.ShowDialog(this) != DialogResult.OK)
8358 if (string.IsNullOrWhiteSpace(inputName.TabName))
8361 id = inputName.TabName.Trim();
8364 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8368 var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8369 await dialog.WaitForAsync(this, task);
8371 catch (WebApiException ex)
8373 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8378 MessageBox.Show(Properties.Resources.FRMessage3);
8381 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8383 var id = this.CurrentPost?.ScreenName ?? "";
8385 await this.RemoveCommand(id, false);
8388 internal async Task RemoveCommand(string id, bool skipInput)
8392 using var inputName = new InputTabName();
8393 inputName.FormTitle = "Unfollow";
8394 inputName.FormDescription = Properties.Resources.FRMessage1;
8395 inputName.TabName = id;
8397 if (inputName.ShowDialog(this) != DialogResult.OK)
8399 if (string.IsNullOrWhiteSpace(inputName.TabName))
8402 id = inputName.TabName.Trim();
8405 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8409 var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8410 await dialog.WaitForAsync(this, task);
8412 catch (WebApiException ex)
8414 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8419 MessageBox.Show(Properties.Resources.FRMessage3);
8422 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8424 var id = this.CurrentPost?.ScreenName ?? "";
8426 await this.ShowFriendship(id);
8429 internal async Task ShowFriendship(string id)
8431 using (var inputName = new InputTabName())
8433 inputName.FormTitle = "Show Friendships";
8434 inputName.FormDescription = Properties.Resources.FRMessage1;
8435 inputName.TabName = id;
8437 if (inputName.ShowDialog(this) != DialogResult.OK)
8439 if (string.IsNullOrWhiteSpace(inputName.TabName))
8442 id = inputName.TabName.Trim();
8445 bool isFollowing, isFollowed;
8447 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8449 var cancellationToken = dialog.EnableCancellation();
8453 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8454 var friendship = await dialog.WaitForAsync(this, task);
8456 isFollowing = friendship.Relationship.Source.Following;
8457 isFollowed = friendship.Relationship.Source.FollowedBy;
8459 catch (WebApiException ex)
8461 if (!cancellationToken.IsCancellationRequested)
8462 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8466 if (cancellationToken.IsCancellationRequested)
8473 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8477 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8481 result += Properties.Resources.GetFriendshipInfo3;
8485 result += Properties.Resources.GetFriendshipInfo4;
8487 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8488 MessageBox.Show(result);
8491 internal async Task ShowFriendship(string[] ids)
8493 foreach (var id in ids)
8495 bool isFollowing, isFollowed;
8497 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8499 var cancellationToken = dialog.EnableCancellation();
8503 var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8504 var friendship = await dialog.WaitForAsync(this, task);
8506 isFollowing = friendship.Relationship.Source.Following;
8507 isFollowed = friendship.Relationship.Source.FollowedBy;
8509 catch (WebApiException ex)
8511 if (!cancellationToken.IsCancellationRequested)
8512 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8516 if (cancellationToken.IsCancellationRequested)
8526 ff += Properties.Resources.GetFriendshipInfo1;
8530 ff += Properties.Resources.GetFriendshipInfo2;
8533 ff += System.Environment.NewLine + " ";
8536 ff += Properties.Resources.GetFriendshipInfo3;
8540 ff += Properties.Resources.GetFriendshipInfo4;
8542 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8545 if (MessageBox.Show(
8546 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8547 Properties.Resources.GetFriendshipInfo8,
8548 MessageBoxButtons.YesNo,
8549 MessageBoxIcon.Question,
8550 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8552 await this.RemoveCommand(id, true);
8557 MessageBox.Show(result);
8562 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8563 => await this.DoShowUserStatus(this.tw.Username, false);
8565 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8568 public bool IsTwitterId(string name)
8570 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8571 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8573 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8576 private void DoQuoteOfficial()
8578 var post = this.CurrentPost;
8579 if (this.ExistCurrentPost && post != null)
8581 if (post.IsDm || !this.StatusText.Enabled)
8586 MessageBox.Show("Protected.");
8590 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8592 this.inReplyTo = null;
8594 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8596 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8597 this.StatusText.Focus();
8601 private void DoReTweetUnofficial()
8604 var post = this.CurrentPost;
8605 if (this.ExistCurrentPost && post != null)
8607 if (post.IsDm || !this.StatusText.Enabled)
8612 MessageBox.Show("Protected.");
8615 var rtdata = post.Text;
8616 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8618 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8620 // 投稿時に in_reply_to_status_id を付加する
8621 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8622 var inReplyToScreenName = post.ScreenName;
8623 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8625 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8627 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8628 this.StatusText.Focus();
8632 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8633 => this.DoQuoteOfficial();
8635 private async void SearchButton_Click(object sender, EventArgs e)
8638 var pnl = ((Control)sender).Parent;
8639 if (pnl == null) return;
8640 var tbName = pnl.Parent.Text;
8641 var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8642 var cmb = (ComboBox)pnl.Controls["comboSearch"];
8643 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8644 cmb.Text = cmb.Text.Trim();
8645 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8647 var buf = new StringBuilder();
8648 var c = cmb.Text.ToCharArray();
8649 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8651 if (cnt > cmb.Text.Length - 4)
8653 buf.Append(cmb.Text.Substring(cnt));
8662 if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8671 cmb.Text = buf.ToString();
8673 var listView = (DetailsListView)pnl.Parent.Tag;
8675 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8677 tb.SearchWords = cmb.Text;
8678 tb.SearchLang = cmbLang.Text;
8679 if (MyCommon.IsNullOrEmpty(cmb.Text))
8682 this.SaveConfigsTabs();
8687 var idx = cmb.Items.IndexOf(tb.SearchWords);
8688 if (idx > -1) cmb.Items.RemoveAt(idx);
8689 cmb.Items.Insert(0, tb.SearchWords);
8690 cmb.Text = tb.SearchWords;
8692 this.statuses.ClearTabIds(tbName);
8693 this.listCache?.PurgeCache();
8694 this.listCache?.UpdateListSize();
8695 this.SaveConfigsTabs(); // 検索条件の保存
8699 await this.RefreshTabAsync(tb);
8702 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8703 => await this.DoRefreshMore(); // もっと前を取得
8706 /// 指定されたタブのListTabにおける位置を返します
8709 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8711 public int GetTabPageIndex(string tabName)
8712 => this.statuses.Tabs.IndexOf(tabName);
8714 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8718 var restoredTab = this.statuses.UndoRemovedTab();
8719 this.AddNewTab(restoredTab, startup: false);
8721 var tabIndex = this.statuses.Tabs.Count - 1;
8722 this.ListTab.SelectedIndex = tabIndex;
8724 this.SaveConfigsTabs();
8726 catch (TabException ex)
8728 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8732 private async Task DoMoveToRTHome()
8734 var post = this.CurrentPost;
8735 if (post != null && post.RetweetedId != null)
8736 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8739 private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8740 => await this.DoMoveToRTHome();
8742 private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8744 var screenName = this.CurrentPost?.ScreenName;
8745 if (screenName != null)
8746 this.ListManageUserContext(screenName);
8749 private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8751 var screenName = this.CurrentPost?.RetweetedBy;
8752 if (screenName != null)
8753 this.ListManageUserContext(screenName);
8756 public void ListManageUserContext(string screenName)
8758 using var listSelectForm = new MyLists(screenName, this.tw.Api);
8759 listSelectForm.ShowDialog(this);
8762 private void SearchControls_Enter(object sender, EventArgs e)
8764 var pnl = (Control)sender;
8765 foreach (Control ctl in pnl.Controls)
8771 private void SearchControls_Leave(object sender, EventArgs e)
8773 var pnl = (Control)sender;
8774 foreach (Control ctl in pnl.Controls)
8776 ctl.TabStop = false;
8780 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8782 var tab = this.CurrentTab;
8783 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8784 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8787 private void StatusLabel_DoubleClick(object sender, EventArgs e)
8788 => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8790 private void HashManageMenuItem_Click(object sender, EventArgs e)
8795 rslt = this.HashMgr.ShowDialog();
8801 this.TopMost = this.settings.Common.AlwaysTop;
8802 if (rslt == DialogResult.Cancel) return;
8803 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8805 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8806 this.HashTogglePullDownMenuItem.Checked = true;
8807 this.HashToggleMenuItem.Checked = true;
8811 this.HashStripSplitButton.Text = "#[-]";
8812 this.HashTogglePullDownMenuItem.Checked = false;
8813 this.HashToggleMenuItem.Checked = false;
8816 this.MarkSettingCommonModified();
8817 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8820 private void HashToggleMenuItem_Click(object sender, EventArgs e)
8822 this.HashMgr.ToggleHash();
8823 if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8825 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8826 this.HashToggleMenuItem.Checked = true;
8827 this.HashTogglePullDownMenuItem.Checked = true;
8831 this.HashStripSplitButton.Text = "#[-]";
8832 this.HashToggleMenuItem.Checked = false;
8833 this.HashTogglePullDownMenuItem.Checked = false;
8835 this.MarkSettingCommonModified();
8836 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8839 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8840 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8842 public void SetPermanentHashtag(string hashtag)
8844 this.HashMgr.SetPermanentHash("#" + hashtag);
8845 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8846 this.HashTogglePullDownMenuItem.Checked = true;
8847 this.HashToggleMenuItem.Checked = true;
8849 this.MarkSettingCommonModified();
8852 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8854 var tab = this.CurrentTab;
8855 var post = this.CurrentPost;
8856 if (!this.ExistCurrentPost)
8858 this.ReplyOpMenuItem.Enabled = false;
8859 this.ReplyAllOpMenuItem.Enabled = false;
8860 this.DmOpMenuItem.Enabled = false;
8861 this.CreateTabRuleOpMenuItem.Enabled = false;
8862 this.CreateIdRuleOpMenuItem.Enabled = false;
8863 this.CreateSourceRuleOpMenuItem.Enabled = false;
8864 this.ReadOpMenuItem.Enabled = false;
8865 this.UnreadOpMenuItem.Enabled = false;
8866 this.AuthorMenuItem.Visible = false;
8867 this.RetweetedByMenuItem.Visible = false;
8871 this.ReplyOpMenuItem.Enabled = true;
8872 this.ReplyAllOpMenuItem.Enabled = true;
8873 this.DmOpMenuItem.Enabled = true;
8874 this.CreateTabRuleOpMenuItem.Enabled = true;
8875 this.CreateIdRuleOpMenuItem.Enabled = true;
8876 this.CreateSourceRuleOpMenuItem.Enabled = true;
8877 this.ReadOpMenuItem.Enabled = true;
8878 this.UnreadOpMenuItem.Enabled = true;
8879 this.AuthorMenuItem.Visible = true;
8880 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8881 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8882 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8885 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8887 this.FavOpMenuItem.Enabled = false;
8888 this.UnFavOpMenuItem.Enabled = false;
8889 this.OpenStatusOpMenuItem.Enabled = false;
8890 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8891 this.RtOpMenuItem.Enabled = false;
8892 this.RtUnOpMenuItem.Enabled = false;
8893 this.QtOpMenuItem.Enabled = false;
8894 this.FavoriteRetweetMenuItem.Enabled = false;
8895 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8899 this.FavOpMenuItem.Enabled = true;
8900 this.UnFavOpMenuItem.Enabled = true;
8901 this.OpenStatusOpMenuItem.Enabled = true;
8902 this.ShowRelatedStatusesMenuItem2.Enabled = true; // PublicSearchの時問題出るかも
8904 if (!post.CanRetweetBy(this.tw.UserId))
8906 this.RtOpMenuItem.Enabled = false;
8907 this.RtUnOpMenuItem.Enabled = false;
8908 this.QtOpMenuItem.Enabled = false;
8909 this.FavoriteRetweetMenuItem.Enabled = false;
8910 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8914 this.RtOpMenuItem.Enabled = true;
8915 this.RtUnOpMenuItem.Enabled = true;
8916 this.QtOpMenuItem.Enabled = true;
8917 this.FavoriteRetweetMenuItem.Enabled = true;
8918 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8922 if (tab.TabType != MyCommon.TabUsageType.Favorites)
8924 this.RefreshPrevOpMenuItem.Enabled = true;
8928 this.RefreshPrevOpMenuItem.Enabled = false;
8930 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8932 this.OpenRepSourceOpMenuItem.Enabled = false;
8936 this.OpenRepSourceOpMenuItem.Enabled = true;
8939 if (this.ExistCurrentPost && post != null)
8941 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8945 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8946 => this.ContextMenuTabProperty_Opening(sender, null!);
8948 public Twitter TwitterInstance
8951 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8953 if (this.initialLayout)
8956 int splitterDistance;
8957 switch (this.WindowState)
8959 case FormWindowState.Normal:
8960 splitterDistance = this.SplitContainer3.SplitterDistance;
8962 case FormWindowState.Maximized:
8963 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8964 var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8965 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8966 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8972 this.mySpDis3 = splitterDistance;
8973 this.MarkSettingLocalModified();
8976 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8978 this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8980 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8981 this.PublicSearchQueryMenuItem.Enabled = true;
8983 this.PublicSearchQueryMenuItem.Enabled = false;
8985 var post = this.CurrentPost;
8986 if (!this.ExistCurrentPost || post == null)
8988 this.CopySTOTMenuItem.Enabled = false;
8989 this.CopyURLMenuItem.Enabled = false;
8990 this.CopyUserIdStripMenuItem.Enabled = false;
8994 this.CopySTOTMenuItem.Enabled = true;
8995 this.CopyURLMenuItem.Enabled = true;
8996 this.CopyUserIdStripMenuItem.Enabled = true;
8998 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8999 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
9003 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
9004 => this.SetNotifyIconText();
9006 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
9007 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
9009 private async Task DoShowUserStatus(string id, bool showInputDialog)
9011 TwitterUser? user = null;
9013 if (showInputDialog)
9015 using var inputName = new InputTabName();
9016 inputName.FormTitle = "Show UserStatus";
9017 inputName.FormDescription = Properties.Resources.FRMessage1;
9018 inputName.TabName = id;
9020 if (inputName.ShowDialog(this) != DialogResult.OK)
9022 if (string.IsNullOrWhiteSpace(inputName.TabName))
9025 id = inputName.TabName.Trim();
9028 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
9030 var cancellationToken = dialog.EnableCancellation();
9034 var task = this.tw.Api.UsersShow(id);
9035 user = await dialog.WaitForAsync(this, task);
9037 catch (WebApiException ex)
9039 if (!cancellationToken.IsCancellationRequested)
9040 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
9044 if (cancellationToken.IsCancellationRequested)
9048 await this.DoShowUserStatus(user);
9051 private async Task DoShowUserStatus(TwitterUser user)
9053 using var userDialog = new UserInfoDialog(this, this.tw.Api);
9054 var showUserTask = userDialog.ShowUserAsync(user);
9055 userDialog.ShowDialog(this);
9058 this.BringToFront();
9060 // ユーザー情報の表示が完了するまで userDialog を破棄しない
9064 internal Task ShowUserStatus(string id, bool showInputDialog)
9065 => this.DoShowUserStatus(id, showInputDialog);
9067 internal Task ShowUserStatus(string id)
9068 => this.DoShowUserStatus(id, true);
9070 private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9072 var post = this.CurrentPost;
9075 await this.ShowUserStatus(post.ScreenName, false);
9079 private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9081 var retweetedBy = this.CurrentPost?.RetweetedBy;
9082 if (retweetedBy != null)
9084 await this.ShowUserStatus(retweetedBy, false);
9088 private async void RtCountMenuItem_Click(object sender, EventArgs e)
9090 var post = this.CurrentPost;
9091 if (!this.ExistCurrentPost || post == null)
9094 var statusId = post.RetweetedId ?? post.StatusId;
9095 TwitterStatus status;
9097 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9099 var cancellationToken = dialog.EnableCancellation();
9103 var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9104 status = await dialog.WaitForAsync(this, task);
9106 catch (WebApiException ex)
9108 if (!cancellationToken.IsCancellationRequested)
9109 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9113 if (cancellationToken.IsCancellationRequested)
9117 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9120 private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9122 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9125 this.Visible = false;
9127 else if (Form.ActiveForm == null)
9129 this.Visible = true;
9130 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9132 this.BringToFront();
9133 this.StatusText.Focus();
9137 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9138 => this.MultiLinePullDownMenuItem.PerformClick();
9141 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9143 if (this.ImageSelector.Visible)
9144 this.ImageSelector.EndSelection();
9146 this.ImageSelector.BeginSelection();
9149 private void SelectMedia_DragEnter(DragEventArgs e)
9151 if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9153 e.Effect = DragDropEffects.Copy;
9156 e.Effect = DragDropEffects.None;
9159 private void SelectMedia_DragDrop(DragEventArgs e)
9162 this.BringToFront();
9164 var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9165 this.ImageSelector.BeginSelection();
9166 this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9167 this.StatusText.Focus();
9170 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9172 this.TimelinePanel.Visible = false;
9173 this.TimelinePanel.Enabled = false;
9176 private void ImageSelector_EndSelecting(object sender, EventArgs e)
9178 this.TimelinePanel.Visible = true;
9179 this.TimelinePanel.Enabled = true;
9180 this.CurrentListView.Focus();
9183 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9184 => this.AllowDrop = false;
9186 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9187 => this.AllowDrop = true;
9189 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9191 if (this.ImageSelector.Visible)
9193 this.MarkSettingCommonModified();
9194 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9198 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9199 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9202 /// StatusTextでCtrl+Vが押下された時の処理
9204 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9208 if (Clipboard.ContainsText())
9210 // clipboardにテキストがある場合は貼り付け処理
9211 this.StatusText.Paste(Clipboard.GetText());
9213 else if (Clipboard.ContainsImage())
9216 using var image = Clipboard.GetImage();
9217 this.ImageSelector.BeginSelection();
9218 this.ImageSelector.Model.AddMediaItemFromImage(image);
9220 else if (Clipboard.ContainsFileDropList())
9222 var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9223 this.ImageSelector.BeginSelection();
9224 this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9227 catch (ExternalException ex)
9229 MessageBox.Show(ex.Message);
9234 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9236 using var form = new ListManage(this.tw);
9237 form.ShowDialog(this);
9240 private bool ModifySettingCommon { get; set; }
9242 private bool ModifySettingLocal { get; set; }
9244 private bool ModifySettingAtId { get; set; }
9246 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9248 var post = this.CurrentPost;
9249 if (this.ExistCurrentPost && post != null && !post.IsDm)
9250 this.RtCountMenuItem.Enabled = true;
9252 this.RtCountMenuItem.Enabled = false;
9255 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9256 => this.CopyUserId();
9258 private void CopyUserId()
9260 var post = this.CurrentPost;
9261 if (post == null) return;
9262 var clstr = post.ScreenName;
9265 Clipboard.SetDataObject(clstr, false, 5, 100);
9267 catch (Exception ex)
9269 MessageBox.Show(ex.Message);
9273 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9275 var post = this.CurrentPost;
9276 if (this.ExistCurrentPost && post != null && !post.IsDm)
9280 await this.OpenRelatedTab(post);
9282 catch (TabException ex)
9284 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9290 /// 指定されたツイートに対する関連発言タブを開きます
9292 /// <param name="statusId">表示するツイートのID</param>
9293 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9294 public async Task OpenRelatedTab(PostId statusId)
9296 var post = this.statuses[statusId];
9301 post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9303 catch (WebApiException ex)
9305 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9310 await this.OpenRelatedTab(post);
9314 /// 指定されたツイートに対する関連発言タブを開きます
9316 /// <param name="post">表示する対象となるツイート</param>
9317 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9318 private async Task OpenRelatedTab(PostClass post)
9320 var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9321 if (tabRelated != null)
9323 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9326 var tabName = this.statuses.MakeTabName("Related Tweets");
9328 tabRelated = new RelatedPostsTabModel(tabName, post)
9330 UnreadManage = false,
9334 this.statuses.AddTab(tabRelated);
9335 this.AddNewTab(tabRelated, startup: false);
9337 this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9339 await this.RefreshTabAsync(tabRelated);
9341 var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9345 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9347 var tabPage = this.ListTab.TabPages[tabIndex];
9348 var listView = (DetailsListView)tabPage.Tag;
9349 var targetPost = tabRelated.TargetPost;
9350 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9352 if (index != -1 && index < listView.Items.Count)
9354 listView.SelectedIndices.Add(index);
9355 listView.Items[index].Focused = true;
9360 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9362 var buf = new StringBuilder();
9363 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9364 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9365 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9368 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9370 MyCommon.EndingFlag = true;
9374 Application.Restart();
9378 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9382 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9383 => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9385 private bool ExistCurrentPost
9389 var post = this.CurrentPost;
9390 return post != null && !post.IsDeleted;
9394 private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9395 => await this.ShowUserTimeline();
9397 private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9398 => await this.ShowRetweeterTimeline();
9400 private string GetUserIdFromCurPostOrInput(string caption)
9402 var id = this.CurrentPost?.ScreenName ?? "";
9404 using var inputName = new InputTabName();
9405 inputName.FormTitle = caption;
9406 inputName.FormDescription = Properties.Resources.FRMessage1;
9407 inputName.TabName = id;
9409 if (inputName.ShowDialog() == DialogResult.OK &&
9410 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9412 id = inputName.TabName.Trim();
9421 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9423 var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9424 if (!MyCommon.IsNullOrEmpty(id))
9426 await this.AddNewTabForUserTimeline(id);
9430 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9432 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9433 this.timelineScheduler.SystemResumed();
9436 private void SystemEvents_TimeChanged(object sender, EventArgs e)
9438 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9440 TimeZoneInfo.ClearCachedData();
9442 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9444 if (curTimeOffset != prevTimeOffset)
9447 this.listCache?.PurgeCache();
9448 this.CurrentListView.Refresh();
9450 this.DispSelectedPost(forceupdate: true);
9453 this.timelineScheduler.Reset();
9456 private void TimelineRefreshEnableChange(bool isEnable)
9458 this.timelineScheduler.Enabled = isEnable;
9461 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9462 => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9464 private async Task OpenUserAppointUrl()
9466 if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9468 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9470 var post = this.CurrentPost;
9473 var xUrl = this.settings.Common.UserAppointUrl;
9474 xUrl = xUrl.Replace("{ID}", post.ScreenName);
9476 var statusId = post.RetweetedId ?? post.StatusId;
9477 xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9479 await MyCommon.OpenInBrowserAsync(this, xUrl);
9484 await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9489 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9490 => await this.OpenUserAppointUrl();
9492 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9494 if (Form.ActiveForm == null)
9496 await this.InvokeAsync(() =>
9498 this.Visible = true;
9499 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9501 this.BringToFront();
9502 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9504 if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9508 if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9514 private void ReplaceAppName()
9516 this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9517 this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9520 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9521 => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9523 private void PostButton_KeyDown(object sender, KeyEventArgs e)
9525 if (e.KeyCode == Keys.Space)
9527 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9529 e.SuppressKeyPress = true;
9533 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9535 this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9536 this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9537 this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9538 this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9539 this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9541 this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9544 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9545 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9547 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9548 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9550 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9551 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9553 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9554 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9556 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9557 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9559 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9561 if (this.settings.Common.IconSize == iconSize) return;
9563 var oldIconCol = this.Use2ColumnsMode;
9565 this.settings.Common.IconSize = iconSize;
9566 this.ApplyListViewIconSize(iconSize);
9568 if (this.Use2ColumnsMode != oldIconCol)
9570 foreach (TabPage tp in this.ListTab.TabPages)
9572 this.ResetColumns((DetailsListView)tp.Tag);
9576 this.CurrentListView.Refresh();
9577 this.MarkSettingCommonModified();
9580 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9582 var state = this.LockListSortOrderToolStripMenuItem.Checked;
9583 if (this.settings.Common.SortOrderLock == state) return;
9585 this.settings.Common.SortOrderLock = state;
9586 this.MarkSettingCommonModified();
9589 private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9591 if (!MyCommon.IsNullOrEmpty(e.StatusText))
9593 this.StatusLabelUrl.Text = e.StatusText;
9597 this.SetStatusLabelUrl();