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.Connection;
56 using OpenTween.Models;
57 using OpenTween.OpenTweenCustomControl;
58 using OpenTween.Setting;
59 using OpenTween.Thumbnail;
63 public partial class TweenMain : OTBaseForm
67 /// <summary>画面サイズ</summary>
70 /// <summary>画面位置</summary>
73 /// <summary>区切り位置</summary>
76 /// <summary>発言欄区切り位置</summary>
77 private int _mySpDis2;
79 /// <summary>プレビュー区切り位置</summary>
80 private int _mySpDis3;
82 /// <summary>アイコンサイズ</summary>
84 /// 現在は16、24、48の3種類。将来直接数字指定可能とする
85 /// 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様
89 private bool _iconCol; // 1列表示の時true(48サイズのとき)
92 private bool _initial; // true:起動時処理中
93 private bool _initialLayout = true;
94 private bool _ignoreConfigSave; // true:起動時処理中
96 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
97 private bool _tabDrag;
99 private TabPage? _beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
100 private Point _tabMouseDownPoint;
102 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
103 private string? _rclickTabName;
105 private readonly object _syncObject = new object(); // ロック用
107 private const string detailHtmlFormatHeaderMono =
108 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
109 + "<style type=\"text/css\"><!-- "
110 + "body, p, pre {margin: 0;} "
111 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
112 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
113 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
114 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
115 + ".quote-tweet.reply {border-color: #f33;} "
116 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
118 + "</head><body><pre>";
119 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
120 private const string detailHtmlFormatHeaderColor =
121 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
122 + "<style type=\"text/css\"><!-- "
123 + "body, p, pre {margin: 0;} "
124 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
125 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
126 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
127 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
128 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
129 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
131 + "</head><body><p>";
132 private const string detailHtmlFormatFooterColor = "</p></body></html>";
133 private string detailHtmlFormatHeader = null!;
134 private string detailHtmlFormatFooter = null!;
136 private bool _myStatusError = false;
137 private bool _myStatusOnline = false;
138 private bool soundfileListup = false;
139 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
142 private readonly TwitterApi twitterApi = new TwitterApi();
143 private Twitter tw = null!;
146 private readonly GrowlHelper gh = new GrowlHelper(ApplicationSettings.ApplicationName);
150 /// <summary>検索画面インスタンス</summary>
151 internal SearchWordDialog SearchDialog = new SearchWordDialog();
153 private readonly OpenURL UrlDialog = new OpenURL();
155 /// <summary>@id補助</summary>
156 public AtIdSupplement AtIdSupl = null!;
158 /// <summary>Hashtag補助</summary>
159 public AtIdSupplement HashSupl = null!;
161 public HashtagManage HashMgr = null!;
162 private EventViewerDialog evtDialog = null!;
166 /// <summary>未読用フォント</summary>
167 private Font _fntUnread = null!;
169 /// <summary>未読用文字色</summary>
170 private Color _clUnread;
172 /// <summary>既読用フォント</summary>
173 private Font _fntReaded = null!;
175 /// <summary>既読用文字色</summary>
176 private Color _clReaded;
178 /// <summary>Fav用文字色</summary>
179 private Color _clFav;
181 /// <summary>片思い用文字色</summary>
182 private Color _clOWL;
184 /// <summary>Retweet用文字色</summary>
185 private Color _clRetweet;
187 /// <summary>選択中の行用文字色</summary>
188 private readonly Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);
190 /// <summary>発言詳細部用フォント</summary>
191 private Font _fntDetail = null!;
193 /// <summary>発言詳細部用色</summary>
194 private Color _clDetail;
196 /// <summary>発言詳細部用リンク文字色</summary>
197 private Color _clDetailLink;
199 /// <summary>発言詳細部用背景色</summary>
200 private Color _clDetailBackcolor;
202 /// <summary>自分の発言用背景色</summary>
203 private Color _clSelf;
205 /// <summary>自分宛返信用背景色</summary>
206 private Color _clAtSelf;
208 /// <summary>選択発言者の他の発言用背景色</summary>
209 private Color _clTarget;
211 /// <summary>選択発言中の返信先用背景色</summary>
212 private Color _clAtTarget;
214 /// <summary>選択発言者への返信発言用背景色</summary>
215 private Color _clAtFromTarget;
217 /// <summary>選択発言の唯一@先</summary>
218 private Color _clAtTo;
220 /// <summary>リスト部通常発言背景色</summary>
221 private Color _clListBackcolor;
223 /// <summary>入力欄背景色</summary>
224 private Color _clInputBackcolor;
226 /// <summary>入力欄文字色</summary>
227 private Color _clInputFont;
229 /// <summary>入力欄フォント</summary>
230 private Font _fntInputFont = null!;
232 /// <summary>アイコン画像リスト</summary>
233 private ImageCache IconCache = null!;
235 /// <summary>タスクトレイアイコン:通常時 (At.ico)</summary>
236 private Icon NIconAt = null!;
238 /// <summary>タスクトレイアイコン:通信エラー時 (AtRed.ico)</summary>
239 private Icon NIconAtRed = null!;
241 /// <summary>タスクトレイアイコン:オフライン時 (AtSmoke.ico)</summary>
242 private Icon NIconAtSmoke = null!;
244 /// <summary>タスクトレイアイコン:更新中 (Refresh.ico)</summary>
245 private Icon[] NIconRefresh = new Icon[4];
247 /// <summary>未読のあるタブ用アイコン (Tab.ico)</summary>
248 private Icon TabIcon = null!;
250 /// <summary>画面左上のアイコン (Main.ico)</summary>
251 private Icon MainIcon = null!;
253 private Icon ReplyIcon = null!;
254 private Icon ReplyIconBlink = null!;
256 private readonly ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
258 private PostClass? _anchorPost;
259 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
261 /// <summary>発言履歴</summary>
262 private readonly List<StatusTextHistory> _history = new List<StatusTextHistory>();
264 /// <summary>発言履歴カレントインデックス</summary>
267 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
269 /// <summary>リプライ先のステータスID・スクリーン名</summary>
270 private (long StatusId, string ScreenName)? inReplyTo = null;
273 private readonly List<DateTimeUtc> _postTimestamps = new List<DateTimeUtc>();
274 private readonly List<DateTimeUtc> _favTimestamps = new List<DateTimeUtc>();
277 private readonly SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
278 private SolidBrush _brsBackColorMine = null!;
279 private SolidBrush _brsBackColorAt = null!;
280 private SolidBrush _brsBackColorYou = null!;
281 private SolidBrush _brsBackColorAtYou = null!;
282 private SolidBrush _brsBackColorAtFromTarget = null!;
283 private SolidBrush _brsBackColorAtTo = null!;
284 private SolidBrush _brsBackColorNone = null!;
286 /// <summary>Listにフォーカスないときの選択行の背景色</summary>
287 private readonly SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace));
289 private readonly StringFormat sfTab = new StringFormat();
291 //////////////////////////////////////////////////////////////////////////////////////////////////////////
292 private TabInformations _statuses = null!;
295 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
298 /// キャッシュクリアのために null が代入されることがあるため、
299 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
300 /// 一旦ローカル変数に代入してから参照すること。
302 private ListViewItemCache? _listItemCache = null;
304 internal class ListViewItemCache
306 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
307 public ListView TargetList { get; set; } = null!;
309 /// <summary>キャッシュする範囲の開始インデックス</summary>
310 public int StartIndex { get; set; }
312 /// <summary>キャッシュする範囲の終了インデックス</summary>
313 public int EndIndex { get; set; }
315 /// <summary>キャッシュされた範囲に対応する <see cref="ListViewItem"/> と <see cref="PostClass"/> の組</summary>
316 public (ListViewItem, PostClass)[] Cache { get; set; } = null!;
318 /// <summary>キャッシュされたアイテムの件数</summary>
320 => this.EndIndex - this.StartIndex + 1;
322 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
323 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
324 public bool Contains(int index)
325 => index >= this.StartIndex && index <= this.EndIndex;
327 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
328 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
329 public bool IsSupersetOf(int rangeStart, int rangeEnd)
330 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
332 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
333 /// <returns>取得に成功すれば true、それ以外は false</returns>
334 public bool TryGetValue(int index, [NotNullWhen(true)] out ListViewItem? item, [NotNullWhen(true)] out PostClass? post)
336 if (this.Contains(index))
338 (item, post) = this.Cache[index - this.StartIndex];
350 private bool _isColumnChanged = false;
352 private const int MAX_WORKER_THREADS = 20;
353 private readonly SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
354 private readonly CancellationTokenSource workerCts = new CancellationTokenSource();
355 private readonly IProgress<string> workerProgress = null!;
357 private int UnreadCounter = -1;
358 private int UnreadAtCounter = -1;
360 private readonly string[] ColumnOrgText = new string[9];
361 private readonly string[] ColumnText = new string[9];
363 private bool _DoFavRetweetFlags = false;
365 //////////////////////////////////////////////////////////////////////////////////////////////////////////
367 private readonly TimelineScheduler timelineScheduler = new TimelineScheduler();
368 private ThrottlingTimer RefreshThrottlingTimer = null!;
369 private ThrottlingTimer colorizeDebouncer = null!;
370 private ThrottlingTimer selectionDebouncer = null!;
371 private ThrottlingTimer saveConfigDebouncer = null!;
373 private string recommendedStatusFooter = null!;
374 private bool urlMultibyteSplit = false;
375 private bool preventSmsCommand = true;
378 private struct urlUndo
380 public string Before;
384 private List<urlUndo>? urlUndoBuffer = null;
386 private readonly struct ReplyChain
388 public readonly long OriginalId;
389 public readonly long InReplyToId;
390 public readonly TabModel OriginalTab;
392 public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
394 this.OriginalId = originalId;
395 this.InReplyToId = inReplyToId;
396 this.OriginalTab = originalTab;
400 /// <summary>[, ]でのリプライ移動の履歴</summary>
401 private Stack<ReplyChain>? replyChains;
403 /// <summary>ポスト選択履歴</summary>
404 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new Stack<(TabModel, PostClass?)>();
406 public TabModel CurrentTab
407 => this._statuses.SelectedTab;
409 public string CurrentTabName
410 => this._statuses.SelectedTabName;
412 public TabPage CurrentTabPage
413 => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
415 public DetailsListView CurrentListView
416 => (DetailsListView)this.CurrentTabPage.Tag;
418 public PostClass? CurrentPost
419 => this.CurrentTab.SelectedPost;
421 /// <summary>検索処理タイプ</summary>
422 internal enum SEARCHTYPE
429 private class StatusTextHistory
431 public string status = "";
432 public (long StatusId, string ScreenName)? inReplyTo = null;
434 /// <summary>画像投稿サービス名</summary>
435 public string imageService = "";
437 public IMediaItem[]? mediaItems = null;
438 public StatusTextHistory()
441 public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
443 this.status = status;
444 this.inReplyTo = inReplyTo;
448 private void TweenMain_Activated(object sender, EventArgs e)
450 //画面がアクティブになったら、発言欄の背景色戻す
451 if (StatusText.Focused)
453 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
457 private bool disposed = false;
460 /// 使用中のリソースをすべてクリーンアップします。
462 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
463 protected override void Dispose(bool disposing)
465 base.Dispose(disposing);
472 this.components?.Dispose();
475 SearchDialog.Dispose();
478 NIconAtRed?.Dispose();
479 NIconAtSmoke?.Dispose();
480 foreach (var iconRefresh in this.NIconRefresh)
482 iconRefresh?.Dispose();
486 ReplyIcon?.Dispose();
487 ReplyIconBlink?.Dispose();
488 _listViewImageList.Dispose();
489 _brsHighLight.Dispose();
490 _brsBackColorMine?.Dispose();
491 _brsBackColorAt?.Dispose();
492 _brsBackColorYou?.Dispose();
493 _brsBackColorAtYou?.Dispose();
494 _brsBackColorAtFromTarget?.Dispose();
495 _brsBackColorAtTo?.Dispose();
496 _brsBackColorNone?.Dispose();
497 _brsDeactiveSelection?.Dispose();
501 this.workerCts.Cancel();
503 if (IconCache != null)
505 this.IconCache.CancelAsync();
506 this.IconCache.Dispose();
509 this.thumbnailTokenSource?.Dispose();
512 this.twitterApi.Dispose();
513 this._hookGlobalHotkey.Dispose();
516 // 終了時にRemoveHandlerしておかないとメモリリークする
517 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
518 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
519 Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
521 this.disposed = true;
524 private void LoadIcons()
526 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
527 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
530 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
533 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
536 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
539 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
541 // タスクトレイ: オフライン時アイコン
542 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
544 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
545 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
546 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
548 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
549 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
550 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
551 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
552 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
554 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
556 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
557 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
558 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
559 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
560 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
562 if (iconReply != null && iconReplyBlink != null)
564 this.ReplyIcon = iconReply;
565 this.ReplyIconBlink = iconReplyBlink;
569 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
570 this.ReplyIconBlink = this.NIconAt;
573 if (iconRefresh1 == null)
575 this.NIconRefresh = new[] {
576 Properties.Resources.Refresh, Properties.Resources.Refresh2,
577 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
580 else if (iconRefresh2 == null)
582 this.NIconRefresh = new[] { iconRefresh1 };
584 else if (iconRefresh3 == null)
586 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
588 else if (iconRefresh4 == null)
590 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
592 else // iconRefresh1 から iconRefresh4 まで全て揃っている
594 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
598 private Icon? LoadIcon(string filePath)
600 if (!File.Exists(filePath))
605 return new Icon(filePath);
613 private void InitColumns(ListView list, bool startup)
615 this.InitColumnText();
617 ColumnHeader[]? columns = null;
624 new ColumnHeader(), // アイコン
625 new ColumnHeader(), // 本文
628 columns[0].Text = this.ColumnText[0];
629 columns[1].Text = this.ColumnText[2];
633 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
635 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
636 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
637 columns[0].DisplayIndex = 0;
638 columns[1].DisplayIndex = 1;
643 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
645 columns[idx].Width = curListColumn.Width;
646 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
655 new ColumnHeader(), // アイコン
656 new ColumnHeader(), // ニックネーム
657 new ColumnHeader(), // 本文
658 new ColumnHeader(), // 日付
659 new ColumnHeader(), // ユーザID
660 new ColumnHeader(), // 未読
661 new ColumnHeader(), // マーク&プロテクト
662 new ColumnHeader(), // ソース
665 foreach (var i in Enumerable.Range(0, columns.Length))
666 columns[i].Text = this.ColumnText[i];
670 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
672 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
673 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
674 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
675 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
676 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
677 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
678 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
679 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
681 var displayIndex = new[] {
682 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
683 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
684 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
685 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
688 foreach (var i in Enumerable.Range(0, displayIndex.Length))
690 columns[i].DisplayIndex = displayIndex[i];
696 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
698 columns[idx].Width = curListColumn.Width;
699 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
705 list.Columns.AddRange(columns);
713 foreach (var column in columns)
719 private void InitColumnText()
722 ColumnText[1] = Properties.Resources.AddNewTabText2;
723 ColumnText[2] = Properties.Resources.AddNewTabText3;
724 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
725 ColumnText[4] = Properties.Resources.AddNewTabText5;
728 ColumnText[7] = "Source";
730 ColumnOrgText[0] = "";
731 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
732 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
733 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
734 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
735 ColumnOrgText[5] = "";
736 ColumnOrgText[6] = "";
737 ColumnOrgText[7] = "Source";
739 var c = this._statuses.SortMode switch
741 ComparerMode.Nickname => 1, // ニックネーム
742 ComparerMode.Data => 2, // 本文
743 ComparerMode.Id => 3, // 時刻=発言Id
744 ComparerMode.Name => 4, // 名前
745 ComparerMode.Source => 7, // Source
751 if (_statuses.SortOrder == SortOrder.Descending)
753 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
754 ColumnText[2] = ColumnOrgText[2] + "▾";
758 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
759 ColumnText[2] = ColumnOrgText[2] + "▴";
764 if (_statuses.SortOrder == SortOrder.Descending)
766 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
767 ColumnText[c] = ColumnOrgText[c] + "▾";
771 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
772 ColumnText[c] = ColumnOrgText[c] + "▴";
777 private void InitializeTraceFrag()
780 TraceOutToolStripMenuItem.Checked = true;
781 MyCommon.TraceFlag = true;
783 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
785 TraceOutToolStripMenuItem.Checked = true;
786 MyCommon.TraceFlag = true;
790 private void TweenMain_Load(object sender, EventArgs e)
792 _ignoreConfigSave = true;
793 this.Visible = false;
795 if (MyApplication.StartupOptions.ContainsKey("d"))
796 MyCommon.TraceFlag = true;
798 InitializeTraceFrag();
800 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
802 Regex.CacheSize = 100;
805 _statuses = TabInformations.GetInstance();
809 this.Icon = MainIcon; //メインフォーム(TweenMain)
810 NotifyIcon1.Icon = NIconAt; //タスクトレイ
811 TabImage.Images.Add(TabIcon); //タブ見出し
813 //<<<<<<<<<設定関連>>>>>>>>>
817 // 現在の DPI と設定保存時の DPI との比を取得する
818 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
821 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
822 if (fontUIGlobal != null)
824 OTBaseForm.GlobalFont = fontUIGlobal;
825 this.Font = fontUIGlobal;
829 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
831 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
832 SettingManager.Common.TimelinePeriod = 15;
834 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
835 SettingManager.Common.ReplyPeriod = 15;
837 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
838 SettingManager.Common.DMPeriod = 15;
840 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
841 SettingManager.Common.PubSearchPeriod = 30;
843 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
844 SettingManager.Common.UserTimelinePeriod = 15;
846 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
847 SettingManager.Common.ListsPeriod = 15;
850 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
851 SettingManager.Common.CountApi = 60;
852 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
853 SettingManager.Common.CountApiReply = 40;
855 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
856 SettingManager.Common.MoreCountApi = 200;
857 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
858 SettingManager.Common.FirstCountApi = 100;
860 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
861 SettingManager.Common.FavoritesCountApi = 40;
862 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
863 SettingManager.Common.ListCountApi = 100;
864 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
865 SettingManager.Common.SearchCountApi = 100;
866 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
867 SettingManager.Common.UserTimelineCountApi = 20;
869 //廃止サービスが選択されていた場合ux.nuへ読み替え
870 if (SettingManager.Common.AutoShortUrlFirst < 0)
871 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
873 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
874 this.tw = new Twitter(this.twitterApi);
877 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
878 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
882 Networking.Initialize();
884 var saveRequired = false;
885 var firstRun = false;
887 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
888 if (string.IsNullOrEmpty(tw.Username))
893 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
894 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
895 string.IsNullOrEmpty(tw.Username))
897 Application.Exit(); //強制終了
903 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
904 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
905 Networking.SetWebProxy(SettingManager.Local.ProxyType,
906 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
907 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
908 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
910 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
911 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
912 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
913 tw.TrackWord = SettingManager.Common.TrackWord;
914 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(tw.TrackWord);
915 tw.AllAtReply = SettingManager.Common.AllAtReply;
916 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
917 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
918 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
919 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
920 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
922 // アクセストークンが有効であるか確認する
923 // ここが Twitter API への最初のアクセスになるようにすること
926 this.tw.VerifyCredentials();
928 catch (WebApiException ex)
930 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
931 ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
935 //プロキシ設定等の通信まわりの初期化が済んでから処理する
936 ThumbnailGenerator.InitializeGenerator();
938 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
939 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
940 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
942 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
945 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
948 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
949 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
950 HashMgr = new HashtagManage(HashSupl,
951 SettingManager.Common.HashTags.ToArray(),
952 SettingManager.Common.HashSelected,
953 SettingManager.Common.HashIsPermanent,
954 SettingManager.Common.HashIsHead,
955 SettingManager.Common.HashIsNotAddToAtReply);
956 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
959 this.IconCache = new ImageCache();
960 this.tweetDetailsView.IconCache = this.IconCache;
963 _fntUnread = SettingManager.Local.FontUnread;
964 _clUnread = SettingManager.Local.ColorUnread;
965 _fntReaded = SettingManager.Local.FontRead;
966 _clReaded = SettingManager.Local.ColorRead;
967 _clFav = SettingManager.Local.ColorFav;
968 _clOWL = SettingManager.Local.ColorOWL;
969 _clRetweet = SettingManager.Local.ColorRetweet;
970 _fntDetail = SettingManager.Local.FontDetail;
971 _clDetail = SettingManager.Local.ColorDetail;
972 _clDetailLink = SettingManager.Local.ColorDetailLink;
973 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
974 _clSelf = SettingManager.Local.ColorSelf;
975 _clAtSelf = SettingManager.Local.ColorAtSelf;
976 _clTarget = SettingManager.Local.ColorTarget;
977 _clAtTarget = SettingManager.Local.ColorAtTarget;
978 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
979 _clAtTo = SettingManager.Local.ColorAtTo;
980 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
981 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
982 _clInputFont = SettingManager.Local.ColorInputFont;
983 _fntInputFont = SettingManager.Local.FontInputFont;
985 _brsBackColorMine = new SolidBrush(_clSelf);
986 _brsBackColorAt = new SolidBrush(_clAtSelf);
987 _brsBackColorYou = new SolidBrush(_clTarget);
988 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
989 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
990 _brsBackColorAtTo = new SolidBrush(_clAtTo);
991 _brsBackColorNone = new SolidBrush(_clListBackcolor);
993 // StringFormatオブジェクトへの事前設定
994 sfTab.Alignment = StringAlignment.Center;
995 sfTab.LineAlignment = StringAlignment.Center;
997 InitDetailHtmlFormat();
999 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
1001 _history.Add(new StatusTextHistory());
1003 this.inReplyTo = null;
1006 SearchDialog.Owner = this;
1007 UrlDialog.Owner = this;
1010 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
1011 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
1013 //新着取得時のリストスクロールをするか。trueならスクロールしない
1014 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
1015 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
1017 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1018 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1021 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
1022 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1023 _myLoc = SettingManager.Local.FormLocation;
1025 if (this.WindowState != FormWindowState.Minimized)
1027 var tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1028 var outOfScreen = true;
1029 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1031 foreach (var scr in Screen.AllScreens)
1033 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1035 outOfScreen = false;
1041 this._myLoc = new Point(0, 0);
1043 this.DesktopLocation = this._myLoc;
1045 this.TopMost = SettingManager.Common.AlwaysTop;
1046 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
1047 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
1048 if (SettingManager.Local.PreviewDistance == -1)
1050 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
1051 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
1052 SettingManager.Local.PreviewDistance = _mySpDis3;
1056 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
1058 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1059 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1061 StatusText.Font = _fntInputFont;
1062 StatusText.ForeColor = _clInputFont;
1064 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
1065 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
1066 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
1068 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1069 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
1071 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1072 if (SettingManager.Common.UnreadManage == false)
1074 ReadedStripMenuItem.Enabled = false;
1075 UnreadStripMenuItem.Enabled = false;
1078 //リンク先URL表示部の初期化(画面左下)
1079 StatusLabelUrl.Text = "";
1081 StatusLabel.Text = "";
1082 StatusLabel.AutoToolTip = false;
1083 StatusLabel.ToolTipText = "";
1085 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1087 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1088 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1089 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1090 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1092 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1093 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1094 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1095 this.SplitContainer2.Panel2.AccessibleName = "";
1097 ////////////////////////////////////////////////////////////////////////////////
1098 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1099 var mode = ComparerMode.Id;
1100 switch (SettingManager.Common.SortColumn)
1102 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1106 mode = ComparerMode.Id; //Idソートに読み替え
1109 mode = ComparerMode.Nickname;
1112 mode = ComparerMode.Data;
1115 mode = ComparerMode.Id;
1118 mode = ComparerMode.Name;
1121 mode = ComparerMode.Source;
1124 _statuses.SetSortMode(mode, sortOrder);
1125 ////////////////////////////////////////////////////////////////////////////////
1127 ApplyListViewIconSize(SettingManager.Common.IconSize);
1129 //<<<<<<<<タブ関連>>>>>>>
1133 //デフォルトタブの存在チェック、ない場合には追加
1134 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1135 this._statuses.AddTab(new HomeTabModel());
1137 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1138 this._statuses.AddTab(new MentionsTabModel());
1140 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1141 this._statuses.AddTab(new DirectMessagesTabModel());
1143 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1144 this._statuses.AddTab(new FavoritesTabModel());
1146 if (this._statuses.MuteTab == null)
1147 this._statuses.AddTab(new MuteTabModel());
1149 foreach (var tab in _statuses.Tabs)
1151 if (!AddNewTab(tab, startup: true))
1152 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1155 this._statuses.SelectTab(this.ListTab.SelectedTab.Text);
1157 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
1158 Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
1160 if (SettingManager.Common.TabIconDisp)
1162 ListTab.DrawMode = TabDrawMode.Normal;
1166 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1167 ListTab.DrawItem += ListTab_DrawItem;
1168 ListTab.ImageList = null;
1171 if (SettingManager.Common.HotkeyEnabled)
1174 var modKey = HookGlobalHotkey.ModKeys.None;
1175 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1176 modKey |= HookGlobalHotkey.ModKeys.Alt;
1177 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1178 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1179 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1180 modKey |= HookGlobalHotkey.ModKeys.Shift;
1181 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1182 modKey |= HookGlobalHotkey.ModKeys.Win;
1184 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1187 if (SettingManager.Common.IsUseNotifyGrowl)
1190 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1192 SetMainWindowTitle();
1193 SetNotifyIconText();
1195 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1197 this.Visible = true;
1202 this.timelineScheduler.UpdateHome = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
1203 this.timelineScheduler.UpdateMention = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
1204 this.timelineScheduler.UpdateDm = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
1205 this.timelineScheduler.UpdatePublicSearch = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
1206 this.timelineScheduler.UpdateUser = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
1207 this.timelineScheduler.UpdateList = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
1208 this.timelineScheduler.UpdateConfig = () => this.InvokeAsync(() => Task.WhenAll(new[]
1210 this.doGetFollowersMenu(),
1211 this.RefreshBlockIdsAsync(),
1212 this.RefreshMuteUserIdsAsync(),
1213 this.RefreshNoRetweetIdsAsync(),
1214 this.RefreshTwitterConfigurationAsync(),
1216 this.RefreshTimelineScheduler();
1218 var streamingRefreshInterval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1219 this.RefreshThrottlingTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), streamingRefreshInterval);
1220 this.colorizeDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.ColorizeList()), TimeSpan.FromMilliseconds(100), leading: true);
1221 this.selectionDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
1222 this.saveConfigDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
1225 TimerRefreshIcon.Interval = 200;
1226 TimerRefreshIcon.Enabled = false;
1228 _ignoreConfigSave = false;
1229 this.TweenMain_Resize(this, EventArgs.Empty);
1230 if (saveRequired) SaveConfigsAll(false);
1232 foreach (var ua in SettingManager.Common.UserAccounts)
1234 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1236 ua.UserId = tw.UserId;
1243 // 初回起動時だけ右下のメニューを目立たせる
1244 HashStripSplitButton.ShowDropDown();
1248 private void InitDetailHtmlFormat()
1250 if (SettingManager.Common.IsMonospace)
1252 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1253 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1257 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1258 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1261 detailHtmlFormatHeader = detailHtmlFormatHeader
1262 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1263 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1264 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1265 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1266 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1267 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1270 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1275 txt = this._statuses.Tabs[e.Index].TabName;
1282 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1283 if (e.State == DrawItemState.Selected)
1285 e.DrawFocusRectangle();
1290 if (_statuses.Tabs[txt].UnreadCount > 0)
1293 fore = System.Drawing.SystemBrushes.ControlText;
1297 fore = System.Drawing.SystemBrushes.ControlText;
1299 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1302 private void LoadConfig()
1304 SettingManager.Local = SettingManager.Local;
1306 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1307 if (SettingManager.Local.ScaleDimension.IsEmpty)
1308 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1310 var tabSettings = SettingManager.Tabs;
1311 foreach (var tabSetting in tabSettings.Tabs)
1314 switch (tabSetting.TabType)
1316 case MyCommon.TabUsageType.Home:
1317 tab = new HomeTabModel(tabSetting.TabName);
1319 case MyCommon.TabUsageType.Mentions:
1320 tab = new MentionsTabModel(tabSetting.TabName);
1322 case MyCommon.TabUsageType.DirectMessage:
1323 tab = new DirectMessagesTabModel(tabSetting.TabName);
1325 case MyCommon.TabUsageType.Favorites:
1326 tab = new FavoritesTabModel(tabSetting.TabName);
1328 case MyCommon.TabUsageType.UserDefined:
1329 tab = new FilterTabModel(tabSetting.TabName);
1331 case MyCommon.TabUsageType.UserTimeline:
1332 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User!);
1334 case MyCommon.TabUsageType.PublicSearch:
1335 tab = new PublicSearchTabModel(tabSetting.TabName)
1337 SearchWords = tabSetting.SearchWords,
1338 SearchLang = tabSetting.SearchLang,
1341 case MyCommon.TabUsageType.Lists:
1342 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo!);
1344 case MyCommon.TabUsageType.Mute:
1345 tab = new MuteTabModel(tabSetting.TabName);
1351 tab.UnreadManage = tabSetting.UnreadManage;
1352 tab.Protected = tabSetting.Protected;
1353 tab.Notify = tabSetting.Notify;
1354 tab.SoundFile = tabSetting.SoundFile;
1356 if (tab.IsDistributableTabType)
1358 var filterTab = (FilterTabModel)tab;
1359 filterTab.FilterArray = tabSetting.FilterArray;
1360 filterTab.FilterModified = false;
1363 if (this._statuses.ContainsTab(tab.TabName))
1364 tab.TabName = this._statuses.MakeTabName("MyTab");
1366 this._statuses.AddTab(tab);
1368 if (_statuses.Tabs.Count == 0)
1370 _statuses.AddTab(new HomeTabModel());
1371 _statuses.AddTab(new MentionsTabModel());
1372 _statuses.AddTab(new DirectMessagesTabModel());
1373 _statuses.AddTab(new FavoritesTabModel());
1377 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
1381 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1382 var newTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), interval);
1383 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1387 this.RefreshTimelineScheduler();
1390 private void RefreshTimelineScheduler()
1392 this.timelineScheduler.UpdateIntervalHome = TimeSpan.FromSeconds(SettingManager.Common.TimelinePeriod);
1393 this.timelineScheduler.UpdateIntervalMention = TimeSpan.FromSeconds(SettingManager.Common.ReplyPeriod);
1394 this.timelineScheduler.UpdateIntervalDm = TimeSpan.FromSeconds(SettingManager.Common.DMPeriod);
1395 this.timelineScheduler.UpdateIntervalPublicSearch = TimeSpan.FromSeconds(SettingManager.Common.PubSearchPeriod);
1396 this.timelineScheduler.UpdateIntervalUser = TimeSpan.FromSeconds(SettingManager.Common.UserTimelinePeriod);
1397 this.timelineScheduler.UpdateIntervalList = TimeSpan.FromSeconds(SettingManager.Common.ListsPeriod);
1398 this.timelineScheduler.UpdateIntervalConfig = TimeSpan.FromHours(6);
1399 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
1401 this.timelineScheduler.RefreshSchedule();
1404 private void MarkSettingCommonModified()
1406 if (this.saveConfigDebouncer == null)
1409 this.ModifySettingCommon = true;
1410 this.saveConfigDebouncer.Call();
1413 private void MarkSettingLocalModified()
1415 if (this.saveConfigDebouncer == null)
1418 this.ModifySettingLocal = true;
1419 this.saveConfigDebouncer.Call();
1422 internal void MarkSettingAtIdModified()
1424 if (this.saveConfigDebouncer == null)
1427 this.ModifySettingAtId = true;
1428 this.saveConfigDebouncer.Call();
1431 private void RefreshTimeline()
1433 var curTabModel = this.CurrentTab;
1434 var curListView = this.CurrentListView;
1436 // 現在表示中のタブのスクロール位置を退避
1437 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1439 // 各タブのリスト上の選択位置などを退避
1440 var listSelections = this.SaveListViewSelection();
1444 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1445 out var newMentionOrDm, out var isDelete);
1447 if (MyCommon._endingFlag) return;
1450 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1452 var tabPage = this.ListTab.TabPages[index];
1453 var listView = (DetailsListView)tabPage.Tag;
1455 if (listView.VirtualListSize != tab.AllCount || isDelete)
1457 using (ControlTransaction.Update(listView))
1459 if (listView == curListView)
1460 this.PurgeListViewItemCache();
1465 listView.VirtualListSize = tab.AllCount;
1467 catch (NullReferenceException ex)
1469 // WinForms 内部で ListView.set_TopItem が発生させている例外
1470 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1471 MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1475 this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1482 if (SettingManager.Common.TabIconDisp)
1484 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1486 var tabPage = this.ListTab.TabPages[index];
1487 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1488 tabPage.ImageIndex = 0; // 未読アイコン
1493 this.ListTab.Refresh();
1498 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1501 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1503 SetMainWindowTitle();
1504 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1506 HashSupl.AddRangeItem(tw.GetHashList());
1510 internal struct ListViewScroll
1512 public ScrollLockMode ScrollLockMode { get; set; }
1513 public long? TopItemStatusId { get; set; }
1516 internal enum ScrollLockMode
1518 /// <summary>固定しない</summary>
1521 /// <summary>最上部に固定する</summary>
1524 /// <summary>最下部に固定する</summary>
1527 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1532 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1534 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1536 var listScroll = new ListViewScroll
1538 ScrollLockMode = this.GetScrollLockMode(listView),
1541 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1543 var topItemIndex = listView.TopItem?.Index ?? -1;
1544 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1545 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1551 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1553 if (this._statuses.SortMode == ComparerMode.Id)
1555 if (this._statuses.SortOrder == SortOrder.Ascending)
1558 if (this.ListLockMenuItem.Checked)
1559 return ScrollLockMode.None;
1561 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1564 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1565 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1566 return ScrollLockMode.FixedToBottom;
1568 return ScrollLockMode.None;
1573 if (this.ListLockMenuItem.Checked)
1574 return ScrollLockMode.FixedToItem;
1576 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1577 var topItem = listView.TopItem;
1578 if (topItem == null || topItem.Index == 0)
1579 return ScrollLockMode.FixedToTop;
1581 return ScrollLockMode.FixedToItem;
1586 return ScrollLockMode.FixedToItem;
1590 internal struct ListViewSelection
1592 public long[]? SelectedStatusIds { get; set; }
1593 public long? SelectionMarkStatusId { get; set; }
1594 public long? FocusedStatusId { get; set; }
1598 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1600 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1602 var listsDict = new Dictionary<string, ListViewSelection>();
1604 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1606 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1607 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1614 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1616 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1618 if (listView.VirtualListSize == 0)
1620 return new ListViewSelection
1622 SelectedStatusIds = Array.Empty<long>(),
1623 SelectionMarkStatusId = null,
1624 FocusedStatusId = null,
1628 return new ListViewSelection
1630 SelectedStatusIds = tab.SelectedStatusIds,
1631 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1632 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1636 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1638 var index = listView.FocusedItem?.Index ?? -1;
1640 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1643 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1645 var index = listView.SelectionMark;
1647 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1651 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1653 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1655 if (listView.VirtualListSize == 0)
1658 switch (listScroll.ScrollLockMode)
1660 case ScrollLockMode.FixedToTop:
1661 listView.EnsureVisible(0);
1663 case ScrollLockMode.FixedToBottom:
1664 listView.EnsureVisible(listView.VirtualListSize - 1);
1666 case ScrollLockMode.FixedToItem:
1667 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1670 var topItem = listView.Items[topIndex];
1673 listView.TopItem = topItem;
1675 catch (NullReferenceException)
1677 listView.EnsureVisible(listView.VirtualListSize - 1);
1678 listView.EnsureVisible(topIndex);
1682 case ScrollLockMode.None:
1689 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1691 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1693 // status_id から ListView 上のインデックスに変換
1694 int[]? selectedIndices = null;
1695 if (listSelection.SelectedStatusIds != null)
1696 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1698 var focusedIndex = -1;
1699 if (listSelection.FocusedStatusId != null)
1700 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1702 var selectionMarkIndex = -1;
1703 if (listSelection.SelectionMarkStatusId != null)
1704 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1706 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1709 private bool BalloonRequired()
1711 var ev = new Twitter.FormattedEvent
1713 Eventtype = MyCommon.EVENTTYPE.None,
1716 return BalloonRequired(ev);
1719 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1721 if (type == MyCommon.EVENTTYPE.None)
1724 if (!SettingManager.Common.EventNotifyEnabled)
1727 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1730 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1735 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1738 private bool BalloonRequired(Twitter.FormattedEvent ev)
1743 if (NativeMethods.IsScreenSaverRunning())
1747 if (!this.NewPostPopMenuItem.Checked)
1749 // 「新着通知が無効でもイベントを通知する」にも該当しない
1750 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1754 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1755 if (SettingManager.Common.LimitBalloon)
1757 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1761 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1764 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1766 if (SettingManager.Common.ReadOwnPost)
1768 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1773 if (BalloonRequired())
1775 if (notifyPosts != null && notifyPosts.Length > 0)
1777 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1778 if (SettingManager.Common.IsUseNotifyGrowl)
1780 var sb = new StringBuilder();
1784 foreach (var post in notifyPosts)
1786 if (!(notifyPosts.Length > 3))
1792 if (post.IsReply && !post.IsExcludeReply) reply = true;
1793 if (post.IsDm) dm = true;
1794 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1795 switch (SettingManager.Common.NameBalloon)
1797 case MyCommon.NameBalloonEnum.UserID:
1798 sb.Append(post.ScreenName).Append(" : ");
1800 case MyCommon.NameBalloonEnum.NickName:
1801 sb.Append(post.Nickname).Append(" : ");
1804 sb.Append(post.TextFromApi);
1805 if (notifyPosts.Length > 3)
1807 if (notifyPosts.Last() != post) continue;
1810 var title = new StringBuilder();
1811 GrowlHelper.NotifyType nt;
1812 if (SettingManager.Common.DispUsername)
1814 title.Append(tw.Username);
1815 title.Append(" - ");
1820 title.Append(ApplicationSettings.ApplicationName);
1821 title.Append(" [DM] ");
1822 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1823 nt = GrowlHelper.NotifyType.DirectMessage;
1827 title.Append(ApplicationSettings.ApplicationName);
1828 title.Append(" [Reply!] ");
1829 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1830 nt = GrowlHelper.NotifyType.Reply;
1834 title.Append(ApplicationSettings.ApplicationName);
1836 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1837 nt = GrowlHelper.NotifyType.Notify;
1839 var bText = sb.ToString();
1840 if (string.IsNullOrEmpty(bText)) return;
1842 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1843 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1848 var sb = new StringBuilder();
1851 foreach (var post in notifyPosts)
1853 if (post.IsReply && !post.IsExcludeReply) reply = true;
1854 if (post.IsDm) dm = true;
1855 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1856 switch (SettingManager.Common.NameBalloon)
1858 case MyCommon.NameBalloonEnum.UserID:
1859 sb.Append(post.ScreenName).Append(" : ");
1861 case MyCommon.NameBalloonEnum.NickName:
1862 sb.Append(post.Nickname).Append(" : ");
1865 sb.Append(post.TextFromApi);
1869 var title = new StringBuilder();
1871 if (SettingManager.Common.DispUsername)
1873 title.Append(tw.Username);
1874 title.Append(" - ");
1879 ntIcon = ToolTipIcon.Warning;
1880 title.Append(ApplicationSettings.ApplicationName);
1881 title.Append(" [DM] ");
1882 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1886 ntIcon = ToolTipIcon.Warning;
1887 title.Append(ApplicationSettings.ApplicationName);
1888 title.Append(" [Reply!] ");
1889 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1893 ntIcon = ToolTipIcon.Info;
1894 title.Append(ApplicationSettings.ApplicationName);
1896 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1898 var bText = sb.ToString();
1899 if (string.IsNullOrEmpty(bText)) return;
1901 NotifyIcon1.BalloonTipTitle = title.ToString();
1902 NotifyIcon1.BalloonTipText = bText;
1903 NotifyIcon1.BalloonTipIcon = ntIcon;
1904 NotifyIcon1.ShowBalloonTip(500);
1910 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1914 var dir = Application.StartupPath;
1915 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1917 dir = Path.Combine(dir, "Sounds");
1919 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1927 //mentions新着時に画面ブリンク
1928 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1930 NativeMethods.FlashMyWindow(this.Handle, 3);
1934 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1936 var listView = this.CurrentListView;
1937 if (listView != sender)
1940 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1941 this.CurrentTab.SelectPosts(indices);
1943 if (listView.SelectedIndices.Count != 1)
1946 var index = listView.SelectedIndices[0];
1947 if (index > listView.VirtualListSize - 1) return;
1949 this.PushSelectPostChain();
1951 var post = this.CurrentPost!;
1952 this._statuses.SetReadAllTab(post.StatusId, read: true);
1955 ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1957 this.colorizeDebouncer.Call();
1958 this.selectionDebouncer.Call();
1961 private void ChangeCacheStyleRead(bool Read, int Index)
1963 var tabInfo = this.CurrentTab;
1964 //Read:true=既読 false=未読
1965 //未読管理していなかったら既読として扱う
1966 if (!tabInfo.UnreadManage ||
1967 !SettingManager.Common.UnreadManage) Read = true;
1969 var listCache = this._listItemCache;
1970 if (listCache == null)
1973 // キャッシュに含まれていないアイテムは対象外
1974 if (!listCache.TryGetValue(Index, out var itm, out var post))
1977 ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
1980 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView? DList)
1995 if (Item.SubItems[5].Text != star)
1996 Item.SubItems[5].Text = star;
2002 else if (Post.RetweetedId != null)
2004 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
2006 else if (Read || !SettingManager.Common.UseUnreadStyle)
2011 if (DList == null || Item.Index == -1)
2013 Item.ForeColor = cl;
2014 if (SettingManager.Common.UseUnreadStyle)
2019 if (SettingManager.Common.UseUnreadStyle)
2020 DList.ChangeItemFontAndColor(Item, cl, fnt);
2022 DList.ChangeItemForeColor(Item, cl);
2026 private void ColorizeList()
2028 //Index:更新対象のListviewItem.Index。Colorを返す。
2029 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2032 _post = _anchorPost;
2034 _post = this.CurrentPost;
2036 if (_post == null) return;
2038 var listCache = this._listItemCache;
2039 if (listCache == null)
2042 var listView = (DetailsListView)listCache.TargetList;
2044 // ValidateRectが呼ばれる前に選択色などの描画を済ませておく
2047 foreach (var (listViewItem, cachedPost) in listCache.Cache)
2049 var backColor = this.JudgeColor(_post, cachedPost);
2050 listView.ChangeItemBackColor(listViewItem, backColor);
2054 private void ColorizeList(ListViewItem Item, PostClass post)
2056 //Index:更新対象のListviewItem.Index。Colorを返す。
2057 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2060 _post = _anchorPost;
2062 _post = this.CurrentPost;
2064 if (_post == null) return;
2066 if (Item.Index == -1)
2067 Item.BackColor = JudgeColor(_post, post);
2069 this.CurrentListView.ChangeItemBackColor(Item, JudgeColor(_post, post));
2072 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2075 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2078 else if (TargetPost.IsMe)
2081 else if (TargetPost.IsReply)
2084 else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2086 cl = _clAtFromTarget;
2087 else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2090 else if (TargetPost.UserId == BasePost.UserId)
2095 cl = _clListBackcolor;
2100 private void StatusTextHistoryBack()
2102 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2103 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2106 if (this._hisIdx < 0)
2109 var historyItem = this._history[this._hisIdx];
2110 this.inReplyTo = historyItem.inReplyTo;
2111 this.StatusText.Text = historyItem.status;
2112 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2115 private void StatusTextHistoryForward()
2117 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2118 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2121 if (this._hisIdx > this._history.Count - 1)
2122 this._hisIdx = this._history.Count - 1;
2124 var historyItem = this._history[this._hisIdx];
2125 this.inReplyTo = historyItem.inReplyTo;
2126 this.StatusText.Text = historyItem.status;
2127 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2130 private async void PostButton_Click(object sender, EventArgs e)
2132 if (StatusText.Text.Trim().Length == 0)
2134 if (!ImageSelector.Enabled)
2136 await this.DoRefresh();
2141 var currentPost = this.CurrentPost;
2142 if (this.ExistCurrentPost && currentPost != null && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2144 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2146 MessageBoxButtons.YesNoCancel,
2147 MessageBoxIcon.Question);
2150 case DialogResult.Yes:
2151 StatusText.Text = "";
2152 await this.doReTweetOfficial(false);
2154 case DialogResult.Cancel:
2159 if (TextContainsOnlyMentions(this.StatusText.Text))
2161 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2162 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2164 if (ret != DialogResult.OK)
2168 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2170 if (SettingManager.Common.Nicoms)
2172 StatusText.SelectionStart = StatusText.Text.Length;
2173 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2176 StatusText.SelectionStart = StatusText.Text.Length;
2177 CheckReplyTo(StatusText.Text);
2179 var status = new PostStatusParams();
2181 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2182 if (this.GetRestStatusCount(statusTextCompat) >= 0)
2184 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2185 // 収まる場合はこれらのオプションを使用せずに投稿する
2186 status.Text = statusTextCompat;
2187 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2191 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2192 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2194 status.AttachmentUrl = attachmentUrl;
2196 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2198 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2199 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2201 status.AutoPopulateReplyMetadata = true;
2203 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2204 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2209 if (this.GetRestStatusCount(status.Text) < 0)
2211 // 文字数制限を超えているが強制的に投稿するか
2212 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2213 if (ret != DialogResult.OK)
2217 IMediaUploadService? uploadService = null;
2218 IMediaItem[]? uploadItems = null;
2219 if (ImageSelector.Visible)
2222 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2225 uploadService = this.ImageSelector.GetService(serviceName);
2228 this.inReplyTo = null;
2229 StatusText.Text = "";
2230 _history.Add(new StatusTextHistory());
2231 _hisIdx = _history.Count - 1;
2232 if (!SettingManager.Common.FocusLockToStatusText)
2233 this.CurrentListView.Focus();
2234 urlUndoBuffer = null;
2235 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2238 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2240 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2241 await this.OpenUriInBrowserAsync(tmp);
2244 await this.PostMessageAsync(status, uploadService, uploadItems);
2247 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2249 MyCommon._endingFlag = true;
2253 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2255 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2257 //_endingFlag=false:フォームの×ボタン
2259 this.Visible = false;
2263 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2264 _ignoreConfigSave = true;
2265 MyCommon._endingFlag = true;
2266 this.timelineScheduler.Enabled = false;
2267 TimerRefreshIcon.Enabled = false;
2271 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2273 this.Visible = true;
2274 if (this.WindowState == FormWindowState.Minimized)
2276 this.WindowState = FormWindowState.Normal;
2279 this.BringToFront();
2282 private static int errorCount = 0;
2284 private static bool CheckAccountValid()
2286 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2292 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2301 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2302 private Task RefreshTabAsync<T>() where T : TabModel
2303 => this.RefreshTabAsync<T>(backward: false);
2305 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2306 private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2309 from tab in this._statuses.GetTabsByType<T>()
2310 select this.RefreshTabAsync(tab, backward);
2312 return Task.WhenAll(loadTasks);
2315 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2316 private Task RefreshTabAsync(TabModel tab)
2317 => this.RefreshTabAsync(tab, backward: false);
2319 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2320 private async Task RefreshTabAsync(TabModel tab, bool backward)
2322 await this.workerSemaphore.WaitAsync();
2323 this.RefreshTasktrayIcon();
2327 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2328 this.RefreshTimeline();
2330 catch (WebApiException ex)
2332 this._myStatusError = true;
2333 var tabType = tab switch
2335 HomeTabModel _ => "GetTimeline",
2336 MentionsTabModel _ => "GetTimeline",
2337 DirectMessagesTabModel _ => "GetDirectMessage",
2338 FavoritesTabModel _ => "GetFavorites",
2339 PublicSearchTabModel _ => "GetSearch",
2340 UserTimelineTabModel _ => "GetUserTimeline",
2341 ListTimelineTabModel _ => "GetListStatus",
2342 RelatedPostsTabModel _ => "GetRelatedTweets",
2343 _ => tab.GetType().Name.Replace("Model", ""),
2345 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2349 this.workerSemaphore.Release();
2353 private async Task FavAddAsync(long statusId, TabModel tab)
2355 await this.workerSemaphore.WaitAsync();
2356 this.RefreshTasktrayIcon();
2360 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2362 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2364 catch (WebApiException ex)
2366 this._myStatusError = true;
2367 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2371 this.workerSemaphore.Release();
2375 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2377 if (ct.IsCancellationRequested)
2380 if (!CheckAccountValid())
2381 throw new WebApiException("Auth error. Check your account");
2383 if (!tab.Posts.TryGetValue(statusId, out var post))
2389 await Task.Run(async () =>
2391 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2397 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2399 .ConfigureAwait(false);
2401 catch (TwitterApiException ex)
2402 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2404 // エラーコード 139 のみの場合は成功と見なす
2407 if (SettingManager.Common.RestrictFavCheck)
2409 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2410 .ConfigureAwait(false);
2412 if (status.Favorited != true)
2413 throw new WebApiException("NG(Restricted?)");
2416 this._favTimestamps.Add(DateTimeUtc.Now);
2419 if (this._statuses.Posts.TryGetValue(statusId, out var postTl))
2421 postTl.IsFav = true;
2423 var favTab = this._statuses.FavoriteTab;
2424 favTab.AddPostQueue(postTl);
2427 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2428 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2430 if (tb.Contains(statusId))
2431 tb.Posts[statusId].IsFav = true;
2434 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2436 catch (WebApiException)
2438 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2443 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2444 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2446 if (this._favTimestamps[i] < oneHour)
2447 this._favTimestamps.RemoveAt(i);
2450 this._statuses.DistributePosts();
2453 if (ct.IsCancellationRequested)
2456 this.RefreshTimeline();
2458 if (this.CurrentTabName == tab.TabName)
2460 using (ControlTransaction.Update(this.CurrentListView))
2462 var idx = tab.IndexOf(statusId);
2464 this.ChangeCacheStyleRead(post.IsRead, idx);
2467 var currentPost = this.CurrentPost;
2468 if (currentPost != null && statusId == currentPost.StatusId)
2469 this.DispSelectedPost(true); // 選択アイテム再表示
2473 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2475 await this.workerSemaphore.WaitAsync();
2476 this.RefreshTasktrayIcon();
2480 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2482 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2484 catch (WebApiException ex)
2486 this._myStatusError = true;
2487 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2491 this.workerSemaphore.Release();
2495 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2497 if (ct.IsCancellationRequested)
2500 if (!CheckAccountValid())
2501 throw new WebApiException("Auth error. Check your account");
2503 var successIds = new List<long>();
2505 await Task.Run(async () =>
2509 var failedCount = 0;
2510 foreach (var statusId in statusIds)
2514 var post = tab.Posts[statusId];
2516 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2523 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2525 .ConfigureAwait(false);
2527 catch (WebApiException)
2533 successIds.Add(statusId);
2534 post.IsFav = false; // リスト再描画必要
2536 if (this._statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
2537 tabinfoPost.IsFav = false;
2539 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2540 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2542 if (tb.Contains(statusId))
2543 tb.Posts[statusId].IsFav = false;
2548 if (ct.IsCancellationRequested)
2551 var favTab = this._statuses.FavoriteTab;
2552 foreach (var statusId in successIds)
2554 // ツイートが削除された訳ではないので IsDeleted はセットしない
2555 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2558 this.RefreshTimeline();
2560 if (this.CurrentTabName == tab.TabName)
2562 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2568 using (ControlTransaction.Update(this.CurrentListView))
2570 foreach (var statusId in successIds)
2572 var idx = tab.IndexOf(statusId);
2576 var post = tab.Posts[statusId];
2577 this.ChangeCacheStyleRead(post.IsRead, idx);
2581 var currentPost = this.CurrentPost;
2582 if (currentPost != null && successIds.Contains(currentPost.StatusId))
2583 this.DispSelectedPost(true); // 選択アイテム再表示
2588 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2590 await this.workerSemaphore.WaitAsync();
2591 this.RefreshTasktrayIcon();
2595 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2597 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2599 catch (WebApiException ex)
2601 this._myStatusError = true;
2602 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2606 this.workerSemaphore.Release();
2610 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2611 IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2613 if (ct.IsCancellationRequested)
2616 if (!CheckAccountValid())
2617 throw new WebApiException("Auth error. Check your account");
2619 p.Report("Posting...");
2621 PostClass? post = null;
2626 await Task.Run(async () =>
2628 var postParamsWithMedia = postParams;
2630 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2632 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2633 .ConfigureAwait(false);
2636 post = await this.tw.PostStatus(postParamsWithMedia)
2637 .ConfigureAwait(false);
2640 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2642 catch (WebApiException ex)
2644 // 処理は中断せずエラーの表示のみ行う
2645 errMsg = $"Err:{ex.Message}(PostMessage)";
2647 this._myStatusError = true;
2649 catch (UnauthorizedAccessException ex)
2651 // アップロード対象のファイルが開けなかった場合など
2652 errMsg = $"Err:{ex.Message}(PostMessage)";
2654 this._myStatusError = true;
2658 // 使い終わった MediaItem は破棄する
2659 if (uploadItems != null)
2661 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2663 disposableItem.Dispose();
2668 if (ct.IsCancellationRequested)
2671 if (!string.IsNullOrEmpty(errMsg) &&
2672 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2673 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2675 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2677 var ret = MessageBox.Show(
2679 "Failed to update status",
2680 MessageBoxButtons.RetryCancel,
2681 MessageBoxIcon.Question);
2683 if (ret == DialogResult.Retry)
2685 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2689 this.StatusTextHistoryBack();
2690 this.StatusText.Focus();
2692 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2693 if (SettingManager.Common.FocusLockToStatusText)
2694 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2699 this._postTimestamps.Add(DateTimeUtc.Now);
2701 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2702 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2704 if (this._postTimestamps[i] < oneHour)
2705 this._postTimestamps.RemoveAt(i);
2708 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2710 this.HashMgr.ClearHashtag();
2711 this.HashStripSplitButton.Text = "#[-]";
2712 this.HashTogglePullDownMenuItem.Checked = false;
2713 this.HashToggleMenuItem.Checked = false;
2716 this.SetMainWindowTitle();
2719 if (!this.tw.UserStreamActive)
2721 if (SettingManager.Common.PostAndGet)
2722 await this.RefreshTabAsync<HomeTabModel>();
2727 this._statuses.AddPost(post);
2728 this._statuses.DistributePosts();
2730 this.RefreshTimeline();
2735 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2737 await this.workerSemaphore.WaitAsync();
2738 this.RefreshTasktrayIcon();
2742 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2744 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2746 catch (WebApiException ex)
2748 this._myStatusError = true;
2749 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2753 this.workerSemaphore.Release();
2757 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2759 if (ct.IsCancellationRequested)
2762 if (!CheckAccountValid())
2763 throw new WebApiException("Auth error. Check your account");
2766 if (!SettingManager.Common.UnreadManage)
2769 read = this._initial && SettingManager.Common.Read;
2771 p.Report("Posting...");
2773 var posts = new List<PostClass>();
2775 await Task.Run(async () =>
2777 foreach (var statusId in statusIds)
2779 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2780 if (post != null) posts.Add(post);
2784 if (ct.IsCancellationRequested)
2787 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2789 this._postTimestamps.Add(DateTimeUtc.Now);
2791 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2792 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2794 if (this._postTimestamps[i] < oneHour)
2795 this._postTimestamps.RemoveAt(i);
2799 if (!this.tw.UserStreamActive)
2801 // 自分のRTはTLの更新では取得できない場合があるので、
2802 // 投稿時取得の有無に関わらず追加しておく
2803 posts.ForEach(post => this._statuses.AddPost(post));
2805 if (SettingManager.Common.PostAndGet)
2806 await this.RefreshTabAsync<HomeTabModel>();
2809 this._statuses.DistributePosts();
2810 this.RefreshTimeline();
2815 private async Task RefreshFollowerIdsAsync()
2817 await this.workerSemaphore.WaitAsync();
2818 this.RefreshTasktrayIcon();
2822 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2824 await this.tw.RefreshFollowerIds();
2826 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2828 this.RefreshTimeline();
2829 this.PurgeListViewItemCache();
2830 this.CurrentListView.Refresh();
2832 catch (WebApiException ex)
2834 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2838 this.workerSemaphore.Release();
2842 private async Task RefreshNoRetweetIdsAsync()
2844 await this.workerSemaphore.WaitAsync();
2845 this.RefreshTasktrayIcon();
2849 await this.tw.RefreshNoRetweetIds();
2851 this.StatusLabel.Text = "NoRetweetIds refreshed";
2853 catch (WebApiException ex)
2855 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2859 this.workerSemaphore.Release();
2863 private async Task RefreshBlockIdsAsync()
2865 await this.workerSemaphore.WaitAsync();
2866 this.RefreshTasktrayIcon();
2870 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2872 await this.tw.RefreshBlockIds();
2874 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2876 catch (WebApiException ex)
2878 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2882 this.workerSemaphore.Release();
2886 private async Task RefreshTwitterConfigurationAsync()
2888 await this.workerSemaphore.WaitAsync();
2889 this.RefreshTasktrayIcon();
2893 await this.tw.RefreshConfiguration();
2895 if (this.tw.Configuration.PhotoSizeLimit != 0)
2897 foreach (var service in this.ImageSelector.GetServices())
2899 service.UpdateTwitterConfiguration(this.tw.Configuration);
2903 this.PurgeListViewItemCache();
2904 this.CurrentListView.Refresh();
2906 catch (WebApiException ex)
2908 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2912 this.workerSemaphore.Release();
2916 private async Task RefreshMuteUserIdsAsync()
2918 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2922 await tw.RefreshMuteUserIdsAsync();
2924 catch (WebApiException ex)
2926 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2930 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
2933 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2935 if (e.Button == MouseButtons.Left)
2937 this.Visible = true;
2938 if (this.WindowState == FormWindowState.Minimized)
2940 this.WindowState = _formWindowState;
2943 this.BringToFront();
2947 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2949 switch (SettingManager.Common.ListDoubleClickAction)
2952 MakeReplyOrDirectStatus();
2955 await this.FavoriteChange(true);
2958 var post = this.CurrentPost;
2960 await this.ShowUserStatus(post.ScreenName, false);
2963 await ShowUserTimeline();
2966 ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2969 MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty);
2972 StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2980 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2981 => await this.FavoriteChange(true);
2983 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2984 => await this.FavoriteChange(false);
2987 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2988 => await this.FavoritesRetweetOfficial();
2990 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2991 => await this.FavoritesRetweetUnofficial();
2993 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
2995 var tab = this.CurrentTab;
2996 var posts = tab.SelectedPosts;
2998 //trueでFavAdd,falseでFavRemove
2999 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
3000 || !this.ExistCurrentPost) return;
3002 if (posts.Length > 1)
3007 // https://support.twitter.com/articles/76915#favoriting
3008 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3009 _DoFavRetweetFlags = false;
3014 if (multiFavoriteChangeDialogEnable)
3016 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3017 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3018 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3020 if (confirm == DialogResult.Cancel)
3028 var selectedPost = posts.Single();
3029 if (selectedPost.IsFav)
3031 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3035 await this.FavAddAsync(selectedPost.StatusId, tab);
3039 var selectedPosts = posts.Where(x => x.IsFav);
3040 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3041 if (statusIds.Length == 0)
3043 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3047 await this.FavRemoveAsync(statusIds, tab);
3051 private PostClass GetCurTabPost(int Index)
3053 var listCache = this._listItemCache;
3054 if (listCache != null)
3056 if (listCache.TryGetValue(Index, out _, out var post))
3060 return this.CurrentTab[Index];
3063 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3065 var post = this.CurrentPost;
3067 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3069 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3072 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3074 var post = this.CurrentPost;
3076 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3079 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3081 if ((!_initialLayout) && this.Visible)
3083 if (this.WindowState == FormWindowState.Normal)
3085 _mySize = this.ClientSize;
3086 _mySpDis = this.SplitContainer1.SplitterDistance;
3087 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3088 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3089 this.MarkSettingLocalModified();
3094 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3096 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3097 if (comparerMode == null)
3100 this.SetSortColumn(comparerMode.Value);
3104 /// 列インデックスからソートを行う ComparerMode を求める
3106 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3107 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3108 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3111 return ComparerMode.Id;
3113 return columnIndex switch
3115 1 => ComparerMode.Nickname, // ニックネーム
3116 2 => ComparerMode.Data, // 本文
3117 3 => ComparerMode.Id, // 時刻=発言Id
3118 4 => ComparerMode.Name, // 名前
3119 7 => ComparerMode.Source, // Source
3120 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3125 /// 発言一覧の指定した位置の列でソートする
3127 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3128 private void SetSortColumnByDisplayIndex(int columnIndex)
3130 // 表示上の列の位置から ColumnHeader を求める
3131 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3132 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3137 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3138 if (comparerMode == null)
3141 this.SetSortColumn(comparerMode.Value);
3145 /// 発言一覧の最後列の項目でソートする
3147 private void SetSortLastColumn()
3149 // 表示上の最後列にある ColumnHeader を求める
3150 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3151 .OrderByDescending(x => x.DisplayIndex)
3154 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3155 if (comparerMode == null)
3158 this.SetSortColumn(comparerMode.Value);
3162 /// 発言一覧を指定された ComparerMode に基づいてソートする
3164 private void SetSortColumn(ComparerMode sortColumn)
3166 if (SettingManager.Common.SortOrderLock)
3169 this._statuses.ToggleSortOrder(sortColumn);
3170 this.InitColumnText();
3172 var list = this.CurrentListView;
3175 list.Columns[0].Text = this.ColumnText[0];
3176 list.Columns[1].Text = this.ColumnText[2];
3180 for (var i = 0; i <= 7; i++)
3182 list.Columns[i].Text = this.ColumnText[i];
3186 this.PurgeListViewItemCache();
3188 var tab = this.CurrentTab;
3189 var post = this.CurrentPost;
3190 if (tab.AllCount > 0 && post != null)
3192 var idx = tab.IndexOf(post.StatusId);
3195 this.SelectListItem(list, idx);
3196 list.EnsureVisible(idx);
3201 this.MarkSettingCommonModified();
3204 private void TweenMain_LocationChanged(object sender, EventArgs e)
3206 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3208 _myLoc = this.DesktopLocation;
3209 this.MarkSettingLocalModified();
3213 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3215 if (!this.ExistCurrentPost)
3217 ReplyStripMenuItem.Enabled = false;
3218 ReplyAllStripMenuItem.Enabled = false;
3219 DMStripMenuItem.Enabled = false;
3220 ShowProfileMenuItem.Enabled = false;
3221 ShowUserTimelineContextMenuItem.Enabled = false;
3222 ListManageUserContextToolStripMenuItem2.Enabled = false;
3223 MoveToFavToolStripMenuItem.Enabled = false;
3224 TabMenuItem.Enabled = false;
3225 IDRuleMenuItem.Enabled = false;
3226 SourceRuleMenuItem.Enabled = false;
3227 ReadedStripMenuItem.Enabled = false;
3228 UnreadStripMenuItem.Enabled = false;
3232 ShowProfileMenuItem.Enabled = true;
3233 ListManageUserContextToolStripMenuItem2.Enabled = true;
3234 ReplyStripMenuItem.Enabled = true;
3235 ReplyAllStripMenuItem.Enabled = true;
3236 DMStripMenuItem.Enabled = true;
3237 ShowUserTimelineContextMenuItem.Enabled = true;
3238 MoveToFavToolStripMenuItem.Enabled = true;
3239 TabMenuItem.Enabled = true;
3240 IDRuleMenuItem.Enabled = true;
3241 SourceRuleMenuItem.Enabled = true;
3242 ReadedStripMenuItem.Enabled = true;
3243 UnreadStripMenuItem.Enabled = true;
3245 var tab = this.CurrentTab;
3246 var post = this.CurrentPost;
3247 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
3249 FavAddToolStripMenuItem.Enabled = false;
3250 FavRemoveToolStripMenuItem.Enabled = false;
3251 StatusOpenMenuItem.Enabled = false;
3252 ShowRelatedStatusesMenuItem.Enabled = false;
3254 ReTweetStripMenuItem.Enabled = false;
3255 ReTweetUnofficialStripMenuItem.Enabled = false;
3256 QuoteStripMenuItem.Enabled = false;
3257 FavoriteRetweetContextMenu.Enabled = false;
3258 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3262 FavAddToolStripMenuItem.Enabled = true;
3263 FavRemoveToolStripMenuItem.Enabled = true;
3264 StatusOpenMenuItem.Enabled = true;
3265 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3267 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3269 ReTweetStripMenuItem.Enabled = false;
3270 ReTweetUnofficialStripMenuItem.Enabled = false;
3271 QuoteStripMenuItem.Enabled = false;
3272 FavoriteRetweetContextMenu.Enabled = false;
3273 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3277 ReTweetStripMenuItem.Enabled = true;
3278 ReTweetUnofficialStripMenuItem.Enabled = true;
3279 QuoteStripMenuItem.Enabled = true;
3280 FavoriteRetweetContextMenu.Enabled = true;
3281 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3285 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
3287 RepliedStatusOpenMenuItem.Enabled = false;
3291 RepliedStatusOpenMenuItem.Enabled = true;
3293 if (!this.ExistCurrentPost || post == null || string.IsNullOrEmpty(post.RetweetedBy))
3295 MoveToRTHomeMenuItem.Enabled = false;
3299 MoveToRTHomeMenuItem.Enabled = true;
3302 if (this.ExistCurrentPost && post != null)
3304 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3305 if (post.RetweetedByUserId == this.tw.UserId)
3306 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3308 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3312 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3313 => this.MakeReplyOrDirectStatus(false, true);
3315 private void DMStripMenuItem_Click(object sender, EventArgs e)
3316 => this.MakeReplyOrDirectStatus(false, false);
3318 private async Task doStatusDelete()
3320 var posts = this.CurrentTab.SelectedPosts;
3321 if (posts.Length == 0)
3324 // 選択されたツイートの中に削除可能なものが一つでもあるか
3325 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3328 var ret = MessageBox.Show(this,
3329 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3330 Properties.Resources.DeleteStripMenuItem_ClickText2,
3331 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3333 if (ret != DialogResult.OK)
3336 var currentListView = this.CurrentListView;
3337 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3339 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3341 Exception? lastException = null;
3342 foreach (var post in posts)
3344 if (!post.CanDeleteBy(this.tw.UserId))
3351 await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3355 if (post.RetweetedByUserId == this.tw.UserId)
3357 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3359 await this.twitterApi.StatusesDestroy(post.StatusId)
3364 if (post.UserId == this.tw.UserId)
3366 if (post.RetweetedId != null)
3367 // 他人に RT された自分のツイート
3368 // => RT 元の自分のツイートを削除
3369 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3374 await this.twitterApi.StatusesDestroy(post.StatusId)
3380 catch (WebApiException ex)
3386 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3389 if (lastException == null)
3390 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3392 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3394 this.PurgeListViewItemCache();
3396 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3398 var tabPage = this.ListTab.TabPages[index];
3399 var listView = (DetailsListView)tabPage.Tag;
3401 using (ControlTransaction.Update(listView))
3403 listView.VirtualListSize = tab.AllCount;
3405 if (tab.TabName == this.CurrentTabName)
3407 listView.SelectedIndices.Clear();
3409 if (tab.AllCount != 0)
3412 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3413 selectedIndex = focusedIndex;
3415 selectedIndex = tab.AllCount - 1;
3417 listView.SelectedIndices.Add(selectedIndex);
3418 listView.EnsureVisible(selectedIndex);
3419 listView.FocusedItem = listView.Items[selectedIndex];
3424 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3426 if (tabPage.ImageIndex == 0)
3427 tabPage.ImageIndex = -1; // タブアイコン
3431 if (!SettingManager.Common.TabIconDisp)
3432 this.ListTab.Refresh();
3436 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3437 => await this.doStatusDelete();
3439 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3441 using (ControlTransaction.Update(this.CurrentListView))
3443 var tab = this.CurrentTab;
3444 foreach (var statusId in tab.SelectedStatusIds)
3446 this._statuses.SetReadAllTab(statusId, read: true);
3447 var idx = tab.IndexOf(statusId);
3448 ChangeCacheStyleRead(true, idx);
3452 if (SettingManager.Common.TabIconDisp)
3454 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3456 if (tab.UnreadCount == 0)
3458 var tabPage = this.ListTab.TabPages[index];
3459 if (tabPage.ImageIndex == 0)
3460 tabPage.ImageIndex = -1; // タブアイコン
3464 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3467 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3469 using (ControlTransaction.Update(this.CurrentListView))
3471 var tab = this.CurrentTab;
3472 foreach (var statusId in tab.SelectedStatusIds)
3474 this._statuses.SetReadAllTab(statusId, read: false);
3475 var idx = tab.IndexOf(statusId);
3476 ChangeCacheStyleRead(false, idx);
3480 if (SettingManager.Common.TabIconDisp)
3482 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3484 if (tab.UnreadCount > 0)
3486 var tabPage = this.ListTab.TabPages[index];
3487 if (tabPage.ImageIndex == -1)
3488 tabPage.ImageIndex = 0; // タブアイコン
3492 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3495 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3496 => await this.DoRefresh();
3498 private async Task DoRefresh()
3499 => await this.RefreshTabAsync(this.CurrentTab);
3501 private async Task DoRefreshMore()
3502 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3504 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3506 var result = DialogResult.Abort;
3508 using var settingDialog = new AppendSettingDialog();
3509 settingDialog.Icon = this.MainIcon;
3510 settingDialog.Owner = this;
3511 settingDialog.ShowInTaskbar = showTaskbarIcon;
3512 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3514 settingDialog.tw = this.tw;
3515 settingDialog.twitterApi = this.twitterApi;
3517 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3521 result = settingDialog.ShowDialog(this);
3525 return DialogResult.Abort;
3528 if (result == DialogResult.OK)
3532 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3539 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3542 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3544 var oldIconSz = SettingManager.Common.IconSize;
3546 if (ShowSettingDialog() == DialogResult.OK)
3550 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3551 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3552 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3553 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3554 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3555 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3556 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3558 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3559 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3560 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3561 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3562 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3563 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3565 ImageSelector.Reset(tw, this.tw.Configuration);
3569 if (SettingManager.Common.TabIconDisp)
3571 ListTab.DrawItem -= ListTab_DrawItem;
3572 ListTab.DrawMode = TabDrawMode.Normal;
3573 ListTab.ImageList = this.TabImage;
3577 ListTab.DrawItem -= ListTab_DrawItem;
3578 ListTab.DrawItem += ListTab_DrawItem;
3579 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3580 ListTab.ImageList = null;
3583 catch (Exception ex)
3585 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3586 ex.Data["IsTerminatePermission"] = false;
3592 if (!SettingManager.Common.UnreadManage)
3594 ReadedStripMenuItem.Enabled = false;
3595 UnreadStripMenuItem.Enabled = false;
3596 if (SettingManager.Common.TabIconDisp)
3598 foreach (TabPage myTab in ListTab.TabPages)
3600 myTab.ImageIndex = -1;
3606 ReadedStripMenuItem.Enabled = true;
3607 UnreadStripMenuItem.Enabled = true;
3610 catch (Exception ex)
3612 ex.Data["Instance"] = "ListTab(UnreadManage)";
3613 ex.Data["IsTerminatePermission"] = false;
3620 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3622 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3623 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3624 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3626 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3627 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3628 _fntUnread = SettingManager.Local.FontUnread;
3629 _clUnread = SettingManager.Local.ColorUnread;
3630 _fntReaded = SettingManager.Local.FontRead;
3631 _clReaded = SettingManager.Local.ColorRead;
3632 _clFav = SettingManager.Local.ColorFav;
3633 _clOWL = SettingManager.Local.ColorOWL;
3634 _clRetweet = SettingManager.Local.ColorRetweet;
3635 _fntDetail = SettingManager.Local.FontDetail;
3636 _clDetail = SettingManager.Local.ColorDetail;
3637 _clDetailLink = SettingManager.Local.ColorDetailLink;
3638 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3639 _clSelf = SettingManager.Local.ColorSelf;
3640 _clAtSelf = SettingManager.Local.ColorAtSelf;
3641 _clTarget = SettingManager.Local.ColorTarget;
3642 _clAtTarget = SettingManager.Local.ColorAtTarget;
3643 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3644 _clAtTo = SettingManager.Local.ColorAtTo;
3645 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3646 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3647 _clInputFont = SettingManager.Local.ColorInputFont;
3648 _fntInputFont = SettingManager.Local.FontInputFont;
3649 _brsBackColorMine.Dispose();
3650 _brsBackColorAt.Dispose();
3651 _brsBackColorYou.Dispose();
3652 _brsBackColorAtYou.Dispose();
3653 _brsBackColorAtFromTarget.Dispose();
3654 _brsBackColorAtTo.Dispose();
3655 _brsBackColorNone.Dispose();
3656 _brsBackColorMine = new SolidBrush(_clSelf);
3657 _brsBackColorAt = new SolidBrush(_clAtSelf);
3658 _brsBackColorYou = new SolidBrush(_clTarget);
3659 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3660 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3661 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3662 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3666 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3667 StatusText.Font = _fntInputFont;
3668 StatusText.ForeColor = _clInputFont;
3670 catch (Exception ex)
3672 MessageBox.Show(ex.Message);
3677 InitDetailHtmlFormat();
3679 catch (Exception ex)
3681 ex.Data["Instance"] = "Font";
3682 ex.Data["IsTerminatePermission"] = false;
3688 if (SettingManager.Common.TabIconDisp)
3690 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3692 var tabPage = this.ListTab.TabPages[index];
3693 if (tab.UnreadCount == 0)
3694 tabPage.ImageIndex = -1;
3696 tabPage.ImageIndex = 0;
3700 catch (Exception ex)
3702 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3703 ex.Data["IsTerminatePermission"] = false;
3709 var oldIconCol = _iconCol;
3711 if (SettingManager.Common.IconSize != oldIconSz)
3712 ApplyListViewIconSize(SettingManager.Common.IconSize);
3714 foreach (TabPage tp in ListTab.TabPages)
3716 var lst = (DetailsListView)tp.Tag;
3718 using (ControlTransaction.Update(lst))
3720 lst.GridLines = SettingManager.Common.ShowGrid;
3721 lst.Font = _fntReaded;
3722 lst.BackColor = _clListBackcolor;
3724 if (_iconCol != oldIconCol)
3729 catch (Exception ex)
3731 ex.Data["Instance"] = "ListView(IconSize)";
3732 ex.Data["IsTerminatePermission"] = false;
3736 SetMainWindowTitle();
3737 SetNotifyIconText();
3739 this.PurgeListViewItemCache();
3740 this.CurrentListView.Refresh();
3743 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3744 if (SettingManager.Common.HotkeyEnabled)
3746 ///グローバルホットキーの登録。設定で変更可能にするかも
3747 var modKey = HookGlobalHotkey.ModKeys.None;
3748 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3749 modKey |= HookGlobalHotkey.ModKeys.Alt;
3750 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3751 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3752 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3753 modKey |= HookGlobalHotkey.ModKeys.Shift;
3754 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3755 modKey |= HookGlobalHotkey.ModKeys.Win;
3757 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3760 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3763 StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3772 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3773 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3776 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3778 this.TopMost = SettingManager.Common.AlwaysTop;
3779 SaveConfigsAll(false);
3781 if (tw.UserId != oldUser.UserId)
3782 await this.doGetFollowersMenu();
3788 private void SetTabAlignment()
3790 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3791 if (ListTab.Alignment == newAlignment) return;
3793 // 各タブのリスト上の選択位置などを退避
3794 var listSelections = this.SaveListViewSelection();
3796 ListTab.Alignment = newAlignment;
3798 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3800 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3801 using (ControlTransaction.Update(lst))
3804 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3809 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3812 this._iconSz = iconSz switch
3814 MyCommon.IconSizes.IconNone => 0,
3815 MyCommon.IconSizes.Icon16 => 16,
3816 MyCommon.IconSizes.Icon24 => 26,
3817 MyCommon.IconSizes.Icon48 => 48,
3818 MyCommon.IconSizes.Icon48_2 => 48,
3819 _ => throw new InvalidEnumArgumentException(nameof(iconSz), (int)iconSz, typeof(MyCommon.IconSizes)),
3821 this._iconCol = iconSz == MyCommon.IconSizes.Icon48_2;
3825 // ディスプレイの DPI 設定を考慮したサイズを設定する
3826 _listViewImageList.ImageSize = new Size(
3828 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3832 _listViewImageList.ImageSize = new Size(1, 1);
3836 private void ResetColumns(DetailsListView list)
3838 using (ControlTransaction.Update(list))
3839 using (ControlTransaction.Layout(list, false))
3842 list.ColumnClick -= MyList_ColumnClick;
3843 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3844 list.ColumnReordered -= MyList_ColumnReordered;
3845 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3847 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3848 list.Columns.Clear();
3849 cols.ForEach(col => col.Dispose());
3852 InitColumns(list, true);
3854 list.ColumnClick += MyList_ColumnClick;
3855 list.DrawColumnHeader += MyList_DrawColumnHeader;
3856 list.ColumnReordered += MyList_ColumnReordered;
3857 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3861 public void AddNewTabForSearch(string searchWord)
3863 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3864 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3866 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
3868 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3869 this.ListTab.SelectedIndex = tabIndex;
3874 var tabName = searchWord;
3875 for (var i = 0; i <= 100; i++)
3877 if (_statuses.ContainsTab(tabName))
3883 var tab = new PublicSearchTabModel(tabName);
3884 _statuses.AddTab(tab);
3885 AddNewTab(tab, startup: false);
3887 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3889 var tabPage = this.CurrentTabPage;
3890 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3891 cmb.Items.Add(searchWord);
3892 cmb.Text = searchWord;
3895 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
3898 private async Task ShowUserTimeline()
3900 var post = this.CurrentPost;
3901 if (post == null || !this.ExistCurrentPost) return;
3902 await this.AddNewTabForUserTimeline(post.ScreenName);
3905 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3907 if (e.KeyCode == Keys.Escape)
3909 RemoveSpecifiedTab(this.CurrentTabName, false);
3911 e.SuppressKeyPress = true;
3915 public async Task AddNewTabForUserTimeline(string user)
3917 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3918 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
3920 if (tb.ScreenName == user)
3922 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3923 this.ListTab.SelectedIndex = tabIndex;
3928 var tabName = "user:" + user;
3929 while (_statuses.ContainsTab(tabName))
3934 var tab = new UserTimelineTabModel(tabName, user);
3935 this._statuses.AddTab(tab);
3936 this.AddNewTab(tab, startup: false);
3938 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3941 await this.RefreshTabAsync(tab);
3944 public bool AddNewTab(TabModel tab, bool startup)
3947 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
3951 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
3953 var _tabPage = new TabPage();
3954 var _listCustom = new DetailsListView();
3956 var cnt = this._statuses.Tabs.Count;
3958 ///ToDo:Create and set controls follow tabtypes
3960 using (ControlTransaction.Update(_listCustom))
3961 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3962 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3963 using (ControlTransaction.Layout(this.SplitContainer1, false))
3964 using (ControlTransaction.Layout(this.ListTab, false))
3965 using (ControlTransaction.Layout(this))
3966 using (ControlTransaction.Layout(_tabPage, false))
3968 _tabPage.Controls.Add(_listCustom);
3971 var userTab = tab as UserTimelineTabModel;
3972 var listTab = tab as ListTimelineTabModel;
3973 var searchTab = tab as PublicSearchTabModel;
3975 if (userTab != null || listTab != null)
3977 var label = new Label
3979 Dock = DockStyle.Top,
3984 if (listTab != null)
3986 label.Text = listTab.ListInfo.ToString();
3988 else if (userTab != null)
3990 label.Text = userTab.ScreenName + "'s Timeline";
3992 label.TextAlign = ContentAlignment.MiddleLeft;
3993 using (var tmpComboBox = new ComboBox())
3995 label.Height = tmpComboBox.Height;
3997 _tabPage.Controls.Add(label);
4000 else if (searchTab != null)
4002 var pnl = new Panel();
4004 var lbl = new Label();
4005 var cmb = new ComboBox();
4006 var btn = new Button();
4007 var cmbLang = new ComboBox();
4009 using (ControlTransaction.Layout(pnl, false))
4011 pnl.Controls.Add(cmb);
4012 pnl.Controls.Add(cmbLang);
4013 pnl.Controls.Add(btn);
4014 pnl.Controls.Add(lbl);
4015 pnl.Name = "panelSearch";
4017 pnl.Dock = DockStyle.Top;
4018 pnl.Height = cmb.Height;
4019 pnl.Enter += SearchControls_Enter;
4020 pnl.Leave += SearchControls_Leave;
4023 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4024 cmb.Dock = DockStyle.Fill;
4025 cmb.Name = "comboSearch";
4026 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4027 cmb.ImeMode = ImeMode.NoControl;
4028 cmb.TabStop = false;
4030 cmb.AutoCompleteMode = AutoCompleteMode.None;
4031 cmb.KeyDown += SearchComboBox_KeyDown;
4034 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4035 cmbLang.Dock = DockStyle.Right;
4037 cmbLang.Name = "comboLang";
4038 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4039 cmbLang.TabStop = false;
4040 cmbLang.TabIndex = 2;
4041 cmbLang.Items.Add("");
4042 cmbLang.Items.Add("ja");
4043 cmbLang.Items.Add("en");
4044 cmbLang.Items.Add("ar");
4045 cmbLang.Items.Add("da");
4046 cmbLang.Items.Add("nl");
4047 cmbLang.Items.Add("fa");
4048 cmbLang.Items.Add("fi");
4049 cmbLang.Items.Add("fr");
4050 cmbLang.Items.Add("de");
4051 cmbLang.Items.Add("hu");
4052 cmbLang.Items.Add("is");
4053 cmbLang.Items.Add("it");
4054 cmbLang.Items.Add("no");
4055 cmbLang.Items.Add("pl");
4056 cmbLang.Items.Add("pt");
4057 cmbLang.Items.Add("ru");
4058 cmbLang.Items.Add("es");
4059 cmbLang.Items.Add("sv");
4060 cmbLang.Items.Add("th");
4062 lbl.Text = "Search(C-S-f)";
4063 lbl.Name = "label1";
4064 lbl.Dock = DockStyle.Left;
4066 lbl.Height = cmb.Height;
4067 lbl.TextAlign = ContentAlignment.MiddleLeft;
4070 btn.Text = "Search";
4071 btn.Name = "buttonSearch";
4072 btn.UseVisualStyleBackColor = true;
4073 btn.Dock = DockStyle.Right;
4074 btn.TabStop = false;
4076 btn.Click += SearchButton_Click;
4078 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4080 cmb.Items.Add(searchTab.SearchWords);
4081 cmb.Text = searchTab.SearchWords;
4084 cmbLang.Text = searchTab.SearchLang;
4086 _tabPage.Controls.Add(pnl);
4090 _tabPage.Tag = _listCustom;
4091 this.ListTab.Controls.Add(_tabPage);
4093 _tabPage.Location = new Point(4, 4);
4094 _tabPage.Name = "CTab" + cnt;
4095 _tabPage.Size = new Size(380, 260);
4096 _tabPage.TabIndex = 2 + cnt;
4097 _tabPage.Text = tab.TabName;
4098 _tabPage.UseVisualStyleBackColor = true;
4099 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4101 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4102 _listCustom.TabIndex = 1;
4103 _listCustom.AllowColumnReorder = true;
4104 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4105 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4106 _listCustom.Dock = DockStyle.Fill;
4107 _listCustom.FullRowSelect = true;
4108 _listCustom.HideSelection = false;
4109 _listCustom.Location = new Point(0, 0);
4110 _listCustom.Margin = new Padding(0);
4111 _listCustom.Name = "CList" + Environment.TickCount;
4112 _listCustom.ShowItemToolTips = true;
4113 _listCustom.Size = new Size(380, 260);
4114 _listCustom.UseCompatibleStateImageBehavior = false;
4115 _listCustom.View = View.Details;
4116 _listCustom.OwnerDraw = true;
4117 _listCustom.VirtualMode = true;
4118 _listCustom.Font = _fntReaded;
4119 _listCustom.BackColor = _clListBackcolor;
4121 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4122 _listCustom.AllowDrop = true;
4124 _listCustom.SmallImageList = _listViewImageList;
4126 InitColumns(_listCustom, startup);
4128 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4129 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4130 _listCustom.ColumnClick += MyList_ColumnClick;
4131 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4132 _listCustom.DragDrop += TweenMain_DragDrop;
4133 _listCustom.DragEnter += TweenMain_DragEnter;
4134 _listCustom.DragOver += TweenMain_DragOver;
4135 _listCustom.DrawItem += MyList_DrawItem;
4136 _listCustom.MouseClick += MyList_MouseClick;
4137 _listCustom.ColumnReordered += MyList_ColumnReordered;
4138 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4139 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4140 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4141 _listCustom.DrawSubItem += MyList_DrawSubItem;
4142 _listCustom.HScrolled += MyList_HScrolled;
4148 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4150 var tabInfo = _statuses.GetTabByName(TabName);
4151 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
4156 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4157 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4158 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4164 var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4168 var _tabPage = this.ListTab.TabPages[tabIndex];
4170 SetListProperty(); //他のタブに列幅等を反映
4173 var _listCustom = (DetailsListView)_tabPage.Tag;
4174 _tabPage.Tag = null;
4176 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4177 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4178 using (ControlTransaction.Layout(this.SplitContainer1, false))
4179 using (ControlTransaction.Layout(this.ListTab, false))
4180 using (ControlTransaction.Layout(this))
4181 using (ControlTransaction.Layout(_tabPage, false))
4183 if (this.CurrentTabName == TabName)
4185 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4186 this._beforeSelectedTab = null;
4188 this.ListTab.Controls.Remove(_tabPage);
4191 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4193 using var label = _tabPage.Controls["labelUser"];
4194 _tabPage.Controls.Remove(label);
4196 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4198 using var pnl = _tabPage.Controls["panelSearch"];
4200 pnl.Enter -= SearchControls_Enter;
4201 pnl.Leave -= SearchControls_Leave;
4202 _tabPage.Controls.Remove(pnl);
4204 foreach (Control ctrl in pnl.Controls)
4206 if (ctrl.Name == "buttonSearch")
4208 ctrl.Click -= SearchButton_Click;
4210 else if (ctrl.Name == "comboSearch")
4212 ctrl.KeyDown -= SearchComboBox_KeyDown;
4214 pnl.Controls.Remove(ctrl);
4219 _tabPage.Controls.Remove(_listCustom);
4221 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4222 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4223 _listCustom.ColumnClick -= MyList_ColumnClick;
4224 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4225 _listCustom.DragDrop -= TweenMain_DragDrop;
4226 _listCustom.DragEnter -= TweenMain_DragEnter;
4227 _listCustom.DragOver -= TweenMain_DragOver;
4228 _listCustom.DrawItem -= MyList_DrawItem;
4229 _listCustom.MouseClick -= MyList_MouseClick;
4230 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4231 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4232 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4233 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4234 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4235 _listCustom.HScrolled -= MyList_HScrolled;
4237 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4238 _listCustom.Columns.Clear();
4239 cols.ForEach(col => col.Dispose());
4242 _listCustom.ContextMenuStrip = null;
4243 _listCustom.ColumnHeaderContextMenuStrip = null;
4244 _listCustom.Font = null;
4246 _listCustom.SmallImageList = null;
4247 _listCustom.ListViewItemSorter = null;
4250 this.PurgeListViewItemCache();
4254 _listCustom.Dispose();
4255 _statuses.RemoveTab(TabName);
4257 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4259 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4260 lst.VirtualListSize = tab.AllCount;
4266 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4268 this.PurgeListViewItemCache();
4269 _beforeSelectedTab = e.TabPage;
4272 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4276 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4279 var dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4280 if (!dragEnableRectangle.Contains(e.Location))
4282 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4283 tn = this.CurrentTabName;
4286 if (string.IsNullOrEmpty(tn)) return;
4288 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4291 var tabPage = this.ListTab.TabPages[tabIndex];
4292 ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4300 var cpos = new Point(e.X, e.Y);
4301 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4303 var rect = ListTab.GetTabRect(index);
4304 if (rect.Contains(cpos))
4306 _rclickTabName = tab.TabName;
4312 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4314 SetMainWindowTitle();
4315 SetStatusLabelUrl();
4316 SetApiStatusLabel();
4317 if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4318 this.Tag = ListTab.Tag;
4319 TabMenuControl(this.CurrentTabName);
4320 this.PushSelectPostChain();
4324 private void SetListProperty()
4326 if (!_isColumnChanged) return;
4328 var currentListView = this.CurrentListView;
4330 var dispOrder = new int[currentListView.Columns.Count];
4331 for (var i = 0; i < currentListView.Columns.Count; i++)
4333 for (var j = 0; j < currentListView.Columns.Count; j++)
4335 if (currentListView.Columns[j].DisplayIndex == i)
4344 foreach (TabPage tb in ListTab.TabPages)
4346 if (tb.Text == this.CurrentTabName)
4349 if (tb.Tag != null && tb.Controls.Count > 0)
4351 var lst = (DetailsListView)tb.Tag;
4352 for (var i = 0; i < lst.Columns.Count; i++)
4354 lst.Columns[dispOrder[i]].DisplayIndex = i;
4355 lst.Columns[i].Width = currentListView.Columns[i].Width;
4360 _isColumnChanged = false;
4363 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4365 if (e.KeyChar == '@')
4367 if (!SettingManager.Common.UseAtIdSupplement) return;
4369 var cnt = AtIdSupl.ItemCount;
4370 ShowSuplDialog(StatusText, AtIdSupl);
4371 if (cnt != AtIdSupl.ItemCount)
4372 this.MarkSettingAtIdModified();
4375 else if (e.KeyChar == '#')
4377 if (!SettingManager.Common.UseHashSupplement) return;
4378 ShowSuplDialog(StatusText, HashSupl);
4383 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4384 => this.ShowSuplDialog(owner, dialog, 0, "");
4386 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4387 => this.ShowSuplDialog(owner, dialog, offset, "");
4389 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4391 dialog.StartsWith = startswith;
4398 dialog.ShowDialog();
4400 this.TopMost = SettingManager.Common.AlwaysTop;
4401 var selStart = owner.SelectionStart;
4404 if (dialog.DialogResult == DialogResult.OK)
4406 if (!string.IsNullOrEmpty(dialog.inputText))
4410 fHalf = owner.Text.Substring(0, selStart - offset);
4412 if (selStart < owner.Text.Length)
4414 eHalf = owner.Text.Substring(selStart);
4416 owner.Text = fHalf + dialog.inputText + eHalf;
4417 owner.SelectionStart = selStart + dialog.inputText.Length;
4424 fHalf = owner.Text.Substring(0, selStart);
4426 if (selStart < owner.Text.Length)
4428 eHalf = owner.Text.Substring(selStart);
4430 owner.Text = fHalf + eHalf;
4433 owner.SelectionStart = selStart;
4439 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4442 if (!e.Alt && !e.Control && !e.Shift)
4444 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4446 var isSpace = false;
4447 foreach (var c in StatusText.Text)
4449 if (c == ' ' || c == ' ')
4462 StatusText.Text = "";
4463 JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4467 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
4470 private void StatusText_TextChanged(object sender, EventArgs e)
4473 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4474 lblLen.Text = pLen.ToString();
4477 StatusText.ForeColor = Color.Red;
4481 StatusText.ForeColor = _clInputFont;
4484 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4486 if (string.IsNullOrEmpty(StatusText.Text))
4488 this.inReplyTo = null;
4493 /// メンション以外の文字列が含まれていないテキストであるか判定します
4495 internal static bool TextContainsOnlyMentions(string text)
4497 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4500 foreach (var mention in mentions)
4502 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4504 if (!string.IsNullOrWhiteSpace(textPart))
4507 startIndex = mention.Indices[1];
4510 var textPartLast = text.Substring(startIndex);
4512 if (!string.IsNullOrWhiteSpace(textPartLast))
4519 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4521 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4523 var _autoPopulatedUserIds = new List<long>();
4525 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4526 if (replyToPost != null)
4528 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4530 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4531 _autoPopulatedUserIds.Add(replyToPost.UserId);
4533 foreach (var (userId, screenName) in replyToPost.ReplyToList)
4535 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4537 statusText = statusText.Substring(screenName.Length + 2);
4538 _autoPopulatedUserIds.Add(userId);
4544 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4550 /// attachment_url に指定可能な URL が含まれていれば除去
4552 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
4554 attachmentUrl = null;
4556 // attachment_url は media_id と同時に使用できない
4557 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4560 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4564 attachmentUrl = match.Value;
4567 statusText = statusText.Substring(0, match.Index);
4569 // テキストと URL の間にスペースが含まれていれば除去
4570 return statusText.TrimEnd(' ');
4573 private string FormatStatusTextExtended(string statusText)
4574 => this.FormatStatusTextExtended(statusText, out _, out _);
4577 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4579 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
4581 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4583 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4585 return this.FormatStatusText(statusText);
4589 /// ツイート投稿前のフッター付与などの前処理を行います
4591 private string FormatStatusText(string statusText)
4593 statusText = statusText.Replace("\r\n", "\n");
4595 if (this.urlMultibyteSplit)
4598 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4601 if (SettingManager.Common.WideSpaceConvert)
4603 // 文中の全角スペースを半角スペース1個にする
4604 statusText = statusText.Replace(" ", " ");
4607 // DM の場合はこれ以降の処理を行わない
4608 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4612 if (SettingManager.Common.PostShiftEnter)
4614 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4618 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4619 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4621 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4624 if (statusText.Contains("RT @"))
4625 disableFooter = true;
4627 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4628 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4630 var mentionSelf = $"@{this.tw.Username} ";
4631 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4633 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4634 statusText = statusText.Substring(mentionSelf.Length);
4641 var hashtag = this.HashMgr.UseHash;
4642 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4645 header = HashMgr.UseHash + " ";
4647 footer = " " + HashMgr.UseHash;
4652 if (SettingManager.Local.UseRecommendStatus)
4655 footer += this.recommendedStatusFooter;
4657 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4659 // テキストボックスに入力されている文字列を使用する
4660 footer += " " + SettingManager.Local.StatusText.Trim();
4664 statusText = header + statusText + footer;
4666 if (this.preventSmsCommand)
4668 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4669 // 参照: https://support.twitter.com/articles/14020
4671 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4672 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4674 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4675 statusText = '\u200b' + statusText;
4683 /// 投稿欄に表示する入力可能な文字数を計算します
4685 private int GetRestStatusCount(string statusText)
4687 var remainCount = this.tw.GetTextLengthRemain(statusText);
4689 var uploadService = this.GetSelectedImageService();
4690 if (uploadService != null)
4692 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4693 remainCount -= uploadService.GetReservedTextLength(1);
4699 private IMediaUploadService? GetSelectedImageService()
4700 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4702 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4704 if (sender != this.CurrentListView)
4707 var listCache = this._listItemCache;
4708 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4710 // If the newly requested cache is a subset of the old cache,
4711 // no need to rebuild everything, so do nothing.
4715 // Now we need to rebuild the cache.
4716 this.CreateCache(e.StartIndex, e.EndIndex);
4719 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4721 var listCache = this._listItemCache;
4722 if (listCache?.TargetList == sender)
4724 if (listCache.TryGetValue(e.ItemIndex, out var item, out _))
4731 // A cache miss, so create a new ListViewItem and pass it back.
4732 var tabPage = (TabPage)((DetailsListView)sender).Parent;
4733 var tab = this._statuses.Tabs[tabPage.Text];
4736 e.Item = this.CreateItem(tab, tab[e.ItemIndex]);
4740 // 不正な要求に対する間に合わせの応答
4741 string[] sitem = {"", "", "", "", "", "", "", ""};
4742 e.Item = new ImageListViewItem(sitem);
4746 private void CreateCache(int startIndex, int endIndex)
4748 var tabInfo = this.CurrentTab;
4750 if (tabInfo.AllCount == 0)
4753 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4754 int FilterRange(int index)
4755 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4757 // キャッシュ要求(要求範囲±30を作成)
4758 startIndex = FilterRange(startIndex - 30);
4759 endIndex = FilterRange(endIndex + 30);
4761 var cacheLength = endIndex - startIndex + 1;
4763 var tab = this.CurrentTab;
4764 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4765 var listItems = Enumerable.Range(0, cacheLength)
4766 .Select(x => this.CreateItem(tab, posts[x]))
4769 var listCache = new ListViewItemCache
4771 TargetList = this.CurrentListView,
4772 StartIndex = startIndex,
4773 EndIndex = endIndex,
4774 Cache = Enumerable.Zip(listItems, posts, (x, y) => (x, y)).ToArray(),
4777 Interlocked.Exchange(ref this._listItemCache, listCache);
4781 /// DetailsListView のための ListViewItem のキャッシュを消去する
4783 private void PurgeListViewItemCache()
4784 => Interlocked.Exchange(ref this._listItemCache, null);
4786 private ListViewItem CreateItem(TabModel tab, PostClass Post)
4788 var mk = new StringBuilder();
4790 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4791 ImageListViewItem itm;
4792 if (Post.RetweetedId == null)
4794 string[] sitem= {"",
4796 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4797 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4802 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4806 string[] sitem = {"",
4808 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4809 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4810 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4814 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4816 itm.StateIndex = Post.StateIndex;
4819 var read = Post.IsRead;
4820 // 未読管理していなかったら既読として扱う
4821 if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4824 ChangeItemStyleRead(read, itm, Post, null);
4826 if (tab.TabName == this.CurrentTabName)
4827 this.ColorizeList(itm, Post);
4833 /// 全てのタブの振り分けルールを反映し直します
4835 private void ApplyPostFilters()
4837 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4839 this.PurgeListViewItemCache();
4840 this._statuses.FilterAll();
4842 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4844 var tabPage = this.ListTab.TabPages[index];
4845 var listview = (DetailsListView)tabPage.Tag;
4846 using (ControlTransaction.Update(listview))
4848 listview.VirtualListSize = tab.AllCount;
4851 if (SettingManager.Common.TabIconDisp)
4853 if (tab.UnreadCount > 0)
4854 tabPage.ImageIndex = 0;
4856 tabPage.ImageIndex = -1;
4860 if (!SettingManager.Common.TabIconDisp)
4861 this.ListTab.Refresh();
4863 SetMainWindowTitle();
4864 SetStatusLabelUrl();
4868 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4869 => e.DrawDefault = true;
4871 private void MyList_HScrolled(object sender, EventArgs e)
4872 => ((DetailsListView)sender).Refresh();
4874 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4876 if (e.State == 0) return;
4877 e.DrawDefault = false;
4880 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4882 if (e.Item.BackColor == _clSelf)
4883 brs2 = _brsBackColorMine;
4884 else if (e.Item.BackColor == _clAtSelf)
4885 brs2 = _brsBackColorAt;
4886 else if (e.Item.BackColor == _clTarget)
4887 brs2 = _brsBackColorYou;
4888 else if (e.Item.BackColor == _clAtTarget)
4889 brs2 = _brsBackColorAtYou;
4890 else if (e.Item.BackColor == _clAtFromTarget)
4891 brs2 = _brsBackColorAtFromTarget;
4892 else if (e.Item.BackColor == _clAtTo)
4893 brs2 = _brsBackColorAtTo;
4895 brs2 = _brsBackColorNone;
4900 if (((Control)sender).Focused)
4901 brs2 = _brsHighLight;
4903 brs2 = _brsDeactiveSelection;
4905 e.Graphics.FillRectangle(brs2, e.Bounds);
4906 e.DrawFocusRectangle();
4907 this.DrawListViewItemIcon(e);
4910 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
4912 if (e.ItemState == 0) return;
4914 if (e.ColumnIndex > 0)
4917 var post = (PostClass)e.Item.Tag;
4919 RectangleF rct = e.Bounds;
4920 rct.Width = e.Header.Width;
4921 var fontHeight = e.Item.Font.Height;
4924 rct.Y += fontHeight;
4925 rct.Height -= fontHeight;
4928 var drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
4930 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
4931 if (this._iconCol || drawLineCount > 1)
4933 if (heightDiff < fontHeight * 0.7)
4935 // 最終行が70%以上欠けていたら、最終行は表示しない
4936 rct.Height = (fontHeight * drawLineCount) - 1;
4946 var color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
4947 (((Control)sender).Focused) ? _clHighLight : //選択中の行
4952 var rctB = e.Bounds;
4953 rctB.Width = e.Header.Width;
4954 rctB.Height = fontHeight;
4956 using var fnt = new Font(e.Item.Font, FontStyle.Bold);
4958 TextRenderer.DrawText(e.Graphics,
4959 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
4961 Rectangle.Round(rct),
4963 TextFormatFlags.WordBreak |
4964 TextFormatFlags.EndEllipsis |
4965 TextFormatFlags.GlyphOverhangPadding |
4966 TextFormatFlags.NoPrefix);
4967 TextRenderer.DrawText(e.Graphics,
4968 e.Item.SubItems[4].Text + " / " + e.Item.SubItems[1].Text + " (" + e.Item.SubItems[3].Text + ") " + e.Item.SubItems[5].Text + e.Item.SubItems[6].Text + " [" + e.Item.SubItems[7].Text + "]",
4972 TextFormatFlags.SingleLine |
4973 TextFormatFlags.EndEllipsis |
4974 TextFormatFlags.GlyphOverhangPadding |
4975 TextFormatFlags.NoPrefix);
4980 if (e.ColumnIndex != 2)
4981 text = e.SubItem.Text;
4983 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
4985 if (drawLineCount == 1)
4987 TextRenderer.DrawText(e.Graphics,
4990 Rectangle.Round(rct),
4992 TextFormatFlags.SingleLine |
4993 TextFormatFlags.EndEllipsis |
4994 TextFormatFlags.GlyphOverhangPadding |
4995 TextFormatFlags.NoPrefix |
4996 TextFormatFlags.VerticalCenter);
5000 TextRenderer.DrawText(e.Graphics,
5003 Rectangle.Round(rct),
5005 TextFormatFlags.WordBreak |
5006 TextFormatFlags.EndEllipsis |
5007 TextFormatFlags.GlyphOverhangPadding |
5008 TextFormatFlags.NoPrefix);
5015 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5017 if (_iconSz == 0) return;
5019 var item = (ImageListViewItem)e.Item;
5021 //e.Bounds.Leftが常に0を指すから自前で計算
5022 var itemRect = item.Bounds;
5023 var col0 = e.Item.ListView.Columns[0];
5024 itemRect.Width = col0.Width;
5026 if (col0.DisplayIndex > 0)
5028 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5030 if (clm.DisplayIndex < col0.DisplayIndex)
5031 itemRect.X += clm.Width;
5035 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5036 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5037 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5040 var img = item.Image;
5043 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5044 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5046 if (iconRect.Width > 0)
5048 e.Graphics.FillRectangle(Brushes.White, iconRect);
5049 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5052 e.Graphics.DrawImage(img.Image, iconRect);
5054 catch (ArgumentException)
5056 item.RefreshImageAsync();
5062 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5064 item.GetImageAsync();
5067 if (item.StateIndex > -1)
5069 var stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5070 if (stateRect.Width > 0)
5071 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5075 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5077 base.ScaleControl(factor, specified);
5079 ScaleChildControl(this.TabImage, factor);
5081 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5082 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5084 foreach (var listview in listviews)
5086 ScaleChildControl(listview, factor);
5090 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5092 var tab = this.CurrentTab;
5094 if (tab.AllCount == 0)
5096 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5100 var selectedIndex = tab.SelectedIndex;
5105 case SEARCHTYPE.NextSearch: // 次を検索
5106 if (selectedIndex != -1)
5107 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5111 case SEARCHTYPE.PrevSearch: // 前を検索
5112 if (selectedIndex != -1)
5113 startIndex = Math.Max(selectedIndex - 1, 0);
5115 startIndex = tab.AllCount - 1;
5117 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5119 if (selectedIndex != -1)
5120 startIndex = selectedIndex;
5126 Func<string, bool> stringComparer;
5129 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5131 catch (ArgumentException)
5133 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5137 var reverse = searchType == SEARCHTYPE.PrevSearch;
5138 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5139 .DefaultIfEmpty(-1).First();
5141 if (foundIndex == -1)
5143 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5147 var listView = this.CurrentListView;
5148 this.SelectListItem(listView, foundIndex);
5149 listView.EnsureVisible(foundIndex);
5152 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5153 => this.ShowSearchDialog(); // 検索メニュー
5155 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5157 var previousSearch = this.SearchDialog.ResultOptions;
5158 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5160 this.SearchDialog.Reset();
5161 this.ShowSearchDialog();
5167 previousSearch.Query,
5168 previousSearch.CaseSensitive,
5169 previousSearch.UseRegex,
5170 SEARCHTYPE.NextSearch);
5173 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5175 var previousSearch = this.SearchDialog.ResultOptions;
5176 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5178 this.SearchDialog.Reset();
5179 this.ShowSearchDialog();
5185 previousSearch.Query,
5186 previousSearch.CaseSensitive,
5187 previousSearch.UseRegex,
5188 SEARCHTYPE.PrevSearch);
5192 /// 検索ダイアログを表示し、検索を実行します
5194 private void ShowSearchDialog()
5196 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5198 this.TopMost = SettingManager.Common.AlwaysTop;
5201 this.TopMost = SettingManager.Common.AlwaysTop;
5203 var searchOptions = this.SearchDialog.ResultOptions!;
5204 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5206 if (searchOptions.NewTab)
5208 var tabName = Properties.Resources.SearchResults_TabName;
5212 tabName = this._statuses.MakeTabName(tabName);
5214 catch (TabException ex)
5216 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5219 var resultTab = new LocalSearchTabModel(tabName);
5220 this.AddNewTab(resultTab, startup: false);
5221 this._statuses.AddTab(resultTab);
5223 var targetTab = this.CurrentTab;
5225 Func<string, bool> stringComparer;
5228 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5230 catch (ArgumentException)
5232 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5236 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5237 if (foundIndices.Length == 0)
5239 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5243 var foundPosts = foundIndices.Select(x => targetTab[x]);
5244 foreach (var post in foundPosts)
5246 resultTab.AddPostQueue(post);
5249 this._statuses.DistributePosts();
5250 this.RefreshTimeline();
5252 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5253 this.ListTab.SelectedIndex = tabIndex;
5258 searchOptions.Query,
5259 searchOptions.CaseSensitive,
5260 searchOptions.UseRegex,
5261 SEARCHTYPE.DialogSearch);
5264 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5266 this.AddNewTabForSearch(searchOptions.Query);
5270 /// <summary>発言検索に使用するメソッドを生成します</summary>
5271 /// <exception cref="ArgumentException">
5272 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5274 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5278 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5279 var regex = new Regex(query, regexOption);
5281 return x => regex.IsMatch(x);
5285 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5287 return x => x.IndexOf(query, comparisonType) != -1;
5291 private void AboutMenuItem_Click(object sender, EventArgs e)
5293 using (var about = new TweenAboutBox())
5295 about.ShowDialog(this);
5297 this.TopMost = SettingManager.Common.AlwaysTop;
5300 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5302 var bgnIdx = this._statuses.SelectedTabIndex;
5304 if (ImageSelector.Enabled)
5307 TabModel? foundTab = null;
5311 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5313 var unreadIndex = tab.NextUnreadIndex;
5314 if (unreadIndex != -1)
5316 ListTab.SelectedIndex = index;
5318 foundIndex = unreadIndex;
5323 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5324 if (foundTab == null && bgnIdx > 0)
5326 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5328 var unreadIndex = tab.NextUnreadIndex;
5329 if (unreadIndex != -1)
5331 ListTab.SelectedIndex = index;
5333 foundIndex = unreadIndex;
5339 DetailsListView lst;
5341 if (foundTab == null)
5343 //全部調べたが未読見つからず→先頭タブの最新発言へ
5344 ListTab.SelectedIndex = 0;
5345 var tabPage = this.ListTab.TabPages[0];
5346 var tab = this._statuses.Tabs[0];
5348 if (tab.AllCount == 0)
5351 if (_statuses.SortOrder == SortOrder.Ascending)
5352 foundIndex = tab.AllCount - 1;
5356 lst = (DetailsListView)tabPage.Tag;
5360 var foundTabIndex = this._statuses.Tabs.IndexOf(foundTab);
5361 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
5364 SelectListItem(lst, foundIndex);
5366 if (_statuses.SortMode == ComparerMode.Id)
5368 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5369 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5375 lst.EnsureVisible(foundIndex);
5380 lst.EnsureVisible(foundIndex);
5386 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5388 var tab = this.CurrentTab;
5389 var post = this.CurrentPost;
5390 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5391 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5394 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5395 => await this.CheckNewVersion(false);
5397 private void RunTweenUp()
5399 var pinfo = new ProcessStartInfo
5401 UseShellExecute = true,
5402 WorkingDirectory = MyCommon.settingPath,
5403 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5404 Arguments = "\"" + Application.StartupPath + "\"",
5409 Process.Start(pinfo);
5413 MessageBox.Show("Failed to execute TweenUp3.exe.");
5417 public class VersionInfo
5419 public Version Version { get; }
5420 public Uri DownloadUri { get; }
5421 public string ReleaseNote { get; }
5423 public VersionInfo(Version version, Uri downloadUri, string releaseNote)
5424 => (this.Version, this.DownloadUri, this.ReleaseNote) = (version, downloadUri, releaseNote);
5428 /// OpenTween の最新バージョンの情報を取得します
5430 public async Task<VersionInfo> GetVersionInfoAsync()
5432 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5433 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5435 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5436 .ConfigureAwait(false);
5438 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5439 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5441 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5442 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5444 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5446 return new VersionInfo(
5447 version: Version.Parse(msgHeader[0]),
5448 downloadUri: new Uri(msgHeader[1]),
5449 releaseNote: msgBody
5453 private async Task CheckNewVersion(bool startup = false)
5455 if (ApplicationSettings.VersionInfoUrl == null)
5456 return; // 更新チェック無効化
5460 var versionInfo = await this.GetVersionInfoAsync();
5462 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5467 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5468 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5469 msgtext = MyCommon.ReplaceAppName(msgtext);
5471 MessageBox.Show(msgtext,
5472 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5473 MessageBoxButtons.OK, MessageBoxIcon.Information);
5478 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5481 using var dialog = new UpdateDialog();
5483 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5484 MyCommon.GetReadableVersion(versionInfo.Version));
5485 dialog.DetailsText = versionInfo.ReleaseNote;
5487 if (dialog.ShowDialog(this) == DialogResult.Yes)
5489 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5491 else if (dialog.SkipButtonPressed)
5493 SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5494 this.MarkSettingCommonModified();
5499 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5502 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5503 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5504 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5509 private void UpdateSelectedPost()
5511 //件数関連の場合、タイトル即時書き換え
5512 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5513 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5514 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5515 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5517 SetMainWindowTitle();
5519 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5520 SetStatusLabelUrl();
5522 if (SettingManager.Common.TabIconDisp)
5524 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5526 if (tab.UnreadCount == 0)
5528 var tabPage = this.ListTab.TabPages[index];
5529 if (tabPage.ImageIndex == 0)
5530 tabPage.ImageIndex = -1;
5536 this.ListTab.Refresh();
5539 this.DispSelectedPost();
5542 public string createDetailHtml(string orgdata)
5543 => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5545 private void DispSelectedPost()
5546 => this.DispSelectedPost(false);
5548 private PostClass displayPost = new PostClass();
5551 /// サムネイル表示に使用する CancellationToken の生成元
5553 private CancellationTokenSource? thumbnailTokenSource = null;
5555 private void DispSelectedPost(bool forceupdate)
5557 var currentPost = this.CurrentPost;
5558 if (currentPost == null)
5561 var oldDisplayPost = this.displayPost;
5562 this.displayPost = currentPost;
5564 if (!forceupdate && currentPost.Equals(oldDisplayPost))
5567 var loadTasks = new List<Task>
5569 this.tweetDetailsView.ShowPostDetails(currentPost),
5572 this.SplitContainer3.Panel2Collapsed = true;
5574 if (SettingManager.Common.PreviewEnable)
5576 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5577 oldTokenSource?.Cancel();
5579 var token = this.thumbnailTokenSource!.Token;
5580 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5583 async Task delayedTasks()
5587 await Task.WhenAll(loadTasks);
5589 catch (OperationCanceledException) { }
5592 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
5596 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5597 => await this.OpenApplicationWebsite();
5599 private async Task OpenApplicationWebsite()
5600 => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5602 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5603 => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5605 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5607 var tab = this.CurrentTab;
5608 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5610 var pnl = this.CurrentTabPage.Controls["panelSearch"];
5611 if (pnl.Controls["comboSearch"].Focused ||
5612 pnl.Controls["comboLang"].Focused ||
5613 pnl.Controls["buttonSearch"].Focused) return;
5616 if (e.Control || e.Shift || e.Alt)
5617 this._anchorFlag = false;
5619 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5622 e.SuppressKeyPress = true;
5625 if (asyncTask != null)
5629 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5631 private void InitializeShortcuts()
5633 this.shortcutCommands = new[]
5635 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5636 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5637 .FocusedOn(FocusedControl.ListTab)
5638 .Do(() => SendKeys.Send("{DOWN}")),
5640 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5641 .FocusedOn(FocusedControl.ListTab)
5642 .Do(() => SendKeys.Send("{UP}")),
5644 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5645 .FocusedOn(FocusedControl.ListTab)
5646 .Do(() => SendKeys.Send("{PGDN}")),
5648 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5649 .FocusedOn(FocusedControl.ListTab)
5650 .Do(() => SendKeys.Send("{PGUP}")),
5652 ShortcutCommand.Create(Keys.F1)
5653 .Do(() => this.OpenApplicationWebsite()),
5655 ShortcutCommand.Create(Keys.F3)
5656 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
5658 ShortcutCommand.Create(Keys.F5)
5659 .Do(() => this.DoRefresh()),
5661 ShortcutCommand.Create(Keys.F6)
5662 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5664 ShortcutCommand.Create(Keys.F7)
5665 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5667 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5668 .NotFocusedOn(FocusedControl.StatusText)
5669 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty); }),
5671 ShortcutCommand.Create(Keys.G)
5672 .NotFocusedOn(FocusedControl.StatusText)
5673 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty); }),
5675 ShortcutCommand.Create(Keys.Right, Keys.N)
5676 .FocusedOn(FocusedControl.ListTab)
5677 .Do(() => this.GoRelPost(forward: true)),
5679 ShortcutCommand.Create(Keys.Left, Keys.P)
5680 .FocusedOn(FocusedControl.ListTab)
5681 .Do(() => this.GoRelPost(forward: false)),
5683 ShortcutCommand.Create(Keys.OemPeriod)
5684 .FocusedOn(FocusedControl.ListTab)
5685 .Do(() => this.GoAnchor()),
5687 ShortcutCommand.Create(Keys.I)
5688 .FocusedOn(FocusedControl.ListTab)
5689 .OnlyWhen(() => this.StatusText.Enabled)
5690 .Do(() => this.StatusText.Focus()),
5692 ShortcutCommand.Create(Keys.Enter)
5693 .FocusedOn(FocusedControl.ListTab)
5694 .Do(() => this.MakeReplyOrDirectStatus()),
5696 ShortcutCommand.Create(Keys.R)
5697 .FocusedOn(FocusedControl.ListTab)
5698 .Do(() => this.DoRefresh()),
5700 ShortcutCommand.Create(Keys.L)
5701 .FocusedOn(FocusedControl.ListTab)
5702 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5704 ShortcutCommand.Create(Keys.H)
5705 .FocusedOn(FocusedControl.ListTab)
5706 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5708 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5709 .FocusedOn(FocusedControl.ListTab)
5710 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5712 ShortcutCommand.Create(Keys.S)
5713 .FocusedOn(FocusedControl.ListTab)
5714 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5716 ShortcutCommand.Create(Keys.A)
5717 .FocusedOn(FocusedControl.ListTab)
5718 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5720 // ] in_reply_to参照元へ戻る
5721 ShortcutCommand.Create(Keys.Oem4)
5722 .FocusedOn(FocusedControl.ListTab)
5723 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5725 // [ in_reply_toへジャンプ
5726 ShortcutCommand.Create(Keys.Oem6)
5727 .FocusedOn(FocusedControl.ListTab)
5728 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5730 ShortcutCommand.Create(Keys.Escape)
5731 .FocusedOn(FocusedControl.ListTab)
5733 this._anchorFlag = false;
5734 var tab = this.CurrentTab;
5735 var tabtype = tab.TabType;
5736 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5738 RemoveSpecifiedTab(tab.TabName, false);
5743 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5744 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5745 .FocusedOn(FocusedControl.ListTab)
5746 .Do(() => this._anchorFlag = false, preventDefault: false),
5748 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5749 ShortcutCommand.Create(Keys.Up, Keys.Down)
5750 .FocusedOn(FocusedControl.PostBrowser)
5753 ShortcutCommand.Create(Keys.Control | Keys.R)
5754 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5756 ShortcutCommand.Create(Keys.Control | Keys.D)
5757 .Do(() => this.doStatusDelete()),
5759 ShortcutCommand.Create(Keys.Control | Keys.M)
5760 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5762 ShortcutCommand.Create(Keys.Control | Keys.S)
5763 .Do(() => this.FavoriteChange(FavAdd: true)),
5765 ShortcutCommand.Create(Keys.Control | Keys.I)
5766 .Do(() => this.doRepliedStatusOpen()),
5768 ShortcutCommand.Create(Keys.Control | Keys.Q)
5769 .Do(() => this.doQuoteOfficial()),
5771 ShortcutCommand.Create(Keys.Control | Keys.B)
5772 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
5774 ShortcutCommand.Create(Keys.Control | Keys.T)
5775 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
5777 ShortcutCommand.Create(Keys.Control | Keys.L)
5778 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
5780 ShortcutCommand.Create(Keys.Control | Keys.Y)
5781 .NotFocusedOn(FocusedControl.PostBrowser)
5782 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
5784 ShortcutCommand.Create(Keys.Control | Keys.F)
5785 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
5787 ShortcutCommand.Create(Keys.Control | Keys.U)
5788 .Do(() => this.ShowUserTimeline()),
5790 ShortcutCommand.Create(Keys.Control | Keys.H)
5791 .Do(() => this.MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty)),
5793 ShortcutCommand.Create(Keys.Control | Keys.G)
5794 .Do(() => this.MoveToFavToolStripMenuItem_Click(this.MoveToFavToolStripMenuItem, EventArgs.Empty)),
5796 ShortcutCommand.Create(Keys.Control | Keys.O)
5797 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
5799 ShortcutCommand.Create(Keys.Control | Keys.E)
5800 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
5802 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5803 .FocusedOn(FocusedControl.ListTab)
5804 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
5806 ShortcutCommand.Create(Keys.Control | Keys.N)
5807 .FocusedOn(FocusedControl.ListTab)
5808 .Do(() => this.GoNextTab(forward: true)),
5810 ShortcutCommand.Create(Keys.Control | Keys.P)
5811 .FocusedOn(FocusedControl.ListTab)
5812 .Do(() => this.GoNextTab(forward: false)),
5814 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5815 .FocusedOn(FocusedControl.ListTab)
5816 .Do(() => this.CopyStot()),
5818 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5819 ShortcutCommand.Create(Keys.Control | Keys.D1)
5820 .FocusedOn(FocusedControl.ListTab)
5821 .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5822 .Do(() => this.ListTab.SelectedIndex = 0),
5824 ShortcutCommand.Create(Keys.Control | Keys.D2)
5825 .FocusedOn(FocusedControl.ListTab)
5826 .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5827 .Do(() => this.ListTab.SelectedIndex = 1),
5829 ShortcutCommand.Create(Keys.Control | Keys.D3)
5830 .FocusedOn(FocusedControl.ListTab)
5831 .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5832 .Do(() => this.ListTab.SelectedIndex = 2),
5834 ShortcutCommand.Create(Keys.Control | Keys.D4)
5835 .FocusedOn(FocusedControl.ListTab)
5836 .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5837 .Do(() => this.ListTab.SelectedIndex = 3),
5839 ShortcutCommand.Create(Keys.Control | Keys.D5)
5840 .FocusedOn(FocusedControl.ListTab)
5841 .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5842 .Do(() => this.ListTab.SelectedIndex = 4),
5844 ShortcutCommand.Create(Keys.Control | Keys.D6)
5845 .FocusedOn(FocusedControl.ListTab)
5846 .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5847 .Do(() => this.ListTab.SelectedIndex = 5),
5849 ShortcutCommand.Create(Keys.Control | Keys.D7)
5850 .FocusedOn(FocusedControl.ListTab)
5851 .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
5852 .Do(() => this.ListTab.SelectedIndex = 6),
5854 ShortcutCommand.Create(Keys.Control | Keys.D8)
5855 .FocusedOn(FocusedControl.ListTab)
5856 .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
5857 .Do(() => this.ListTab.SelectedIndex = 7),
5859 ShortcutCommand.Create(Keys.Control | Keys.D9)
5860 .FocusedOn(FocusedControl.ListTab)
5861 .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
5863 ShortcutCommand.Create(Keys.Control | Keys.A)
5864 .FocusedOn(FocusedControl.StatusText)
5865 .Do(() => this.StatusText.SelectAll()),
5867 ShortcutCommand.Create(Keys.Control | Keys.V)
5868 .FocusedOn(FocusedControl.StatusText)
5869 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
5871 ShortcutCommand.Create(Keys.Control | Keys.Up)
5872 .FocusedOn(FocusedControl.StatusText)
5873 .Do(() => this.StatusTextHistoryBack()),
5875 ShortcutCommand.Create(Keys.Control | Keys.Down)
5876 .FocusedOn(FocusedControl.StatusText)
5877 .Do(() => this.StatusTextHistoryForward()),
5879 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
5880 .FocusedOn(FocusedControl.StatusText)
5882 if (ListTab.SelectedIndex == 0)
5884 ListTab.SelectedIndex = ListTab.TabCount - 1;
5888 ListTab.SelectedIndex -= 1;
5893 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
5894 .FocusedOn(FocusedControl.StatusText)
5896 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
5898 ListTab.SelectedIndex = 0;
5902 ListTab.SelectedIndex += 1;
5907 ShortcutCommand.Create(Keys.Control | Keys.Y)
5908 .FocusedOn(FocusedControl.PostBrowser)
5910 var multiline = !SettingManager.Local.StatusMultiline;
5911 SettingManager.Local.StatusMultiline = multiline;
5912 MultiLineMenuItem.Checked = multiline;
5913 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
5916 ShortcutCommand.Create(Keys.Shift | Keys.F3)
5917 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
5919 ShortcutCommand.Create(Keys.Shift | Keys.F5)
5920 .Do(() => this.DoRefreshMore()),
5922 ShortcutCommand.Create(Keys.Shift | Keys.F6)
5923 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
5925 ShortcutCommand.Create(Keys.Shift | Keys.F7)
5926 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
5928 ShortcutCommand.Create(Keys.Shift | Keys.R)
5929 .NotFocusedOn(FocusedControl.StatusText)
5930 .Do(() => this.DoRefreshMore()),
5932 ShortcutCommand.Create(Keys.Shift | Keys.H)
5933 .FocusedOn(FocusedControl.ListTab)
5934 .Do(() => this.GoTopEnd(GoTop: true)),
5936 ShortcutCommand.Create(Keys.Shift | Keys.L)
5937 .FocusedOn(FocusedControl.ListTab)
5938 .Do(() => this.GoTopEnd(GoTop: false)),
5940 ShortcutCommand.Create(Keys.Shift | Keys.M)
5941 .FocusedOn(FocusedControl.ListTab)
5942 .Do(() => this.GoMiddle()),
5944 ShortcutCommand.Create(Keys.Shift | Keys.G)
5945 .FocusedOn(FocusedControl.ListTab)
5946 .Do(() => this.GoLast()),
5948 ShortcutCommand.Create(Keys.Shift | Keys.Z)
5949 .FocusedOn(FocusedControl.ListTab)
5950 .Do(() => this.MoveMiddle()),
5952 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
5953 .FocusedOn(FocusedControl.ListTab)
5954 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
5956 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
5957 .FocusedOn(FocusedControl.ListTab)
5958 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
5960 // お気に入り前後ジャンプ(SHIFT+N←/P→)
5961 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
5962 .FocusedOn(FocusedControl.ListTab)
5963 .Do(() => this.GoFav(forward: true)),
5965 // お気に入り前後ジャンプ(SHIFT+N←/P→)
5966 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
5967 .FocusedOn(FocusedControl.ListTab)
5968 .Do(() => this.GoFav(forward: false)),
5970 ShortcutCommand.Create(Keys.Shift | Keys.Space)
5971 .FocusedOn(FocusedControl.ListTab)
5972 .Do(() => this.GoBackSelectPostChain()),
5974 ShortcutCommand.Create(Keys.Alt | Keys.R)
5975 .Do(() => this.doReTweetOfficial(isConfirm: true)),
5977 ShortcutCommand.Create(Keys.Alt | Keys.P)
5978 .OnlyWhen(() => this.CurrentPost != null)
5979 .Do(() => this.doShowUserStatus(this.CurrentPost!.ScreenName, ShowInputDialog: false)),
5981 ShortcutCommand.Create(Keys.Alt | Keys.Up)
5982 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
5984 ShortcutCommand.Create(Keys.Alt | Keys.Down)
5985 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
5987 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
5988 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
5990 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
5991 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
5993 // 別タブの同じ書き込みへ(ALT+←/→)
5994 ShortcutCommand.Create(Keys.Alt | Keys.Right)
5995 .FocusedOn(FocusedControl.ListTab)
5996 .Do(() => this.GoSamePostToAnotherTab(left: false)),
5998 ShortcutCommand.Create(Keys.Alt | Keys.Left)
5999 .FocusedOn(FocusedControl.ListTab)
6000 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6002 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6003 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6005 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6006 .Do(() => this.CopyIdUri()),
6008 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6009 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6010 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6012 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6013 .Do(() => this.FavoriteChange(FavAdd: false)),
6015 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6016 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
6018 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6019 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
6021 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6022 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
6024 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6025 .Do(() => this.doMoveToRTHome()),
6027 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6028 .FocusedOn(FocusedControl.StatusText)
6030 var tab = this.CurrentTab;
6031 var selectedIndex = tab.SelectedIndex;
6032 if (selectedIndex != -1 && selectedIndex > 0)
6034 var listView = this.CurrentListView;
6035 var idx = selectedIndex - 1;
6036 SelectListItem(listView, idx);
6037 listView.EnsureVisible(idx);
6041 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6042 .FocusedOn(FocusedControl.StatusText)
6044 var tab = this.CurrentTab;
6045 var selectedIndex = tab.SelectedIndex;
6046 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6048 var listView = this.CurrentListView;
6049 var idx = selectedIndex + 1;
6050 SelectListItem(listView, idx);
6051 listView.EnsureVisible(idx);
6055 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6056 .FocusedOn(FocusedControl.StatusText)
6058 if (StatusText.SelectionStart > 0)
6060 var endidx = StatusText.SelectionStart - 1;
6062 for (var i = StatusText.SelectionStart - 1; i >= 0; i--)
6064 var c = StatusText.Text[i];
6065 if (char.IsLetterOrDigit(c) || c == '_')
6071 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6072 var cnt = AtIdSupl.ItemCount;
6073 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6074 if (AtIdSupl.ItemCount != cnt)
6075 this.MarkSettingAtIdModified();
6079 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6080 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6090 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6091 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6092 .FocusedOn(FocusedControl.ListTab)
6093 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6095 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6096 .FocusedOn(FocusedControl.ListTab)
6097 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6099 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6100 .FocusedOn(FocusedControl.ListTab)
6101 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6103 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6104 .FocusedOn(FocusedControl.ListTab)
6105 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6107 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6108 .FocusedOn(FocusedControl.ListTab)
6109 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6111 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6112 .FocusedOn(FocusedControl.ListTab)
6113 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6115 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6116 .FocusedOn(FocusedControl.ListTab)
6117 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6119 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6120 .FocusedOn(FocusedControl.ListTab)
6121 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6123 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6124 .FocusedOn(FocusedControl.ListTab)
6125 .Do(() => this.SetSortLastColumn()),
6127 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6128 .FocusedOn(FocusedControl.ListTab)
6129 .Do(() => this.FavoritesRetweetOfficial()),
6131 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6132 .FocusedOn(FocusedControl.ListTab)
6133 .Do(() => this.FavoritesRetweetUnofficial()),
6135 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6136 .FocusedOn(FocusedControl.ListTab)
6137 .Do(() => this.OpenUserAppointUrl()),
6139 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6140 .FocusedOn(FocusedControl.PostBrowser)
6141 .Do(() => this.doReTweetUnofficial()),
6143 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6144 .OnlyWhen(() => this.ExistCurrentPost)
6145 .Do(() => this.tweetDetailsView.DoTranslation()),
6147 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6148 .Do(() => this.doReTweetUnofficial()),
6150 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6151 .Do(() => this.CopyUserId()),
6153 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6154 .Do(() => this.tweetThumbnail1.ScrollUp()),
6156 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6157 .Do(() => this.tweetThumbnail1.ScrollDown()),
6159 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6160 .FocusedOn(FocusedControl.ListTab)
6161 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6162 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6166 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
6168 // Task を返す非同期処理があれば asyncTask に代入する
6171 // ShortcutCommand に対応しているコマンドはここで処理される
6172 foreach (var command in this.shortcutCommands)
6174 if (command.IsMatch(keyData, focusedOn))
6176 asyncTask = command.RunCommand();
6177 return command.PreventDefault;
6184 private void GoNextTab(bool forward)
6186 var idx = this._statuses.SelectedTabIndex;
6187 var tabCount = this._statuses.Tabs.Count;
6191 if (idx > tabCount - 1) idx = 0;
6196 if (idx < 0) idx = tabCount - 1;
6198 ListTab.SelectedIndex = idx;
6201 private void CopyStot()
6203 var sb = new StringBuilder();
6204 var tab = this.CurrentTab;
6205 var IsProtected = false;
6206 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6207 foreach (var post in tab.SelectedPosts)
6209 if (post.IsDeleted) continue;
6212 if (post.RetweetedId != null)
6213 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6215 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6219 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6224 MessageBox.Show(Properties.Resources.CopyStotText1);
6228 var clstr = sb.ToString();
6231 Clipboard.SetDataObject(clstr, false, 5, 100);
6233 catch (Exception ex)
6235 MessageBox.Show(ex.Message);
6240 private void CopyIdUri()
6242 var tab = this.CurrentTab;
6243 if (tab == null || tab is DirectMessagesTabModel)
6246 var copyUrls = new List<string>();
6247 foreach (var post in tab.SelectedPosts)
6248 copyUrls.Add(MyCommon.GetStatusUrl(post));
6250 if (copyUrls.Count == 0)
6255 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6257 catch (ExternalException ex)
6259 MessageBox.Show(ex.Message);
6263 private void GoFav(bool forward)
6265 var tab = this.CurrentTab;
6266 if (tab.AllCount == 0)
6269 var selectedIndex = tab.SelectedIndex;
6277 if (selectedIndex == -1)
6283 fIdx = selectedIndex + 1;
6284 if (fIdx > tab.AllCount - 1)
6287 toIdx = tab.AllCount;
6292 if (selectedIndex == -1)
6294 fIdx = tab.AllCount - 1;
6298 fIdx = selectedIndex - 1;
6306 for (var idx = fIdx; idx != toIdx; idx += stp)
6310 var listView = this.CurrentListView;
6311 SelectListItem(listView, idx);
6312 listView.EnsureVisible(idx);
6318 private void GoSamePostToAnotherTab(bool left)
6320 var tab = this.CurrentTab;
6322 // Directタブは対象外(見つかるはずがない)
6323 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6326 var selectedStatusId = tab.SelectedStatusId;
6327 if (selectedStatusId == -1)
6330 int fIdx, toIdx, stp;
6335 if (ListTab.SelectedIndex == 0)
6341 fIdx = ListTab.SelectedIndex - 1;
6349 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6355 fIdx = ListTab.SelectedIndex + 1;
6357 toIdx = ListTab.TabCount;
6361 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6363 var targetTab = this._statuses.Tabs[tabidx];
6366 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6369 var foundIndex = targetTab.IndexOf(selectedStatusId);
6370 if (foundIndex != -1)
6372 ListTab.SelectedIndex = tabidx;
6373 var listView = this.CurrentListView;
6374 SelectListItem(listView, foundIndex);
6375 listView.EnsureVisible(foundIndex);
6381 private void GoPost(bool forward)
6383 var tab = this.CurrentTab;
6384 var currentPost = this.CurrentPost;
6386 if (currentPost == null)
6389 var selectedIndex = tab.SelectedIndex;
6391 int fIdx, toIdx, stp;
6395 fIdx = selectedIndex + 1;
6396 if (fIdx > tab.AllCount - 1) return;
6397 toIdx = tab.AllCount;
6402 fIdx = selectedIndex - 1;
6403 if (fIdx < 0) return;
6409 if (currentPost.RetweetedBy == null)
6411 name = currentPost.ScreenName;
6415 name = currentPost.RetweetedBy;
6417 for (var idx = fIdx; idx != toIdx; idx += stp)
6419 var post = tab[idx];
6420 if (post.RetweetedId == null)
6422 if (post.ScreenName == name)
6424 var listView = this.CurrentListView;
6425 SelectListItem(listView, idx);
6426 listView.EnsureVisible(idx);
6432 if (post.RetweetedBy == name)
6434 var listView = this.CurrentListView;
6435 SelectListItem(listView, idx);
6436 listView.EnsureVisible(idx);
6443 private void GoRelPost(bool forward)
6445 var tab = this.CurrentTab;
6446 var selectedIndex = tab.SelectedIndex;
6448 if (selectedIndex == -1)
6451 int fIdx, toIdx, stp;
6455 fIdx = selectedIndex + 1;
6456 if (fIdx > tab.AllCount - 1) return;
6457 toIdx = tab.AllCount;
6462 fIdx = selectedIndex - 1;
6463 if (fIdx < 0) return;
6470 var currentPost = this.CurrentPost;
6471 if (currentPost == null) return;
6472 _anchorPost = currentPost;
6477 if (_anchorPost == null) return;
6480 for (var idx = fIdx; idx != toIdx; idx += stp)
6482 var post = tab[idx];
6483 if (post.ScreenName == _anchorPost.ScreenName ||
6484 post.RetweetedBy == _anchorPost.ScreenName ||
6485 post.ScreenName == _anchorPost.RetweetedBy ||
6486 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6487 _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6488 _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6489 post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6490 post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6492 var listView = this.CurrentListView;
6493 SelectListItem(listView, idx);
6494 listView.EnsureVisible(idx);
6500 private void GoAnchor()
6502 if (_anchorPost == null) return;
6503 var idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6504 if (idx == -1) return;
6506 var listView = this.CurrentListView;
6507 SelectListItem(listView, idx);
6508 listView.EnsureVisible(idx);
6511 private void GoTopEnd(bool GoTop)
6513 var listView = this.CurrentListView;
6514 if (listView.VirtualListSize == 0)
6522 _item = listView.GetItemAt(0, 25);
6530 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6532 idx = listView.VirtualListSize - 1;
6536 SelectListItem(listView, idx);
6539 private void GoMiddle()
6541 var listView = this.CurrentListView;
6542 if (listView.VirtualListSize == 0)
6550 _item = listView.GetItemAt(0, 0);
6560 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6563 idx2 = listView.VirtualListSize - 1;
6569 idx3 = (idx1 + idx2) / 2;
6571 SelectListItem(listView, idx3);
6574 private void GoLast()
6576 var listView = this.CurrentListView;
6577 if (listView.VirtualListSize == 0) return;
6579 if (_statuses.SortOrder == SortOrder.Ascending)
6581 SelectListItem(listView, listView.VirtualListSize - 1);
6582 listView.EnsureVisible(listView.VirtualListSize - 1);
6586 SelectListItem(listView, 0);
6587 listView.EnsureVisible(0);
6591 private void MoveTop()
6593 var listView = this.CurrentListView;
6594 if (listView.SelectedIndices.Count == 0) return;
6595 var idx = listView.SelectedIndices[0];
6596 if (_statuses.SortOrder == SortOrder.Ascending)
6598 listView.EnsureVisible(listView.VirtualListSize - 1);
6602 listView.EnsureVisible(0);
6604 listView.EnsureVisible(idx);
6607 private async Task GoInReplyToPostTree()
6609 var curTabClass = this.CurrentTab;
6610 var currentPost = this.CurrentPost;
6612 if (currentPost == null)
6615 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6619 var post = await tw.GetStatusApi(false, currentPost.StatusId);
6621 currentPost.InReplyToStatusId = post.InReplyToStatusId;
6622 currentPost.InReplyToUser = post.InReplyToUser;
6623 currentPost.IsReply = post.IsReply;
6624 this.PurgeListViewItemCache();
6626 var index = curTabClass.SelectedIndex;
6627 this.CurrentListView.RedrawItems(index, index, false);
6629 catch (WebApiException ex)
6631 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6635 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6637 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6639 replyChains = new Stack<ReplyChain>();
6641 replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6644 string inReplyToTabName;
6645 var inReplyToId = currentPost.InReplyToStatusId.Value;
6646 var inReplyToUser = currentPost.InReplyToUser;
6648 var inReplyToPosts = from tab in _statuses.Tabs
6649 orderby tab != curTabClass
6650 from post in tab.Posts.Values
6651 where post.StatusId == inReplyToId
6652 let index = tab.IndexOf(post.StatusId)
6654 select new {Tab = tab, Index = index};
6656 var inReplyPost = inReplyToPosts.FirstOrDefault();
6657 if (inReplyPost == null)
6661 await Task.Run(async () =>
6663 var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6664 .ConfigureAwait(false);
6667 _statuses.AddPost(post);
6668 _statuses.DistributePosts();
6671 catch (WebApiException ex)
6673 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6674 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6678 this.RefreshTimeline();
6680 inReplyPost = inReplyToPosts.FirstOrDefault();
6681 if (inReplyPost == null)
6683 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6687 inReplyToTabName = inReplyPost.Tab.TabName;
6688 inReplyToIndex = inReplyPost.Index;
6690 var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6691 var tabPage = this.ListTab.TabPages[tabIndex];
6692 var listView = (DetailsListView)tabPage.Tag;
6694 if (this.CurrentTabName != inReplyToTabName)
6696 this.ListTab.SelectedIndex = tabIndex;
6699 this.SelectListItem(listView, inReplyToIndex);
6700 listView.EnsureVisible(inReplyToIndex);
6703 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6705 var curTabClass = this.CurrentTab;
6706 var currentPost = this.CurrentPost;
6708 if (currentPost == null)
6713 if (currentPost.InReplyToStatusId != null)
6715 var posts = from t in _statuses.Tabs
6717 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6718 let indexOf = t.IndexOf(p.Value.StatusId)
6720 orderby isForward ? indexOf : indexOf * -1
6721 orderby t != curTabClass
6722 select new {Tab = t, Post = p.Value, Index = indexOf};
6725 var postList = posts.ToList();
6726 for (var i = postList.Count - 1; i >= 0; i--)
6729 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
6731 postList.RemoveAt(index);
6734 var currentIndex = this.CurrentTab.SelectedIndex;
6735 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
6736 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
6737 if (post == null) post = postList.First();
6738 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6739 this.ListTab.SelectedIndex = tabIndex;
6740 var listView = this.CurrentListView;
6741 SelectListItem(listView, post.Index);
6742 listView.EnsureVisible(post.Index);
6744 catch (InvalidOperationException)
6752 if (replyChains == null || replyChains.Count < 1)
6754 var posts = from t in _statuses.Tabs
6756 where p.Value.InReplyToStatusId == currentPost.StatusId
6757 let indexOf = t.IndexOf(p.Value.StatusId)
6760 orderby t != curTabClass
6761 select new {Tab = t, Index = indexOf};
6764 var post = posts.First();
6765 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6766 this.ListTab.SelectedIndex = tabIndex;
6767 var listView = this.CurrentListView;
6768 SelectListItem(listView, post.Index);
6769 listView.EnsureVisible(post.Index);
6771 catch (InvalidOperationException)
6778 var chainHead = replyChains.Pop();
6779 if (chainHead.InReplyToId == currentPost.StatusId)
6781 var tab = chainHead.OriginalTab;
6782 if (!this._statuses.Tabs.Contains(tab))
6788 var idx = tab.IndexOf(chainHead.OriginalId);
6795 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6798 this.ListTab.SelectedIndex = tabIndex;
6804 var listView = this.CurrentListView;
6805 SelectListItem(listView, idx);
6806 listView.EnsureVisible(idx);
6813 this.GoBackInReplyToPostTree(parallel);
6819 private void GoBackSelectPostChain()
6821 if (this.selectPostChains.Count > 1)
6824 TabModel? foundTab = null;
6830 this.selectPostChains.Pop();
6831 var (tab, post) = this.selectPostChains.Peek();
6833 if (!this._statuses.Tabs.Contains(tab))
6834 continue; // 該当タブが存在しないので無視
6838 idx = tab.IndexOf(post.StatusId);
6839 if (idx == -1) continue; //該当ポストが存在しないので無視
6844 this.selectPostChains.Pop();
6846 catch (InvalidOperationException)
6852 while (this.selectPostChains.Count > 1);
6854 if (foundTab == null)
6857 //履歴が残り1つであればクリアしておく
6858 if (this.selectPostChains.Count == 1)
6859 this.selectPostChains.Clear();
6863 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
6864 var tabPage = this.ListTab.TabPages[tabIndex];
6865 var lst = (DetailsListView)tabPage.Tag;
6866 this.ListTab.SelectedIndex = tabIndex;
6870 SelectListItem(lst, idx);
6871 lst.EnsureVisible(idx);
6877 private void PushSelectPostChain()
6879 var currentTab = this.CurrentTab;
6880 var currentPost = this.CurrentPost;
6882 var count = this.selectPostChains.Count;
6885 var (tab, post) = this.selectPostChains.Peek();
6886 if (tab == currentTab)
6888 if (post == currentPost) return; //最新の履歴と同一
6889 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
6892 if (count >= 2500) TrimPostChain();
6893 this.selectPostChains.Push((currentTab, currentPost));
6896 private void TrimPostChain()
6898 if (this.selectPostChains.Count <= 2000) return;
6899 var p = new Stack<(TabModel, PostClass?)>(2000);
6900 for (var i = 0; i < 2000; i++)
6902 p.Push(this.selectPostChains.Pop());
6904 this.selectPostChains.Clear();
6905 for (var i = 0; i < 2000; i++)
6907 this.selectPostChains.Push(p.Pop());
6911 private bool GoStatus(long statusId)
6913 if (statusId == 0) return false;
6915 var tab = this._statuses.Tabs
6916 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
6917 .Where(x => x.Contains(statusId))
6923 var index = tab.IndexOf(statusId);
6925 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6926 this.ListTab.SelectedIndex = tabIndex;
6928 var listView = this.CurrentListView;
6929 this.SelectListItem(listView, index);
6930 listView.EnsureVisible(index);
6935 private bool GoDirectMessage(long statusId)
6937 if (statusId == 0) return false;
6939 var tab = this._statuses.DirectMessageTab;
6940 var index = tab.IndexOf(statusId);
6945 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6946 this.ListTab.SelectedIndex = tabIndex;
6948 var listView = this.CurrentListView;
6949 this.SelectListItem(listView, index);
6950 listView.EnsureVisible(index);
6955 private void MyList_MouseClick(object sender, MouseEventArgs e)
6956 => this._anchorFlag = false;
6958 private void StatusText_Enter(object sender, EventArgs e)
6960 // フォーカスの戻り先を StatusText に設定
6961 this.Tag = StatusText;
6962 StatusText.BackColor = _clInputBackcolor;
6965 public Color InputBackColor
6967 get => _clInputBackcolor;
6968 set => _clInputBackcolor = value;
6971 private void StatusText_Leave(object sender, EventArgs e)
6973 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
6974 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
6975 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
6978 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
6980 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
6983 e.SuppressKeyPress = true;
6986 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
6988 if (asyncTask != null)
6992 private void SaveConfigsAll(bool ifModified)
6996 SaveConfigsCommon();
7003 if (ModifySettingCommon) SaveConfigsCommon();
7004 if (ModifySettingLocal) SaveConfigsLocal();
7005 if (ModifySettingAtId) SaveConfigsAtId();
7009 private void SaveConfigsAtId()
7011 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7013 ModifySettingAtId = false;
7014 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7015 SettingManager.SaveAtIdList();
7018 private void SaveConfigsCommon()
7020 if (_ignoreConfigSave) return;
7022 ModifySettingCommon = false;
7025 SettingManager.Common.UserName = tw.Username;
7026 SettingManager.Common.UserId = tw.UserId;
7027 SettingManager.Common.Token = tw.AccessToken;
7028 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7029 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7030 SettingManager.Common.SortColumn = this._statuses.SortMode switch
7032 ComparerMode.Nickname => 1, // ニックネーム
7033 ComparerMode.Data => 2, // 本文
7034 ComparerMode.Id => 3, // 時刻=発言Id
7035 ComparerMode.Name => 4, // 名前
7036 ComparerMode.Source => 7, // Source
7037 _ => throw new InvalidOperationException($"Invalid sort mode: {this._statuses.SortMode}"),
7039 SettingManager.Common.HashTags = HashMgr.HashHistories;
7040 if (HashMgr.IsPermanent)
7042 SettingManager.Common.HashSelected = HashMgr.UseHash;
7046 SettingManager.Common.HashSelected = "";
7048 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7049 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7050 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7051 SettingManager.Common.TrackWord = tw.TrackWord;
7052 SettingManager.Common.AllAtReply = tw.AllAtReply;
7053 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7054 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7056 SettingManager.SaveCommon();
7060 private void SaveConfigsLocal()
7062 if (_ignoreConfigSave) return;
7065 ModifySettingLocal = false;
7066 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7067 SettingManager.Local.FormSize = _mySize;
7068 SettingManager.Local.FormLocation = _myLoc;
7069 SettingManager.Local.SplitterDistance = _mySpDis;
7070 SettingManager.Local.PreviewDistance = _mySpDis3;
7071 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7072 SettingManager.Local.StatusTextHeight = _mySpDis2;
7074 SettingManager.Local.FontUnread = _fntUnread;
7075 SettingManager.Local.ColorUnread = _clUnread;
7076 SettingManager.Local.FontRead = _fntReaded;
7077 SettingManager.Local.ColorRead = _clReaded;
7078 SettingManager.Local.FontDetail = _fntDetail;
7079 SettingManager.Local.ColorDetail = _clDetail;
7080 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7081 SettingManager.Local.ColorDetailLink = _clDetailLink;
7082 SettingManager.Local.ColorFav = _clFav;
7083 SettingManager.Local.ColorOWL = _clOWL;
7084 SettingManager.Local.ColorRetweet = _clRetweet;
7085 SettingManager.Local.ColorSelf = _clSelf;
7086 SettingManager.Local.ColorAtSelf = _clAtSelf;
7087 SettingManager.Local.ColorTarget = _clTarget;
7088 SettingManager.Local.ColorAtTarget = _clAtTarget;
7089 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7090 SettingManager.Local.ColorAtTo = _clAtTo;
7091 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7092 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7093 SettingManager.Local.ColorInputFont = _clInputFont;
7094 SettingManager.Local.FontInputFont = _fntInputFont;
7096 if (_ignoreConfigSave) return;
7097 SettingManager.SaveLocal();
7101 private void SaveConfigsTabs()
7103 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7105 var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7107 foreach (var tab in tabs)
7109 if (!tab.IsPermanentTabType)
7112 var tabSetting = new SettingTabs.SettingTabItem
7114 TabName = tab.TabName,
7115 TabType = tab.TabType,
7116 UnreadManage = tab.UnreadManage,
7117 Protected = tab.Protected,
7118 Notify = tab.Notify,
7119 SoundFile = tab.SoundFile,
7124 case FilterTabModel filterTab:
7125 tabSetting.FilterArray = filterTab.FilterArray;
7127 case UserTimelineTabModel userTab:
7128 tabSetting.User = userTab.ScreenName;
7130 case PublicSearchTabModel searchTab:
7131 tabSetting.SearchWords = searchTab.SearchWords;
7132 tabSetting.SearchLang = searchTab.SearchLang;
7134 case ListTimelineTabModel listTab:
7135 tabSetting.ListInfo = listTab.ListInfo;
7139 tabSettingList.Add(tabSetting);
7142 SettingManager.Tabs.Tabs = tabSettingList;
7143 SettingManager.SaveTabs();
7146 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7148 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7149 if (ret != DialogResult.OK)
7152 var match = Twitter.StatusUrlRegex.Match(inputText);
7155 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7156 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7162 var statusId = long.Parse(match.Groups["StatusId"].Value);
7163 await this.OpenRelatedTab(statusId);
7165 catch (TabException ex)
7167 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7171 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7173 var tab = this.CurrentTab;
7175 var rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7176 Properties.Resources.SaveLogMenuItem_ClickText2,
7177 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7178 if (rslt == DialogResult.Cancel) return;
7180 SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7181 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7182 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7183 SaveFileDialog1.FilterIndex = 0;
7184 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7185 SaveFileDialog1.RestoreDirectory = true;
7187 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7189 if (!SaveFileDialog1.ValidateNames) return;
7190 using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
7191 if (rslt == DialogResult.Yes)
7194 for (var idx = 0; idx < tab.AllCount; idx++)
7196 var post = tab[idx];
7199 protect = "Protect";
7200 sw.WriteLine(post.Nickname + "\t" +
7201 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7202 post.CreatedAt.ToLocalTimeString() + "\t" +
7203 post.ScreenName + "\t" +
7204 post.StatusId + "\t" +
7205 post.ImageUrl + "\t" +
7206 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7212 foreach (var post in this.CurrentTab.SelectedPosts)
7216 protect = "Protect";
7217 sw.WriteLine(post.Nickname + "\t" +
7218 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7219 post.CreatedAt.ToLocalTimeString() + "\t" +
7220 post.ScreenName + "\t" +
7221 post.StatusId + "\t" +
7222 post.ImageUrl + "\t" +
7223 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7228 this.TopMost = SettingManager.Common.AlwaysTop;
7231 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
7235 using (var inputName = new InputTabName())
7237 inputName.TabName = origTabName;
7238 inputName.ShowDialog();
7239 if (inputName.DialogResult == DialogResult.Cancel) return false;
7240 newTabName = inputName.TabName;
7242 this.TopMost = SettingManager.Common.AlwaysTop;
7243 if (!string.IsNullOrEmpty(newTabName))
7246 if (this._statuses.ContainsTab(newTabName))
7248 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7249 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7253 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7254 var tabPage = this.ListTab.TabPages[tabIndex];
7257 if (tabPage != null)
7258 tabPage.Text = newTabName;
7260 _statuses.RenameTab(origTabName, newTabName);
7262 SaveConfigsCommon();
7264 _rclickTabName = newTabName;
7273 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7275 if (e.Button == MouseButtons.Middle)
7277 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7279 if (this.ListTab.GetTabRect(index).Contains(e.Location))
7281 this.RemoveSpecifiedTab(tab.TabName, true);
7282 this.SaveConfigsTabs();
7289 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7290 => this.TabRename(this.CurrentTabName, out _);
7292 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7294 if (SettingManager.Common.TabMouseLock) return;
7295 if (e.Button == MouseButtons.Left)
7297 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7299 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7302 _tabMouseDownPoint = e.Location;
7313 private void ListTab_DragEnter(object sender, DragEventArgs e)
7315 if (e.Data.GetDataPresent(typeof(TabPage)))
7316 e.Effect = DragDropEffects.Move;
7318 e.Effect = DragDropEffects.None;
7321 private void ListTab_DragDrop(object sender, DragEventArgs e)
7323 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7328 var cpos = new Point(e.X, e.Y);
7329 var spos = ListTab.PointToClient(cpos);
7330 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7332 var rect = ListTab.GetTabRect(index);
7333 if (rect.Contains(spos))
7336 if (spos.X <= (rect.Left + rect.Right) / 2)
7345 //タブのないところにドロップ->最後尾へ移動
7346 if (string.IsNullOrEmpty(tn))
7348 var lastTab = this._statuses.Tabs.Last();
7349 tn = lastTab.TabName;
7353 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
7354 if (tp.Text == tn) return;
7356 ReOrderTab(tp.Text, tn, bef);
7359 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7361 var baseIndex = this.GetTabPageIndex(baseTabText);
7362 if (baseIndex == -1)
7365 var targetIndex = this.GetTabPageIndex(targetTabText);
7366 if (targetIndex == -1)
7369 using (ControlTransaction.Layout(this.ListTab))
7371 var tab = this._statuses.Tabs[targetIndex];
7372 var tabPage = this.ListTab.TabPages[targetIndex];
7374 this.ListTab.TabPages.Remove(tabPage);
7376 if (targetIndex < baseIndex)
7379 if (!isBeforeBaseTab)
7382 this._statuses.MoveTab(baseIndex, tab);
7384 ListTab.TabPages.Insert(baseIndex, tabPage);
7390 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7392 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7393 //isReply:true=@,false=DM
7394 if (!StatusText.Enabled) return;
7395 if (!this.ExistCurrentPost) return;
7397 var tab = this.CurrentTab;
7398 var selectedPosts = tab.SelectedPosts;
7400 // 複数あてリプライはReplyではなく通常ポスト
7401 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7402 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7403 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7405 if (selectedPosts.Length > 0)
7408 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7410 var post = selectedPosts.Single();
7413 if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7416 this.inReplyTo = null;
7417 StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7418 StatusText.SelectionStart = StatusText.Text.Length;
7422 if (string.IsNullOrEmpty(StatusText.Text))
7425 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7426 var inReplyToScreenName = post.ScreenName;
7427 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7429 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7430 StatusText.Text = "@" + post.ScreenName + " ";
7438 //1件選んでEnter or DoubleClick
7439 if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7441 if (this.inReplyTo?.ScreenName == post.ScreenName)
7444 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7445 var inReplyToScreenName = post.ScreenName;
7446 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7450 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7453 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7456 this.inReplyTo = null;
7457 StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7462 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7463 var inReplyToScreenName = post.ScreenName;
7464 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7465 StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7472 this.inReplyTo = null;
7473 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7478 //1件選んでCtrl-Rの場合(返信先操作せず)
7479 var sidx = StatusText.SelectionStart;
7480 var id = "@" + post.ScreenName + " ";
7483 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7488 StatusText.Text = StatusText.Text.Insert(sidx, id);
7490 StatusText.SelectionStart = sidx;
7499 if (!isAuto && !isReply) return;
7501 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7505 //Enter or DoubleClick
7507 var sTxt = StatusText.Text;
7508 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7511 this.inReplyTo = null;
7513 foreach (var post in selectedPosts)
7515 if (!sTxt.Contains("@" + post.ScreenName + " "))
7516 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7518 StatusText.Text = sTxt;
7524 if (selectedPosts.Length > 1)
7529 var sidx = StatusText.SelectionStart;
7530 foreach (var post in selectedPosts)
7532 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7534 ids += "@" + post.ScreenName + " ";
7538 foreach (var (_, screenName) in post.ReplyToList)
7540 if (!ids.Contains("@" + screenName + " ") &&
7541 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7543 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7545 ids += "@" + m.Result("${id}") + " ";
7547 ids += "@" + screenName + " ";
7552 if (ids.Length == 0) return;
7553 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7555 this.inReplyTo = null;
7556 StatusText.Text = ". " + StatusText.Text;
7561 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7566 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7568 StatusText.SelectionStart = sidx;
7574 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7577 var sidx = StatusText.SelectionStart;
7578 var post = selectedPosts.Single();
7579 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7581 ids += "@" + post.ScreenName + " ";
7583 foreach (var (_, screenName) in post.ReplyToList)
7585 if (!ids.Contains("@" + screenName + " ") &&
7586 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7588 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7590 ids += "@" + m.Result("${id}") + " ";
7592 ids += "@" + screenName + " ";
7595 if (!string.IsNullOrEmpty(post.RetweetedBy))
7597 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7599 ids += "@" + post.RetweetedBy + " ";
7602 if (ids.Length == 0) return;
7603 if (string.IsNullOrEmpty(StatusText.Text))
7606 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7607 var inReplyToScreenName = post.ScreenName;
7608 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7610 StatusText.Text = ids;
7611 StatusText.SelectionStart = ids.Length;
7618 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7623 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7625 StatusText.SelectionStart = sidx;
7631 StatusText.SelectionStart = StatusText.Text.Length;
7636 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7637 => this._tabDrag = false;
7639 private int iconCnt = 0;
7640 private int blinkCnt = 0;
7641 private bool blink = false;
7643 private void RefreshTasktrayIcon()
7645 void EnableTasktrayAnimation()
7646 => this.TimerRefreshIcon.Enabled = true;
7648 void DisableTasktrayAnimation()
7649 => this.TimerRefreshIcon.Enabled = false;
7651 var busyTasks = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7655 if (iconCnt >= this.NIconRefresh.Length)
7658 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7659 _myStatusError = false;
7660 EnableTasktrayAnimation();
7664 var replyIconType = SettingManager.Common.ReplyIconState;
7666 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
7668 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
7669 if (replyTab != null && replyTab.UnreadCount > 0)
7673 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
7682 NotifyIcon1.Icon = blink ? ReplyIconBlink : ReplyIcon;
7683 EnableTasktrayAnimation();
7687 DisableTasktrayAnimation();
7693 // 優先度:リプライ→エラー→オフライン→アイドル
7694 // エラーは更新アイコンでクリアされる
7695 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
7696 NotifyIcon1.Icon = ReplyIcon;
7697 else if (_myStatusError)
7698 NotifyIcon1.Icon = NIconAtRed;
7699 else if (_myStatusOnline)
7700 NotifyIcon1.Icon = NIconAt;
7702 NotifyIcon1.Icon = NIconAtSmoke;
7705 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
7706 => this.RefreshTasktrayIcon(); // 200ms
7708 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7710 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7711 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7712 _rclickTabName = this.CurrentTabName;
7714 if (_statuses == null) return;
7715 if (_statuses.Tabs == null) return;
7717 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7720 NotifyDispMenuItem.Checked = tb.Notify;
7721 this.NotifyTbMenuItem.Checked = tb.Notify;
7723 soundfileListup = true;
7724 SoundFileComboBox.Items.Clear();
7725 this.SoundFileTbComboBox.Items.Clear();
7726 SoundFileComboBox.Items.Add("");
7727 this.SoundFileTbComboBox.Items.Add("");
7728 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7729 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7731 oDir = oDir.GetDirectories("Sounds")[0];
7733 foreach (var oFile in oDir.GetFiles("*.wav"))
7735 SoundFileComboBox.Items.Add(oFile.Name);
7736 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7738 var idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7739 if (idx == -1) idx = 0;
7740 SoundFileComboBox.SelectedIndex = idx;
7741 this.SoundFileTbComboBox.SelectedIndex = idx;
7742 soundfileListup = false;
7743 UreadManageMenuItem.Checked = tb.UnreadManage;
7744 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7746 TabMenuControl(_rclickTabName);
7749 private void TabMenuControl(string tabName)
7751 var tabInfo = _statuses.GetTabByName(tabName)!;
7753 this.FilterEditMenuItem.Enabled = true;
7754 this.EditRuleTbMenuItem.Enabled = true;
7756 if (tabInfo.IsDefaultTabType)
7758 this.ProtectTabMenuItem.Enabled = false;
7759 this.ProtectTbMenuItem.Enabled = false;
7763 this.ProtectTabMenuItem.Enabled = true;
7764 this.ProtectTbMenuItem.Enabled = true;
7767 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7769 this.ProtectTabMenuItem.Checked = true;
7770 this.ProtectTbMenuItem.Checked = true;
7771 this.DeleteTabMenuItem.Enabled = false;
7772 this.DeleteTbMenuItem.Enabled = false;
7776 this.ProtectTabMenuItem.Checked = false;
7777 this.ProtectTbMenuItem.Checked = false;
7778 this.DeleteTabMenuItem.Enabled = true;
7779 this.DeleteTbMenuItem.Enabled = true;
7783 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7785 var checkState = ((ToolStripMenuItem)sender).Checked;
7788 this.ProtectTbMenuItem.Checked = checkState;
7789 this.ProtectTabMenuItem.Checked = checkState;
7792 this.DeleteTabMenuItem.Enabled = !checkState;
7793 this.DeleteTbMenuItem.Enabled = !checkState;
7795 if (string.IsNullOrEmpty(_rclickTabName)) return;
7796 _statuses.Tabs[_rclickTabName].Protected = checkState;
7801 private void UreadManageMenuItem_Click(object sender, EventArgs e)
7803 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7804 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7806 if (string.IsNullOrEmpty(_rclickTabName)) return;
7807 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7812 public void ChangeTabUnreadManage(string tabName, bool isManage)
7814 var idx = this.GetTabPageIndex(tabName);
7818 var tab = this._statuses.Tabs[tabName];
7819 tab.UnreadManage = isManage;
7821 if (SettingManager.Common.TabIconDisp)
7823 var tabPage = this.ListTab.TabPages[idx];
7824 if (tab.UnreadCount > 0)
7825 tabPage.ImageIndex = 0;
7827 tabPage.ImageIndex = -1;
7830 if (this.CurrentTabName == tabName)
7832 this.PurgeListViewItemCache();
7833 this.CurrentListView.Refresh();
7836 SetMainWindowTitle();
7837 SetStatusLabelUrl();
7838 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
7841 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
7843 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7844 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
7846 if (string.IsNullOrEmpty(_rclickTabName)) return;
7848 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
7853 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
7855 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
7857 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
7862 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
7864 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
7865 _rclickTabName = this.CurrentTabName;
7867 RemoveSpecifiedTab(_rclickTabName, true);
7871 private void FilterEditMenuItem_Click(object sender, EventArgs e)
7873 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.HomeTab.TabName;
7875 using (var fltDialog = new FilterDialog())
7877 fltDialog.Owner = this;
7878 fltDialog.SetCurrent(_rclickTabName);
7879 fltDialog.ShowDialog(this);
7881 this.TopMost = SettingManager.Common.AlwaysTop;
7883 this.ApplyPostFilters();
7887 private async void AddTabMenuItem_Click(object sender, EventArgs e)
7889 string? tabName = null;
7890 MyCommon.TabUsageType tabUsage;
7891 using (var inputName = new InputTabName())
7893 inputName.TabName = _statuses.MakeTabName("MyTab");
7894 inputName.IsShowUsage = true;
7895 inputName.ShowDialog();
7896 if (inputName.DialogResult == DialogResult.Cancel) return;
7897 tabName = inputName.TabName;
7898 tabUsage = inputName.Usage;
7900 this.TopMost = SettingManager.Common.AlwaysTop;
7901 if (!string.IsNullOrEmpty(tabName))
7904 ListElement? list = null;
7905 if (tabUsage == MyCommon.TabUsageType.Lists)
7907 using var listAvail = new ListAvailable();
7908 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
7910 if (listAvail.SelectedList == null)
7912 list = listAvail.SelectedList;
7918 case MyCommon.TabUsageType.UserDefined:
7919 tab = new FilterTabModel(tabName);
7921 case MyCommon.TabUsageType.PublicSearch:
7922 tab = new PublicSearchTabModel(tabName);
7924 case MyCommon.TabUsageType.Lists:
7925 tab = new ListTimelineTabModel(tabName, list!);
7931 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
7933 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
7934 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7941 var tabIndex = this._statuses.Tabs.Count - 1;
7943 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
7945 ListTab.SelectedIndex = tabIndex;
7946 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
7948 if (tabUsage == MyCommon.TabUsageType.Lists)
7950 ListTab.SelectedIndex = tabIndex;
7951 await this.RefreshTabAsync(this.CurrentTab);
7957 private void TabMenuItem_Click(object sender, EventArgs e)
7959 using (var fltDialog = new FilterDialog())
7961 fltDialog.Owner = this;
7964 foreach (var post in this.CurrentTab.SelectedPosts)
7967 if (!SelectTab(out var tab)) return;
7969 fltDialog.SetCurrent(tab.TabName);
7971 if (post.RetweetedBy == null)
7973 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
7977 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
7979 fltDialog.ShowDialog(this);
7980 this.TopMost = SettingManager.Common.AlwaysTop;
7984 this.ApplyPostFilters();
7988 protected override bool ProcessDialogKey(Keys keyData)
7990 //TextBox1でEnterを押してもビープ音が鳴らないようにする
7991 if ((keyData & Keys.KeyCode) == Keys.Enter)
7993 if (StatusText.Focused)
7995 var _NewLine = false;
7998 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8000 if (StatusText.Multiline)
8002 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8004 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8008 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8012 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8014 if (StatusText.Multiline)
8016 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8018 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8022 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8028 if (StatusText.Multiline)
8030 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8032 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8033 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8037 if (((keyData & Keys.Shift) == Keys.Shift) ||
8038 (((keyData & Keys.Control) != Keys.Control) &&
8039 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8045 var pos1 = StatusText.SelectionStart;
8046 if (StatusText.SelectionLength > 0)
8048 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8050 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8051 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8056 PostButton_Click(this.PostButton, EventArgs.Empty);
8062 var tab = this.CurrentTab;
8063 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8065 var tabPage = this.CurrentTabPage;
8066 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8067 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8069 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
8076 return base.ProcessDialogKey(keyData);
8079 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8080 => this.MakeReplyOrDirectStatus(false, true, true);
8082 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8084 var tab = this.CurrentTab;
8085 var selectedPosts = tab.SelectedPosts;
8088 if (selectedPosts.Length == 0)
8091 var screenNameArray = selectedPosts
8092 .Select(x => x.RetweetedBy ?? x.ScreenName)
8095 this.AddFilterRuleByScreenName(screenNameArray);
8097 if (screenNameArray.Length != 0)
8099 var atids = new List<string>();
8100 foreach (var screenName in screenNameArray)
8102 atids.Add("@" + screenName);
8104 var cnt = AtIdSupl.ItemCount;
8105 AtIdSupl.AddRangeItem(atids.ToArray());
8106 if (AtIdSupl.ItemCount != cnt)
8107 this.MarkSettingAtIdModified();
8111 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8113 var tab = this.CurrentTab;
8114 var selectedPosts = tab.SelectedPosts;
8116 if (selectedPosts.Length == 0)
8119 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8121 this.AddFilterRuleBySource(sourceArray);
8124 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8127 if (!SelectTab(out var tab)) return;
8131 if (tab.TabType != MyCommon.TabUsageType.Mute)
8133 this.MoveOrCopy(out mv, out mk);
8137 // ミュートタブでは常に MoveMatches を true にする
8142 foreach (var screenName in screenNameArray)
8144 tab.AddFilter(new PostFilterRule
8146 FilterName = screenName,
8147 UseNameField = true,
8151 FilterByUrl = false,
8155 this.ApplyPostFilters();
8159 public void AddFilterRuleBySource(params string[] sourceArray)
8161 // タブ選択ダイアログを表示(or追加)
8162 if (!this.SelectTab(out var filterTab))
8167 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8169 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8170 this.MoveOrCopy(out mv, out mk);
8174 // ミュートタブでは常に MoveMatches を true にする
8179 // 振り分けルールに追加するSource
8180 foreach (var source in sourceArray)
8182 filterTab.AddFilter(new PostFilterRule
8184 FilterSource = source,
8188 FilterByUrl = false,
8192 this.ApplyPostFilters();
8193 this.SaveConfigsTabs();
8196 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
8203 using (var dialog = new TabsDialog(_statuses))
8205 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8207 tab = dialog.SelectedTab;
8210 this.CurrentTabPage.Focus();
8215 using (var inputName = new InputTabName())
8217 inputName.TabName = _statuses.MakeTabName("MyTab");
8218 inputName.ShowDialog();
8219 if (inputName.DialogResult == DialogResult.Cancel) return false;
8220 tabName = inputName.TabName;
8222 this.TopMost = SettingManager.Common.AlwaysTop;
8223 if (!string.IsNullOrEmpty(tabName))
8225 var newTab = new FilterTabModel(tabName);
8226 if (!_statuses.AddTab(newTab) || !AddNewTab(newTab, startup: false))
8228 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8229 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8248 private void MoveOrCopy(out bool move, out bool mark)
8252 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8253 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8261 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8262 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8273 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8276 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8277 => this.CopyIdUri();
8279 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8281 if (StatusText.Focused)
8284 StatusText.SelectAll();
8288 // ListView上でのCtrl+A
8289 NativeMethods.SelectAllItems(this.CurrentListView);
8293 private void MoveMiddle()
8299 var listView = this.CurrentListView;
8300 if (listView.SelectedIndices.Count == 0) return;
8302 var idx = listView.SelectedIndices[0];
8304 _item = listView.GetItemAt(0, 25);
8310 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8312 idx2 = listView.VirtualListSize - 1;
8316 idx -= Math.Abs(idx1 - idx2) / 2;
8317 if (idx < 0) idx = 0;
8319 listView.EnsureVisible(listView.VirtualListSize - 1);
8320 listView.EnsureVisible(idx);
8323 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8325 var linkElements = this.tweetDetailsView.GetLinkElements();
8327 if (linkElements.Length == 0)
8330 var links = new List<OpenUrlItem>(linkElements.Length);
8332 foreach (var linkElm in linkElements)
8334 var displayUrl = linkElm.GetAttribute("title");
8335 var href = linkElm.GetAttribute("href");
8336 var linkedText = linkElm.InnerText;
8338 if (string.IsNullOrEmpty(displayUrl))
8341 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
8345 bool isReverseSettings;
8347 if (links.Count == 1)
8349 // ツイートに含まれる URL が 1 つのみの場合
8350 // => OpenURL ダイアログを表示せずにリンクを開く
8351 selectedUrl = links[0].Href;
8353 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8354 isReverseSettings = false;
8358 // ツイートに含まれる URL が複数ある場合
8359 // => OpenURL を表示しユーザーが選択したリンクを開く
8360 this.UrlDialog.ClearUrl();
8362 foreach (var link in links)
8363 this.UrlDialog.AddUrl(link);
8365 if (this.UrlDialog.ShowDialog(this) != DialogResult.OK)
8368 this.TopMost = SettingManager.Common.AlwaysTop;
8370 selectedUrl = this.UrlDialog.SelectedUrl;
8372 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8373 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
8376 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
8379 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8381 if (string.IsNullOrEmpty(_rclickTabName)) return;
8382 ClearTab(_rclickTabName, true);
8385 private void ClearTab(string tabName, bool showWarning)
8389 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8390 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8396 _statuses.ClearTabIds(tabName);
8397 if (this.CurrentTabName == tabName)
8400 _anchorFlag = false;
8401 this.PurgeListViewItemCache();
8404 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8405 var tabPage = this.ListTab.TabPages[tabIndex];
8406 tabPage.ImageIndex = -1;
8408 var listView = (DetailsListView)tabPage.Tag;
8409 listView.VirtualListSize = 0;
8411 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8413 SetMainWindowTitle();
8414 SetStatusLabelUrl();
8417 private static long followers = 0;
8419 private void SetMainWindowTitle()
8422 var ttl = new StringBuilder(256);
8425 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8426 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8427 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8428 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8430 foreach (var tab in _statuses.Tabs)
8432 ur += tab.UnreadCount;
8437 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8438 ttl.Append(ApplicationSettings.ApplicationName);
8440 switch (SettingManager.Common.DispLatestPost)
8442 case MyCommon.DispTitleEnum.Ver:
8443 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8445 case MyCommon.DispTitleEnum.Post:
8446 if (_history != null && _history.Count > 1)
8447 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8449 case MyCommon.DispTitleEnum.UnreadRepCount:
8450 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8452 case MyCommon.DispTitleEnum.UnreadAllCount:
8453 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8455 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8456 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8458 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8459 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8461 case MyCommon.DispTitleEnum.OwnStatus:
8462 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8463 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8469 this.Text = ttl.ToString();
8471 catch (AccessViolationException)
8473 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8477 private string GetStatusLabelText()
8480 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8481 if (_statuses == null) return "";
8482 var tbRep = _statuses.MentionTab;
8483 var tbDm = _statuses.DirectMessageTab;
8484 if (tbRep == null || tbDm == null) return "";
8485 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
8490 var slbl = new StringBuilder(256);
8493 foreach (var tab in _statuses.Tabs)
8495 ur += tab.UnreadCount;
8497 if (tab.TabName == this.CurrentTabName)
8499 tur = tab.UnreadCount;
8510 UnreadAtCounter = urat;
8512 var homeTab = this._statuses.HomeTab;
8514 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8515 if (SettingManager.Common.TimelinePeriod == 0)
8517 slbl.Append(Properties.Resources.SetStatusLabelText2);
8521 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8523 return slbl.ToString();
8526 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8530 if (this.InvokeRequired && !this.IsDisposed)
8532 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8536 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
8537 SetApiStatusLabel(endpointName);
8540 catch (ObjectDisposedException)
8544 catch (InvalidOperationException)
8550 private void SetApiStatusLabel(string? endpointName = null)
8552 var tabType = this.CurrentTab.TabType;
8554 if (endpointName == null)
8557 endpointName = tabType switch
8559 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
8560 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
8561 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
8562 MyCommon.TabUsageType.Favorites => "/favorites/list",
8563 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
8564 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
8565 MyCommon.TabUsageType.Lists => "/lists/statuses",
8566 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
8567 MyCommon.TabUsageType.Related => "/statuses/show/:id",
8570 this.toolStripApiGauge.ApiEndpoint = endpointName;
8574 // 表示中のタブに関連する endpoint であれば更新
8575 var update = endpointName switch
8577 "/statuses/home_timeline" => tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined,
8578 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
8579 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
8580 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
8581 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
8582 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
8583 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
8584 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
8589 this.toolStripApiGauge.ApiEndpoint = endpointName;
8594 private void SetStatusLabelUrl()
8595 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8597 public void SetStatusLabel(string text)
8598 => this.StatusLabel.Text = text;
8600 private void SetNotifyIconText()
8602 var ur = new StringBuilder(64);
8604 // タスクトレイアイコンのツールチップテキスト書き換え
8606 ur.Remove(0, ur.Length);
8607 if (SettingManager.Common.DispUsername)
8609 ur.Append(tw.Username);
8612 ur.Append(ApplicationSettings.ApplicationName);
8614 ur.Append("(Debug Build)");
8616 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8619 ur.Append(UnreadCounter);
8621 ur.Append(UnreadAtCounter);
8624 NotifyIcon1.Text = ur.ToString();
8627 internal void CheckReplyTo(string StatusText)
8631 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8633 foreach (Match hm in m)
8635 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8637 hstr += "#" + hm.Result("$3") + " ";
8638 HashSupl.AddItem("#" + hm.Result("$3"));
8641 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8643 hstr += HashMgr.UseHash;
8645 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8647 // 本当にリプライ先指定すべきかどうかの判定
8648 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8650 if (SettingManager.Common.UseAtIdSupplement)
8652 var bCnt = AtIdSupl.ItemCount;
8653 foreach (Match mid in m)
8655 AtIdSupl.AddItem(mid.Result("${id}"));
8657 if (bCnt != AtIdSupl.ItemCount)
8658 this.MarkSettingAtIdModified();
8661 // リプライ先ステータスIDの指定がない場合は指定しない
8662 if (this.inReplyTo == null)
8666 // 次の条件を満たす場合に in_reply_to_status_id 指定
8667 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8668 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8669 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8673 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8674 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8676 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8680 foreach (Match mid in m)
8682 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8687 this.inReplyTo = null;
8690 private void TweenMain_Resize(object sender, EventArgs e)
8692 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8694 this.Visible = false;
8696 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8698 // 現在の DPI と設定保存時の DPI との比を取得する
8699 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8701 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8704 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8705 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8706 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8708 this.SplitContainer1.SplitterDistance = splitterDistance;
8712 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8713 if (StatusText.Multiline)
8715 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8716 var dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8717 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8719 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8721 StatusText.Height = statusTextHeight;
8725 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8727 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8731 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8732 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8734 this.SplitContainer3.SplitterDistance = previewDistance;
8737 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8738 this.SplitContainer3.Panel2Collapsed = true;
8740 _initialLayout = false;
8742 if (this.WindowState != FormWindowState.Minimized)
8744 _formWindowState = this.WindowState;
8748 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8750 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8751 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8752 if (PlaySoundMenuItem.Checked)
8754 SettingManager.Common.PlaySound = true;
8758 SettingManager.Common.PlaySound = false;
8760 this.MarkSettingCommonModified();
8763 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
8765 if (this._initialLayout)
8768 int splitterDistance;
8769 switch (this.WindowState)
8771 case FormWindowState.Normal:
8772 splitterDistance = this.SplitContainer1.SplitterDistance;
8774 case FormWindowState.Maximized:
8775 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8776 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
8777 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
8778 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
8784 this._mySpDis = splitterDistance;
8785 this.MarkSettingLocalModified();
8788 private async Task doRepliedStatusOpen()
8790 var currentPost = this.CurrentPost;
8791 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
8793 if (MyCommon.IsKeyDown(Keys.Shift))
8795 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
8798 if (this._statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
8800 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
8804 foreach (var tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
8806 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
8807 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
8808 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
8811 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
8816 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
8817 => await this.doRepliedStatusOpen();
8819 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
8821 if (this._initialLayout)
8822 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
8824 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
8825 if (multiline != this.StatusText.Multiline)
8827 this.StatusText.Multiline = multiline;
8828 SettingManager.Local.StatusMultiline = multiline;
8829 this.MarkSettingLocalModified();
8833 private void StatusText_MultilineChanged(object sender, EventArgs e)
8835 if (this.StatusText.Multiline)
8836 this.StatusText.ScrollBars = ScrollBars.Vertical;
8838 this.StatusText.ScrollBars = ScrollBars.None;
8840 if (!this._initialLayout)
8841 this.MarkSettingLocalModified();
8844 private void MultiLineMenuItem_Click(object sender, EventArgs e)
8847 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
8848 StatusText.Multiline = menuItemChecked;
8849 SettingManager.Local.StatusMultiline = menuItemChecked;
8850 if (menuItemChecked)
8852 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
8853 SplitContainer2.SplitterDistance = 0;
8855 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
8859 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8861 this.MarkSettingLocalModified();
8864 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
8866 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
8868 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
8869 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
8870 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
8872 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
8877 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
8878 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
8879 //Appendix A. Collected ABNF for URI
8880 //http://www.ietf.org/rfc/rfc3986.txt
8882 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
8885 if (StatusText.SelectionLength > 0)
8887 var tmp = StatusText.SelectedText;
8888 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
8889 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
8891 // 文字列が選択されている場合はその文字列について処理
8893 //nico.ms使用、nicovideoにマッチしたら変換
8894 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
8896 result = nicoms.Shorten(tmp);
8898 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
8903 var srcUri = new Uri(tmp);
8904 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
8905 result = resultUri.AbsoluteUri;
8907 catch (WebApiException e)
8909 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
8912 catch (UriFormatException e)
8914 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
8923 if (!string.IsNullOrEmpty(result))
8925 var undotmp = new urlUndo();
8927 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
8928 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
8929 if (origUrlIndex == -1)
8932 StatusText.Select(origUrlIndex, tmp.Length);
8933 StatusText.SelectedText = result;
8936 undotmp.Before = tmp;
8937 undotmp.After = result;
8939 if (urlUndoBuffer == null)
8941 urlUndoBuffer = new List<urlUndo>();
8942 UrlUndoToolStripMenuItem.Enabled = true;
8945 urlUndoBuffer.Add(undotmp);
8951 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
8952 @"(?<url>(?<protocol>https?://)" +
8953 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
8954 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
8955 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
8956 // 正規表現にマッチしたURL文字列をtinyurl化
8957 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
8959 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
8961 var tmp = mt.Result("${url}");
8962 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
8963 tmp = "http://" + tmp;
8964 var undotmp = new urlUndo();
8967 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
8969 //nico.ms使用、nicovideoにマッチしたら変換
8970 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
8972 result = nicoms.Shorten(tmp);
8974 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
8979 var srcUri = new Uri(tmp);
8980 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
8981 result = resultUri.AbsoluteUri;
8983 catch (HttpRequestException e)
8985 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
8986 // のように長いので「:」が含まれていればそれ以降のみを抽出する
8987 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
8989 this.StatusLabel.Text = Converter_Type + ":" + message;
8992 catch (WebApiException e)
8994 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
8997 catch (UriFormatException e)
8999 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9008 if (!string.IsNullOrEmpty(result))
9010 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9011 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9012 if (origUrlIndex == -1)
9015 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9016 StatusText.SelectedText = result;
9018 undotmp.Before = mt.Result("${url}");
9019 undotmp.After = result;
9021 if (urlUndoBuffer == null)
9023 urlUndoBuffer = new List<urlUndo>();
9024 UrlUndoToolStripMenuItem.Enabled = true;
9027 urlUndoBuffer.Add(undotmp);
9035 private void doUrlUndo()
9037 if (urlUndoBuffer != null)
9039 var tmp = StatusText.Text;
9040 foreach (var data in urlUndoBuffer)
9042 tmp = tmp.Replace(data.After, data.Before);
9044 StatusText.Text = tmp;
9045 urlUndoBuffer = null;
9046 UrlUndoToolStripMenuItem.Enabled = false;
9047 StatusText.SelectionStart = 0;
9048 StatusText.SelectionLength = 0;
9052 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9053 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9055 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9056 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9058 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9059 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9061 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9063 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9065 var rnd = new Random();
9067 MyCommon.UrlConverter svc;
9068 // 前回使用した短縮URLサービス以外を選択する
9071 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9073 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9074 await UrlConvertAsync(svc);
9078 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9079 => this.doUrlUndo();
9081 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9083 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9084 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9085 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9086 this.MarkSettingCommonModified();
9089 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9091 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9092 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9093 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9094 this.MarkSettingCommonModified();
9097 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9099 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9100 MenuStrip1.Tag = new object();
9101 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9104 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9106 var currentTabPage = this.CurrentTabPage;
9107 if (this.Tag != null) // 設定された戻り先へ遷移
9109 if (this.Tag == currentTabPage)
9110 ((Control)currentTabPage.Tag).Select();
9112 ((Control)this.Tag).Select();
9114 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9116 this.Tag = currentTabPage.Tag;
9117 ((Control)this.Tag).Select();
9119 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9120 MenuStrip1.Tag = null;
9123 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9125 var lst = (DetailsListView)sender;
9126 if (SettingManager.Local == null) return;
9130 SettingManager.Local.Width1 = lst.Columns[0].Width;
9131 SettingManager.Local.Width3 = lst.Columns[1].Width;
9135 var darr = new int[lst.Columns.Count];
9136 for (var i = 0; i < lst.Columns.Count; i++)
9138 darr[lst.Columns[i].DisplayIndex] = i;
9140 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9142 for (var i = 0; i < lst.Columns.Count; i++)
9147 SettingManager.Local.DisplayIndex1 = i;
9150 SettingManager.Local.DisplayIndex2 = i;
9153 SettingManager.Local.DisplayIndex3 = i;
9156 SettingManager.Local.DisplayIndex4 = i;
9159 SettingManager.Local.DisplayIndex5 = i;
9162 SettingManager.Local.DisplayIndex6 = i;
9165 SettingManager.Local.DisplayIndex7 = i;
9168 SettingManager.Local.DisplayIndex8 = i;
9172 SettingManager.Local.Width1 = lst.Columns[0].Width;
9173 SettingManager.Local.Width2 = lst.Columns[1].Width;
9174 SettingManager.Local.Width3 = lst.Columns[2].Width;
9175 SettingManager.Local.Width4 = lst.Columns[3].Width;
9176 SettingManager.Local.Width5 = lst.Columns[4].Width;
9177 SettingManager.Local.Width6 = lst.Columns[5].Width;
9178 SettingManager.Local.Width7 = lst.Columns[6].Width;
9179 SettingManager.Local.Width8 = lst.Columns[7].Width;
9181 this.MarkSettingLocalModified();
9182 _isColumnChanged = true;
9185 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9187 var lst = (DetailsListView)sender;
9188 if (SettingManager.Local == null) return;
9190 var modified = false;
9193 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9195 SettingManager.Local.Width1 = lst.Columns[0].Width;
9198 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9200 SettingManager.Local.Width3 = lst.Columns[1].Width;
9206 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9208 SettingManager.Local.Width1 = lst.Columns[0].Width;
9211 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9213 SettingManager.Local.Width2 = lst.Columns[1].Width;
9216 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9218 SettingManager.Local.Width3 = lst.Columns[2].Width;
9221 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9223 SettingManager.Local.Width4 = lst.Columns[3].Width;
9226 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9228 SettingManager.Local.Width5 = lst.Columns[4].Width;
9231 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9233 SettingManager.Local.Width6 = lst.Columns[5].Width;
9236 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9238 SettingManager.Local.Width7 = lst.Columns[6].Width;
9241 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9243 SettingManager.Local.Width8 = lst.Columns[7].Width;
9249 this.MarkSettingLocalModified();
9250 this._isColumnChanged = true;
9254 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9256 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9257 this.MarkSettingLocalModified();
9260 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9262 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9264 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9266 SelectMedia_DragDrop(e);
9269 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9271 var (url, title) = GetUrlFromDataObject(e.Data);
9277 appendText = title + " " + url;
9279 if (this.StatusText.TextLength == 0)
9280 this.StatusText.Text = appendText;
9282 this.StatusText.Text += " " + appendText;
9284 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9286 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9288 this.StatusText.Text += text;
9290 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9292 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9293 if (data != null) StatusText.Text += data;
9298 /// IDataObject から URL とタイトルの対を取得します
9301 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9303 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9304 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9305 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
9307 if (data.GetDataPresent("text/x-moz-url"))
9309 // Firefox, Google Chrome で利用可能
9310 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9312 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
9313 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9314 if (lines.Length < 2)
9315 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9317 return (lines[0], lines[1]);
9319 else if (data.GetDataPresent("IESiteModeToUrl"))
9321 // Internet Exproler 用
9322 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9324 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
9325 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9326 if (lines.Length < 2)
9327 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9329 return (lines[0], lines[1]);
9331 else if (data.GetDataPresent("UniformResourceLocatorW"))
9335 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
9336 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9340 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9343 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9345 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9347 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9349 SelectMedia_DragEnter(e);
9353 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9355 e.Effect = DragDropEffects.Copy;
9358 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9360 e.Effect = DragDropEffects.Copy;
9363 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9365 e.Effect = DragDropEffects.Copy;
9369 e.Effect = DragDropEffects.None;
9372 private void TweenMain_DragOver(object sender, DragEventArgs e)
9376 public bool IsNetworkAvailable()
9378 var nw = MyCommon.IsNetworkAvailable();
9379 _myStatusOnline = nw;
9383 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9385 var uriStr = uri.AbsoluteUri;
9387 // OpenTween 内部で使用する URL
9388 if (uri.Authority == "opentween")
9390 await this.OpenInternalUriAsync(uri);
9394 // ハッシュタグを含む Twitter 検索
9395 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9398 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9399 var pos = unescapedQuery.IndexOf('#');
9400 if (pos == -1) return;
9402 var hash = unescapedQuery.Substring(pos);
9403 this.HashSupl.AddItem(hash);
9404 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9405 this.AddNewTabForSearch(hash);
9410 // フラグが立っている場合は設定と逆の動作をする
9411 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9412 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9414 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9415 if (userUriMatch.Success)
9417 var screenName = userUriMatch.Groups["ScreenName"].Value;
9418 if (this.IsTwitterId(screenName))
9420 await this.AddNewTabForUserTimeline(screenName);
9427 await this.OpenUriInBrowserAsync(uriStr);
9431 /// OpenTween 内部の機能を呼び出すための URL を開きます
9433 private async Task OpenInternalUriAsync(Uri uri)
9435 // ツイートを開く (//opentween/status/:status_id)
9436 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9439 var statusId = long.Parse(match.Groups[1].Value);
9440 await this.OpenRelatedTab(statusId);
9445 public Task OpenUriInBrowserAsync(string UriString)
9447 return Task.Run(() =>
9449 var myPath = UriString;
9453 var configBrowserPath = SettingManager.Local.BrowserPath;
9454 if (!string.IsNullOrEmpty(configBrowserPath))
9456 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9458 var sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9459 var browserPath = configBrowserPath.Substring(1, sep - 1);
9461 if (sep < configBrowserPath.Length - 1)
9463 arg = configBrowserPath.Substring(sep + 1);
9465 myPath = arg + " " + myPath;
9466 System.Diagnostics.Process.Start(browserPath, myPath);
9470 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9475 System.Diagnostics.Process.Start(myPath);
9484 private void ListTabSelect(TabPage _tab)
9488 this.PurgeListViewItemCache();
9490 this._statuses.SelectTab(_tab.Text);
9492 var listView = this.CurrentListView;
9495 _anchorFlag = false;
9499 listView.Columns[1].Text = ColumnText[2];
9503 for (var i = 0; i < listView.Columns.Count; i++)
9505 listView.Columns[i].Text = ColumnText[i];
9510 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9511 => this.ListTabSelect(e.TabPage);
9513 private void SelectListItem(DetailsListView LView, int Index)
9516 var bnd = new Rectangle();
9518 var item = LView.FocusedItem;
9527 LView.SelectedIndices.Clear();
9529 while (LView.SelectedIndices.Count > 0);
9530 item = LView.Items[Index];
9531 item.Selected = true;
9532 item.Focused = true;
9534 if (flg) LView.Invalidate(bnd);
9537 private void SelectListItem(DetailsListView LView , int[]? Index, int focusedIndex, int selectionMarkIndex)
9540 var bnd = new Rectangle();
9542 var item = LView.FocusedItem;
9553 LView.SelectedIndices.Clear();
9555 while (LView.SelectedIndices.Count > 0);
9556 LView.SelectItems(Index);
9558 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9560 LView.SelectionMark = selectionMarkIndex;
9562 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9564 LView.Items[focusedIndex].Focused = true;
9566 else if (Index != null && Index.Length != 0)
9568 LView.Items[Index.Last()].Focused = true;
9571 if (flg) LView.Invalidate(bnd);
9574 private void StartUserStream()
9576 tw.NewPostFromStream += tw_NewPostFromStream;
9577 tw.UserStreamStarted += tw_UserStreamStarted;
9578 tw.UserStreamStopped += tw_UserStreamStopped;
9579 tw.PostDeleted += tw_PostDeleted;
9580 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9582 this.RefreshUserStreamsMenu();
9584 if (SettingManager.Common.UserstreamStartup)
9585 tw.StartUserStream();
9588 private async void TweenMain_Shown(object sender, EventArgs e)
9590 NotifyIcon1.Visible = true;
9592 if (this.IsNetworkAvailable())
9596 var loadTasks = new List<Task>
9598 this.RefreshMuteUserIdsAsync(),
9599 this.RefreshBlockIdsAsync(),
9600 this.RefreshNoRetweetIdsAsync(),
9601 this.RefreshTwitterConfigurationAsync(),
9602 this.RefreshTabAsync<HomeTabModel>(),
9603 this.RefreshTabAsync<MentionsTabModel>(),
9604 this.RefreshTabAsync<DirectMessagesTabModel>(),
9605 this.RefreshTabAsync<PublicSearchTabModel>(),
9606 this.RefreshTabAsync<UserTimelineTabModel>(),
9607 this.RefreshTabAsync<ListTimelineTabModel>(),
9610 if (SettingManager.Common.StartupFollowers)
9611 loadTasks.Add(this.RefreshFollowerIdsAsync());
9613 if (SettingManager.Common.GetFav)
9614 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9616 var allTasks = Task.WhenAll(loadTasks);
9621 var timeout = Task.Delay(5000);
9622 if (await Task.WhenAny(allTasks, timeout) != timeout)
9626 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9628 if (MyCommon._endingFlag)
9632 if (MyCommon._endingFlag) return;
9634 if (ApplicationSettings.VersionInfoUrl != null)
9636 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9637 if (SettingManager.Common.StartupVersion)
9638 await this.CheckNewVersion(true);
9642 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9643 this.VerUpMenuItem.Enabled = false;
9644 this.VerUpMenuItem.Available = false;
9645 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9648 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9649 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9651 MessageBox.Show(Properties.Resources.ReAuthorizeText);
9652 SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
9656 var reloadTasks = new List<Task>();
9658 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9659 reloadTasks.Add(this.RefreshFollowerIdsAsync());
9661 if (!tw.GetNoRetweetSuccess)
9662 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9664 if (this.tw.Configuration.PhotoSizeLimit == 0)
9665 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9667 await Task.WhenAll(reloadTasks);
9672 this.timelineScheduler.Enabled = true;
9675 private async Task doGetFollowersMenu()
9677 await this.RefreshFollowerIdsAsync();
9678 this.DispSelectedPost(true);
9681 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9682 => await this.doGetFollowersMenu();
9684 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9685 => this.doReTweetUnofficial();
9687 private async Task doReTweetOfficial(bool isConfirm)
9690 if (this.ExistCurrentPost)
9692 var selectedPosts = this.CurrentTab.SelectedPosts;
9694 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9696 if (selectedPosts.Any(x => x.IsProtect))
9697 MessageBox.Show("Protected.");
9699 _DoFavRetweetFlags = false;
9703 if (selectedPosts.Length > 15)
9705 MessageBox.Show(Properties.Resources.RetweetLimitText);
9706 _DoFavRetweetFlags = false;
9709 else if (selectedPosts.Length > 1)
9711 var QuestionText = Properties.Resources.RetweetQuestion2;
9712 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9713 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9715 case DialogResult.Cancel:
9716 case DialogResult.No:
9717 _DoFavRetweetFlags = false;
9723 if (!SettingManager.Common.RetweetNoConfirm)
9725 var Questiontext = Properties.Resources.RetweetQuestion1;
9726 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9727 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9729 _DoFavRetweetFlags = false;
9735 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9737 await this.RetweetAsync(statusIds);
9741 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9742 => await this.doReTweetOfficial(true);
9744 private async Task FavoritesRetweetOfficial()
9746 if (!this.ExistCurrentPost) return;
9747 _DoFavRetweetFlags = true;
9748 var retweetTask = this.doReTweetOfficial(true);
9749 if (_DoFavRetweetFlags)
9751 _DoFavRetweetFlags = false;
9752 var favoriteTask = this.FavoriteChange(true, false);
9754 await Task.WhenAll(retweetTask, favoriteTask);
9762 private async Task FavoritesRetweetUnofficial()
9764 var post = this.CurrentPost;
9765 if (this.ExistCurrentPost && post != null && !post.IsDm)
9767 _DoFavRetweetFlags = true;
9768 var favoriteTask = this.FavoriteChange(true);
9769 if (!post.IsProtect && _DoFavRetweetFlags)
9771 _DoFavRetweetFlags = false;
9772 doReTweetUnofficial();
9780 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
9782 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
9783 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
9784 /// <returns>復元されたツイート本文</returns>
9785 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
9787 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
9790 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
9792 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
9794 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
9796 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
9800 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
9802 statusHtml = statusHtml.Replace("<br>", " ");
9804 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
9805 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
9806 statusHtml = statusHtml.Replace(" ", " ");
9808 return WebUtility.HtmlDecode(statusHtml);
9811 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
9813 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
9815 if (this.CurrentPost != null)
9816 this.DispSelectedPost(true);
9819 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
9821 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
9822 DebugModeToolStripMenuItem.Visible = true;
9824 DebugModeToolStripMenuItem.Visible = false;
9827 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
9828 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
9830 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
9831 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
9833 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
9834 => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
9836 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
9838 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
9839 this.MarkSettingCommonModified();
9842 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
9844 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
9845 this.MarkSettingCommonModified();
9848 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
9850 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
9851 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
9852 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
9853 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
9854 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
9855 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
9858 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
9860 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
9861 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
9862 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
9863 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
9864 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
9865 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
9868 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
9870 if (TraceOutToolStripMenuItem.Checked)
9871 MyCommon.TraceFlag = true;
9873 MyCommon.TraceFlag = false;
9876 private void TweenMain_Deactivate(object sender, EventArgs e)
9877 => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
9879 private void TabRenameMenuItem_Click(object sender, EventArgs e)
9881 if (string.IsNullOrEmpty(_rclickTabName)) return;
9883 _ = TabRename(_rclickTabName, out _);
9886 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
9887 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
9889 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
9890 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
9892 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
9894 TwitterApiStatus? apiStatus;
9896 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
9898 var cancellationToken = dialog.EnableCancellation();
9902 var task = this.tw.GetInfoApi();
9903 apiStatus = await dialog.WaitForAsync(this, task);
9905 catch (WebApiException)
9910 if (cancellationToken.IsCancellationRequested)
9913 if (apiStatus == null)
9915 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
9920 using var apiDlg = new ApiInfoDialog();
9921 apiDlg.ShowDialog(this);
9924 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
9926 var id = this.CurrentPost?.ScreenName ?? "";
9928 await this.FollowCommand(id);
9931 internal async Task FollowCommand(string id)
9933 using (var inputName = new InputTabName())
9935 inputName.FormTitle = "Follow";
9936 inputName.FormDescription = Properties.Resources.FRMessage1;
9937 inputName.TabName = id;
9939 if (inputName.ShowDialog(this) != DialogResult.OK)
9941 if (string.IsNullOrWhiteSpace(inputName.TabName))
9944 id = inputName.TabName.Trim();
9947 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
9951 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
9952 await dialog.WaitForAsync(this, task);
9954 catch (WebApiException ex)
9956 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
9961 MessageBox.Show(Properties.Resources.FRMessage3);
9964 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
9966 var id = this.CurrentPost?.ScreenName ?? "";
9968 await this.RemoveCommand(id, false);
9971 internal async Task RemoveCommand(string id, bool skipInput)
9975 using var inputName = new InputTabName();
9976 inputName.FormTitle = "Unfollow";
9977 inputName.FormDescription = Properties.Resources.FRMessage1;
9978 inputName.TabName = id;
9980 if (inputName.ShowDialog(this) != DialogResult.OK)
9982 if (string.IsNullOrWhiteSpace(inputName.TabName))
9985 id = inputName.TabName.Trim();
9988 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
9992 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
9993 await dialog.WaitForAsync(this, task);
9995 catch (WebApiException ex)
9997 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10002 MessageBox.Show(Properties.Resources.FRMessage3);
10005 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10007 var id = this.CurrentPost?.ScreenName ?? "";
10009 await this.ShowFriendship(id);
10012 internal async Task ShowFriendship(string id)
10014 using (var inputName = new InputTabName())
10016 inputName.FormTitle = "Show Friendships";
10017 inputName.FormDescription = Properties.Resources.FRMessage1;
10018 inputName.TabName = id;
10020 if (inputName.ShowDialog(this) != DialogResult.OK)
10022 if (string.IsNullOrWhiteSpace(inputName.TabName))
10025 id = inputName.TabName.Trim();
10028 bool isFollowing, isFollowed;
10030 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10032 var cancellationToken = dialog.EnableCancellation();
10036 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10037 var friendship = await dialog.WaitForAsync(this, task);
10039 isFollowing = friendship.Relationship.Source.Following;
10040 isFollowed = friendship.Relationship.Source.FollowedBy;
10042 catch (WebApiException ex)
10044 if (!cancellationToken.IsCancellationRequested)
10045 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10049 if (cancellationToken.IsCancellationRequested)
10056 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10060 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10064 result += Properties.Resources.GetFriendshipInfo3;
10068 result += Properties.Resources.GetFriendshipInfo4;
10070 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10071 MessageBox.Show(result);
10074 internal async Task ShowFriendship(string[] ids)
10076 foreach (var id in ids)
10078 bool isFollowing, isFollowed;
10080 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10082 var cancellationToken = dialog.EnableCancellation();
10086 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10087 var friendship = await dialog.WaitForAsync(this, task);
10089 isFollowing = friendship.Relationship.Source.Following;
10090 isFollowed = friendship.Relationship.Source.FollowedBy;
10092 catch (WebApiException ex)
10094 if (!cancellationToken.IsCancellationRequested)
10095 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10099 if (cancellationToken.IsCancellationRequested)
10109 ff += Properties.Resources.GetFriendshipInfo1;
10113 ff += Properties.Resources.GetFriendshipInfo2;
10116 ff += System.Environment.NewLine + " ";
10119 ff += Properties.Resources.GetFriendshipInfo3;
10123 ff += Properties.Resources.GetFriendshipInfo4;
10125 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10128 if (MessageBox.Show(
10129 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10130 MessageBoxButtons.YesNo,
10131 MessageBoxIcon.Question,
10132 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10134 await this.RemoveCommand(id, true);
10139 MessageBox.Show(result);
10144 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10145 => await this.doShowUserStatus(tw.Username, false);
10147 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10148 // URLから切り出した文字列を渡す
10150 public bool IsTwitterId(string name)
10152 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10153 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10155 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10158 private void doQuoteOfficial()
10160 var post = this.CurrentPost;
10161 if (this.ExistCurrentPost && post != null)
10163 if (post.IsDm || !StatusText.Enabled)
10166 if (post.IsProtect)
10168 MessageBox.Show("Protected.");
10172 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10174 this.inReplyTo = null;
10176 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10178 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10179 StatusText.Focus();
10183 private void doReTweetUnofficial()
10186 var post = this.CurrentPost;
10187 if (this.ExistCurrentPost && post != null)
10189 if (post.IsDm || !StatusText.Enabled)
10192 if (post.IsProtect)
10194 MessageBox.Show("Protected.");
10197 var rtdata = post.Text;
10198 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10200 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10202 // 投稿時に in_reply_to_status_id を付加する
10203 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10204 var inReplyToScreenName = post.ScreenName;
10205 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10207 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10209 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10210 StatusText.Focus();
10214 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10215 => this.doQuoteOfficial();
10217 private async void SearchButton_Click(object sender, EventArgs e)
10220 var pnl = ((Control)sender).Parent;
10221 if (pnl == null) return;
10222 var tbName = pnl.Parent.Text;
10223 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10224 var cmb = (ComboBox)pnl.Controls["comboSearch"];
10225 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
10226 cmb.Text = cmb.Text.Trim();
10227 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10229 var buf = new StringBuilder();
10230 var c = cmb.Text.ToCharArray();
10231 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
10233 if (cnt > cmb.Text.Length - 4)
10235 buf.Append(cmb.Text.Substring(cnt));
10244 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10246 buf.Append(" OR ");
10251 buf.Append(c[cnt]);
10253 cmb.Text = buf.ToString();
10255 var listView = (DetailsListView)pnl.Parent.Tag;
10257 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10259 tb.SearchWords = cmb.Text;
10260 tb.SearchLang = cmbLang.Text;
10261 if (string.IsNullOrEmpty(cmb.Text))
10269 var idx = cmb.Items.IndexOf(tb.SearchWords);
10270 if (idx > -1) cmb.Items.RemoveAt(idx);
10271 cmb.Items.Insert(0, tb.SearchWords);
10272 cmb.Text = tb.SearchWords;
10274 this.PurgeListViewItemCache();
10275 listView.VirtualListSize = 0;
10276 _statuses.ClearTabIds(tbName);
10277 SaveConfigsTabs(); //検索条件の保存
10281 await this.RefreshTabAsync(tb);
10284 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10285 => await this.DoRefreshMore(); // もっと前を取得
10288 /// 指定されたタブのListTabにおける位置を返します
10291 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10293 public int GetTabPageIndex(string tabName)
10294 => this._statuses.Tabs.IndexOf(tabName);
10296 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10298 if (_statuses.RemovedTab.Count == 0)
10300 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10305 DetailsListView? listView;
10307 var tb = _statuses.RemovedTab.Pop();
10308 if (tb.TabType == MyCommon.TabUsageType.Related)
10310 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10311 if (relatedTab != null)
10313 // 関連発言なら既存のタブを置き換える
10314 tb.TabName = relatedTab.TabName;
10315 this.ClearTab(tb.TabName, false);
10317 this._statuses.ReplaceTab(tb);
10319 var tabIndex = this._statuses.Tabs.IndexOf(tb);
10320 var tabPage = this.ListTab.TabPages[tabIndex];
10321 listView = (DetailsListView)tabPage.Tag;
10322 this.ListTab.SelectedIndex = tabIndex;
10326 const string TabName = "Related Tweets";
10327 var renamed = TabName;
10328 for (var i = 2; i <= 100; i++)
10330 if (!_statuses.ContainsTab(renamed))
10332 renamed = TabName + i;
10334 tb.TabName = renamed;
10336 _statuses.AddTab(tb);
10337 AddNewTab(tb, startup: false);
10339 var tabIndex = this._statuses.Tabs.Count - 1;
10340 var tabPage = this.ListTab.TabPages[tabIndex];
10342 listView = (DetailsListView)tabPage.Tag;
10343 this.ListTab.SelectedIndex = tabIndex;
10348 var renamed = tb.TabName;
10349 for (var i = 1; i < int.MaxValue; i++)
10351 if (!_statuses.ContainsTab(renamed))
10353 renamed = tb.TabName + "(" + i + ")";
10355 tb.TabName = renamed;
10357 _statuses.AddTab(tb);
10358 AddNewTab(tb, startup: false);
10360 var tabIndex = this._statuses.Tabs.Count - 1;
10361 var tabPage = this.ListTab.TabPages[tabIndex];
10363 listView = (DetailsListView)tabPage.Tag;
10364 this.ListTab.SelectedIndex = tabIndex;
10368 if (listView != null)
10370 using (ControlTransaction.Update(listView))
10372 listView.VirtualListSize = tb.AllCount;
10378 private async Task doMoveToRTHome()
10380 var post = this.CurrentPost;
10381 if (post != null && post.RetweetedId != null)
10382 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10385 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10386 => await this.doMoveToRTHome();
10388 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10390 var screenName = this.CurrentPost?.ScreenName;
10391 if (screenName != null)
10392 this.ListManageUserContext(screenName);
10395 public void ListManageUserContext(string screenName)
10397 using var listSelectForm = new MyLists(screenName, this.twitterApi);
10398 listSelectForm.ShowDialog(this);
10401 private void SearchControls_Enter(object sender, EventArgs e)
10403 var pnl = (Control)sender;
10404 foreach (Control ctl in pnl.Controls)
10406 ctl.TabStop = true;
10410 private void SearchControls_Leave(object sender, EventArgs e)
10412 var pnl = (Control)sender;
10413 foreach (Control ctl in pnl.Controls)
10415 ctl.TabStop = false;
10419 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10421 var tab = this.CurrentTab;
10422 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10423 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10426 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10427 => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10429 private void HashManageMenuItem_Click(object sender, EventArgs e)
10434 rslt = HashMgr.ShowDialog();
10440 this.TopMost = SettingManager.Common.AlwaysTop;
10441 if (rslt == DialogResult.Cancel) return;
10442 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10444 HashStripSplitButton.Text = HashMgr.UseHash;
10445 HashTogglePullDownMenuItem.Checked = true;
10446 HashToggleMenuItem.Checked = true;
10450 HashStripSplitButton.Text = "#[-]";
10451 HashTogglePullDownMenuItem.Checked = false;
10452 HashToggleMenuItem.Checked = false;
10455 this.MarkSettingCommonModified();
10456 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10459 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10461 HashMgr.ToggleHash();
10462 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10464 HashStripSplitButton.Text = HashMgr.UseHash;
10465 HashToggleMenuItem.Checked = true;
10466 HashTogglePullDownMenuItem.Checked = true;
10470 HashStripSplitButton.Text = "#[-]";
10471 HashToggleMenuItem.Checked = false;
10472 HashTogglePullDownMenuItem.Checked = false;
10474 this.MarkSettingCommonModified();
10475 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10478 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10479 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
10481 public void SetPermanentHashtag(string hashtag)
10483 HashMgr.SetPermanentHash("#" + hashtag);
10484 HashStripSplitButton.Text = HashMgr.UseHash;
10485 HashTogglePullDownMenuItem.Checked = true;
10486 HashToggleMenuItem.Checked = true;
10488 this.MarkSettingCommonModified();
10491 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10493 if (!this.ExistCurrentPost)
10495 this.ReplyOpMenuItem.Enabled = false;
10496 this.ReplyAllOpMenuItem.Enabled = false;
10497 this.DmOpMenuItem.Enabled = false;
10498 this.ShowProfMenuItem.Enabled = false;
10499 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10500 this.ListManageMenuItem.Enabled = false;
10501 this.OpenFavOpMenuItem.Enabled = false;
10502 this.CreateTabRuleOpMenuItem.Enabled = false;
10503 this.CreateIdRuleOpMenuItem.Enabled = false;
10504 this.CreateSourceRuleOpMenuItem.Enabled = false;
10505 this.ReadOpMenuItem.Enabled = false;
10506 this.UnreadOpMenuItem.Enabled = false;
10510 this.ReplyOpMenuItem.Enabled = true;
10511 this.ReplyAllOpMenuItem.Enabled = true;
10512 this.DmOpMenuItem.Enabled = true;
10513 this.ShowProfMenuItem.Enabled = true;
10514 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10515 this.ListManageMenuItem.Enabled = true;
10516 this.OpenFavOpMenuItem.Enabled = true;
10517 this.CreateTabRuleOpMenuItem.Enabled = true;
10518 this.CreateIdRuleOpMenuItem.Enabled = true;
10519 this.CreateSourceRuleOpMenuItem.Enabled = true;
10520 this.ReadOpMenuItem.Enabled = true;
10521 this.UnreadOpMenuItem.Enabled = true;
10524 var tab = this.CurrentTab;
10525 var post = this.CurrentPost;
10526 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
10528 this.FavOpMenuItem.Enabled = false;
10529 this.UnFavOpMenuItem.Enabled = false;
10530 this.OpenStatusOpMenuItem.Enabled = false;
10531 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10532 this.RtOpMenuItem.Enabled = false;
10533 this.RtUnOpMenuItem.Enabled = false;
10534 this.QtOpMenuItem.Enabled = false;
10535 this.FavoriteRetweetMenuItem.Enabled = false;
10536 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10540 this.FavOpMenuItem.Enabled = true;
10541 this.UnFavOpMenuItem.Enabled = true;
10542 this.OpenStatusOpMenuItem.Enabled = true;
10543 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10545 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10547 this.RtOpMenuItem.Enabled = false;
10548 this.RtUnOpMenuItem.Enabled = false;
10549 this.QtOpMenuItem.Enabled = false;
10550 this.FavoriteRetweetMenuItem.Enabled = false;
10551 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10555 this.RtOpMenuItem.Enabled = true;
10556 this.RtUnOpMenuItem.Enabled = true;
10557 this.QtOpMenuItem.Enabled = true;
10558 this.FavoriteRetweetMenuItem.Enabled = true;
10559 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10563 if (tab.TabType != MyCommon.TabUsageType.Favorites)
10565 this.RefreshPrevOpMenuItem.Enabled = true;
10569 this.RefreshPrevOpMenuItem.Enabled = false;
10571 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
10573 OpenRepSourceOpMenuItem.Enabled = false;
10577 OpenRepSourceOpMenuItem.Enabled = true;
10579 if (!this.ExistCurrentPost || post == null || string.IsNullOrEmpty(post.RetweetedBy))
10581 OpenRterHomeMenuItem.Enabled = false;
10585 OpenRterHomeMenuItem.Enabled = true;
10588 if (this.ExistCurrentPost && post != null)
10590 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10594 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10595 => this.ContextMenuTabProperty_Opening(sender, null!);
10597 public Twitter TwitterInstance
10600 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10602 if (this._initialLayout)
10605 int splitterDistance;
10606 switch (this.WindowState)
10608 case FormWindowState.Normal:
10609 splitterDistance = this.SplitContainer3.SplitterDistance;
10611 case FormWindowState.Maximized:
10612 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10613 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10614 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10615 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10621 this._mySpDis3 = splitterDistance;
10622 this.MarkSettingLocalModified();
10625 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10627 if (_statuses.RemovedTab.Count == 0)
10629 UndoRemoveTabMenuItem.Enabled = false;
10633 UndoRemoveTabMenuItem.Enabled = true;
10636 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10637 PublicSearchQueryMenuItem.Enabled = true;
10639 PublicSearchQueryMenuItem.Enabled = false;
10641 var post = this.CurrentPost;
10642 if (!this.ExistCurrentPost || post == null)
10644 this.CopySTOTMenuItem.Enabled = false;
10645 this.CopyURLMenuItem.Enabled = false;
10646 this.CopyUserIdStripMenuItem.Enabled = false;
10650 this.CopySTOTMenuItem.Enabled = true;
10651 this.CopyURLMenuItem.Enabled = true;
10652 this.CopyUserIdStripMenuItem.Enabled = true;
10654 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10655 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10659 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10660 => this.SetNotifyIconText();
10662 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10663 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10665 private async Task doShowUserStatus(string id, bool ShowInputDialog)
10667 TwitterUser? user = null;
10669 if (ShowInputDialog)
10671 using var inputName = new InputTabName();
10672 inputName.FormTitle = "Show UserStatus";
10673 inputName.FormDescription = Properties.Resources.FRMessage1;
10674 inputName.TabName = id;
10676 if (inputName.ShowDialog(this) != DialogResult.OK)
10678 if (string.IsNullOrWhiteSpace(inputName.TabName))
10681 id = inputName.TabName.Trim();
10684 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10686 var cancellationToken = dialog.EnableCancellation();
10690 var task = this.twitterApi.UsersShow(id);
10691 user = await dialog.WaitForAsync(this, task);
10693 catch (WebApiException ex)
10695 if (!cancellationToken.IsCancellationRequested)
10696 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10700 if (cancellationToken.IsCancellationRequested)
10704 await this.doShowUserStatus(user);
10707 private async Task doShowUserStatus(TwitterUser user)
10709 using var userDialog = new UserInfoDialog(this, this.twitterApi);
10710 var showUserTask = userDialog.ShowUserAsync(user);
10711 userDialog.ShowDialog(this);
10714 this.BringToFront();
10716 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10717 await showUserTask;
10720 internal Task ShowUserStatus(string id, bool ShowInputDialog)
10721 => this.doShowUserStatus(id, ShowInputDialog);
10723 internal Task ShowUserStatus(string id)
10724 => this.doShowUserStatus(id, true);
10726 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10728 var post = this.CurrentPost;
10731 await this.ShowUserStatus(post.ScreenName, false);
10735 private async void RtCountMenuItem_Click(object sender, EventArgs e)
10737 var post = this.CurrentPost;
10738 if (!this.ExistCurrentPost || post == null)
10741 var statusId = post.RetweetedId ?? post.StatusId;
10742 TwitterStatus status;
10744 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
10746 var cancellationToken = dialog.EnableCancellation();
10750 var task = this.twitterApi.StatusesShow(statusId);
10751 status = await dialog.WaitForAsync(this, task);
10753 catch (WebApiException ex)
10755 if (!cancellationToken.IsCancellationRequested)
10756 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
10760 if (cancellationToken.IsCancellationRequested)
10764 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
10767 private readonly HookGlobalHotkey _hookGlobalHotkey;
10770 _hookGlobalHotkey = new HookGlobalHotkey(this);
10772 // この呼び出しは、Windows フォーム デザイナで必要です。
10773 InitializeComponent();
10775 // InitializeComponent() 呼び出しの後で初期化を追加します。
10777 if (!this.DesignMode)
10779 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
10780 this.StatusText.Dock = DockStyle.Fill;
10783 this.tweetDetailsView.Owner = this;
10785 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
10786 this.gh.NotifyClicked += GrowlHelper_Callback;
10788 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
10789 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
10791 this.ImageSelector.Visible = false;
10792 this.ImageSelector.Enabled = false;
10793 this.ImageSelector.FilePickDialog = OpenFileDialog1;
10795 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
10797 this.ReplaceAppName();
10798 this.InitializeShortcuts();
10801 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
10803 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
10806 this.Visible = false;
10808 else if (Form.ActiveForm == null)
10810 this.Visible = true;
10811 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
10813 this.BringToFront();
10814 this.StatusText.Focus();
10818 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
10819 => this.MultiLinePullDownMenuItem.PerformClick();
10822 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
10824 if (ImageSelector.Visible)
10825 ImageSelector.EndSelection();
10827 ImageSelector.BeginSelection();
10830 private void SelectMedia_DragEnter(DragEventArgs e)
10832 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
10834 e.Effect = DragDropEffects.Copy;
10837 e.Effect = DragDropEffects.None;
10840 private void SelectMedia_DragDrop(DragEventArgs e)
10843 this.BringToFront();
10844 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
10845 StatusText.Focus();
10848 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
10850 TimelinePanel.Visible = false;
10851 TimelinePanel.Enabled = false;
10854 private void ImageSelector_EndSelecting(object sender, EventArgs e)
10856 TimelinePanel.Visible = true;
10857 TimelinePanel.Enabled = true;
10858 this.CurrentListView.Focus();
10861 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
10862 => this.AllowDrop = false;
10864 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
10865 => this.AllowDrop = true;
10867 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
10869 if (ImageSelector.Visible)
10871 this.MarkSettingCommonModified();
10872 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10876 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
10877 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10880 /// StatusTextでCtrl+Vが押下された時の処理
10882 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
10886 if (Clipboard.ContainsText())
10888 // clipboardにテキストがある場合は貼り付け処理
10889 this.StatusText.Paste(Clipboard.GetText());
10891 else if (Clipboard.ContainsImage())
10894 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
10895 Properties.Resources.PostPictureWarn4,
10896 MessageBoxButtons.OKCancel,
10897 MessageBoxIcon.Question,
10898 MessageBoxDefaultButton.Button2)
10899 == DialogResult.OK)
10901 // clipboardから画像を取得
10902 using var image = Clipboard.GetImage();
10903 this.ImageSelector.BeginSelection(image);
10907 catch (ExternalException ex)
10909 MessageBox.Show(ex.Message);
10914 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
10916 using var form = new ListManage(tw);
10917 form.ShowDialog(this);
10920 private bool ModifySettingCommon { get; set; }
10921 private bool ModifySettingLocal { get; set; }
10922 private bool ModifySettingAtId { get; set; }
10924 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
10926 var post = this.CurrentPost;
10927 if (this.ExistCurrentPost && post != null && !post.IsDm)
10928 RtCountMenuItem.Enabled = true;
10930 RtCountMenuItem.Enabled = false;
10933 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
10934 => this.CopyUserId();
10936 private void CopyUserId()
10938 var post = this.CurrentPost;
10939 if (post == null) return;
10940 var clstr = post.ScreenName;
10943 Clipboard.SetDataObject(clstr, false, 5, 100);
10945 catch (Exception ex)
10947 MessageBox.Show(ex.Message);
10951 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
10953 var post = this.CurrentPost;
10954 if (this.ExistCurrentPost && post != null && !post.IsDm)
10958 await this.OpenRelatedTab(post);
10960 catch (TabException ex)
10962 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
10968 /// 指定されたツイートに対する関連発言タブを開きます
10970 /// <param name="statusId">表示するツイートのID</param>
10971 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
10972 public async Task OpenRelatedTab(long statusId)
10974 var post = this._statuses[statusId];
10979 post = await this.tw.GetStatusApi(false, statusId);
10981 catch (WebApiException ex)
10983 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
10988 await this.OpenRelatedTab(post);
10992 /// 指定されたツイートに対する関連発言タブを開きます
10994 /// <param name="post">表示する対象となるツイート</param>
10995 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
10996 private async Task OpenRelatedTab(PostClass post)
10998 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
10999 if (tabRelated != null)
11001 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11004 var tabName = this._statuses.MakeTabName("Related Tweets");
11006 tabRelated = new RelatedPostsTabModel(tabName, post)
11008 UnreadManage = false,
11012 this._statuses.AddTab(tabRelated);
11013 this.AddNewTab(tabRelated, startup: false);
11015 this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11017 await this.RefreshTabAsync(tabRelated);
11019 var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11021 if (tabIndex != -1)
11023 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11025 var tabPage = this.ListTab.TabPages[tabIndex];
11026 var listView = (DetailsListView)tabPage.Tag;
11027 var targetPost = tabRelated.TargetPost;
11028 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11030 if (index != -1 && index < listView.Items.Count)
11032 listView.SelectedIndices.Add(index);
11033 listView.Items[index].Focused = true;
11038 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11040 var buf = new StringBuilder();
11041 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11042 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11043 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11046 #region "Userstream"
11047 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11051 if (InvokeRequired && !IsDisposed)
11053 await this.InvokeAsync(() =>
11055 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11056 if (this.CurrentTab.Contains(e.StatusId))
11058 this.PurgeListViewItemCache();
11059 this.CurrentListView.Update();
11060 var post = this.CurrentPost;
11061 if (post != null && post.StatusId == e.StatusId)
11062 this.DispSelectedPost(true);
11068 catch (ObjectDisposedException)
11072 catch (InvalidOperationException)
11078 private void tw_NewPostFromStream(object sender, EventArgs e)
11080 if (SettingManager.Common.ReadOldPosts)
11082 _statuses.SetReadHomeTab(); //新着時未読クリア
11085 this._statuses.DistributePosts();
11087 this.RefreshThrottlingTimer.Call();
11090 private async void tw_UserStreamStarted(object sender, EventArgs e)
11094 if (InvokeRequired && !IsDisposed)
11096 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11100 catch (ObjectDisposedException)
11104 catch (InvalidOperationException)
11109 this.RefreshUserStreamsMenu();
11110 this.MenuItemUserStream.Enabled = true;
11112 StatusLabel.Text = "UserStream Started.";
11115 private async void tw_UserStreamStopped(object sender, EventArgs e)
11119 if (InvokeRequired && !IsDisposed)
11121 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11125 catch (ObjectDisposedException)
11129 catch (InvalidOperationException)
11134 this.RefreshUserStreamsMenu();
11135 this.MenuItemUserStream.Enabled = true;
11137 StatusLabel.Text = "UserStream Stopped.";
11140 private void RefreshUserStreamsMenu()
11142 if (this.tw.UserStreamActive)
11144 this.MenuItemUserStream.Text = "&UserStream ▶";
11145 this.StopToolStripMenuItem.Text = "&Stop";
11149 this.MenuItemUserStream.Text = "&UserStream ■";
11150 this.StopToolStripMenuItem.Text = "&Start";
11154 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11158 if (InvokeRequired && !IsDisposed)
11160 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11164 catch (ObjectDisposedException)
11168 catch (InvalidOperationException)
11172 var ev = e.EventData;
11173 StatusLabel.Text = "Event: " + ev.Event;
11175 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11177 if (this.CurrentTab.Contains(ev.Id))
11179 this.PurgeListViewItemCache();
11180 this.CurrentListView.Update();
11182 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11184 var favTab = this._statuses.FavoriteTab;
11185 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11190 private void NotifyEvent(Twitter.FormattedEvent ev)
11193 if (BalloonRequired(ev))
11195 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11196 var title = new StringBuilder();
11197 if (SettingManager.Common.DispUsername)
11199 title.Append(tw.Username);
11200 title.Append(" - ");
11202 title.Append(ApplicationSettings.ApplicationName);
11203 title.Append(" [");
11204 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11205 title.Append("] by ");
11206 if (!string.IsNullOrEmpty(ev.Username))
11208 title.Append(ev.Username);
11212 if (!string.IsNullOrEmpty(ev.Target))
11217 if (SettingManager.Common.IsUseNotifyGrowl)
11219 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11220 ev.Id.ToString(), title.ToString(), text);
11224 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11225 NotifyIcon1.BalloonTipTitle = title.ToString();
11226 NotifyIcon1.BalloonTipText = text;
11227 NotifyIcon1.ShowBalloonTip(500);
11232 var snd = SettingManager.Common.EventSoundFile;
11233 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11235 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11239 var dir = Application.StartupPath;
11240 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11242 dir = Path.Combine(dir, "Sounds");
11244 using var player = new SoundPlayer(Path.Combine(dir, snd));
11254 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11256 MenuItemUserStream.Enabled = false;
11257 if (StopRefreshAllMenuItem.Checked)
11259 StopRefreshAllMenuItem.Checked = false;
11262 if (this.tw.UserStreamActive)
11264 tw.StopUserStream();
11268 tw.StartUserStream();
11272 private static string inputTrack = "";
11274 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11276 if (TrackToolStripMenuItem.Checked)
11278 using (var inputForm = new InputTabName())
11280 inputForm.TabName = inputTrack;
11281 inputForm.FormTitle = "Input track word";
11282 inputForm.FormDescription = "Track word";
11283 if (inputForm.ShowDialog() != DialogResult.OK)
11285 TrackToolStripMenuItem.Checked = false;
11288 inputTrack = inputForm.TabName.Trim();
11290 if (!inputTrack.Equals(tw.TrackWord))
11292 tw.TrackWord = inputTrack;
11293 this.MarkSettingCommonModified();
11294 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11295 tw.ReconnectUserStream();
11301 tw.ReconnectUserStream();
11303 this.MarkSettingCommonModified();
11306 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11308 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11309 this.MarkSettingCommonModified();
11310 tw.ReconnectUserStream();
11313 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11315 if (evtDialog == null || evtDialog.IsDisposed)
11317 this.evtDialog = new EventViewerDialog
11323 this.evtDialog.Location = new Point
11325 X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11326 Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11329 evtDialog.EventSource = tw.StoredEvent;
11330 if (!evtDialog.Visible)
11332 evtDialog.Show(this);
11336 evtDialog.Activate();
11338 this.TopMost = SettingManager.Common.AlwaysTop;
11342 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11344 MyCommon._endingFlag = true;
11348 Application.Restart();
11352 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11356 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11357 => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11359 private bool ExistCurrentPost
11363 var post = this.CurrentPost;
11364 return post != null && !post.IsDeleted;
11368 private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11369 => await this.ShowUserTimeline();
11371 private string GetUserIdFromCurPostOrInput(string caption)
11373 var id = this.CurrentPost?.ScreenName ?? "";
11375 using var inputName = new InputTabName();
11376 inputName.FormTitle = caption;
11377 inputName.FormDescription = Properties.Resources.FRMessage1;
11378 inputName.TabName = id;
11380 if (inputName.ShowDialog() == DialogResult.OK &&
11381 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11383 id = inputName.TabName.Trim();
11392 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11394 var id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11395 if (!string.IsNullOrEmpty(id))
11397 await this.AddNewTabForUserTimeline(id);
11401 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11403 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
11404 this.timelineScheduler.SystemResumed();
11407 private void SystemEvents_TimeChanged(object sender, EventArgs e)
11409 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11411 TimeZoneInfo.ClearCachedData();
11413 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11415 if (curTimeOffset != prevTimeOffset)
11418 this.PurgeListViewItemCache();
11419 this.CurrentListView.Refresh();
11421 this.DispSelectedPost(forceupdate: true);
11425 private void TimelineRefreshEnableChange(bool isEnable)
11429 tw.StartUserStream();
11433 tw.StopUserStream();
11435 this.timelineScheduler.Enabled = isEnable;
11438 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11439 => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11441 private async Task OpenUserAppointUrl()
11443 if (SettingManager.Common.UserAppointUrl != null)
11445 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11447 var post = this.CurrentPost;
11450 var xUrl = SettingManager.Common.UserAppointUrl;
11451 xUrl = xUrl.Replace("{ID}", post.ScreenName);
11453 var statusId = post.RetweetedId ?? post.StatusId;
11454 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11456 await this.OpenUriInBrowserAsync(xUrl);
11461 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11466 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11467 => await this.OpenUserAppointUrl();
11469 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11471 if (Form.ActiveForm == null)
11473 await this.InvokeAsync(() =>
11475 this.Visible = true;
11476 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11478 this.BringToFront();
11479 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11481 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11485 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11491 private void ReplaceAppName()
11493 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11494 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11497 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11498 => this.SplitContainer3.Panel2Collapsed = false;
11500 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11501 => await this.OpenThumbnailPicture(e.Thumbnail);
11503 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11504 => await this.OpenUriInBrowserAsync(e.ImageUrl);
11506 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11508 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11510 await this.OpenUriInBrowserAsync(url);
11513 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11514 => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11516 private void PostButton_KeyDown(object sender, KeyEventArgs e)
11518 if (e.KeyCode == Keys.Space)
11520 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
11522 e.SuppressKeyPress = true;
11526 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11528 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11529 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11530 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11531 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11532 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11534 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11537 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11538 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11540 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11541 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11543 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11544 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11546 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11547 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11549 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11550 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11552 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11554 if (SettingManager.Common.IconSize == iconSize) return;
11556 var oldIconCol = _iconCol;
11558 SettingManager.Common.IconSize = iconSize;
11559 ApplyListViewIconSize(iconSize);
11561 if (_iconCol != oldIconCol)
11563 foreach (TabPage tp in ListTab.TabPages)
11565 ResetColumns((DetailsListView)tp.Tag);
11569 this.CurrentListView.Refresh();
11570 this.MarkSettingCommonModified();
11573 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11575 var state = this.LockListSortOrderToolStripMenuItem.Checked;
11576 if (SettingManager.Common.SortOrderLock == state) return;
11578 SettingManager.Common.SortOrderLock = state;
11579 this.MarkSettingCommonModified();
11582 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11584 if (!string.IsNullOrEmpty(e.StatusText))
11586 this.StatusLabelUrl.Text = e.StatusText;
11590 this.SetStatusLabelUrl();