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 using System.Collections.Generic;
31 using System.ComponentModel;
37 using System.Net.Http;
39 using System.Text.RegularExpressions;
40 using System.Threading;
41 using System.Threading.Tasks;
42 using System.Windows.Forms;
43 using OpenTween.Models;
44 using OpenTween.Setting;
48 public partial class TweetDetailsView : UserControl
50 public TweenMain Owner { get; set; } = null!;
52 /// <summary>プロフィール画像のキャッシュ</summary>
53 public ImageCache IconCache { get; set; } = null!;
55 /// <summary><see cref="PostClass"/> のダンプを表示するか</summary>
56 public bool DumpPostClass { get; set; }
58 /// <summary>現在表示中の発言</summary>
59 public PostClass? CurrentPost { get; private set; }
62 public new bool TabStop
65 set => base.TabStop = value;
68 /// <summary>ステータスバーに表示するテキストの変化を通知するイベント</summary>
69 public event EventHandler<TweetDetailsViewStatusChengedEventArgs>? StatusChanged;
71 /// <summary><see cref="ContextMenuPostBrowser"/> 展開時の <see cref="PostBrowser"/>.StatusText を保持するフィールド</summary>
72 private string postBrowserStatusText = "";
74 public TweetDetailsView()
76 this.InitializeComponent();
81 this.AuthorNameLinkLabel.Text = "";
82 this.RetweetedByLinkLabel.Text = "";
83 this.DateTimeLabel.Text = "";
84 this.SourceLinkLabel.Text = "";
86 new InternetSecurityManager(this.PostBrowser);
87 this.PostBrowser.AllowWebBrowserDrop = false; // COMException を回避するため、ActiveX の初期化が終わってから設定する
90 public void ClearPostBrowser()
91 => this.PostBrowser.DocumentText = this.Owner.CreateDetailHtml("");
93 public async Task ShowPostDetails(PostClass post)
95 this.CurrentPost = post;
97 var loadTasks = new List<Task>();
99 using (ControlTransaction.Update(this.TableLayoutPanel1))
101 this.SourceLinkLabel.Text = post.Source;
102 this.SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
108 nameText = "DM FROM <- ";
110 nameText = "DM TO -> ";
116 nameText += post.ScreenName + "/" + post.Nickname;
117 this.AuthorNameLinkLabel.Text = nameText;
119 if (post.RetweetedId != null)
121 this.RetweetedByLinkLabel.Visible = true;
122 this.RetweetedByLinkLabel.Text = $"(RT:{post.RetweetedBy})";
126 this.RetweetedByLinkLabel.Visible = false;
127 this.RetweetedByLinkLabel.Text = "";
130 var nameForeColor = SystemColors.ControlText;
131 if (post.IsOwl && (SettingManager.Common.OneWayLove || post.IsDm))
132 nameForeColor = SettingManager.Local.ColorOWL;
133 if (post.RetweetedId != null)
134 nameForeColor = SettingManager.Local.ColorRetweet;
136 nameForeColor = SettingManager.Local.ColorFav;
138 this.AuthorNameLinkLabel.LinkColor = nameForeColor;
139 this.AuthorNameLinkLabel.ActiveLinkColor = nameForeColor;
140 this.RetweetedByLinkLabel.LinkColor = nameForeColor;
141 this.RetweetedByLinkLabel.ActiveLinkColor = nameForeColor;
143 loadTasks.Add(this.SetUserPictureAsync(post.ImageUrl));
145 this.DateTimeLabel.Text = post.CreatedAt.ToLocalTimeString();
148 if (this.DumpPostClass)
150 var sb = new StringBuilder(512);
152 sb.Append("-----Start PostClass Dump<br>");
153 sb.AppendFormat("TextFromApi : {0}<br>", post.TextFromApi);
154 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", post.TextFromApi);
155 sb.AppendFormat("StatusId : {0}<br>", post.StatusId);
156 sb.AppendFormat("ImageUrl : {0}<br>", post.ImageUrl);
157 sb.AppendFormat("InReplyToStatusId : {0}<br>", post.InReplyToStatusId);
158 sb.AppendFormat("InReplyToUser : {0}<br>", post.InReplyToUser);
159 sb.AppendFormat("IsDM : {0}<br>", post.IsDm);
160 sb.AppendFormat("IsFav : {0}<br>", post.IsFav);
161 sb.AppendFormat("IsMark : {0}<br>", post.IsMark);
162 sb.AppendFormat("IsMe : {0}<br>", post.IsMe);
163 sb.AppendFormat("IsOwl : {0}<br>", post.IsOwl);
164 sb.AppendFormat("IsProtect : {0}<br>", post.IsProtect);
165 sb.AppendFormat("IsRead : {0}<br>", post.IsRead);
166 sb.AppendFormat("IsReply : {0}<br>", post.IsReply);
168 foreach (var nm in post.ReplyToList.Select(x => x.ScreenName))
170 sb.AppendFormat("ReplyToList : {0}<br>", nm);
173 sb.AppendFormat("ScreenName : {0}<br>", post.ScreenName);
174 sb.AppendFormat("NickName : {0}<br>", post.Nickname);
175 sb.AppendFormat("Text : {0}<br>", post.Text);
176 sb.AppendFormat("(PlainText) : <xmp>{0}</xmp><br>", post.Text);
177 sb.AppendFormat("CreatedAt : {0}<br>", post.CreatedAt.ToLocalTimeString());
178 sb.AppendFormat("Source : {0}<br>", post.Source);
179 sb.AppendFormat("UserId : {0}<br>", post.UserId);
180 sb.AppendFormat("FilterHit : {0}<br>", post.FilterHit);
181 sb.AppendFormat("RetweetedBy : {0}<br>", post.RetweetedBy);
182 sb.AppendFormat("RetweetedId : {0}<br>", post.RetweetedId);
184 sb.AppendFormat("Media.Count : {0}<br>", post.Media.Count);
185 if (post.Media.Count > 0)
187 for (var i = 0; i < post.Media.Count; i++)
189 var info = post.Media[i];
190 sb.AppendFormat("Media[{0}].Url : {1}<br>", i, info.Url);
191 sb.AppendFormat("Media[{0}].VideoUrl : {1}<br>", i, info.VideoUrl ?? "---");
194 sb.Append("-----End PostClass Dump<br>");
196 this.PostBrowser.DocumentText = this.Owner.CreateDetailHtml(sb.ToString());
200 using (ControlTransaction.Update(this.PostBrowser))
202 this.PostBrowser.DocumentText =
203 this.Owner.CreateDetailHtml(post.IsDeleted ? "(DELETED)" : post.Text);
205 this.PostBrowser.Document.Window.ScrollTo(0, 0);
208 loadTasks.Add(this.AppendQuoteTweetAsync(post));
210 await Task.WhenAll(loadTasks);
213 public void ScrollDownPostBrowser(bool forward)
215 var doc = this.PostBrowser.Document;
216 if (doc == null) return;
218 var tags = doc.GetElementsByTagName("html");
222 tags[0].ScrollTop += SettingManager.Local.FontDetail.Height;
224 tags[0].ScrollTop -= SettingManager.Local.FontDetail.Height;
228 public void PageDownPostBrowser(bool forward)
230 var doc = this.PostBrowser.Document;
231 if (doc == null) return;
233 var tags = doc.GetElementsByTagName("html");
237 tags[0].ScrollTop += this.PostBrowser.ClientRectangle.Height - SettingManager.Local.FontDetail.Height;
239 tags[0].ScrollTop -= this.PostBrowser.ClientRectangle.Height - SettingManager.Local.FontDetail.Height;
243 public HtmlElement[] GetLinkElements()
245 return this.PostBrowser.Document.Links.Cast<HtmlElement>()
246 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
250 private async Task SetUserPictureAsync(string normalImageUrl, bool force = false)
252 if (MyCommon.IsNullOrEmpty(normalImageUrl))
255 if (this.IconCache == null)
258 this.ClearUserPicture();
260 var imageSize = Twitter.DecideProfileImageSize(this.UserPicture.Width);
261 var cachedImage = this.IconCache.TryGetLargerOrSameSizeFromCache(normalImageUrl, imageSize);
262 if (cachedImage != null)
264 // 既にキャッシュされていればそれを表示して終了
265 this.UserPicture.Image = cachedImage.Clone();
269 // 小さいサイズの画像がキャッシュにある場合は高解像度の画像が取得できるまでの間表示する
270 var fallbackImage = this.IconCache.TryGetLargerOrSameSizeFromCache(normalImageUrl, "mini");
271 if (fallbackImage != null)
272 this.UserPicture.Image = fallbackImage.Clone();
274 await this.UserPicture.SetImageFromTask(
277 var imageUrl = Twitter.CreateProfileImageUrl(normalImageUrl, imageSize);
278 var image = await this.IconCache.DownloadImageAsync(imageUrl, force)
279 .ConfigureAwait(false);
281 return await image.CloneAsync()
282 .ConfigureAwait(false);
284 useStatusImage: false
289 /// UserPicture.Image に設定されている画像を破棄します。
291 private void ClearUserPicture()
293 if (this.UserPicture.Image != null)
295 var oldImage = this.UserPicture.Image;
296 this.UserPicture.Image = null;
302 /// 発言詳細欄のツイートURLを展開する
304 private async Task AppendQuoteTweetAsync(PostClass post)
306 var quoteStatusIds = post.QuoteStatusIds;
307 if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
311 var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
313 var loadingReplyHtml = string.Empty;
314 if (post.InReplyToStatusId != null)
315 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
317 var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
319 using (ControlTransaction.Update(this.PostBrowser))
320 this.PostBrowser.DocumentText = this.Owner.CreateDetailHtml(body);
323 var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
325 if (post.InReplyToStatusId != null)
326 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
328 var quoteHtmls = await Task.WhenAll(loadTweetTasks);
330 // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
331 if (this.CurrentPost != post || this.CurrentPost.IsDeleted)
334 body = post.Text + string.Concat(quoteHtmls);
336 using (ControlTransaction.Update(this.PostBrowser))
337 this.PostBrowser.DocumentText = this.Owner.CreateDetailHtml(body);
340 private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
342 var post = TabInformations.GetInstance()[statusId];
347 post = await this.Owner.TwitterInstance.GetStatusApi(false, statusId)
348 .ConfigureAwait(false);
350 catch (WebApiException ex)
352 return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
356 if (!TabInformations.GetInstance().AddQuoteTweet(post))
357 return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
360 return FormatQuoteTweetHtml(post, isReply);
363 internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
365 var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
366 " — " + WebUtility.HtmlEncode(post.Nickname) +
367 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
368 WebUtility.HtmlEncode(post.CreatedAt.ToLocalTimeString());
370 return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
373 internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
375 var blockClassName = "quote-tweet";
378 blockClassName += " reply";
380 return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
381 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
386 /// 指定されたHTMLからリンクを除去します
388 internal static string StripLinkTagHtml(string html)
389 => Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1"); // a 要素はネストされていない前提の正規表現パターン
391 public async Task DoTranslation()
393 if (this.CurrentPost == null || this.CurrentPost.IsDeleted)
396 await this.DoTranslation(this.CurrentPost.TextFromApi);
399 private async Task DoTranslation(string str)
401 if (MyCommon.IsNullOrEmpty(str))
404 var bing = new Bing();
407 var translatedText = await bing.TranslateAsync(str,
409 langTo: SettingManager.Common.TranslateLanguage);
411 this.PostBrowser.DocumentText = this.Owner.CreateDetailHtml(translatedText);
413 catch (WebApiException e)
415 this.RaiseStatusChanged("Err:" + e.Message);
417 catch (OperationCanceledException)
419 this.RaiseStatusChanged("Err:Timeout");
423 private async Task DoSearchToolStrip(string url)
425 // 発言詳細で「選択文字列で検索」(選択文字列取得)
426 var selText = this.PostBrowser.GetSelectedText();
430 if (url == Properties.Resources.SearchItem4Url)
433 this.Owner.AddNewTabForSearch(selText);
437 var tmp = string.Format(url, Uri.EscapeDataString(selText));
438 await MyCommon.OpenInBrowserAsync(this, tmp);
442 private string? GetUserId()
444 var m = Regex.Match(this.postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
445 if (m.Success && this.Owner.IsTwitterId(m.Result("${ScreenName}")))
446 return m.Result("${ScreenName}");
451 protected void RaiseStatusChanged(string statusText)
452 => this.StatusChanged?.Invoke(this, new TweetDetailsViewStatusChengedEventArgs(statusText));
454 private void TweetDetailsView_FontChanged(object sender, EventArgs e)
456 // OTBaseForm.GlobalFont による UI フォントの変更に対応
457 var origFont = this.AuthorNameLinkLabel.Font;
458 this.AuthorNameLinkLabel.Font = new Font(this.Font.Name, origFont.Size, origFont.Style);
459 this.RetweetedByLinkLabel.Font = new Font(this.Font.Name, origFont.Size, origFont.Style);
462 #region TableLayoutPanel1
464 private async void UserPicture_Click(object sender, EventArgs e)
466 var screenName = this.CurrentPost?.ScreenName;
467 if (screenName != null)
468 await this.Owner.ShowUserStatus(screenName, showInputDialog: false);
471 private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
473 if (e.Url.AbsoluteUri != "about:blank")
475 await this.ShowPostDetails(this.CurrentPost!); // 現在の発言を表示し直す (Navigated の段階ではキャンセルできない)
476 await MyCommon.OpenInBrowserAsync(this, e.Url.OriginalString);
480 private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
482 if (e.Url.Scheme == "data")
484 this.RaiseStatusChanged(this.PostBrowser.StatusText.Replace("&", "&&"));
486 else if (e.Url.AbsoluteUri != "about:blank")
489 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
490 await this.Owner.OpenUriAsync(e.Url, MyCommon.IsKeyDown(Keys.Control));
494 private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
496 var keyRes = this.Owner.CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out var asyncTask);
503 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
505 var shortcut = (Shortcut)e.KeyData;
510 case Shortcut.CtrlIns:
514 // その他のショートカットキーは無効にする
521 if (asyncTask != null)
525 private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
529 if (this.PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
530 || this.PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
531 || this.PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
533 this.RaiseStatusChanged(this.PostBrowser.StatusText.Replace("&", "&&"));
535 if (MyCommon.IsNullOrEmpty(this.PostBrowser.StatusText))
537 this.RaiseStatusChanged(statusText: "");
545 private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
547 var sourceUri = this.CurrentPost?.SourceUri;
548 if (sourceUri != null && e.Button == MouseButtons.Left)
550 await MyCommon.OpenInBrowserAsync(this, sourceUri.AbsoluteUri);
554 private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
556 var sourceUri = this.CurrentPost?.SourceUri;
557 if (sourceUri != null)
559 this.RaiseStatusChanged(MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri));
563 private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
564 => this.RaiseStatusChanged(statusText: "");
568 #region ContextMenuUserPicture
570 private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
572 // 発言詳細のアイコン右クリック時のメニュー制御
573 if (this.CurrentPost != null)
575 var name = this.CurrentPost.ImageUrl;
576 if (!MyCommon.IsNullOrEmpty(name))
578 var idx = name.LastIndexOf('/');
581 name = Path.GetFileName(name.Substring(idx));
582 if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
584 name = name.Replace("_normal", "");
585 this.IconNameToolStripMenuItem.Text = name;
586 this.IconNameToolStripMenuItem.Enabled = true;
590 this.IconNameToolStripMenuItem.Enabled = false;
591 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
596 this.IconNameToolStripMenuItem.Enabled = false;
597 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
600 this.ReloadIconToolStripMenuItem.Enabled = true;
602 if (this.IconCache.TryGetFromCache(this.CurrentPost.ImageUrl) != null)
604 this.SaveIconPictureToolStripMenuItem.Enabled = true;
608 this.SaveIconPictureToolStripMenuItem.Enabled = false;
613 this.IconNameToolStripMenuItem.Enabled = false;
614 this.ReloadIconToolStripMenuItem.Enabled = false;
615 this.SaveIconPictureToolStripMenuItem.Enabled = false;
616 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
621 this.IconNameToolStripMenuItem.Enabled = false;
622 this.ReloadIconToolStripMenuItem.Enabled = false;
623 this.SaveIconPictureToolStripMenuItem.Enabled = false;
624 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
626 if (this.CurrentPost != null)
628 if (this.CurrentPost.UserId == this.Owner.TwitterInstance.UserId)
630 this.FollowToolStripMenuItem.Enabled = false;
631 this.UnFollowToolStripMenuItem.Enabled = false;
632 this.ShowFriendShipToolStripMenuItem.Enabled = false;
633 this.ShowUserStatusToolStripMenuItem.Enabled = true;
634 this.SearchPostsDetailNameToolStripMenuItem.Enabled = true;
635 this.SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
636 this.ListManageUserContextToolStripMenuItem3.Enabled = true;
640 this.FollowToolStripMenuItem.Enabled = true;
641 this.UnFollowToolStripMenuItem.Enabled = true;
642 this.ShowFriendShipToolStripMenuItem.Enabled = true;
643 this.ShowUserStatusToolStripMenuItem.Enabled = true;
644 this.SearchPostsDetailNameToolStripMenuItem.Enabled = true;
645 this.SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
646 this.ListManageUserContextToolStripMenuItem3.Enabled = true;
651 this.FollowToolStripMenuItem.Enabled = false;
652 this.UnFollowToolStripMenuItem.Enabled = false;
653 this.ShowFriendShipToolStripMenuItem.Enabled = false;
654 this.ShowUserStatusToolStripMenuItem.Enabled = false;
655 this.SearchPostsDetailNameToolStripMenuItem.Enabled = false;
656 this.SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
657 this.ListManageUserContextToolStripMenuItem3.Enabled = false;
661 private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
663 if (this.CurrentPost == null)
666 if (this.CurrentPost.UserId == this.Owner.TwitterInstance.UserId)
669 await this.Owner.FollowCommand(this.CurrentPost.ScreenName);
672 private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
674 if (this.CurrentPost == null)
677 if (this.CurrentPost.UserId == this.Owner.TwitterInstance.UserId)
680 await this.Owner.RemoveCommand(this.CurrentPost.ScreenName, false);
683 private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
685 if (this.CurrentPost == null)
688 if (this.CurrentPost.UserId == this.Owner.TwitterInstance.UserId)
691 await this.Owner.ShowFriendship(this.CurrentPost.ScreenName);
694 // ListManageUserContextToolStripMenuItem3.Click は ListManageUserContextToolStripMenuItem_Click を共用
696 private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
698 if (this.CurrentPost == null)
701 await this.Owner.ShowUserStatus(this.CurrentPost.ScreenName, false);
704 private async void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
706 if (this.CurrentPost == null)
709 await this.Owner.AddNewTabForUserTimeline(this.CurrentPost.ScreenName);
712 private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
714 if (this.CurrentPost == null)
717 this.Owner.AddNewTabForSearch("@" + this.CurrentPost.ScreenName);
720 private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
722 var imageNormalUrl = this.CurrentPost?.ImageUrl;
723 if (MyCommon.IsNullOrEmpty(imageNormalUrl))
726 var imageOriginalUrl = Twitter.CreateProfileImageUrl(imageNormalUrl, "original");
727 await MyCommon.OpenInBrowserAsync(this, imageOriginalUrl);
730 private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
732 var imageUrl = this.CurrentPost?.ImageUrl;
733 if (MyCommon.IsNullOrEmpty(imageUrl))
736 await this.SetUserPictureAsync(imageUrl, force: true);
739 private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
741 var imageUrl = this.CurrentPost?.ImageUrl;
742 if (MyCommon.IsNullOrEmpty(imageUrl))
745 var memoryImage = this.IconCache.TryGetFromCache(imageUrl);
746 if (memoryImage == null)
749 this.Owner.SaveFileDialog1.FileName = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);
751 if (this.Owner.SaveFileDialog1.ShowDialog() == DialogResult.OK)
755 using var orgBmp = new Bitmap(memoryImage.Image);
756 using var bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height);
758 using (var g = Graphics.FromImage(bmp2))
760 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
761 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
763 bmp2.Save(this.Owner.SaveFileDialog1.FileName);
767 // 処理中にキャッシュアウトする可能性あり
774 #region ContextMenuPostBrowser
776 private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
779 if (this.PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
781 this.postBrowserStatusText = this.PostBrowser.StatusText;
782 var name = this.GetUserId();
783 this.UrlCopyContextMenuItem.Enabled = true;
786 this.FollowContextMenuItem.Enabled = true;
787 this.RemoveContextMenuItem.Enabled = true;
788 this.FriendshipContextMenuItem.Enabled = true;
789 this.ShowUserStatusContextMenuItem.Enabled = true;
790 this.SearchPostsDetailToolStripMenuItem.Enabled = true;
791 this.IdFilterAddMenuItem.Enabled = true;
792 this.ListManageUserContextToolStripMenuItem.Enabled = true;
793 this.SearchAtPostsDetailToolStripMenuItem.Enabled = true;
797 this.FollowContextMenuItem.Enabled = false;
798 this.RemoveContextMenuItem.Enabled = false;
799 this.FriendshipContextMenuItem.Enabled = false;
800 this.ShowUserStatusContextMenuItem.Enabled = false;
801 this.SearchPostsDetailToolStripMenuItem.Enabled = false;
802 this.IdFilterAddMenuItem.Enabled = false;
803 this.ListManageUserContextToolStripMenuItem.Enabled = false;
804 this.SearchAtPostsDetailToolStripMenuItem.Enabled = false;
807 if (Regex.IsMatch(this.postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
808 this.UseHashtagMenuItem.Enabled = true;
810 this.UseHashtagMenuItem.Enabled = false;
814 this.postBrowserStatusText = "";
815 this.UrlCopyContextMenuItem.Enabled = false;
816 this.FollowContextMenuItem.Enabled = false;
817 this.RemoveContextMenuItem.Enabled = false;
818 this.FriendshipContextMenuItem.Enabled = false;
819 this.ShowUserStatusContextMenuItem.Enabled = false;
820 this.SearchPostsDetailToolStripMenuItem.Enabled = false;
821 this.SearchAtPostsDetailToolStripMenuItem.Enabled = false;
822 this.UseHashtagMenuItem.Enabled = false;
823 this.IdFilterAddMenuItem.Enabled = false;
824 this.ListManageUserContextToolStripMenuItem.Enabled = false;
826 // 文字列選択されていないときは選択文字列関係の項目を非表示に
827 var selText = this.PostBrowser.GetSelectedText();
830 this.SelectionSearchContextMenuItem.Enabled = false;
831 this.SelectionCopyContextMenuItem.Enabled = false;
832 this.SelectionTranslationToolStripMenuItem.Enabled = false;
836 this.SelectionSearchContextMenuItem.Enabled = true;
837 this.SelectionCopyContextMenuItem.Enabled = true;
838 this.SelectionTranslationToolStripMenuItem.Enabled = true;
840 // 発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
841 var ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
842 var fAllFlag = false;
843 foreach (Match mu in ma)
845 if (!mu.Result("${ScreenName}").Equals(this.Owner.TwitterInstance.Username, StringComparison.InvariantCultureIgnoreCase))
851 this.FriendshipAllMenuItem.Enabled = fAllFlag;
853 if (this.CurrentPost == null)
854 this.TranslationToolStripMenuItem.Enabled = false;
856 this.TranslationToolStripMenuItem.Enabled = true;
861 private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
862 => await this.DoSearchToolStrip(Properties.Resources.SearchItem2Url);
864 private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
865 => await this.DoSearchToolStrip(Properties.Resources.SearchItem1Url);
867 private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
868 => await this.DoSearchToolStrip(Properties.Resources.SearchItem4Url);
870 private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
872 // 発言詳細の選択文字列で現在のタブを検索
873 var selText = this.PostBrowser.GetSelectedText();
877 var searchOptions = new SearchWordDialog.SearchOptions(
878 SearchWordDialog.SearchType.Timeline,
881 caseSensitive: false,
884 this.Owner.SearchDialog.ResultOptions = searchOptions;
886 this.Owner.DoTabSearch(
888 searchOptions.CaseSensitive,
889 searchOptions.UseRegex,
890 TweenMain.SEARCHTYPE.NextSearch);
894 private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
897 var selText = this.PostBrowser.GetSelectedText();
900 Clipboard.SetDataObject(selText, false, 5, 100);
904 MessageBox.Show(ex.Message);
908 private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
912 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
914 if (link.GetAttribute("href") == this.postBrowserStatusText)
916 var linkStr = link.GetAttribute("title");
917 if (MyCommon.IsNullOrEmpty(linkStr))
918 linkStr = link.GetAttribute("href");
920 Clipboard.SetDataObject(linkStr, false, 5, 100);
925 Clipboard.SetDataObject(this.postBrowserStatusText, false, 5, 100);
929 MessageBox.Show(ex.Message);
933 private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
934 => this.PostBrowser.Document.ExecCommand("SelectAll", false, null); // 発言詳細ですべて選択
936 private async void FollowContextMenuItem_Click(object sender, EventArgs e)
938 var name = this.GetUserId();
940 await this.Owner.FollowCommand(name);
943 private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
945 var name = this.GetUserId();
947 await this.Owner.RemoveCommand(name, false);
950 private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
952 var name = this.GetUserId();
954 await this.Owner.ShowFriendship(name);
957 private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
959 var ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
960 var ids = new List<string>();
961 foreach (Match mu in ma)
963 if (!mu.Result("${ScreenName}").Equals(this.Owner.TwitterInstance.Username, StringComparison.InvariantCultureIgnoreCase))
965 ids.Add(mu.Result("${ScreenName}"));
969 await this.Owner.ShowFriendship(ids.ToArray());
972 private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
974 var name = this.GetUserId();
976 await this.Owner.ShowUserStatus(name);
979 private async void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
981 var name = this.GetUserId();
983 await this.Owner.AddNewTabForUserTimeline(name);
986 private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
988 var name = this.GetUserId();
989 if (name != null) this.Owner.AddNewTabForSearch("@" + name);
992 private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
994 var name = this.GetUserId();
996 this.Owner.AddFilterRuleByScreenName(name);
999 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
1001 var menuItem = (ToolStripMenuItem)sender;
1004 if (menuItem.Owner == this.ContextMenuPostBrowser)
1006 user = this.GetUserId();
1007 if (user == null) return;
1009 else if (this.CurrentPost != null)
1011 user = this.CurrentPost.ScreenName;
1018 this.Owner.ListManageUserContext(user);
1021 private void UseHashtagMenuItem_Click(object sender, EventArgs e)
1023 var m = Regex.Match(this.postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
1025 this.Owner.SetPermanentHashtag(Uri.UnescapeDataString(m.Groups["hash"].Value));
1028 private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
1030 var text = this.PostBrowser.GetSelectedText();
1031 await this.DoTranslation(text);
1034 private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
1035 => await this.DoTranslation();
1039 #region ContextMenuSource
1041 private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
1043 if (this.CurrentPost == null || this.CurrentPost.IsDeleted || this.CurrentPost.IsDm)
1045 this.SourceCopyMenuItem.Enabled = false;
1046 this.SourceUrlCopyMenuItem.Enabled = false;
1050 this.SourceCopyMenuItem.Enabled = true;
1051 this.SourceUrlCopyMenuItem.Enabled = true;
1055 private void SourceCopyMenuItem_Click(object sender, EventArgs e)
1057 if (this.CurrentPost == null)
1062 Clipboard.SetDataObject(this.CurrentPost.Source, false, 5, 100);
1064 catch (Exception ex)
1066 MessageBox.Show(ex.Message);
1070 private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
1072 var sourceUri = this.CurrentPost?.SourceUri;
1073 if (sourceUri == null)
1078 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
1080 catch (Exception ex)
1082 MessageBox.Show(ex.Message);
1088 private async void AuthorNameLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
1090 var screenName = this.CurrentPost?.ScreenName;
1091 if (screenName != null)
1092 await this.Owner.ShowUserStatus(screenName, showInputDialog: false);
1095 private async void RetweetedByLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
1097 var screenName = this.CurrentPost?.RetweetedBy;
1098 if (screenName != null)
1099 await this.Owner.ShowUserStatus(screenName, showInputDialog: false);
1103 public class TweetDetailsViewStatusChengedEventArgs : EventArgs
1105 /// <summary>ステータスバーに表示するテキスト</summary>
1107 /// 空文字列の場合は <see cref="TweenMain"/> の既定のテキストを表示する
1109 public string StatusText { get; }
1111 public TweetDetailsViewStatusChengedEventArgs(string statusText)
1112 => this.StatusText = statusText;