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 selectionDebouncer = null!;
370 private ThrottlingTimer saveConfigDebouncer = null!;
372 private string recommendedStatusFooter = null!;
373 private bool urlMultibyteSplit = false;
374 private bool preventSmsCommand = true;
377 private struct urlUndo
379 public string Before;
383 private List<urlUndo>? urlUndoBuffer = null;
385 private readonly struct ReplyChain
387 public readonly long OriginalId;
388 public readonly long InReplyToId;
389 public readonly TabModel OriginalTab;
391 public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
393 this.OriginalId = originalId;
394 this.InReplyToId = inReplyToId;
395 this.OriginalTab = originalTab;
399 /// <summary>[, ]でのリプライ移動の履歴</summary>
400 private Stack<ReplyChain>? replyChains;
402 /// <summary>ポスト選択履歴</summary>
403 private readonly Stack<(TabModel, PostClass?)> selectPostChains = new Stack<(TabModel, PostClass?)>();
405 public TabModel CurrentTab
406 => this._statuses.SelectedTab;
408 public string CurrentTabName
409 => this._statuses.SelectedTabName;
411 public TabPage CurrentTabPage
412 => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
414 public DetailsListView CurrentListView
415 => (DetailsListView)this.CurrentTabPage.Tag;
417 public PostClass? CurrentPost
418 => this.CurrentTab.SelectedPost;
420 /// <summary>検索処理タイプ</summary>
421 internal enum SEARCHTYPE
428 private class StatusTextHistory
430 public string status = "";
431 public (long StatusId, string ScreenName)? inReplyTo = null;
433 /// <summary>画像投稿サービス名</summary>
434 public string imageService = "";
436 public IMediaItem[]? mediaItems = null;
437 public StatusTextHistory()
440 public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
442 this.status = status;
443 this.inReplyTo = inReplyTo;
447 private void TweenMain_Activated(object sender, EventArgs e)
449 //画面がアクティブになったら、発言欄の背景色戻す
450 if (StatusText.Focused)
452 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
456 private bool disposed = false;
459 /// 使用中のリソースをすべてクリーンアップします。
461 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
462 protected override void Dispose(bool disposing)
464 base.Dispose(disposing);
471 this.components?.Dispose();
474 SearchDialog.Dispose();
477 NIconAtRed?.Dispose();
478 NIconAtSmoke?.Dispose();
479 foreach (var iconRefresh in this.NIconRefresh)
481 iconRefresh?.Dispose();
485 ReplyIcon?.Dispose();
486 ReplyIconBlink?.Dispose();
487 _listViewImageList.Dispose();
488 _brsHighLight.Dispose();
489 _brsBackColorMine?.Dispose();
490 _brsBackColorAt?.Dispose();
491 _brsBackColorYou?.Dispose();
492 _brsBackColorAtYou?.Dispose();
493 _brsBackColorAtFromTarget?.Dispose();
494 _brsBackColorAtTo?.Dispose();
495 _brsBackColorNone?.Dispose();
496 _brsDeactiveSelection?.Dispose();
500 this.workerCts.Cancel();
502 if (IconCache != null)
504 this.IconCache.CancelAsync();
505 this.IconCache.Dispose();
508 this.thumbnailTokenSource?.Dispose();
511 this.twitterApi.Dispose();
512 this._hookGlobalHotkey.Dispose();
515 // 終了時にRemoveHandlerしておかないとメモリリークする
516 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
517 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
518 Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
520 this.disposed = true;
523 private void LoadIcons()
525 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
526 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
529 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
532 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
535 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
538 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
540 // タスクトレイ: オフライン時アイコン
541 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
543 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
544 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
545 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
547 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
548 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
549 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
550 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
551 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
553 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
555 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
556 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
557 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
558 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
559 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
561 if (iconReply != null && iconReplyBlink != null)
563 this.ReplyIcon = iconReply;
564 this.ReplyIconBlink = iconReplyBlink;
568 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
569 this.ReplyIconBlink = this.NIconAt;
572 if (iconRefresh1 == null)
574 this.NIconRefresh = new[] {
575 Properties.Resources.Refresh, Properties.Resources.Refresh2,
576 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
579 else if (iconRefresh2 == null)
581 this.NIconRefresh = new[] { iconRefresh1 };
583 else if (iconRefresh3 == null)
585 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
587 else if (iconRefresh4 == null)
589 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
591 else // iconRefresh1 から iconRefresh4 まで全て揃っている
593 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
597 private Icon? LoadIcon(string filePath)
599 if (!File.Exists(filePath))
604 return new Icon(filePath);
612 private void InitColumns(ListView list, bool startup)
614 this.InitColumnText();
616 ColumnHeader[]? columns = null;
623 new ColumnHeader(), // アイコン
624 new ColumnHeader(), // 本文
627 columns[0].Text = this.ColumnText[0];
628 columns[1].Text = this.ColumnText[2];
632 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
634 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
635 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
636 columns[0].DisplayIndex = 0;
637 columns[1].DisplayIndex = 1;
642 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
644 columns[idx].Width = curListColumn.Width;
645 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
654 new ColumnHeader(), // アイコン
655 new ColumnHeader(), // ニックネーム
656 new ColumnHeader(), // 本文
657 new ColumnHeader(), // 日付
658 new ColumnHeader(), // ユーザID
659 new ColumnHeader(), // 未読
660 new ColumnHeader(), // マーク&プロテクト
661 new ColumnHeader(), // ソース
664 foreach (var i in Enumerable.Range(0, columns.Length))
665 columns[i].Text = this.ColumnText[i];
669 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
671 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
672 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
673 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
674 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
675 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
676 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
677 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
678 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
680 var displayIndex = new[] {
681 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
682 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
683 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
684 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
687 foreach (var i in Enumerable.Range(0, displayIndex.Length))
689 columns[i].DisplayIndex = displayIndex[i];
695 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
697 columns[idx].Width = curListColumn.Width;
698 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
704 list.Columns.AddRange(columns);
712 foreach (var column in columns)
718 private void InitColumnText()
721 ColumnText[1] = Properties.Resources.AddNewTabText2;
722 ColumnText[2] = Properties.Resources.AddNewTabText3;
723 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
724 ColumnText[4] = Properties.Resources.AddNewTabText5;
727 ColumnText[7] = "Source";
729 ColumnOrgText[0] = "";
730 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
731 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
732 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
733 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
734 ColumnOrgText[5] = "";
735 ColumnOrgText[6] = "";
736 ColumnOrgText[7] = "Source";
738 var c = this._statuses.SortMode switch
740 ComparerMode.Nickname => 1, // ニックネーム
741 ComparerMode.Data => 2, // 本文
742 ComparerMode.Id => 3, // 時刻=発言Id
743 ComparerMode.Name => 4, // 名前
744 ComparerMode.Source => 7, // Source
750 if (_statuses.SortOrder == SortOrder.Descending)
752 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
753 ColumnText[2] = ColumnOrgText[2] + "▾";
757 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
758 ColumnText[2] = ColumnOrgText[2] + "▴";
763 if (_statuses.SortOrder == SortOrder.Descending)
765 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
766 ColumnText[c] = ColumnOrgText[c] + "▾";
770 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
771 ColumnText[c] = ColumnOrgText[c] + "▴";
776 private void InitializeTraceFrag()
779 TraceOutToolStripMenuItem.Checked = true;
780 MyCommon.TraceFlag = true;
782 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
784 TraceOutToolStripMenuItem.Checked = true;
785 MyCommon.TraceFlag = true;
789 private void TweenMain_Load(object sender, EventArgs e)
791 _ignoreConfigSave = true;
792 this.Visible = false;
794 if (MyApplication.StartupOptions.ContainsKey("d"))
795 MyCommon.TraceFlag = true;
797 InitializeTraceFrag();
799 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
801 Regex.CacheSize = 100;
804 _statuses = TabInformations.GetInstance();
808 this.Icon = MainIcon; //メインフォーム(TweenMain)
809 NotifyIcon1.Icon = NIconAt; //タスクトレイ
810 TabImage.Images.Add(TabIcon); //タブ見出し
812 //<<<<<<<<<設定関連>>>>>>>>>
816 // 現在の DPI と設定保存時の DPI との比を取得する
817 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
820 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
821 if (fontUIGlobal != null)
823 OTBaseForm.GlobalFont = fontUIGlobal;
824 this.Font = fontUIGlobal;
828 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
830 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
831 SettingManager.Common.TimelinePeriod = 15;
833 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
834 SettingManager.Common.ReplyPeriod = 15;
836 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
837 SettingManager.Common.DMPeriod = 15;
839 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
840 SettingManager.Common.PubSearchPeriod = 30;
842 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
843 SettingManager.Common.UserTimelinePeriod = 15;
845 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
846 SettingManager.Common.ListsPeriod = 15;
849 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
850 SettingManager.Common.CountApi = 60;
851 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
852 SettingManager.Common.CountApiReply = 40;
854 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
855 SettingManager.Common.MoreCountApi = 200;
856 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
857 SettingManager.Common.FirstCountApi = 100;
859 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
860 SettingManager.Common.FavoritesCountApi = 40;
861 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
862 SettingManager.Common.ListCountApi = 100;
863 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
864 SettingManager.Common.SearchCountApi = 100;
865 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
866 SettingManager.Common.UserTimelineCountApi = 20;
868 //廃止サービスが選択されていた場合ux.nuへ読み替え
869 if (SettingManager.Common.AutoShortUrlFirst < 0)
870 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
872 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
873 this.tw = new Twitter(this.twitterApi);
876 if (MyCommon.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
877 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
881 Networking.Initialize();
883 var saveRequired = false;
884 var firstRun = false;
886 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
887 if (MyCommon.IsNullOrEmpty(tw.Username))
892 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
893 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
894 MyCommon.IsNullOrEmpty(tw.Username))
896 Application.Exit(); //強制終了
902 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
903 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
904 Networking.SetWebProxy(SettingManager.Local.ProxyType,
905 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
906 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
907 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
909 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
910 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
911 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
912 tw.TrackWord = SettingManager.Common.TrackWord;
913 TrackToolStripMenuItem.Checked = !MyCommon.IsNullOrEmpty(tw.TrackWord);
914 tw.AllAtReply = SettingManager.Common.AllAtReply;
915 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
916 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
917 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
918 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
919 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
921 // アクセストークンが有効であるか確認する
922 // ここが Twitter API への最初のアクセスになるようにすること
925 this.tw.VerifyCredentials();
927 catch (WebApiException ex)
929 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
930 ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
934 //プロキシ設定等の通信まわりの初期化が済んでから処理する
935 ThumbnailGenerator.InitializeGenerator();
937 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
938 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
939 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
941 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
944 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
947 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
948 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
949 HashMgr = new HashtagManage(HashSupl,
950 SettingManager.Common.HashTags.ToArray(),
951 SettingManager.Common.HashSelected,
952 SettingManager.Common.HashIsPermanent,
953 SettingManager.Common.HashIsHead,
954 SettingManager.Common.HashIsNotAddToAtReply);
955 if (!MyCommon.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
958 this.IconCache = new ImageCache();
959 this.tweetDetailsView.IconCache = this.IconCache;
962 _fntUnread = SettingManager.Local.FontUnread;
963 _clUnread = SettingManager.Local.ColorUnread;
964 _fntReaded = SettingManager.Local.FontRead;
965 _clReaded = SettingManager.Local.ColorRead;
966 _clFav = SettingManager.Local.ColorFav;
967 _clOWL = SettingManager.Local.ColorOWL;
968 _clRetweet = SettingManager.Local.ColorRetweet;
969 _fntDetail = SettingManager.Local.FontDetail;
970 _clDetail = SettingManager.Local.ColorDetail;
971 _clDetailLink = SettingManager.Local.ColorDetailLink;
972 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
973 _clSelf = SettingManager.Local.ColorSelf;
974 _clAtSelf = SettingManager.Local.ColorAtSelf;
975 _clTarget = SettingManager.Local.ColorTarget;
976 _clAtTarget = SettingManager.Local.ColorAtTarget;
977 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
978 _clAtTo = SettingManager.Local.ColorAtTo;
979 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
980 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
981 _clInputFont = SettingManager.Local.ColorInputFont;
982 _fntInputFont = SettingManager.Local.FontInputFont;
984 _brsBackColorMine = new SolidBrush(_clSelf);
985 _brsBackColorAt = new SolidBrush(_clAtSelf);
986 _brsBackColorYou = new SolidBrush(_clTarget);
987 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
988 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
989 _brsBackColorAtTo = new SolidBrush(_clAtTo);
990 _brsBackColorNone = new SolidBrush(_clListBackcolor);
992 // StringFormatオブジェクトへの事前設定
993 sfTab.Alignment = StringAlignment.Center;
994 sfTab.LineAlignment = StringAlignment.Center;
996 InitDetailHtmlFormat();
998 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
1000 _history.Add(new StatusTextHistory());
1002 this.inReplyTo = null;
1005 SearchDialog.Owner = this;
1006 UrlDialog.Owner = this;
1009 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
1010 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
1012 //新着取得時のリストスクロールをするか。trueならスクロールしない
1013 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
1014 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
1016 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1017 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1020 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
1021 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1022 _myLoc = SettingManager.Local.FormLocation;
1024 if (this.WindowState != FormWindowState.Minimized)
1026 var tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1027 var outOfScreen = true;
1028 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1030 foreach (var scr in Screen.AllScreens)
1032 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1034 outOfScreen = false;
1040 this._myLoc = new Point(0, 0);
1042 this.DesktopLocation = this._myLoc;
1044 this.TopMost = SettingManager.Common.AlwaysTop;
1045 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
1046 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
1047 if (SettingManager.Local.PreviewDistance == -1)
1049 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
1050 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
1051 SettingManager.Local.PreviewDistance = _mySpDis3;
1055 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
1057 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1058 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1060 StatusText.Font = _fntInputFont;
1061 StatusText.ForeColor = _clInputFont;
1063 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
1064 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
1065 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
1067 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1068 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
1070 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1071 if (SettingManager.Common.UnreadManage == false)
1073 ReadedStripMenuItem.Enabled = false;
1074 UnreadStripMenuItem.Enabled = false;
1077 //リンク先URL表示部の初期化(画面左下)
1078 StatusLabelUrl.Text = "";
1080 StatusLabel.Text = "";
1081 StatusLabel.AutoToolTip = false;
1082 StatusLabel.ToolTipText = "";
1084 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1086 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1087 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1088 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1089 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1091 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1092 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1093 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1094 this.SplitContainer2.Panel2.AccessibleName = "";
1096 ////////////////////////////////////////////////////////////////////////////////
1097 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1098 var mode = ComparerMode.Id;
1099 switch (SettingManager.Common.SortColumn)
1101 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1105 mode = ComparerMode.Id; //Idソートに読み替え
1108 mode = ComparerMode.Nickname;
1111 mode = ComparerMode.Data;
1114 mode = ComparerMode.Id;
1117 mode = ComparerMode.Name;
1120 mode = ComparerMode.Source;
1123 _statuses.SetSortMode(mode, sortOrder);
1124 ////////////////////////////////////////////////////////////////////////////////
1126 ApplyListViewIconSize(SettingManager.Common.IconSize);
1128 //<<<<<<<<タブ関連>>>>>>>
1130 //デフォルトタブの存在チェック、ない場合には追加
1131 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1132 this._statuses.AddTab(new HomeTabModel());
1134 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1135 this._statuses.AddTab(new MentionsTabModel());
1137 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1138 this._statuses.AddTab(new DirectMessagesTabModel());
1140 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1141 this._statuses.AddTab(new FavoritesTabModel());
1143 if (this._statuses.MuteTab == null)
1144 this._statuses.AddTab(new MuteTabModel());
1146 foreach (var tab in _statuses.Tabs)
1148 if (!AddNewTab(tab, startup: true))
1149 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1152 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.selectionDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
1221 this.saveConfigDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
1224 TimerRefreshIcon.Interval = 200;
1225 TimerRefreshIcon.Enabled = false;
1227 _ignoreConfigSave = false;
1228 this.TweenMain_Resize(this, EventArgs.Empty);
1229 if (saveRequired) SaveConfigsAll(false);
1231 foreach (var ua in SettingManager.Common.UserAccounts)
1233 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1235 ua.UserId = tw.UserId;
1242 // 初回起動時だけ右下のメニューを目立たせる
1243 HashStripSplitButton.ShowDropDown();
1247 private void InitDetailHtmlFormat()
1249 if (SettingManager.Common.IsMonospace)
1251 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1252 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1256 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1257 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1260 detailHtmlFormatHeader = detailHtmlFormatHeader
1261 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1262 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1263 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1264 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1265 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1266 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1269 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1274 txt = this._statuses.Tabs[e.Index].TabName;
1281 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1282 if (e.State == DrawItemState.Selected)
1284 e.DrawFocusRectangle();
1289 if (_statuses.Tabs[txt].UnreadCount > 0)
1292 fore = System.Drawing.SystemBrushes.ControlText;
1296 fore = System.Drawing.SystemBrushes.ControlText;
1298 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1301 private void LoadConfig()
1303 SettingManager.Local = SettingManager.Local;
1305 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1306 if (SettingManager.Local.ScaleDimension.IsEmpty)
1307 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1309 var tabSettings = SettingManager.Tabs;
1310 foreach (var tabSetting in tabSettings.Tabs)
1313 switch (tabSetting.TabType)
1315 case MyCommon.TabUsageType.Home:
1316 tab = new HomeTabModel(tabSetting.TabName);
1318 case MyCommon.TabUsageType.Mentions:
1319 tab = new MentionsTabModel(tabSetting.TabName);
1321 case MyCommon.TabUsageType.DirectMessage:
1322 tab = new DirectMessagesTabModel(tabSetting.TabName);
1324 case MyCommon.TabUsageType.Favorites:
1325 tab = new FavoritesTabModel(tabSetting.TabName);
1327 case MyCommon.TabUsageType.UserDefined:
1328 tab = new FilterTabModel(tabSetting.TabName);
1330 case MyCommon.TabUsageType.UserTimeline:
1331 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User!);
1333 case MyCommon.TabUsageType.PublicSearch:
1334 tab = new PublicSearchTabModel(tabSetting.TabName)
1336 SearchWords = tabSetting.SearchWords,
1337 SearchLang = tabSetting.SearchLang,
1340 case MyCommon.TabUsageType.Lists:
1341 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo!);
1343 case MyCommon.TabUsageType.Mute:
1344 tab = new MuteTabModel(tabSetting.TabName);
1350 tab.UnreadManage = tabSetting.UnreadManage;
1351 tab.Protected = tabSetting.Protected;
1352 tab.Notify = tabSetting.Notify;
1353 tab.SoundFile = tabSetting.SoundFile;
1355 if (tab.IsDistributableTabType)
1357 var filterTab = (FilterTabModel)tab;
1358 filterTab.FilterArray = tabSetting.FilterArray;
1359 filterTab.FilterModified = false;
1362 if (this._statuses.ContainsTab(tab.TabName))
1363 tab.TabName = this._statuses.MakeTabName("MyTab");
1365 this._statuses.AddTab(tab);
1367 if (_statuses.Tabs.Count == 0)
1369 _statuses.AddTab(new HomeTabModel());
1370 _statuses.AddTab(new MentionsTabModel());
1371 _statuses.AddTab(new DirectMessagesTabModel());
1372 _statuses.AddTab(new FavoritesTabModel());
1376 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
1380 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1381 var newTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), interval);
1382 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1386 this.RefreshTimelineScheduler();
1389 private void RefreshTimelineScheduler()
1391 static TimeSpan intervalSecondsOrDisabled(int seconds)
1392 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
1394 this.timelineScheduler.UpdateIntervalHome = intervalSecondsOrDisabled(SettingManager.Common.TimelinePeriod);
1395 this.timelineScheduler.UpdateIntervalMention = intervalSecondsOrDisabled(SettingManager.Common.ReplyPeriod);
1396 this.timelineScheduler.UpdateIntervalDm = intervalSecondsOrDisabled(SettingManager.Common.DMPeriod);
1397 this.timelineScheduler.UpdateIntervalPublicSearch = intervalSecondsOrDisabled(SettingManager.Common.PubSearchPeriod);
1398 this.timelineScheduler.UpdateIntervalUser = intervalSecondsOrDisabled(SettingManager.Common.UserTimelinePeriod);
1399 this.timelineScheduler.UpdateIntervalList = intervalSecondsOrDisabled(SettingManager.Common.ListsPeriod);
1400 this.timelineScheduler.UpdateIntervalConfig = TimeSpan.FromHours(6);
1401 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
1403 this.timelineScheduler.RefreshSchedule();
1406 private void MarkSettingCommonModified()
1408 if (this.saveConfigDebouncer == null)
1411 this.ModifySettingCommon = true;
1412 this.saveConfigDebouncer.Call();
1415 private void MarkSettingLocalModified()
1417 if (this.saveConfigDebouncer == null)
1420 this.ModifySettingLocal = true;
1421 this.saveConfigDebouncer.Call();
1424 internal void MarkSettingAtIdModified()
1426 if (this.saveConfigDebouncer == null)
1429 this.ModifySettingAtId = true;
1430 this.saveConfigDebouncer.Call();
1433 private void RefreshTimeline()
1435 var curTabModel = this.CurrentTab;
1436 var curListView = this.CurrentListView;
1438 // 現在表示中のタブのスクロール位置を退避
1439 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1441 // 各タブのリスト上の選択位置などを退避
1442 var listSelections = this.SaveListViewSelection();
1446 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1447 out var newMentionOrDm, out var isDelete);
1449 if (MyCommon._endingFlag) return;
1452 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1454 var tabPage = this.ListTab.TabPages[index];
1455 var listView = (DetailsListView)tabPage.Tag;
1457 if (listView.VirtualListSize != tab.AllCount || isDelete)
1459 using (ControlTransaction.Update(listView))
1461 if (listView == curListView)
1462 this.PurgeListViewItemCache();
1467 listView.VirtualListSize = tab.AllCount;
1469 catch (NullReferenceException ex)
1471 // WinForms 内部で ListView.set_TopItem が発生させている例外
1472 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1473 MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1477 this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1484 if (SettingManager.Common.TabIconDisp)
1486 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1488 var tabPage = this.ListTab.TabPages[index];
1489 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1490 tabPage.ImageIndex = 0; // 未読アイコン
1495 this.ListTab.Refresh();
1500 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1503 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1505 SetMainWindowTitle();
1506 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1508 HashSupl.AddRangeItem(tw.GetHashList());
1512 internal struct ListViewScroll
1514 public ScrollLockMode ScrollLockMode { get; set; }
1515 public long? TopItemStatusId { get; set; }
1518 internal enum ScrollLockMode
1520 /// <summary>固定しない</summary>
1523 /// <summary>最上部に固定する</summary>
1526 /// <summary>最下部に固定する</summary>
1529 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1534 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1536 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1538 var listScroll = new ListViewScroll
1540 ScrollLockMode = this.GetScrollLockMode(listView),
1543 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1545 var topItemIndex = listView.TopItem?.Index ?? -1;
1546 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1547 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1553 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1555 if (this._statuses.SortMode == ComparerMode.Id)
1557 if (this._statuses.SortOrder == SortOrder.Ascending)
1560 if (this.ListLockMenuItem.Checked)
1561 return ScrollLockMode.None;
1563 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1566 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1567 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1568 return ScrollLockMode.FixedToBottom;
1570 return ScrollLockMode.None;
1575 if (this.ListLockMenuItem.Checked)
1576 return ScrollLockMode.FixedToItem;
1578 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1579 var topItem = listView.TopItem;
1580 if (topItem == null || topItem.Index == 0)
1581 return ScrollLockMode.FixedToTop;
1583 return ScrollLockMode.FixedToItem;
1588 return ScrollLockMode.FixedToItem;
1592 internal struct ListViewSelection
1594 public long[]? SelectedStatusIds { get; set; }
1595 public long? SelectionMarkStatusId { get; set; }
1596 public long? FocusedStatusId { get; set; }
1600 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1602 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1604 var listsDict = new Dictionary<string, ListViewSelection>();
1606 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1608 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1609 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1616 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1618 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1620 if (listView.VirtualListSize == 0)
1622 return new ListViewSelection
1624 SelectedStatusIds = Array.Empty<long>(),
1625 SelectionMarkStatusId = null,
1626 FocusedStatusId = null,
1630 return new ListViewSelection
1632 SelectedStatusIds = tab.SelectedStatusIds,
1633 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1634 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1638 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1640 var index = listView.FocusedItem?.Index ?? -1;
1642 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1645 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1647 var index = listView.SelectionMark;
1649 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1653 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1655 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1657 if (listView.VirtualListSize == 0)
1660 switch (listScroll.ScrollLockMode)
1662 case ScrollLockMode.FixedToTop:
1663 listView.EnsureVisible(0);
1665 case ScrollLockMode.FixedToBottom:
1666 listView.EnsureVisible(listView.VirtualListSize - 1);
1668 case ScrollLockMode.FixedToItem:
1669 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1672 var topItem = listView.Items[topIndex];
1675 listView.TopItem = topItem;
1677 catch (NullReferenceException)
1679 listView.EnsureVisible(listView.VirtualListSize - 1);
1680 listView.EnsureVisible(topIndex);
1684 case ScrollLockMode.None:
1691 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1693 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1695 // status_id から ListView 上のインデックスに変換
1696 int[]? selectedIndices = null;
1697 if (listSelection.SelectedStatusIds != null)
1698 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1700 var focusedIndex = -1;
1701 if (listSelection.FocusedStatusId != null)
1702 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1704 var selectionMarkIndex = -1;
1705 if (listSelection.SelectionMarkStatusId != null)
1706 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1708 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1711 private bool BalloonRequired()
1713 var ev = new Twitter.FormattedEvent
1715 Eventtype = MyCommon.EVENTTYPE.None,
1718 return BalloonRequired(ev);
1721 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1723 if (type == MyCommon.EVENTTYPE.None)
1726 if (!SettingManager.Common.EventNotifyEnabled)
1729 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1732 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1737 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1740 private bool BalloonRequired(Twitter.FormattedEvent ev)
1745 if (NativeMethods.IsScreenSaverRunning())
1749 if (!this.NewPostPopMenuItem.Checked)
1751 // 「新着通知が無効でもイベントを通知する」にも該当しない
1752 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1756 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1757 if (SettingManager.Common.LimitBalloon)
1759 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1763 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1766 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1768 if (SettingManager.Common.ReadOwnPost)
1770 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1775 if (BalloonRequired())
1777 if (notifyPosts != null && notifyPosts.Length > 0)
1779 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1780 if (SettingManager.Common.IsUseNotifyGrowl)
1782 var sb = new StringBuilder();
1786 foreach (var post in notifyPosts)
1788 if (!(notifyPosts.Length > 3))
1794 if (post.IsReply && !post.IsExcludeReply) reply = true;
1795 if (post.IsDm) dm = true;
1796 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1797 switch (SettingManager.Common.NameBalloon)
1799 case MyCommon.NameBalloonEnum.UserID:
1800 sb.Append(post.ScreenName).Append(" : ");
1802 case MyCommon.NameBalloonEnum.NickName:
1803 sb.Append(post.Nickname).Append(" : ");
1806 sb.Append(post.TextFromApi);
1807 if (notifyPosts.Length > 3)
1809 if (notifyPosts.Last() != post) continue;
1812 var title = new StringBuilder();
1813 GrowlHelper.NotifyType nt;
1814 if (SettingManager.Common.DispUsername)
1816 title.Append(tw.Username);
1817 title.Append(" - ");
1822 title.Append(ApplicationSettings.ApplicationName);
1823 title.Append(" [DM] ");
1824 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1825 nt = GrowlHelper.NotifyType.DirectMessage;
1829 title.Append(ApplicationSettings.ApplicationName);
1830 title.Append(" [Reply!] ");
1831 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1832 nt = GrowlHelper.NotifyType.Reply;
1836 title.Append(ApplicationSettings.ApplicationName);
1838 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1839 nt = GrowlHelper.NotifyType.Notify;
1841 var bText = sb.ToString();
1842 if (MyCommon.IsNullOrEmpty(bText)) return;
1844 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1845 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1850 var sb = new StringBuilder();
1853 foreach (var post in notifyPosts)
1855 if (post.IsReply && !post.IsExcludeReply) reply = true;
1856 if (post.IsDm) dm = true;
1857 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1858 switch (SettingManager.Common.NameBalloon)
1860 case MyCommon.NameBalloonEnum.UserID:
1861 sb.Append(post.ScreenName).Append(" : ");
1863 case MyCommon.NameBalloonEnum.NickName:
1864 sb.Append(post.Nickname).Append(" : ");
1867 sb.Append(post.TextFromApi);
1871 var title = new StringBuilder();
1873 if (SettingManager.Common.DispUsername)
1875 title.Append(tw.Username);
1876 title.Append(" - ");
1881 ntIcon = ToolTipIcon.Warning;
1882 title.Append(ApplicationSettings.ApplicationName);
1883 title.Append(" [DM] ");
1884 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1888 ntIcon = ToolTipIcon.Warning;
1889 title.Append(ApplicationSettings.ApplicationName);
1890 title.Append(" [Reply!] ");
1891 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1895 ntIcon = ToolTipIcon.Info;
1896 title.Append(ApplicationSettings.ApplicationName);
1898 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1900 var bText = sb.ToString();
1901 if (MyCommon.IsNullOrEmpty(bText)) return;
1903 NotifyIcon1.BalloonTipTitle = title.ToString();
1904 NotifyIcon1.BalloonTipText = bText;
1905 NotifyIcon1.BalloonTipIcon = ntIcon;
1906 NotifyIcon1.ShowBalloonTip(500);
1912 if (!_initial && SettingManager.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1916 var dir = Application.StartupPath;
1917 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1919 dir = Path.Combine(dir, "Sounds");
1921 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1929 //mentions新着時に画面ブリンク
1930 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1932 NativeMethods.FlashMyWindow(this.Handle, 3);
1936 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1938 var listView = this.CurrentListView;
1939 if (listView != sender)
1942 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1943 this.CurrentTab.SelectPosts(indices);
1945 if (listView.SelectedIndices.Count != 1)
1948 var index = listView.SelectedIndices[0];
1949 if (index > listView.VirtualListSize - 1) return;
1951 this.PushSelectPostChain();
1953 var post = this.CurrentPost!;
1954 this._statuses.SetReadAllTab(post.StatusId, read: true);
1957 ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1959 this.ColorizeList();
1960 this.selectionDebouncer.Call();
1963 private void ChangeCacheStyleRead(bool Read, int Index)
1965 var tabInfo = this.CurrentTab;
1966 //Read:true=既読 false=未読
1967 //未読管理していなかったら既読として扱う
1968 if (!tabInfo.UnreadManage ||
1969 !SettingManager.Common.UnreadManage) Read = true;
1971 var listCache = this._listItemCache;
1972 if (listCache == null)
1975 // キャッシュに含まれていないアイテムは対象外
1976 if (!listCache.TryGetValue(Index, out var itm, out var post))
1979 ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
1982 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView? DList)
1997 if (Item.SubItems[5].Text != star)
1998 Item.SubItems[5].Text = star;
2004 else if (Post.RetweetedId != null)
2006 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
2008 else if (Read || !SettingManager.Common.UseUnreadStyle)
2013 if (DList == null || Item.Index == -1)
2015 Item.ForeColor = cl;
2016 if (SettingManager.Common.UseUnreadStyle)
2022 if (SettingManager.Common.UseUnreadStyle)
2023 DList.ChangeItemFontAndColor(Item, cl, fnt);
2025 DList.ChangeItemForeColor(Item, cl);
2029 private void ColorizeList()
2031 //Index:更新対象のListviewItem.Index。Colorを返す。
2032 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2035 _post = _anchorPost;
2037 _post = this.CurrentPost;
2039 if (_post == null) return;
2041 var listCache = this._listItemCache;
2042 if (listCache == null)
2045 var listView = (DetailsListView)listCache.TargetList;
2047 // ValidateRectが呼ばれる前に選択色などの描画を済ませておく
2050 foreach (var (listViewItem, cachedPost) in listCache.Cache)
2052 var backColor = this.JudgeColor(_post, cachedPost);
2053 listView.ChangeItemBackColor(listViewItem, backColor);
2057 private void ColorizeList(ListViewItem Item, PostClass post)
2059 //Index:更新対象のListviewItem.Index。Colorを返す。
2060 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2063 _post = _anchorPost;
2065 _post = this.CurrentPost;
2067 if (_post == null) return;
2069 if (Item.Index == -1)
2070 Item.BackColor = JudgeColor(_post, post);
2072 this.CurrentListView.ChangeItemBackColor(Item, JudgeColor(_post, post));
2075 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2078 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2081 else if (TargetPost.IsMe)
2084 else if (TargetPost.IsReply)
2087 else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2089 cl = _clAtFromTarget;
2090 else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2093 else if (TargetPost.UserId == BasePost.UserId)
2098 cl = _clListBackcolor;
2103 private void StatusTextHistoryBack()
2105 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2106 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2109 if (this._hisIdx < 0)
2112 var historyItem = this._history[this._hisIdx];
2113 this.inReplyTo = historyItem.inReplyTo;
2114 this.StatusText.Text = historyItem.status;
2115 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2118 private void StatusTextHistoryForward()
2120 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2121 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2124 if (this._hisIdx > this._history.Count - 1)
2125 this._hisIdx = this._history.Count - 1;
2127 var historyItem = this._history[this._hisIdx];
2128 this.inReplyTo = historyItem.inReplyTo;
2129 this.StatusText.Text = historyItem.status;
2130 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2133 private async void PostButton_Click(object sender, EventArgs e)
2135 if (StatusText.Text.Trim().Length == 0)
2137 if (!ImageSelector.Enabled)
2139 await this.DoRefresh();
2144 var currentPost = this.CurrentPost;
2145 if (this.ExistCurrentPost && currentPost != null && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2147 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2149 MessageBoxButtons.YesNoCancel,
2150 MessageBoxIcon.Question);
2153 case DialogResult.Yes:
2154 StatusText.Text = "";
2155 await this.doReTweetOfficial(false);
2157 case DialogResult.Cancel:
2162 if (TextContainsOnlyMentions(this.StatusText.Text))
2164 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2165 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2167 if (ret != DialogResult.OK)
2171 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2173 if (SettingManager.Common.Nicoms)
2175 StatusText.SelectionStart = StatusText.Text.Length;
2176 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2179 StatusText.SelectionStart = StatusText.Text.Length;
2180 CheckReplyTo(StatusText.Text);
2182 var status = new PostStatusParams();
2184 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2185 if (this.GetRestStatusCount(statusTextCompat) >= 0)
2187 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2188 // 収まる場合はこれらのオプションを使用せずに投稿する
2189 status.Text = statusTextCompat;
2190 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2194 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2195 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2197 status.AttachmentUrl = attachmentUrl;
2199 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2201 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2202 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2204 status.AutoPopulateReplyMetadata = true;
2206 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2207 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2212 if (this.GetRestStatusCount(status.Text) < 0)
2214 // 文字数制限を超えているが強制的に投稿するか
2215 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2216 if (ret != DialogResult.OK)
2220 IMediaUploadService? uploadService = null;
2221 IMediaItem[]? uploadItems = null;
2222 if (ImageSelector.Visible)
2225 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2228 uploadService = this.ImageSelector.GetService(serviceName);
2231 this.inReplyTo = null;
2232 StatusText.Text = "";
2233 _history.Add(new StatusTextHistory());
2234 _hisIdx = _history.Count - 1;
2235 if (!SettingManager.Common.FocusLockToStatusText)
2236 this.CurrentListView.Focus();
2237 urlUndoBuffer = null;
2238 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2241 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2243 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2244 await this.OpenUriInBrowserAsync(tmp);
2247 await this.PostMessageAsync(status, uploadService, uploadItems);
2250 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2252 MyCommon._endingFlag = true;
2256 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2258 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2260 //_endingFlag=false:フォームの×ボタン
2262 this.Visible = false;
2266 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2267 _ignoreConfigSave = true;
2268 MyCommon._endingFlag = true;
2269 this.timelineScheduler.Enabled = false;
2270 TimerRefreshIcon.Enabled = false;
2274 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2276 this.Visible = true;
2277 if (this.WindowState == FormWindowState.Minimized)
2279 this.WindowState = FormWindowState.Normal;
2282 this.BringToFront();
2285 private static int errorCount = 0;
2287 private static bool CheckAccountValid()
2289 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2295 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2304 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2305 private Task RefreshTabAsync<T>() where T : TabModel
2306 => this.RefreshTabAsync<T>(backward: false);
2308 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2309 private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2312 from tab in this._statuses.GetTabsByType<T>()
2313 select this.RefreshTabAsync(tab, backward);
2315 return Task.WhenAll(loadTasks);
2318 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2319 private Task RefreshTabAsync(TabModel tab)
2320 => this.RefreshTabAsync(tab, backward: false);
2322 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2323 private async Task RefreshTabAsync(TabModel tab, bool backward)
2325 await this.workerSemaphore.WaitAsync();
2329 this.RefreshTasktrayIcon();
2330 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2331 this.RefreshTimeline();
2333 catch (WebApiException ex)
2335 this._myStatusError = true;
2336 var tabType = tab switch
2338 HomeTabModel _ => "GetTimeline",
2339 MentionsTabModel _ => "GetTimeline",
2340 DirectMessagesTabModel _ => "GetDirectMessage",
2341 FavoritesTabModel _ => "GetFavorites",
2342 PublicSearchTabModel _ => "GetSearch",
2343 UserTimelineTabModel _ => "GetUserTimeline",
2344 ListTimelineTabModel _ => "GetListStatus",
2345 RelatedPostsTabModel _ => "GetRelatedTweets",
2346 _ => tab.GetType().Name.Replace("Model", ""),
2348 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2352 this.workerSemaphore.Release();
2356 private async Task FavAddAsync(long statusId, TabModel tab)
2358 await this.workerSemaphore.WaitAsync();
2362 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2364 this.RefreshTasktrayIcon();
2365 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2367 catch (WebApiException ex)
2369 this._myStatusError = true;
2370 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2374 this.workerSemaphore.Release();
2378 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2380 if (ct.IsCancellationRequested)
2383 if (!CheckAccountValid())
2384 throw new WebApiException("Auth error. Check your account");
2386 if (!tab.Posts.TryGetValue(statusId, out var post))
2392 await Task.Run(async () =>
2394 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2400 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2402 .ConfigureAwait(false);
2404 catch (TwitterApiException ex)
2405 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2407 // エラーコード 139 のみの場合は成功と見なす
2410 if (SettingManager.Common.RestrictFavCheck)
2412 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2413 .ConfigureAwait(false);
2415 if (status.Favorited != true)
2416 throw new WebApiException("NG(Restricted?)");
2419 this._favTimestamps.Add(DateTimeUtc.Now);
2422 if (this._statuses.Posts.TryGetValue(statusId, out var postTl))
2424 postTl.IsFav = true;
2426 var favTab = this._statuses.FavoriteTab;
2427 favTab.AddPostQueue(postTl);
2430 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2431 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2433 if (tb.Contains(statusId))
2434 tb.Posts[statusId].IsFav = true;
2437 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2439 catch (WebApiException)
2441 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2446 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2447 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2449 if (this._favTimestamps[i] < oneHour)
2450 this._favTimestamps.RemoveAt(i);
2453 this._statuses.DistributePosts();
2456 if (ct.IsCancellationRequested)
2459 this.RefreshTimeline();
2461 if (this.CurrentTabName == tab.TabName)
2463 using (ControlTransaction.Update(this.CurrentListView))
2465 var idx = tab.IndexOf(statusId);
2467 this.ChangeCacheStyleRead(post.IsRead, idx);
2470 var currentPost = this.CurrentPost;
2471 if (currentPost != null && statusId == currentPost.StatusId)
2472 this.DispSelectedPost(true); // 選択アイテム再表示
2476 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2478 await this.workerSemaphore.WaitAsync();
2482 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2484 this.RefreshTasktrayIcon();
2485 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2487 catch (WebApiException ex)
2489 this._myStatusError = true;
2490 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2494 this.workerSemaphore.Release();
2498 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2500 if (ct.IsCancellationRequested)
2503 if (!CheckAccountValid())
2504 throw new WebApiException("Auth error. Check your account");
2506 var successIds = new List<long>();
2508 await Task.Run(async () =>
2512 var failedCount = 0;
2513 foreach (var statusId in statusIds)
2517 var post = tab.Posts[statusId];
2519 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2526 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2528 .ConfigureAwait(false);
2530 catch (WebApiException)
2536 successIds.Add(statusId);
2537 post.IsFav = false; // リスト再描画必要
2539 if (this._statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
2540 tabinfoPost.IsFav = false;
2542 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2543 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2545 if (tb.Contains(statusId))
2546 tb.Posts[statusId].IsFav = false;
2551 if (ct.IsCancellationRequested)
2554 var favTab = this._statuses.FavoriteTab;
2555 foreach (var statusId in successIds)
2557 // ツイートが削除された訳ではないので IsDeleted はセットしない
2558 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2561 this.RefreshTimeline();
2563 if (this.CurrentTabName == tab.TabName)
2565 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2571 using (ControlTransaction.Update(this.CurrentListView))
2573 foreach (var statusId in successIds)
2575 var idx = tab.IndexOf(statusId);
2579 var post = tab.Posts[statusId];
2580 this.ChangeCacheStyleRead(post.IsRead, idx);
2584 var currentPost = this.CurrentPost;
2585 if (currentPost != null && successIds.Contains(currentPost.StatusId))
2586 this.DispSelectedPost(true); // 選択アイテム再表示
2591 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2593 await this.workerSemaphore.WaitAsync();
2597 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2599 this.RefreshTasktrayIcon();
2600 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2602 catch (WebApiException ex)
2604 this._myStatusError = true;
2605 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2609 this.workerSemaphore.Release();
2613 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2614 IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
2616 if (ct.IsCancellationRequested)
2619 if (!CheckAccountValid())
2620 throw new WebApiException("Auth error. Check your account");
2622 p.Report("Posting...");
2624 PostClass? post = null;
2629 await Task.Run(async () =>
2631 var postParamsWithMedia = postParams;
2633 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2635 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2636 .ConfigureAwait(false);
2639 post = await this.tw.PostStatus(postParamsWithMedia)
2640 .ConfigureAwait(false);
2643 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2645 catch (WebApiException ex)
2647 // 処理は中断せずエラーの表示のみ行う
2648 errMsg = $"Err:{ex.Message}(PostMessage)";
2650 this._myStatusError = true;
2652 catch (UnauthorizedAccessException ex)
2654 // アップロード対象のファイルが開けなかった場合など
2655 errMsg = $"Err:{ex.Message}(PostMessage)";
2657 this._myStatusError = true;
2661 // 使い終わった MediaItem は破棄する
2662 if (uploadItems != null)
2664 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2666 disposableItem.Dispose();
2671 if (ct.IsCancellationRequested)
2674 if (!MyCommon.IsNullOrEmpty(errMsg) &&
2675 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2676 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2678 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2680 var ret = MessageBox.Show(
2682 "Failed to update status",
2683 MessageBoxButtons.RetryCancel,
2684 MessageBoxIcon.Question);
2686 if (ret == DialogResult.Retry)
2688 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2692 this.StatusTextHistoryBack();
2693 this.StatusText.Focus();
2695 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2696 if (SettingManager.Common.FocusLockToStatusText)
2697 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2702 this._postTimestamps.Add(DateTimeUtc.Now);
2704 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2705 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2707 if (this._postTimestamps[i] < oneHour)
2708 this._postTimestamps.RemoveAt(i);
2711 if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
2713 this.HashMgr.ClearHashtag();
2714 this.HashStripSplitButton.Text = "#[-]";
2715 this.HashTogglePullDownMenuItem.Checked = false;
2716 this.HashToggleMenuItem.Checked = false;
2719 this.SetMainWindowTitle();
2722 if (!this.tw.UserStreamActive)
2724 if (SettingManager.Common.PostAndGet)
2725 await this.RefreshTabAsync<HomeTabModel>();
2730 this._statuses.AddPost(post);
2731 this._statuses.DistributePosts();
2733 this.RefreshTimeline();
2738 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2740 await this.workerSemaphore.WaitAsync();
2744 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2746 this.RefreshTasktrayIcon();
2747 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2749 catch (WebApiException ex)
2751 this._myStatusError = true;
2752 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2756 this.workerSemaphore.Release();
2760 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2762 if (ct.IsCancellationRequested)
2765 if (!CheckAccountValid())
2766 throw new WebApiException("Auth error. Check your account");
2769 if (!SettingManager.Common.UnreadManage)
2772 read = this._initial && SettingManager.Common.Read;
2774 p.Report("Posting...");
2776 var posts = new List<PostClass>();
2778 await Task.Run(async () =>
2780 foreach (var statusId in statusIds)
2782 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2783 if (post != null) posts.Add(post);
2787 if (ct.IsCancellationRequested)
2790 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2792 this._postTimestamps.Add(DateTimeUtc.Now);
2794 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2795 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2797 if (this._postTimestamps[i] < oneHour)
2798 this._postTimestamps.RemoveAt(i);
2802 if (!this.tw.UserStreamActive)
2804 // 自分のRTはTLの更新では取得できない場合があるので、
2805 // 投稿時取得の有無に関わらず追加しておく
2806 posts.ForEach(post => this._statuses.AddPost(post));
2808 if (SettingManager.Common.PostAndGet)
2809 await this.RefreshTabAsync<HomeTabModel>();
2812 this._statuses.DistributePosts();
2813 this.RefreshTimeline();
2818 private async Task RefreshFollowerIdsAsync()
2820 await this.workerSemaphore.WaitAsync();
2824 this.RefreshTasktrayIcon();
2825 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2827 await this.tw.RefreshFollowerIds();
2829 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2831 this.RefreshTimeline();
2832 this.PurgeListViewItemCache();
2833 this.CurrentListView.Refresh();
2835 catch (WebApiException ex)
2837 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2841 this.workerSemaphore.Release();
2845 private async Task RefreshNoRetweetIdsAsync()
2847 await this.workerSemaphore.WaitAsync();
2851 this.RefreshTasktrayIcon();
2852 await this.tw.RefreshNoRetweetIds();
2854 this.StatusLabel.Text = "NoRetweetIds refreshed";
2856 catch (WebApiException ex)
2858 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2862 this.workerSemaphore.Release();
2866 private async Task RefreshBlockIdsAsync()
2868 await this.workerSemaphore.WaitAsync();
2872 this.RefreshTasktrayIcon();
2873 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2875 await this.tw.RefreshBlockIds();
2877 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2879 catch (WebApiException ex)
2881 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2885 this.workerSemaphore.Release();
2889 private async Task RefreshTwitterConfigurationAsync()
2891 await this.workerSemaphore.WaitAsync();
2895 this.RefreshTasktrayIcon();
2896 await this.tw.RefreshConfiguration();
2898 if (this.tw.Configuration.PhotoSizeLimit != 0)
2900 foreach (var service in this.ImageSelector.GetServices())
2902 service.UpdateTwitterConfiguration(this.tw.Configuration);
2906 this.PurgeListViewItemCache();
2907 this.CurrentListView.Refresh();
2909 catch (WebApiException ex)
2911 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2915 this.workerSemaphore.Release();
2919 private async Task RefreshMuteUserIdsAsync()
2921 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2925 await tw.RefreshMuteUserIdsAsync();
2927 catch (WebApiException ex)
2929 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2933 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
2936 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
2938 if (e.Button == MouseButtons.Left)
2940 this.Visible = true;
2941 if (this.WindowState == FormWindowState.Minimized)
2943 this.WindowState = _formWindowState;
2946 this.BringToFront();
2950 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
2952 switch (SettingManager.Common.ListDoubleClickAction)
2955 MakeReplyOrDirectStatus();
2958 await this.FavoriteChange(true);
2961 var post = this.CurrentPost;
2963 await this.ShowUserStatus(post.ScreenName, false);
2966 await ShowUserTimeline();
2969 ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
2972 MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty);
2975 StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
2983 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
2984 => await this.FavoriteChange(true);
2986 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
2987 => await this.FavoriteChange(false);
2990 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
2991 => await this.FavoritesRetweetOfficial();
2993 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
2994 => await this.FavoritesRetweetUnofficial();
2996 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
2998 var tab = this.CurrentTab;
2999 var posts = tab.SelectedPosts;
3001 //trueでFavAdd,falseでFavRemove
3002 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
3003 || !this.ExistCurrentPost) return;
3005 if (posts.Length > 1)
3010 // https://support.twitter.com/articles/76915#favoriting
3011 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3012 _DoFavRetweetFlags = false;
3017 if (multiFavoriteChangeDialogEnable)
3019 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3020 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3021 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3023 if (confirm == DialogResult.Cancel)
3031 var selectedPost = posts.Single();
3032 if (selectedPost.IsFav)
3034 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3038 await this.FavAddAsync(selectedPost.StatusId, tab);
3042 var selectedPosts = posts.Where(x => x.IsFav);
3043 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3044 if (statusIds.Length == 0)
3046 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3050 await this.FavRemoveAsync(statusIds, tab);
3054 private PostClass GetCurTabPost(int Index)
3056 var listCache = this._listItemCache;
3057 if (listCache != null)
3059 if (listCache.TryGetValue(Index, out _, out var post))
3063 return this.CurrentTab[Index];
3066 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3068 var post = this.CurrentPost;
3070 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3072 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3075 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3077 var post = this.CurrentPost;
3079 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3082 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3084 if ((!_initialLayout) && this.Visible)
3086 if (this.WindowState == FormWindowState.Normal)
3088 _mySize = this.ClientSize;
3089 _mySpDis = this.SplitContainer1.SplitterDistance;
3090 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3091 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3092 this.MarkSettingLocalModified();
3097 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3099 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3100 if (comparerMode == null)
3103 this.SetSortColumn(comparerMode.Value);
3107 /// 列インデックスからソートを行う ComparerMode を求める
3109 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3110 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3111 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3114 return ComparerMode.Id;
3116 return columnIndex switch
3118 1 => ComparerMode.Nickname, // ニックネーム
3119 2 => ComparerMode.Data, // 本文
3120 3 => ComparerMode.Id, // 時刻=発言Id
3121 4 => ComparerMode.Name, // 名前
3122 7 => ComparerMode.Source, // Source
3123 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3128 /// 発言一覧の指定した位置の列でソートする
3130 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3131 private void SetSortColumnByDisplayIndex(int columnIndex)
3133 // 表示上の列の位置から ColumnHeader を求める
3134 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3135 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3140 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3141 if (comparerMode == null)
3144 this.SetSortColumn(comparerMode.Value);
3148 /// 発言一覧の最後列の項目でソートする
3150 private void SetSortLastColumn()
3152 // 表示上の最後列にある ColumnHeader を求める
3153 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3154 .OrderByDescending(x => x.DisplayIndex)
3157 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3158 if (comparerMode == null)
3161 this.SetSortColumn(comparerMode.Value);
3165 /// 発言一覧を指定された ComparerMode に基づいてソートする
3167 private void SetSortColumn(ComparerMode sortColumn)
3169 if (SettingManager.Common.SortOrderLock)
3172 this._statuses.ToggleSortOrder(sortColumn);
3173 this.InitColumnText();
3175 var list = this.CurrentListView;
3178 list.Columns[0].Text = this.ColumnText[0];
3179 list.Columns[1].Text = this.ColumnText[2];
3183 for (var i = 0; i <= 7; i++)
3185 list.Columns[i].Text = this.ColumnText[i];
3189 this.PurgeListViewItemCache();
3191 var tab = this.CurrentTab;
3192 var post = this.CurrentPost;
3193 if (tab.AllCount > 0 && post != null)
3195 var idx = tab.IndexOf(post.StatusId);
3198 this.SelectListItem(list, idx);
3199 list.EnsureVisible(idx);
3204 this.MarkSettingCommonModified();
3207 private void TweenMain_LocationChanged(object sender, EventArgs e)
3209 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3211 _myLoc = this.DesktopLocation;
3212 this.MarkSettingLocalModified();
3216 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3218 if (!this.ExistCurrentPost)
3220 ReplyStripMenuItem.Enabled = false;
3221 ReplyAllStripMenuItem.Enabled = false;
3222 DMStripMenuItem.Enabled = false;
3223 ShowProfileMenuItem.Enabled = false;
3224 ShowUserTimelineContextMenuItem.Enabled = false;
3225 ListManageUserContextToolStripMenuItem2.Enabled = false;
3226 MoveToFavToolStripMenuItem.Enabled = false;
3227 TabMenuItem.Enabled = false;
3228 IDRuleMenuItem.Enabled = false;
3229 SourceRuleMenuItem.Enabled = false;
3230 ReadedStripMenuItem.Enabled = false;
3231 UnreadStripMenuItem.Enabled = false;
3235 ShowProfileMenuItem.Enabled = true;
3236 ListManageUserContextToolStripMenuItem2.Enabled = true;
3237 ReplyStripMenuItem.Enabled = true;
3238 ReplyAllStripMenuItem.Enabled = true;
3239 DMStripMenuItem.Enabled = true;
3240 ShowUserTimelineContextMenuItem.Enabled = true;
3241 MoveToFavToolStripMenuItem.Enabled = true;
3242 TabMenuItem.Enabled = true;
3243 IDRuleMenuItem.Enabled = true;
3244 SourceRuleMenuItem.Enabled = true;
3245 ReadedStripMenuItem.Enabled = true;
3246 UnreadStripMenuItem.Enabled = true;
3248 var tab = this.CurrentTab;
3249 var post = this.CurrentPost;
3250 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
3252 FavAddToolStripMenuItem.Enabled = false;
3253 FavRemoveToolStripMenuItem.Enabled = false;
3254 StatusOpenMenuItem.Enabled = false;
3255 ShowRelatedStatusesMenuItem.Enabled = false;
3257 ReTweetStripMenuItem.Enabled = false;
3258 ReTweetUnofficialStripMenuItem.Enabled = false;
3259 QuoteStripMenuItem.Enabled = false;
3260 FavoriteRetweetContextMenu.Enabled = false;
3261 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3265 FavAddToolStripMenuItem.Enabled = true;
3266 FavRemoveToolStripMenuItem.Enabled = true;
3267 StatusOpenMenuItem.Enabled = true;
3268 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3270 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3272 ReTweetStripMenuItem.Enabled = false;
3273 ReTweetUnofficialStripMenuItem.Enabled = false;
3274 QuoteStripMenuItem.Enabled = false;
3275 FavoriteRetweetContextMenu.Enabled = false;
3276 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3280 ReTweetStripMenuItem.Enabled = true;
3281 ReTweetUnofficialStripMenuItem.Enabled = true;
3282 QuoteStripMenuItem.Enabled = true;
3283 FavoriteRetweetContextMenu.Enabled = true;
3284 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3288 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
3290 RepliedStatusOpenMenuItem.Enabled = false;
3294 RepliedStatusOpenMenuItem.Enabled = true;
3296 if (!this.ExistCurrentPost || post == null || MyCommon.IsNullOrEmpty(post.RetweetedBy))
3298 MoveToRTHomeMenuItem.Enabled = false;
3302 MoveToRTHomeMenuItem.Enabled = true;
3305 if (this.ExistCurrentPost && post != null)
3307 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3308 if (post.RetweetedByUserId == this.tw.UserId)
3309 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3311 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3315 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3316 => this.MakeReplyOrDirectStatus(false, true);
3318 private void DMStripMenuItem_Click(object sender, EventArgs e)
3319 => this.MakeReplyOrDirectStatus(false, false);
3321 private async Task doStatusDelete()
3323 var posts = this.CurrentTab.SelectedPosts;
3324 if (posts.Length == 0)
3327 // 選択されたツイートの中に削除可能なものが一つでもあるか
3328 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3331 var ret = MessageBox.Show(this,
3332 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3333 Properties.Resources.DeleteStripMenuItem_ClickText2,
3334 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3336 if (ret != DialogResult.OK)
3339 var currentListView = this.CurrentListView;
3340 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3342 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3344 Exception? lastException = null;
3345 foreach (var post in posts)
3347 if (!post.CanDeleteBy(this.tw.UserId))
3354 await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3358 if (post.RetweetedByUserId == this.tw.UserId)
3360 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3362 await this.twitterApi.StatusesDestroy(post.StatusId)
3367 if (post.UserId == this.tw.UserId)
3369 if (post.RetweetedId != null)
3370 // 他人に RT された自分のツイート
3371 // => RT 元の自分のツイートを削除
3372 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3377 await this.twitterApi.StatusesDestroy(post.StatusId)
3383 catch (WebApiException ex)
3389 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3392 if (lastException == null)
3393 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3395 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3397 this.PurgeListViewItemCache();
3399 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3401 var tabPage = this.ListTab.TabPages[index];
3402 var listView = (DetailsListView)tabPage.Tag;
3404 using (ControlTransaction.Update(listView))
3406 listView.VirtualListSize = tab.AllCount;
3408 if (tab.TabName == this.CurrentTabName)
3410 listView.SelectedIndices.Clear();
3412 if (tab.AllCount != 0)
3415 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3416 selectedIndex = focusedIndex;
3418 selectedIndex = tab.AllCount - 1;
3420 listView.SelectedIndices.Add(selectedIndex);
3421 listView.EnsureVisible(selectedIndex);
3422 listView.FocusedItem = listView.Items[selectedIndex];
3427 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3429 if (tabPage.ImageIndex == 0)
3430 tabPage.ImageIndex = -1; // タブアイコン
3434 if (!SettingManager.Common.TabIconDisp)
3435 this.ListTab.Refresh();
3439 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3440 => await this.doStatusDelete();
3442 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3444 using (ControlTransaction.Update(this.CurrentListView))
3446 var tab = this.CurrentTab;
3447 foreach (var statusId in tab.SelectedStatusIds)
3449 this._statuses.SetReadAllTab(statusId, read: true);
3450 var idx = tab.IndexOf(statusId);
3451 ChangeCacheStyleRead(true, idx);
3455 if (SettingManager.Common.TabIconDisp)
3457 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3459 if (tab.UnreadCount == 0)
3461 var tabPage = this.ListTab.TabPages[index];
3462 if (tabPage.ImageIndex == 0)
3463 tabPage.ImageIndex = -1; // タブアイコン
3467 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3470 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3472 using (ControlTransaction.Update(this.CurrentListView))
3474 var tab = this.CurrentTab;
3475 foreach (var statusId in tab.SelectedStatusIds)
3477 this._statuses.SetReadAllTab(statusId, read: false);
3478 var idx = tab.IndexOf(statusId);
3479 ChangeCacheStyleRead(false, idx);
3483 if (SettingManager.Common.TabIconDisp)
3485 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3487 if (tab.UnreadCount > 0)
3489 var tabPage = this.ListTab.TabPages[index];
3490 if (tabPage.ImageIndex == -1)
3491 tabPage.ImageIndex = 0; // タブアイコン
3495 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3498 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3499 => await this.DoRefresh();
3501 private async Task DoRefresh()
3502 => await this.RefreshTabAsync(this.CurrentTab);
3504 private async Task DoRefreshMore()
3505 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3507 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3509 var result = DialogResult.Abort;
3511 using var settingDialog = new AppendSettingDialog();
3512 settingDialog.Icon = this.MainIcon;
3513 settingDialog.Owner = this;
3514 settingDialog.ShowInTaskbar = showTaskbarIcon;
3515 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3517 settingDialog.tw = this.tw;
3518 settingDialog.twitterApi = this.twitterApi;
3520 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3524 result = settingDialog.ShowDialog(this);
3528 return DialogResult.Abort;
3531 if (result == DialogResult.OK)
3535 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3542 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3545 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3547 var oldIconSz = SettingManager.Common.IconSize;
3549 if (ShowSettingDialog() == DialogResult.OK)
3553 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3554 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3555 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3556 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3557 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3558 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3559 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3561 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3562 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3563 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3564 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3565 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3566 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3568 ImageSelector.Reset(tw, this.tw.Configuration);
3572 if (SettingManager.Common.TabIconDisp)
3574 ListTab.DrawItem -= ListTab_DrawItem;
3575 ListTab.DrawMode = TabDrawMode.Normal;
3576 ListTab.ImageList = this.TabImage;
3580 ListTab.DrawItem -= ListTab_DrawItem;
3581 ListTab.DrawItem += ListTab_DrawItem;
3582 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3583 ListTab.ImageList = null;
3586 catch (Exception ex)
3588 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3589 ex.Data["IsTerminatePermission"] = false;
3595 if (!SettingManager.Common.UnreadManage)
3597 ReadedStripMenuItem.Enabled = false;
3598 UnreadStripMenuItem.Enabled = false;
3599 if (SettingManager.Common.TabIconDisp)
3601 foreach (TabPage myTab in ListTab.TabPages)
3603 myTab.ImageIndex = -1;
3609 ReadedStripMenuItem.Enabled = true;
3610 UnreadStripMenuItem.Enabled = true;
3613 catch (Exception ex)
3615 ex.Data["Instance"] = "ListTab(UnreadManage)";
3616 ex.Data["IsTerminatePermission"] = false;
3623 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3625 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3626 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3627 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3629 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3630 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3631 _fntUnread = SettingManager.Local.FontUnread;
3632 _clUnread = SettingManager.Local.ColorUnread;
3633 _fntReaded = SettingManager.Local.FontRead;
3634 _clReaded = SettingManager.Local.ColorRead;
3635 _clFav = SettingManager.Local.ColorFav;
3636 _clOWL = SettingManager.Local.ColorOWL;
3637 _clRetweet = SettingManager.Local.ColorRetweet;
3638 _fntDetail = SettingManager.Local.FontDetail;
3639 _clDetail = SettingManager.Local.ColorDetail;
3640 _clDetailLink = SettingManager.Local.ColorDetailLink;
3641 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3642 _clSelf = SettingManager.Local.ColorSelf;
3643 _clAtSelf = SettingManager.Local.ColorAtSelf;
3644 _clTarget = SettingManager.Local.ColorTarget;
3645 _clAtTarget = SettingManager.Local.ColorAtTarget;
3646 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3647 _clAtTo = SettingManager.Local.ColorAtTo;
3648 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3649 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3650 _clInputFont = SettingManager.Local.ColorInputFont;
3651 _fntInputFont = SettingManager.Local.FontInputFont;
3652 _brsBackColorMine.Dispose();
3653 _brsBackColorAt.Dispose();
3654 _brsBackColorYou.Dispose();
3655 _brsBackColorAtYou.Dispose();
3656 _brsBackColorAtFromTarget.Dispose();
3657 _brsBackColorAtTo.Dispose();
3658 _brsBackColorNone.Dispose();
3659 _brsBackColorMine = new SolidBrush(_clSelf);
3660 _brsBackColorAt = new SolidBrush(_clAtSelf);
3661 _brsBackColorYou = new SolidBrush(_clTarget);
3662 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3663 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3664 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3665 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3669 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3670 StatusText.Font = _fntInputFont;
3671 StatusText.ForeColor = _clInputFont;
3673 catch (Exception ex)
3675 MessageBox.Show(ex.Message);
3680 InitDetailHtmlFormat();
3682 catch (Exception ex)
3684 ex.Data["Instance"] = "Font";
3685 ex.Data["IsTerminatePermission"] = false;
3691 if (SettingManager.Common.TabIconDisp)
3693 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3695 var tabPage = this.ListTab.TabPages[index];
3696 if (tab.UnreadCount == 0)
3697 tabPage.ImageIndex = -1;
3699 tabPage.ImageIndex = 0;
3703 catch (Exception ex)
3705 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3706 ex.Data["IsTerminatePermission"] = false;
3712 var oldIconCol = _iconCol;
3714 if (SettingManager.Common.IconSize != oldIconSz)
3715 ApplyListViewIconSize(SettingManager.Common.IconSize);
3717 foreach (TabPage tp in ListTab.TabPages)
3719 var lst = (DetailsListView)tp.Tag;
3721 using (ControlTransaction.Update(lst))
3723 lst.GridLines = SettingManager.Common.ShowGrid;
3724 lst.Font = _fntReaded;
3725 lst.BackColor = _clListBackcolor;
3727 if (_iconCol != oldIconCol)
3732 catch (Exception ex)
3734 ex.Data["Instance"] = "ListView(IconSize)";
3735 ex.Data["IsTerminatePermission"] = false;
3739 SetMainWindowTitle();
3740 SetNotifyIconText();
3742 this.PurgeListViewItemCache();
3743 this.CurrentListView.Refresh();
3746 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3747 if (SettingManager.Common.HotkeyEnabled)
3749 ///グローバルホットキーの登録。設定で変更可能にするかも
3750 var modKey = HookGlobalHotkey.ModKeys.None;
3751 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3752 modKey |= HookGlobalHotkey.ModKeys.Alt;
3753 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3754 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3755 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3756 modKey |= HookGlobalHotkey.ModKeys.Shift;
3757 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3758 modKey |= HookGlobalHotkey.ModKeys.Win;
3760 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3763 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3766 StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3775 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3776 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3779 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3781 this.TopMost = SettingManager.Common.AlwaysTop;
3782 SaveConfigsAll(false);
3784 if (tw.UserId != oldUser.UserId)
3785 await this.doGetFollowersMenu();
3791 private void SetTabAlignment()
3793 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3794 if (ListTab.Alignment == newAlignment) return;
3796 // 各タブのリスト上の選択位置などを退避
3797 var listSelections = this.SaveListViewSelection();
3799 ListTab.Alignment = newAlignment;
3801 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3803 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3804 using (ControlTransaction.Update(lst))
3807 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3812 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3815 this._iconSz = iconSz switch
3817 MyCommon.IconSizes.IconNone => 0,
3818 MyCommon.IconSizes.Icon16 => 16,
3819 MyCommon.IconSizes.Icon24 => 26,
3820 MyCommon.IconSizes.Icon48 => 48,
3821 MyCommon.IconSizes.Icon48_2 => 48,
3822 _ => throw new InvalidEnumArgumentException(nameof(iconSz), (int)iconSz, typeof(MyCommon.IconSizes)),
3824 this._iconCol = iconSz == MyCommon.IconSizes.Icon48_2;
3828 // ディスプレイの DPI 設定を考慮したサイズを設定する
3829 _listViewImageList.ImageSize = new Size(
3831 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3835 _listViewImageList.ImageSize = new Size(1, 1);
3839 private void ResetColumns(DetailsListView list)
3841 using (ControlTransaction.Update(list))
3842 using (ControlTransaction.Layout(list, false))
3845 list.ColumnClick -= MyList_ColumnClick;
3846 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3847 list.ColumnReordered -= MyList_ColumnReordered;
3848 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3850 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3851 list.Columns.Clear();
3852 cols.ForEach(col => col.Dispose());
3855 InitColumns(list, true);
3857 list.ColumnClick += MyList_ColumnClick;
3858 list.DrawColumnHeader += MyList_DrawColumnHeader;
3859 list.ColumnReordered += MyList_ColumnReordered;
3860 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3864 public void AddNewTabForSearch(string searchWord)
3866 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3867 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3869 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
3871 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3872 this.ListTab.SelectedIndex = tabIndex;
3877 var tabName = searchWord;
3878 for (var i = 0; i <= 100; i++)
3880 if (_statuses.ContainsTab(tabName))
3886 var tab = new PublicSearchTabModel(tabName);
3887 _statuses.AddTab(tab);
3888 AddNewTab(tab, startup: false);
3890 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3892 var tabPage = this.CurrentTabPage;
3893 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3894 cmb.Items.Add(searchWord);
3895 cmb.Text = searchWord;
3898 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
3901 private async Task ShowUserTimeline()
3903 var post = this.CurrentPost;
3904 if (post == null || !this.ExistCurrentPost) return;
3905 await this.AddNewTabForUserTimeline(post.ScreenName);
3908 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3910 if (e.KeyCode == Keys.Escape)
3912 RemoveSpecifiedTab(this.CurrentTabName, false);
3914 e.SuppressKeyPress = true;
3918 public async Task AddNewTabForUserTimeline(string user)
3920 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3921 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
3923 if (tb.ScreenName == user)
3925 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3926 this.ListTab.SelectedIndex = tabIndex;
3931 var tabName = "user:" + user;
3932 while (_statuses.ContainsTab(tabName))
3937 var tab = new UserTimelineTabModel(tabName, user);
3938 this._statuses.AddTab(tab);
3939 this.AddNewTab(tab, startup: false);
3941 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3944 await this.RefreshTabAsync(tab);
3947 public bool AddNewTab(TabModel tab, bool startup)
3950 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
3954 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
3956 var _tabPage = new TabPage();
3957 var _listCustom = new DetailsListView();
3959 var cnt = this._statuses.Tabs.Count;
3961 ///ToDo:Create and set controls follow tabtypes
3963 using (ControlTransaction.Update(_listCustom))
3964 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3965 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3966 using (ControlTransaction.Layout(this.SplitContainer1, false))
3967 using (ControlTransaction.Layout(this.ListTab, false))
3968 using (ControlTransaction.Layout(this))
3969 using (ControlTransaction.Layout(_tabPage, false))
3971 _tabPage.Controls.Add(_listCustom);
3974 var userTab = tab as UserTimelineTabModel;
3975 var listTab = tab as ListTimelineTabModel;
3976 var searchTab = tab as PublicSearchTabModel;
3978 if (userTab != null || listTab != null)
3980 var label = new Label
3982 Dock = DockStyle.Top,
3987 if (listTab != null)
3989 label.Text = listTab.ListInfo.ToString();
3991 else if (userTab != null)
3993 label.Text = userTab.ScreenName + "'s Timeline";
3995 label.TextAlign = ContentAlignment.MiddleLeft;
3996 using (var tmpComboBox = new ComboBox())
3998 label.Height = tmpComboBox.Height;
4000 _tabPage.Controls.Add(label);
4003 else if (searchTab != null)
4005 var pnl = new Panel();
4007 var lbl = new Label();
4008 var cmb = new ComboBox();
4009 var btn = new Button();
4010 var cmbLang = new ComboBox();
4012 using (ControlTransaction.Layout(pnl, false))
4014 pnl.Controls.Add(cmb);
4015 pnl.Controls.Add(cmbLang);
4016 pnl.Controls.Add(btn);
4017 pnl.Controls.Add(lbl);
4018 pnl.Name = "panelSearch";
4020 pnl.Dock = DockStyle.Top;
4021 pnl.Height = cmb.Height;
4022 pnl.Enter += SearchControls_Enter;
4023 pnl.Leave += SearchControls_Leave;
4026 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4027 cmb.Dock = DockStyle.Fill;
4028 cmb.Name = "comboSearch";
4029 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4030 cmb.ImeMode = ImeMode.NoControl;
4031 cmb.TabStop = false;
4033 cmb.AutoCompleteMode = AutoCompleteMode.None;
4034 cmb.KeyDown += SearchComboBox_KeyDown;
4037 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4038 cmbLang.Dock = DockStyle.Right;
4040 cmbLang.Name = "comboLang";
4041 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4042 cmbLang.TabStop = false;
4043 cmbLang.TabIndex = 2;
4044 cmbLang.Items.Add("");
4045 cmbLang.Items.Add("ja");
4046 cmbLang.Items.Add("en");
4047 cmbLang.Items.Add("ar");
4048 cmbLang.Items.Add("da");
4049 cmbLang.Items.Add("nl");
4050 cmbLang.Items.Add("fa");
4051 cmbLang.Items.Add("fi");
4052 cmbLang.Items.Add("fr");
4053 cmbLang.Items.Add("de");
4054 cmbLang.Items.Add("hu");
4055 cmbLang.Items.Add("is");
4056 cmbLang.Items.Add("it");
4057 cmbLang.Items.Add("no");
4058 cmbLang.Items.Add("pl");
4059 cmbLang.Items.Add("pt");
4060 cmbLang.Items.Add("ru");
4061 cmbLang.Items.Add("es");
4062 cmbLang.Items.Add("sv");
4063 cmbLang.Items.Add("th");
4065 lbl.Text = "Search(C-S-f)";
4066 lbl.Name = "label1";
4067 lbl.Dock = DockStyle.Left;
4069 lbl.Height = cmb.Height;
4070 lbl.TextAlign = ContentAlignment.MiddleLeft;
4073 btn.Text = "Search";
4074 btn.Name = "buttonSearch";
4075 btn.UseVisualStyleBackColor = true;
4076 btn.Dock = DockStyle.Right;
4077 btn.TabStop = false;
4079 btn.Click += SearchButton_Click;
4081 if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
4083 cmb.Items.Add(searchTab.SearchWords);
4084 cmb.Text = searchTab.SearchWords;
4087 cmbLang.Text = searchTab.SearchLang;
4089 _tabPage.Controls.Add(pnl);
4093 _tabPage.Tag = _listCustom;
4094 this.ListTab.Controls.Add(_tabPage);
4096 _tabPage.Location = new Point(4, 4);
4097 _tabPage.Name = "CTab" + cnt;
4098 _tabPage.Size = new Size(380, 260);
4099 _tabPage.TabIndex = 2 + cnt;
4100 _tabPage.Text = tab.TabName;
4101 _tabPage.UseVisualStyleBackColor = true;
4102 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4104 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4105 _listCustom.TabIndex = 1;
4106 _listCustom.AllowColumnReorder = true;
4107 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4108 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4109 _listCustom.Dock = DockStyle.Fill;
4110 _listCustom.FullRowSelect = true;
4111 _listCustom.HideSelection = false;
4112 _listCustom.Location = new Point(0, 0);
4113 _listCustom.Margin = new Padding(0);
4114 _listCustom.Name = "CList" + Environment.TickCount;
4115 _listCustom.ShowItemToolTips = true;
4116 _listCustom.Size = new Size(380, 260);
4117 _listCustom.UseCompatibleStateImageBehavior = false;
4118 _listCustom.View = View.Details;
4119 _listCustom.OwnerDraw = true;
4120 _listCustom.VirtualMode = true;
4121 _listCustom.Font = _fntReaded;
4122 _listCustom.BackColor = _clListBackcolor;
4124 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4125 _listCustom.AllowDrop = true;
4127 _listCustom.SmallImageList = _listViewImageList;
4129 InitColumns(_listCustom, startup);
4131 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4132 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4133 _listCustom.ColumnClick += MyList_ColumnClick;
4134 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4135 _listCustom.DragDrop += TweenMain_DragDrop;
4136 _listCustom.DragEnter += TweenMain_DragEnter;
4137 _listCustom.DragOver += TweenMain_DragOver;
4138 _listCustom.DrawItem += MyList_DrawItem;
4139 _listCustom.MouseClick += MyList_MouseClick;
4140 _listCustom.ColumnReordered += MyList_ColumnReordered;
4141 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4142 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4143 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4144 _listCustom.DrawSubItem += MyList_DrawSubItem;
4145 _listCustom.HScrolled += MyList_HScrolled;
4151 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4153 var tabInfo = _statuses.GetTabByName(TabName);
4154 if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
4159 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4160 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4161 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4167 var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4171 var _tabPage = this.ListTab.TabPages[tabIndex];
4173 SetListProperty(); //他のタブに列幅等を反映
4176 var _listCustom = (DetailsListView)_tabPage.Tag;
4177 _tabPage.Tag = null;
4179 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4180 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4181 using (ControlTransaction.Layout(this.SplitContainer1, false))
4182 using (ControlTransaction.Layout(this.ListTab, false))
4183 using (ControlTransaction.Layout(this))
4184 using (ControlTransaction.Layout(_tabPage, false))
4186 if (this.CurrentTabName == TabName)
4188 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4189 this._beforeSelectedTab = null;
4191 this.ListTab.Controls.Remove(_tabPage);
4194 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4196 using var label = _tabPage.Controls["labelUser"];
4197 _tabPage.Controls.Remove(label);
4199 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4201 using var pnl = _tabPage.Controls["panelSearch"];
4203 pnl.Enter -= SearchControls_Enter;
4204 pnl.Leave -= SearchControls_Leave;
4205 _tabPage.Controls.Remove(pnl);
4207 foreach (Control ctrl in pnl.Controls)
4209 if (ctrl.Name == "buttonSearch")
4211 ctrl.Click -= SearchButton_Click;
4213 else if (ctrl.Name == "comboSearch")
4215 ctrl.KeyDown -= SearchComboBox_KeyDown;
4217 pnl.Controls.Remove(ctrl);
4222 _tabPage.Controls.Remove(_listCustom);
4224 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4225 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4226 _listCustom.ColumnClick -= MyList_ColumnClick;
4227 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4228 _listCustom.DragDrop -= TweenMain_DragDrop;
4229 _listCustom.DragEnter -= TweenMain_DragEnter;
4230 _listCustom.DragOver -= TweenMain_DragOver;
4231 _listCustom.DrawItem -= MyList_DrawItem;
4232 _listCustom.MouseClick -= MyList_MouseClick;
4233 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4234 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4235 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4236 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4237 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4238 _listCustom.HScrolled -= MyList_HScrolled;
4240 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4241 _listCustom.Columns.Clear();
4242 cols.ForEach(col => col.Dispose());
4245 _listCustom.ContextMenuStrip = null;
4246 _listCustom.ColumnHeaderContextMenuStrip = null;
4247 _listCustom.Font = null;
4249 _listCustom.SmallImageList = null;
4250 _listCustom.ListViewItemSorter = null;
4253 this.PurgeListViewItemCache();
4257 _listCustom.Dispose();
4258 _statuses.RemoveTab(TabName);
4260 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4262 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4263 lst.VirtualListSize = tab.AllCount;
4269 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4271 this.PurgeListViewItemCache();
4272 _beforeSelectedTab = e.TabPage;
4275 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4279 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4282 var dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4283 if (!dragEnableRectangle.Contains(e.Location))
4285 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4286 tn = this.CurrentTabName;
4289 if (MyCommon.IsNullOrEmpty(tn)) return;
4291 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4294 var tabPage = this.ListTab.TabPages[tabIndex];
4295 ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4303 var cpos = new Point(e.X, e.Y);
4304 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4306 var rect = ListTab.GetTabRect(index);
4307 if (rect.Contains(cpos))
4309 _rclickTabName = tab.TabName;
4315 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4317 SetMainWindowTitle();
4318 SetStatusLabelUrl();
4319 SetApiStatusLabel();
4320 if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4321 this.Tag = ListTab.Tag;
4322 TabMenuControl(this.CurrentTabName);
4323 this.PushSelectPostChain();
4327 private void SetListProperty()
4329 if (!_isColumnChanged) return;
4331 var currentListView = this.CurrentListView;
4333 var dispOrder = new int[currentListView.Columns.Count];
4334 for (var i = 0; i < currentListView.Columns.Count; i++)
4336 for (var j = 0; j < currentListView.Columns.Count; j++)
4338 if (currentListView.Columns[j].DisplayIndex == i)
4347 foreach (TabPage tb in ListTab.TabPages)
4349 if (tb.Text == this.CurrentTabName)
4352 if (tb.Tag != null && tb.Controls.Count > 0)
4354 var lst = (DetailsListView)tb.Tag;
4355 for (var i = 0; i < lst.Columns.Count; i++)
4357 lst.Columns[dispOrder[i]].DisplayIndex = i;
4358 lst.Columns[i].Width = currentListView.Columns[i].Width;
4363 _isColumnChanged = false;
4366 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4368 if (e.KeyChar == '@')
4370 if (!SettingManager.Common.UseAtIdSupplement) return;
4372 var cnt = AtIdSupl.ItemCount;
4373 ShowSuplDialog(StatusText, AtIdSupl);
4374 if (cnt != AtIdSupl.ItemCount)
4375 this.MarkSettingAtIdModified();
4378 else if (e.KeyChar == '#')
4380 if (!SettingManager.Common.UseHashSupplement) return;
4381 ShowSuplDialog(StatusText, HashSupl);
4386 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4387 => this.ShowSuplDialog(owner, dialog, 0, "");
4389 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4390 => this.ShowSuplDialog(owner, dialog, offset, "");
4392 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4394 dialog.StartsWith = startswith;
4401 dialog.ShowDialog();
4403 this.TopMost = SettingManager.Common.AlwaysTop;
4404 var selStart = owner.SelectionStart;
4407 if (dialog.DialogResult == DialogResult.OK)
4409 if (!MyCommon.IsNullOrEmpty(dialog.inputText))
4413 fHalf = owner.Text.Substring(0, selStart - offset);
4415 if (selStart < owner.Text.Length)
4417 eHalf = owner.Text.Substring(selStart);
4419 owner.Text = fHalf + dialog.inputText + eHalf;
4420 owner.SelectionStart = selStart + dialog.inputText.Length;
4427 fHalf = owner.Text.Substring(0, selStart);
4429 if (selStart < owner.Text.Length)
4431 eHalf = owner.Text.Substring(selStart);
4433 owner.Text = fHalf + eHalf;
4436 owner.SelectionStart = selStart;
4442 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4445 if (!e.Alt && !e.Control && !e.Shift)
4447 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4449 var isSpace = false;
4450 foreach (var c in StatusText.Text)
4452 if (c == ' ' || c == ' ')
4465 StatusText.Text = "";
4466 JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4470 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
4473 private void StatusText_TextChanged(object sender, EventArgs e)
4476 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4477 lblLen.Text = pLen.ToString();
4480 StatusText.ForeColor = Color.Red;
4484 StatusText.ForeColor = _clInputFont;
4487 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4489 if (MyCommon.IsNullOrEmpty(StatusText.Text))
4491 this.inReplyTo = null;
4496 /// メンション以外の文字列が含まれていないテキストであるか判定します
4498 internal static bool TextContainsOnlyMentions(string text)
4500 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4503 foreach (var mention in mentions)
4505 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4507 if (!string.IsNullOrWhiteSpace(textPart))
4510 startIndex = mention.Indices[1];
4513 var textPartLast = text.Substring(startIndex);
4515 if (!string.IsNullOrWhiteSpace(textPartLast))
4522 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4524 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4526 var _autoPopulatedUserIds = new List<long>();
4528 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4529 if (replyToPost != null)
4531 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4533 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4534 _autoPopulatedUserIds.Add(replyToPost.UserId);
4536 foreach (var (userId, screenName) in replyToPost.ReplyToList)
4538 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4540 statusText = statusText.Substring(screenName.Length + 2);
4541 _autoPopulatedUserIds.Add(userId);
4547 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4553 /// attachment_url に指定可能な URL が含まれていれば除去
4555 private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
4557 attachmentUrl = null;
4559 // attachment_url は media_id と同時に使用できない
4560 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4563 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4567 attachmentUrl = match.Value;
4570 statusText = statusText.Substring(0, match.Index);
4572 // テキストと URL の間にスペースが含まれていれば除去
4573 return statusText.TrimEnd(' ');
4576 private string FormatStatusTextExtended(string statusText)
4577 => this.FormatStatusTextExtended(statusText, out _, out _);
4580 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4582 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
4584 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4586 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4588 return this.FormatStatusText(statusText);
4592 /// ツイート投稿前のフッター付与などの前処理を行います
4594 private string FormatStatusText(string statusText)
4596 statusText = statusText.Replace("\r\n", "\n");
4598 if (this.urlMultibyteSplit)
4601 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4604 if (SettingManager.Common.WideSpaceConvert)
4606 // 文中の全角スペースを半角スペース1個にする
4607 statusText = statusText.Replace(" ", " ");
4610 // DM の場合はこれ以降の処理を行わない
4611 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4615 if (SettingManager.Common.PostShiftEnter)
4617 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4621 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4622 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4624 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4627 if (statusText.Contains("RT @"))
4628 disableFooter = true;
4630 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4631 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4633 var mentionSelf = $"@{this.tw.Username} ";
4634 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4636 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4637 statusText = statusText.Substring(mentionSelf.Length);
4644 var hashtag = this.HashMgr.UseHash;
4645 if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4648 header = HashMgr.UseHash + " ";
4650 footer = " " + HashMgr.UseHash;
4655 if (SettingManager.Local.UseRecommendStatus)
4658 footer += this.recommendedStatusFooter;
4660 else if (!MyCommon.IsNullOrEmpty(SettingManager.Local.StatusText))
4662 // テキストボックスに入力されている文字列を使用する
4663 footer += " " + SettingManager.Local.StatusText.Trim();
4667 statusText = header + statusText + footer;
4669 if (this.preventSmsCommand)
4671 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4672 // 参照: https://support.twitter.com/articles/14020
4674 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4675 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4677 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4678 statusText = '\u200b' + statusText;
4686 /// 投稿欄に表示する入力可能な文字数を計算します
4688 private int GetRestStatusCount(string statusText)
4690 var remainCount = this.tw.GetTextLengthRemain(statusText);
4692 var uploadService = this.GetSelectedImageService();
4693 if (uploadService != null)
4695 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4696 remainCount -= uploadService.GetReservedTextLength(1);
4702 private IMediaUploadService? GetSelectedImageService()
4703 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4705 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4707 if (sender != this.CurrentListView)
4710 var listCache = this._listItemCache;
4711 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4713 // If the newly requested cache is a subset of the old cache,
4714 // no need to rebuild everything, so do nothing.
4718 // Now we need to rebuild the cache.
4719 this.CreateCache(e.StartIndex, e.EndIndex);
4722 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4724 var listCache = this._listItemCache;
4725 if (listCache?.TargetList == sender)
4727 if (listCache.TryGetValue(e.ItemIndex, out var item, out _))
4734 // A cache miss, so create a new ListViewItem and pass it back.
4735 var tabPage = (TabPage)((DetailsListView)sender).Parent;
4736 var tab = this._statuses.Tabs[tabPage.Text];
4739 e.Item = this.CreateItem(tab, tab[e.ItemIndex]);
4743 // 不正な要求に対する間に合わせの応答
4744 string[] sitem = {"", "", "", "", "", "", "", ""};
4745 e.Item = new ImageListViewItem(sitem);
4749 private void CreateCache(int startIndex, int endIndex)
4751 var tabInfo = this.CurrentTab;
4753 if (tabInfo.AllCount == 0)
4756 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4757 int FilterRange(int index)
4758 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4760 // キャッシュ要求(要求範囲±30を作成)
4761 startIndex = FilterRange(startIndex - 30);
4762 endIndex = FilterRange(endIndex + 30);
4764 var cacheLength = endIndex - startIndex + 1;
4766 var tab = this.CurrentTab;
4767 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4768 var listItems = Enumerable.Range(0, cacheLength)
4769 .Select(x => this.CreateItem(tab, posts[x]))
4772 var listCache = new ListViewItemCache
4774 TargetList = this.CurrentListView,
4775 StartIndex = startIndex,
4776 EndIndex = endIndex,
4777 Cache = Enumerable.Zip(listItems, posts, (x, y) => (x, y)).ToArray(),
4780 Interlocked.Exchange(ref this._listItemCache, listCache);
4784 /// DetailsListView のための ListViewItem のキャッシュを消去する
4786 private void PurgeListViewItemCache()
4787 => Interlocked.Exchange(ref this._listItemCache, null);
4789 private ListViewItem CreateItem(TabModel tab, PostClass Post)
4791 var mk = new StringBuilder();
4793 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4794 ImageListViewItem itm;
4795 if (Post.RetweetedId == null)
4797 string[] sitem= {"",
4799 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4800 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4805 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4809 string[] sitem = {"",
4811 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4812 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4813 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4817 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4819 itm.StateIndex = Post.StateIndex;
4822 var read = Post.IsRead;
4823 // 未読管理していなかったら既読として扱う
4824 if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4827 ChangeItemStyleRead(read, itm, Post, null);
4829 if (tab.TabName == this.CurrentTabName)
4830 this.ColorizeList(itm, Post);
4836 /// 全てのタブの振り分けルールを反映し直します
4838 private void ApplyPostFilters()
4840 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4842 this.PurgeListViewItemCache();
4843 this._statuses.FilterAll();
4845 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4847 var tabPage = this.ListTab.TabPages[index];
4848 var listview = (DetailsListView)tabPage.Tag;
4849 using (ControlTransaction.Update(listview))
4851 listview.VirtualListSize = tab.AllCount;
4854 if (SettingManager.Common.TabIconDisp)
4856 if (tab.UnreadCount > 0)
4857 tabPage.ImageIndex = 0;
4859 tabPage.ImageIndex = -1;
4863 if (!SettingManager.Common.TabIconDisp)
4864 this.ListTab.Refresh();
4866 SetMainWindowTitle();
4867 SetStatusLabelUrl();
4871 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4872 => e.DrawDefault = true;
4874 private void MyList_HScrolled(object sender, EventArgs e)
4875 => ((DetailsListView)sender).Refresh();
4877 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4879 if (e.State == 0) return;
4880 e.DrawDefault = false;
4883 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4885 if (e.Item.BackColor == _clSelf)
4886 brs2 = _brsBackColorMine;
4887 else if (e.Item.BackColor == _clAtSelf)
4888 brs2 = _brsBackColorAt;
4889 else if (e.Item.BackColor == _clTarget)
4890 brs2 = _brsBackColorYou;
4891 else if (e.Item.BackColor == _clAtTarget)
4892 brs2 = _brsBackColorAtYou;
4893 else if (e.Item.BackColor == _clAtFromTarget)
4894 brs2 = _brsBackColorAtFromTarget;
4895 else if (e.Item.BackColor == _clAtTo)
4896 brs2 = _brsBackColorAtTo;
4898 brs2 = _brsBackColorNone;
4903 if (((Control)sender).Focused)
4904 brs2 = _brsHighLight;
4906 brs2 = _brsDeactiveSelection;
4908 e.Graphics.FillRectangle(brs2, e.Bounds);
4909 e.DrawFocusRectangle();
4910 this.DrawListViewItemIcon(e);
4913 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
4915 if (e.ItemState == 0) return;
4917 if (e.ColumnIndex > 0)
4920 var post = (PostClass)e.Item.Tag;
4922 RectangleF rct = e.Bounds;
4923 rct.Width = e.Header.Width;
4924 var fontHeight = e.Item.Font.Height;
4927 rct.Y += fontHeight;
4928 rct.Height -= fontHeight;
4931 var drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
4933 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
4934 if (this._iconCol || drawLineCount > 1)
4936 if (heightDiff < fontHeight * 0.7)
4938 // 最終行が70%以上欠けていたら、最終行は表示しない
4939 rct.Height = (fontHeight * drawLineCount) - 1;
4949 var color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
4950 (((Control)sender).Focused) ? _clHighLight : //選択中の行
4955 var rctB = e.Bounds;
4956 rctB.Width = e.Header.Width;
4957 rctB.Height = fontHeight;
4959 using var fnt = new Font(e.Item.Font, FontStyle.Bold);
4961 TextRenderer.DrawText(e.Graphics,
4962 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
4964 Rectangle.Round(rct),
4966 TextFormatFlags.WordBreak |
4967 TextFormatFlags.EndEllipsis |
4968 TextFormatFlags.GlyphOverhangPadding |
4969 TextFormatFlags.NoPrefix);
4970 TextRenderer.DrawText(e.Graphics,
4971 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 + "]",
4975 TextFormatFlags.SingleLine |
4976 TextFormatFlags.EndEllipsis |
4977 TextFormatFlags.GlyphOverhangPadding |
4978 TextFormatFlags.NoPrefix);
4983 if (e.ColumnIndex != 2)
4984 text = e.SubItem.Text;
4986 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
4988 if (drawLineCount == 1)
4990 TextRenderer.DrawText(e.Graphics,
4993 Rectangle.Round(rct),
4995 TextFormatFlags.SingleLine |
4996 TextFormatFlags.EndEllipsis |
4997 TextFormatFlags.GlyphOverhangPadding |
4998 TextFormatFlags.NoPrefix |
4999 TextFormatFlags.VerticalCenter);
5003 TextRenderer.DrawText(e.Graphics,
5006 Rectangle.Round(rct),
5008 TextFormatFlags.WordBreak |
5009 TextFormatFlags.EndEllipsis |
5010 TextFormatFlags.GlyphOverhangPadding |
5011 TextFormatFlags.NoPrefix);
5018 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5020 if (_iconSz == 0) return;
5022 var item = (ImageListViewItem)e.Item;
5024 //e.Bounds.Leftが常に0を指すから自前で計算
5025 var itemRect = item.Bounds;
5026 var col0 = e.Item.ListView.Columns[0];
5027 itemRect.Width = col0.Width;
5029 if (col0.DisplayIndex > 0)
5031 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5033 if (clm.DisplayIndex < col0.DisplayIndex)
5034 itemRect.X += clm.Width;
5038 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5039 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5040 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5043 var img = item.Image;
5046 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5047 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5049 if (iconRect.Width > 0)
5051 e.Graphics.FillRectangle(Brushes.White, iconRect);
5052 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5055 e.Graphics.DrawImage(img.Image, iconRect);
5057 catch (ArgumentException)
5059 item.RefreshImageAsync();
5065 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5067 item.GetImageAsync();
5070 if (item.StateIndex > -1)
5072 var stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5073 if (stateRect.Width > 0)
5074 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5078 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5080 base.ScaleControl(factor, specified);
5082 ScaleChildControl(this.TabImage, factor);
5084 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5085 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5087 foreach (var listview in listviews)
5089 ScaleChildControl(listview, factor);
5093 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5095 var tab = this.CurrentTab;
5097 if (tab.AllCount == 0)
5099 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5103 var selectedIndex = tab.SelectedIndex;
5108 case SEARCHTYPE.NextSearch: // 次を検索
5109 if (selectedIndex != -1)
5110 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5114 case SEARCHTYPE.PrevSearch: // 前を検索
5115 if (selectedIndex != -1)
5116 startIndex = Math.Max(selectedIndex - 1, 0);
5118 startIndex = tab.AllCount - 1;
5120 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5122 if (selectedIndex != -1)
5123 startIndex = selectedIndex;
5129 Func<string, bool> stringComparer;
5132 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5134 catch (ArgumentException)
5136 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5140 var reverse = searchType == SEARCHTYPE.PrevSearch;
5141 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5142 .DefaultIfEmpty(-1).First();
5144 if (foundIndex == -1)
5146 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5150 var listView = this.CurrentListView;
5151 this.SelectListItem(listView, foundIndex);
5152 listView.EnsureVisible(foundIndex);
5155 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5156 => this.ShowSearchDialog(); // 検索メニュー
5158 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5160 var previousSearch = this.SearchDialog.ResultOptions;
5161 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5163 this.SearchDialog.Reset();
5164 this.ShowSearchDialog();
5170 previousSearch.Query,
5171 previousSearch.CaseSensitive,
5172 previousSearch.UseRegex,
5173 SEARCHTYPE.NextSearch);
5176 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5178 var previousSearch = this.SearchDialog.ResultOptions;
5179 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5181 this.SearchDialog.Reset();
5182 this.ShowSearchDialog();
5188 previousSearch.Query,
5189 previousSearch.CaseSensitive,
5190 previousSearch.UseRegex,
5191 SEARCHTYPE.PrevSearch);
5195 /// 検索ダイアログを表示し、検索を実行します
5197 private void ShowSearchDialog()
5199 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5201 this.TopMost = SettingManager.Common.AlwaysTop;
5204 this.TopMost = SettingManager.Common.AlwaysTop;
5206 var searchOptions = this.SearchDialog.ResultOptions!;
5207 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5209 if (searchOptions.NewTab)
5211 var tabName = Properties.Resources.SearchResults_TabName;
5215 tabName = this._statuses.MakeTabName(tabName);
5217 catch (TabException ex)
5219 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5222 var resultTab = new LocalSearchTabModel(tabName);
5223 this.AddNewTab(resultTab, startup: false);
5224 this._statuses.AddTab(resultTab);
5226 var targetTab = this.CurrentTab;
5228 Func<string, bool> stringComparer;
5231 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5233 catch (ArgumentException)
5235 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5239 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5240 if (foundIndices.Length == 0)
5242 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5246 var foundPosts = foundIndices.Select(x => targetTab[x]);
5247 foreach (var post in foundPosts)
5249 resultTab.AddPostQueue(post);
5252 this._statuses.DistributePosts();
5253 this.RefreshTimeline();
5255 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5256 this.ListTab.SelectedIndex = tabIndex;
5261 searchOptions.Query,
5262 searchOptions.CaseSensitive,
5263 searchOptions.UseRegex,
5264 SEARCHTYPE.DialogSearch);
5267 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5269 this.AddNewTabForSearch(searchOptions.Query);
5273 /// <summary>発言検索に使用するメソッドを生成します</summary>
5274 /// <exception cref="ArgumentException">
5275 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5277 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5281 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5282 var regex = new Regex(query, regexOption);
5284 return x => regex.IsMatch(x);
5288 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5290 return x => x.IndexOf(query, comparisonType) != -1;
5294 private void AboutMenuItem_Click(object sender, EventArgs e)
5296 using (var about = new TweenAboutBox())
5298 about.ShowDialog(this);
5300 this.TopMost = SettingManager.Common.AlwaysTop;
5303 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5305 var bgnIdx = this._statuses.SelectedTabIndex;
5307 if (ImageSelector.Enabled)
5310 TabModel? foundTab = null;
5314 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5316 var unreadIndex = tab.NextUnreadIndex;
5317 if (unreadIndex != -1)
5319 ListTab.SelectedIndex = index;
5321 foundIndex = unreadIndex;
5326 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5327 if (foundTab == null && bgnIdx > 0)
5329 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5331 var unreadIndex = tab.NextUnreadIndex;
5332 if (unreadIndex != -1)
5334 ListTab.SelectedIndex = index;
5336 foundIndex = unreadIndex;
5342 DetailsListView lst;
5344 if (foundTab == null)
5346 //全部調べたが未読見つからず→先頭タブの最新発言へ
5347 ListTab.SelectedIndex = 0;
5348 var tabPage = this.ListTab.TabPages[0];
5349 var tab = this._statuses.Tabs[0];
5351 if (tab.AllCount == 0)
5354 if (_statuses.SortOrder == SortOrder.Ascending)
5355 foundIndex = tab.AllCount - 1;
5359 lst = (DetailsListView)tabPage.Tag;
5363 var foundTabIndex = this._statuses.Tabs.IndexOf(foundTab);
5364 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
5367 SelectListItem(lst, foundIndex);
5369 if (_statuses.SortMode == ComparerMode.Id)
5371 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5372 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5378 lst.EnsureVisible(foundIndex);
5383 lst.EnsureVisible(foundIndex);
5389 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5391 var tab = this.CurrentTab;
5392 var post = this.CurrentPost;
5393 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5394 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5397 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5398 => await this.CheckNewVersion(false);
5400 private void RunTweenUp()
5402 var pinfo = new ProcessStartInfo
5404 UseShellExecute = true,
5405 WorkingDirectory = MyCommon.settingPath,
5406 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5407 Arguments = "\"" + Application.StartupPath + "\"",
5412 Process.Start(pinfo);
5416 MessageBox.Show("Failed to execute TweenUp3.exe.");
5420 public class VersionInfo
5422 public Version Version { get; }
5423 public Uri DownloadUri { get; }
5424 public string ReleaseNote { get; }
5426 public VersionInfo(Version version, Uri downloadUri, string releaseNote)
5427 => (this.Version, this.DownloadUri, this.ReleaseNote) = (version, downloadUri, releaseNote);
5431 /// OpenTween の最新バージョンの情報を取得します
5433 public async Task<VersionInfo> GetVersionInfoAsync()
5435 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5436 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5438 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5439 .ConfigureAwait(false);
5441 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5442 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5444 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5445 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5447 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5449 return new VersionInfo(
5450 version: Version.Parse(msgHeader[0]),
5451 downloadUri: new Uri(msgHeader[1]),
5452 releaseNote: msgBody
5456 private async Task CheckNewVersion(bool startup = false)
5458 if (ApplicationSettings.VersionInfoUrl == null)
5459 return; // 更新チェック無効化
5463 var versionInfo = await this.GetVersionInfoAsync();
5465 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5470 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5471 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5472 msgtext = MyCommon.ReplaceAppName(msgtext);
5474 MessageBox.Show(msgtext,
5475 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5476 MessageBoxButtons.OK, MessageBoxIcon.Information);
5481 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5484 using var dialog = new UpdateDialog();
5486 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5487 MyCommon.GetReadableVersion(versionInfo.Version));
5488 dialog.DetailsText = versionInfo.ReleaseNote;
5490 if (dialog.ShowDialog(this) == DialogResult.Yes)
5492 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5494 else if (dialog.SkipButtonPressed)
5496 SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5497 this.MarkSettingCommonModified();
5502 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5505 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5506 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5507 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5512 private void UpdateSelectedPost()
5514 //件数関連の場合、タイトル即時書き換え
5515 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5516 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5517 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5518 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5520 SetMainWindowTitle();
5522 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5523 SetStatusLabelUrl();
5525 if (SettingManager.Common.TabIconDisp)
5527 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5529 if (tab.UnreadCount == 0)
5531 var tabPage = this.ListTab.TabPages[index];
5532 if (tabPage.ImageIndex == 0)
5533 tabPage.ImageIndex = -1;
5539 this.ListTab.Refresh();
5542 this.DispSelectedPost();
5545 public string createDetailHtml(string orgdata)
5546 => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5548 private void DispSelectedPost()
5549 => this.DispSelectedPost(false);
5551 private PostClass displayPost = new PostClass();
5554 /// サムネイル表示に使用する CancellationToken の生成元
5556 private CancellationTokenSource? thumbnailTokenSource = null;
5558 private void DispSelectedPost(bool forceupdate)
5560 var currentPost = this.CurrentPost;
5561 if (currentPost == null)
5564 var oldDisplayPost = this.displayPost;
5565 this.displayPost = currentPost;
5567 if (!forceupdate && currentPost.Equals(oldDisplayPost))
5570 var loadTasks = new List<Task>
5572 this.tweetDetailsView.ShowPostDetails(currentPost),
5575 this.SplitContainer3.Panel2Collapsed = true;
5577 if (SettingManager.Common.PreviewEnable)
5579 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5580 oldTokenSource?.Cancel();
5582 var token = this.thumbnailTokenSource!.Token;
5583 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5586 async Task delayedTasks()
5590 await Task.WhenAll(loadTasks);
5592 catch (OperationCanceledException) { }
5595 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
5599 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5600 => await this.OpenApplicationWebsite();
5602 private async Task OpenApplicationWebsite()
5603 => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5605 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5606 => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5608 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5610 var tab = this.CurrentTab;
5611 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5613 var pnl = this.CurrentTabPage.Controls["panelSearch"];
5614 if (pnl.Controls["comboSearch"].Focused ||
5615 pnl.Controls["comboLang"].Focused ||
5616 pnl.Controls["buttonSearch"].Focused) return;
5619 if (e.Control || e.Shift || e.Alt)
5620 this._anchorFlag = false;
5622 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5625 e.SuppressKeyPress = true;
5628 if (asyncTask != null)
5632 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5634 private void InitializeShortcuts()
5636 this.shortcutCommands = new[]
5638 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5639 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5640 .FocusedOn(FocusedControl.ListTab)
5641 .Do(() => SendKeys.Send("{DOWN}")),
5643 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5644 .FocusedOn(FocusedControl.ListTab)
5645 .Do(() => SendKeys.Send("{UP}")),
5647 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5648 .FocusedOn(FocusedControl.ListTab)
5649 .Do(() => SendKeys.Send("{PGDN}")),
5651 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5652 .FocusedOn(FocusedControl.ListTab)
5653 .Do(() => SendKeys.Send("{PGUP}")),
5655 ShortcutCommand.Create(Keys.F1)
5656 .Do(() => this.OpenApplicationWebsite()),
5658 ShortcutCommand.Create(Keys.F3)
5659 .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
5661 ShortcutCommand.Create(Keys.F5)
5662 .Do(() => this.DoRefresh()),
5664 ShortcutCommand.Create(Keys.F6)
5665 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5667 ShortcutCommand.Create(Keys.F7)
5668 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5670 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5671 .NotFocusedOn(FocusedControl.StatusText)
5672 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty); }),
5674 ShortcutCommand.Create(Keys.G)
5675 .NotFocusedOn(FocusedControl.StatusText)
5676 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty); }),
5678 ShortcutCommand.Create(Keys.Right, Keys.N)
5679 .FocusedOn(FocusedControl.ListTab)
5680 .Do(() => this.GoRelPost(forward: true)),
5682 ShortcutCommand.Create(Keys.Left, Keys.P)
5683 .FocusedOn(FocusedControl.ListTab)
5684 .Do(() => this.GoRelPost(forward: false)),
5686 ShortcutCommand.Create(Keys.OemPeriod)
5687 .FocusedOn(FocusedControl.ListTab)
5688 .Do(() => this.GoAnchor()),
5690 ShortcutCommand.Create(Keys.I)
5691 .FocusedOn(FocusedControl.ListTab)
5692 .OnlyWhen(() => this.StatusText.Enabled)
5693 .Do(() => this.StatusText.Focus()),
5695 ShortcutCommand.Create(Keys.Enter)
5696 .FocusedOn(FocusedControl.ListTab)
5697 .Do(() => this.MakeReplyOrDirectStatus()),
5699 ShortcutCommand.Create(Keys.R)
5700 .FocusedOn(FocusedControl.ListTab)
5701 .Do(() => this.DoRefresh()),
5703 ShortcutCommand.Create(Keys.L)
5704 .FocusedOn(FocusedControl.ListTab)
5705 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5707 ShortcutCommand.Create(Keys.H)
5708 .FocusedOn(FocusedControl.ListTab)
5709 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5711 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5712 .FocusedOn(FocusedControl.ListTab)
5713 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5715 ShortcutCommand.Create(Keys.S)
5716 .FocusedOn(FocusedControl.ListTab)
5717 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5719 ShortcutCommand.Create(Keys.A)
5720 .FocusedOn(FocusedControl.ListTab)
5721 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5723 // ] in_reply_to参照元へ戻る
5724 ShortcutCommand.Create(Keys.Oem4)
5725 .FocusedOn(FocusedControl.ListTab)
5726 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5728 // [ in_reply_toへジャンプ
5729 ShortcutCommand.Create(Keys.Oem6)
5730 .FocusedOn(FocusedControl.ListTab)
5731 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5733 ShortcutCommand.Create(Keys.Escape)
5734 .FocusedOn(FocusedControl.ListTab)
5736 this._anchorFlag = false;
5737 var tab = this.CurrentTab;
5738 var tabtype = tab.TabType;
5739 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5741 RemoveSpecifiedTab(tab.TabName, false);
5746 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5747 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5748 .FocusedOn(FocusedControl.ListTab)
5749 .Do(() => this._anchorFlag = false, preventDefault: false),
5751 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5752 ShortcutCommand.Create(Keys.Up, Keys.Down)
5753 .FocusedOn(FocusedControl.PostBrowser)
5756 ShortcutCommand.Create(Keys.Control | Keys.R)
5757 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5759 ShortcutCommand.Create(Keys.Control | Keys.D)
5760 .Do(() => this.doStatusDelete()),
5762 ShortcutCommand.Create(Keys.Control | Keys.M)
5763 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5765 ShortcutCommand.Create(Keys.Control | Keys.S)
5766 .Do(() => this.FavoriteChange(FavAdd: true)),
5768 ShortcutCommand.Create(Keys.Control | Keys.I)
5769 .Do(() => this.doRepliedStatusOpen()),
5771 ShortcutCommand.Create(Keys.Control | Keys.Q)
5772 .Do(() => this.doQuoteOfficial()),
5774 ShortcutCommand.Create(Keys.Control | Keys.B)
5775 .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
5777 ShortcutCommand.Create(Keys.Control | Keys.T)
5778 .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
5780 ShortcutCommand.Create(Keys.Control | Keys.L)
5781 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
5783 ShortcutCommand.Create(Keys.Control | Keys.Y)
5784 .NotFocusedOn(FocusedControl.PostBrowser)
5785 .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
5787 ShortcutCommand.Create(Keys.Control | Keys.F)
5788 .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
5790 ShortcutCommand.Create(Keys.Control | Keys.U)
5791 .Do(() => this.ShowUserTimeline()),
5793 ShortcutCommand.Create(Keys.Control | Keys.H)
5794 .Do(() => this.MoveToHomeToolStripMenuItem_Click(this.MoveToHomeToolStripMenuItem, EventArgs.Empty)),
5796 ShortcutCommand.Create(Keys.Control | Keys.G)
5797 .Do(() => this.MoveToFavToolStripMenuItem_Click(this.MoveToFavToolStripMenuItem, EventArgs.Empty)),
5799 ShortcutCommand.Create(Keys.Control | Keys.O)
5800 .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
5802 ShortcutCommand.Create(Keys.Control | Keys.E)
5803 .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
5805 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5806 .FocusedOn(FocusedControl.ListTab)
5807 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
5809 ShortcutCommand.Create(Keys.Control | Keys.N)
5810 .FocusedOn(FocusedControl.ListTab)
5811 .Do(() => this.GoNextTab(forward: true)),
5813 ShortcutCommand.Create(Keys.Control | Keys.P)
5814 .FocusedOn(FocusedControl.ListTab)
5815 .Do(() => this.GoNextTab(forward: false)),
5817 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5818 .FocusedOn(FocusedControl.ListTab)
5819 .Do(() => this.CopyStot()),
5821 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5822 ShortcutCommand.Create(Keys.Control | Keys.D1)
5823 .FocusedOn(FocusedControl.ListTab)
5824 .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5825 .Do(() => this.ListTab.SelectedIndex = 0),
5827 ShortcutCommand.Create(Keys.Control | Keys.D2)
5828 .FocusedOn(FocusedControl.ListTab)
5829 .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5830 .Do(() => this.ListTab.SelectedIndex = 1),
5832 ShortcutCommand.Create(Keys.Control | Keys.D3)
5833 .FocusedOn(FocusedControl.ListTab)
5834 .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5835 .Do(() => this.ListTab.SelectedIndex = 2),
5837 ShortcutCommand.Create(Keys.Control | Keys.D4)
5838 .FocusedOn(FocusedControl.ListTab)
5839 .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5840 .Do(() => this.ListTab.SelectedIndex = 3),
5842 ShortcutCommand.Create(Keys.Control | Keys.D5)
5843 .FocusedOn(FocusedControl.ListTab)
5844 .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5845 .Do(() => this.ListTab.SelectedIndex = 4),
5847 ShortcutCommand.Create(Keys.Control | Keys.D6)
5848 .FocusedOn(FocusedControl.ListTab)
5849 .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5850 .Do(() => this.ListTab.SelectedIndex = 5),
5852 ShortcutCommand.Create(Keys.Control | Keys.D7)
5853 .FocusedOn(FocusedControl.ListTab)
5854 .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
5855 .Do(() => this.ListTab.SelectedIndex = 6),
5857 ShortcutCommand.Create(Keys.Control | Keys.D8)
5858 .FocusedOn(FocusedControl.ListTab)
5859 .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
5860 .Do(() => this.ListTab.SelectedIndex = 7),
5862 ShortcutCommand.Create(Keys.Control | Keys.D9)
5863 .FocusedOn(FocusedControl.ListTab)
5864 .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
5866 ShortcutCommand.Create(Keys.Control | Keys.A)
5867 .FocusedOn(FocusedControl.StatusText)
5868 .Do(() => this.StatusText.SelectAll()),
5870 ShortcutCommand.Create(Keys.Control | Keys.V)
5871 .FocusedOn(FocusedControl.StatusText)
5872 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
5874 ShortcutCommand.Create(Keys.Control | Keys.Up)
5875 .FocusedOn(FocusedControl.StatusText)
5876 .Do(() => this.StatusTextHistoryBack()),
5878 ShortcutCommand.Create(Keys.Control | Keys.Down)
5879 .FocusedOn(FocusedControl.StatusText)
5880 .Do(() => this.StatusTextHistoryForward()),
5882 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
5883 .FocusedOn(FocusedControl.StatusText)
5885 if (ListTab.SelectedIndex == 0)
5887 ListTab.SelectedIndex = ListTab.TabCount - 1;
5891 ListTab.SelectedIndex -= 1;
5896 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
5897 .FocusedOn(FocusedControl.StatusText)
5899 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
5901 ListTab.SelectedIndex = 0;
5905 ListTab.SelectedIndex += 1;
5910 ShortcutCommand.Create(Keys.Control | Keys.Y)
5911 .FocusedOn(FocusedControl.PostBrowser)
5913 var multiline = !SettingManager.Local.StatusMultiline;
5914 SettingManager.Local.StatusMultiline = multiline;
5915 MultiLineMenuItem.Checked = multiline;
5916 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
5919 ShortcutCommand.Create(Keys.Shift | Keys.F3)
5920 .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
5922 ShortcutCommand.Create(Keys.Shift | Keys.F5)
5923 .Do(() => this.DoRefreshMore()),
5925 ShortcutCommand.Create(Keys.Shift | Keys.F6)
5926 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
5928 ShortcutCommand.Create(Keys.Shift | Keys.F7)
5929 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
5931 ShortcutCommand.Create(Keys.Shift | Keys.R)
5932 .NotFocusedOn(FocusedControl.StatusText)
5933 .Do(() => this.DoRefreshMore()),
5935 ShortcutCommand.Create(Keys.Shift | Keys.H)
5936 .FocusedOn(FocusedControl.ListTab)
5937 .Do(() => this.GoTopEnd(GoTop: true)),
5939 ShortcutCommand.Create(Keys.Shift | Keys.L)
5940 .FocusedOn(FocusedControl.ListTab)
5941 .Do(() => this.GoTopEnd(GoTop: false)),
5943 ShortcutCommand.Create(Keys.Shift | Keys.M)
5944 .FocusedOn(FocusedControl.ListTab)
5945 .Do(() => this.GoMiddle()),
5947 ShortcutCommand.Create(Keys.Shift | Keys.G)
5948 .FocusedOn(FocusedControl.ListTab)
5949 .Do(() => this.GoLast()),
5951 ShortcutCommand.Create(Keys.Shift | Keys.Z)
5952 .FocusedOn(FocusedControl.ListTab)
5953 .Do(() => this.MoveMiddle()),
5955 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
5956 .FocusedOn(FocusedControl.ListTab)
5957 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
5959 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
5960 .FocusedOn(FocusedControl.ListTab)
5961 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
5963 // お気に入り前後ジャンプ(SHIFT+N←/P→)
5964 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
5965 .FocusedOn(FocusedControl.ListTab)
5966 .Do(() => this.GoFav(forward: true)),
5968 // お気に入り前後ジャンプ(SHIFT+N←/P→)
5969 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
5970 .FocusedOn(FocusedControl.ListTab)
5971 .Do(() => this.GoFav(forward: false)),
5973 ShortcutCommand.Create(Keys.Shift | Keys.Space)
5974 .FocusedOn(FocusedControl.ListTab)
5975 .Do(() => this.GoBackSelectPostChain()),
5977 ShortcutCommand.Create(Keys.Alt | Keys.R)
5978 .Do(() => this.doReTweetOfficial(isConfirm: true)),
5980 ShortcutCommand.Create(Keys.Alt | Keys.P)
5981 .OnlyWhen(() => this.CurrentPost != null)
5982 .Do(() => this.doShowUserStatus(this.CurrentPost!.ScreenName, ShowInputDialog: false)),
5984 ShortcutCommand.Create(Keys.Alt | Keys.Up)
5985 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
5987 ShortcutCommand.Create(Keys.Alt | Keys.Down)
5988 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
5990 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
5991 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
5993 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
5994 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
5996 // 別タブの同じ書き込みへ(ALT+←/→)
5997 ShortcutCommand.Create(Keys.Alt | Keys.Right)
5998 .FocusedOn(FocusedControl.ListTab)
5999 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6001 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6002 .FocusedOn(FocusedControl.ListTab)
6003 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6005 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6006 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6008 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6009 .Do(() => this.CopyIdUri()),
6011 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6012 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6013 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6015 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6016 .Do(() => this.FavoriteChange(FavAdd: false)),
6018 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6019 .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
6021 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6022 .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
6024 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6025 .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
6027 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6028 .Do(() => this.doMoveToRTHome()),
6030 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6031 .FocusedOn(FocusedControl.StatusText)
6033 var tab = this.CurrentTab;
6034 var selectedIndex = tab.SelectedIndex;
6035 if (selectedIndex != -1 && selectedIndex > 0)
6037 var listView = this.CurrentListView;
6038 var idx = selectedIndex - 1;
6039 SelectListItem(listView, idx);
6040 listView.EnsureVisible(idx);
6044 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6045 .FocusedOn(FocusedControl.StatusText)
6047 var tab = this.CurrentTab;
6048 var selectedIndex = tab.SelectedIndex;
6049 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6051 var listView = this.CurrentListView;
6052 var idx = selectedIndex + 1;
6053 SelectListItem(listView, idx);
6054 listView.EnsureVisible(idx);
6058 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6059 .FocusedOn(FocusedControl.StatusText)
6061 if (StatusText.SelectionStart > 0)
6063 var endidx = StatusText.SelectionStart - 1;
6065 for (var i = StatusText.SelectionStart - 1; i >= 0; i--)
6067 var c = StatusText.Text[i];
6068 if (char.IsLetterOrDigit(c) || c == '_')
6074 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6075 var cnt = AtIdSupl.ItemCount;
6076 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6077 if (AtIdSupl.ItemCount != cnt)
6078 this.MarkSettingAtIdModified();
6082 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6083 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6093 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6094 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6095 .FocusedOn(FocusedControl.ListTab)
6096 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6098 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6099 .FocusedOn(FocusedControl.ListTab)
6100 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6102 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6103 .FocusedOn(FocusedControl.ListTab)
6104 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6106 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6107 .FocusedOn(FocusedControl.ListTab)
6108 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6110 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6111 .FocusedOn(FocusedControl.ListTab)
6112 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6114 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6115 .FocusedOn(FocusedControl.ListTab)
6116 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6118 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6119 .FocusedOn(FocusedControl.ListTab)
6120 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6122 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6123 .FocusedOn(FocusedControl.ListTab)
6124 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6126 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6127 .FocusedOn(FocusedControl.ListTab)
6128 .Do(() => this.SetSortLastColumn()),
6130 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6131 .FocusedOn(FocusedControl.ListTab)
6132 .Do(() => this.FavoritesRetweetOfficial()),
6134 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6135 .FocusedOn(FocusedControl.ListTab)
6136 .Do(() => this.FavoritesRetweetUnofficial()),
6138 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6139 .FocusedOn(FocusedControl.ListTab)
6140 .Do(() => this.OpenUserAppointUrl()),
6142 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6143 .FocusedOn(FocusedControl.PostBrowser)
6144 .Do(() => this.doReTweetUnofficial()),
6146 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6147 .OnlyWhen(() => this.ExistCurrentPost)
6148 .Do(() => this.tweetDetailsView.DoTranslation()),
6150 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6151 .Do(() => this.doReTweetUnofficial()),
6153 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6154 .Do(() => this.CopyUserId()),
6156 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6157 .Do(() => this.tweetThumbnail1.ScrollUp()),
6159 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6160 .Do(() => this.tweetThumbnail1.ScrollDown()),
6162 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6163 .FocusedOn(FocusedControl.ListTab)
6164 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6165 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6169 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
6171 // Task を返す非同期処理があれば asyncTask に代入する
6174 // ShortcutCommand に対応しているコマンドはここで処理される
6175 foreach (var command in this.shortcutCommands)
6177 if (command.IsMatch(keyData, focusedOn))
6179 asyncTask = command.RunCommand();
6180 return command.PreventDefault;
6187 private void GoNextTab(bool forward)
6189 var idx = this._statuses.SelectedTabIndex;
6190 var tabCount = this._statuses.Tabs.Count;
6194 if (idx > tabCount - 1) idx = 0;
6199 if (idx < 0) idx = tabCount - 1;
6201 ListTab.SelectedIndex = idx;
6204 private void CopyStot()
6206 var sb = new StringBuilder();
6207 var tab = this.CurrentTab;
6208 var IsProtected = false;
6209 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6210 foreach (var post in tab.SelectedPosts)
6212 if (post.IsDeleted) continue;
6215 if (post.RetweetedId != null)
6216 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6218 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6222 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6227 MessageBox.Show(Properties.Resources.CopyStotText1);
6231 var clstr = sb.ToString();
6234 Clipboard.SetDataObject(clstr, false, 5, 100);
6236 catch (Exception ex)
6238 MessageBox.Show(ex.Message);
6243 private void CopyIdUri()
6245 var tab = this.CurrentTab;
6246 if (tab == null || tab is DirectMessagesTabModel)
6249 var copyUrls = new List<string>();
6250 foreach (var post in tab.SelectedPosts)
6251 copyUrls.Add(MyCommon.GetStatusUrl(post));
6253 if (copyUrls.Count == 0)
6258 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6260 catch (ExternalException ex)
6262 MessageBox.Show(ex.Message);
6266 private void GoFav(bool forward)
6268 var tab = this.CurrentTab;
6269 if (tab.AllCount == 0)
6272 var selectedIndex = tab.SelectedIndex;
6280 if (selectedIndex == -1)
6286 fIdx = selectedIndex + 1;
6287 if (fIdx > tab.AllCount - 1)
6290 toIdx = tab.AllCount;
6295 if (selectedIndex == -1)
6297 fIdx = tab.AllCount - 1;
6301 fIdx = selectedIndex - 1;
6309 for (var idx = fIdx; idx != toIdx; idx += stp)
6313 var listView = this.CurrentListView;
6314 SelectListItem(listView, idx);
6315 listView.EnsureVisible(idx);
6321 private void GoSamePostToAnotherTab(bool left)
6323 var tab = this.CurrentTab;
6325 // Directタブは対象外(見つかるはずがない)
6326 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6329 var selectedStatusId = tab.SelectedStatusId;
6330 if (selectedStatusId == -1)
6333 int fIdx, toIdx, stp;
6338 if (ListTab.SelectedIndex == 0)
6344 fIdx = ListTab.SelectedIndex - 1;
6352 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6358 fIdx = ListTab.SelectedIndex + 1;
6360 toIdx = ListTab.TabCount;
6364 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6366 var targetTab = this._statuses.Tabs[tabidx];
6369 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6372 var foundIndex = targetTab.IndexOf(selectedStatusId);
6373 if (foundIndex != -1)
6375 ListTab.SelectedIndex = tabidx;
6376 var listView = this.CurrentListView;
6377 SelectListItem(listView, foundIndex);
6378 listView.EnsureVisible(foundIndex);
6384 private void GoPost(bool forward)
6386 var tab = this.CurrentTab;
6387 var currentPost = this.CurrentPost;
6389 if (currentPost == null)
6392 var selectedIndex = tab.SelectedIndex;
6394 int fIdx, toIdx, stp;
6398 fIdx = selectedIndex + 1;
6399 if (fIdx > tab.AllCount - 1) return;
6400 toIdx = tab.AllCount;
6405 fIdx = selectedIndex - 1;
6406 if (fIdx < 0) return;
6412 if (currentPost.RetweetedBy == null)
6414 name = currentPost.ScreenName;
6418 name = currentPost.RetweetedBy;
6420 for (var idx = fIdx; idx != toIdx; idx += stp)
6422 var post = tab[idx];
6423 if (post.RetweetedId == null)
6425 if (post.ScreenName == name)
6427 var listView = this.CurrentListView;
6428 SelectListItem(listView, idx);
6429 listView.EnsureVisible(idx);
6435 if (post.RetweetedBy == name)
6437 var listView = this.CurrentListView;
6438 SelectListItem(listView, idx);
6439 listView.EnsureVisible(idx);
6446 private void GoRelPost(bool forward)
6448 var tab = this.CurrentTab;
6449 var selectedIndex = tab.SelectedIndex;
6451 if (selectedIndex == -1)
6454 int fIdx, toIdx, stp;
6458 fIdx = selectedIndex + 1;
6459 if (fIdx > tab.AllCount - 1) return;
6460 toIdx = tab.AllCount;
6465 fIdx = selectedIndex - 1;
6466 if (fIdx < 0) return;
6473 var currentPost = this.CurrentPost;
6474 if (currentPost == null) return;
6475 _anchorPost = currentPost;
6480 if (_anchorPost == null) return;
6483 for (var idx = fIdx; idx != toIdx; idx += stp)
6485 var post = tab[idx];
6486 if (post.ScreenName == _anchorPost.ScreenName ||
6487 post.RetweetedBy == _anchorPost.ScreenName ||
6488 post.ScreenName == _anchorPost.RetweetedBy ||
6489 (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6490 _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6491 _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6492 post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6493 post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6495 var listView = this.CurrentListView;
6496 SelectListItem(listView, idx);
6497 listView.EnsureVisible(idx);
6503 private void GoAnchor()
6505 if (_anchorPost == null) return;
6506 var idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6507 if (idx == -1) return;
6509 var listView = this.CurrentListView;
6510 SelectListItem(listView, idx);
6511 listView.EnsureVisible(idx);
6514 private void GoTopEnd(bool GoTop)
6516 var listView = this.CurrentListView;
6517 if (listView.VirtualListSize == 0)
6525 _item = listView.GetItemAt(0, 25);
6533 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6535 idx = listView.VirtualListSize - 1;
6539 SelectListItem(listView, idx);
6542 private void GoMiddle()
6544 var listView = this.CurrentListView;
6545 if (listView.VirtualListSize == 0)
6553 _item = listView.GetItemAt(0, 0);
6563 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6566 idx2 = listView.VirtualListSize - 1;
6572 idx3 = (idx1 + idx2) / 2;
6574 SelectListItem(listView, idx3);
6577 private void GoLast()
6579 var listView = this.CurrentListView;
6580 if (listView.VirtualListSize == 0) return;
6582 if (_statuses.SortOrder == SortOrder.Ascending)
6584 SelectListItem(listView, listView.VirtualListSize - 1);
6585 listView.EnsureVisible(listView.VirtualListSize - 1);
6589 SelectListItem(listView, 0);
6590 listView.EnsureVisible(0);
6594 private void MoveTop()
6596 var listView = this.CurrentListView;
6597 if (listView.SelectedIndices.Count == 0) return;
6598 var idx = listView.SelectedIndices[0];
6599 if (_statuses.SortOrder == SortOrder.Ascending)
6601 listView.EnsureVisible(listView.VirtualListSize - 1);
6605 listView.EnsureVisible(0);
6607 listView.EnsureVisible(idx);
6610 private async Task GoInReplyToPostTree()
6612 var curTabClass = this.CurrentTab;
6613 var currentPost = this.CurrentPost;
6615 if (currentPost == null)
6618 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6622 var post = await tw.GetStatusApi(false, currentPost.StatusId);
6624 currentPost.InReplyToStatusId = post.InReplyToStatusId;
6625 currentPost.InReplyToUser = post.InReplyToUser;
6626 currentPost.IsReply = post.IsReply;
6627 this.PurgeListViewItemCache();
6629 var index = curTabClass.SelectedIndex;
6630 this.CurrentListView.RedrawItems(index, index, false);
6632 catch (WebApiException ex)
6634 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6638 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6640 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6642 replyChains = new Stack<ReplyChain>();
6644 replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6647 string inReplyToTabName;
6648 var inReplyToId = currentPost.InReplyToStatusId.Value;
6649 var inReplyToUser = currentPost.InReplyToUser;
6651 var inReplyToPosts = from tab in _statuses.Tabs
6652 orderby tab != curTabClass
6653 from post in tab.Posts.Values
6654 where post.StatusId == inReplyToId
6655 let index = tab.IndexOf(post.StatusId)
6657 select new {Tab = tab, Index = index};
6659 var inReplyPost = inReplyToPosts.FirstOrDefault();
6660 if (inReplyPost == null)
6664 await Task.Run(async () =>
6666 var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6667 .ConfigureAwait(false);
6670 _statuses.AddPost(post);
6671 _statuses.DistributePosts();
6674 catch (WebApiException ex)
6676 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6677 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6681 this.RefreshTimeline();
6683 inReplyPost = inReplyToPosts.FirstOrDefault();
6684 if (inReplyPost == null)
6686 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6690 inReplyToTabName = inReplyPost.Tab.TabName;
6691 inReplyToIndex = inReplyPost.Index;
6693 var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6694 var tabPage = this.ListTab.TabPages[tabIndex];
6695 var listView = (DetailsListView)tabPage.Tag;
6697 if (this.CurrentTabName != inReplyToTabName)
6699 this.ListTab.SelectedIndex = tabIndex;
6702 this.SelectListItem(listView, inReplyToIndex);
6703 listView.EnsureVisible(inReplyToIndex);
6706 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6708 var curTabClass = this.CurrentTab;
6709 var currentPost = this.CurrentPost;
6711 if (currentPost == null)
6716 if (currentPost.InReplyToStatusId != null)
6718 var posts = from t in _statuses.Tabs
6720 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6721 let indexOf = t.IndexOf(p.Value.StatusId)
6723 orderby isForward ? indexOf : indexOf * -1
6724 orderby t != curTabClass
6725 select new {Tab = t, Post = p.Value, Index = indexOf};
6728 var postList = posts.ToList();
6729 for (var i = postList.Count - 1; i >= 0; i--)
6732 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
6734 postList.RemoveAt(index);
6737 var currentIndex = this.CurrentTab.SelectedIndex;
6738 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
6739 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
6740 if (post == null) post = postList.First();
6741 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6742 this.ListTab.SelectedIndex = tabIndex;
6743 var listView = this.CurrentListView;
6744 SelectListItem(listView, post.Index);
6745 listView.EnsureVisible(post.Index);
6747 catch (InvalidOperationException)
6755 if (replyChains == null || replyChains.Count < 1)
6757 var posts = from t in _statuses.Tabs
6759 where p.Value.InReplyToStatusId == currentPost.StatusId
6760 let indexOf = t.IndexOf(p.Value.StatusId)
6763 orderby t != curTabClass
6764 select new {Tab = t, Index = indexOf};
6767 var post = posts.First();
6768 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6769 this.ListTab.SelectedIndex = tabIndex;
6770 var listView = this.CurrentListView;
6771 SelectListItem(listView, post.Index);
6772 listView.EnsureVisible(post.Index);
6774 catch (InvalidOperationException)
6781 var chainHead = replyChains.Pop();
6782 if (chainHead.InReplyToId == currentPost.StatusId)
6784 var tab = chainHead.OriginalTab;
6785 if (!this._statuses.Tabs.Contains(tab))
6791 var idx = tab.IndexOf(chainHead.OriginalId);
6798 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6801 this.ListTab.SelectedIndex = tabIndex;
6807 var listView = this.CurrentListView;
6808 SelectListItem(listView, idx);
6809 listView.EnsureVisible(idx);
6816 this.GoBackInReplyToPostTree(parallel);
6822 private void GoBackSelectPostChain()
6824 if (this.selectPostChains.Count > 1)
6827 TabModel? foundTab = null;
6833 this.selectPostChains.Pop();
6834 var (tab, post) = this.selectPostChains.Peek();
6836 if (!this._statuses.Tabs.Contains(tab))
6837 continue; // 該当タブが存在しないので無視
6841 idx = tab.IndexOf(post.StatusId);
6842 if (idx == -1) continue; //該当ポストが存在しないので無視
6847 this.selectPostChains.Pop();
6849 catch (InvalidOperationException)
6855 while (this.selectPostChains.Count > 1);
6857 if (foundTab == null)
6860 //履歴が残り1つであればクリアしておく
6861 if (this.selectPostChains.Count == 1)
6862 this.selectPostChains.Clear();
6866 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
6867 var tabPage = this.ListTab.TabPages[tabIndex];
6868 var lst = (DetailsListView)tabPage.Tag;
6869 this.ListTab.SelectedIndex = tabIndex;
6873 SelectListItem(lst, idx);
6874 lst.EnsureVisible(idx);
6880 private void PushSelectPostChain()
6882 var currentTab = this.CurrentTab;
6883 var currentPost = this.CurrentPost;
6885 var count = this.selectPostChains.Count;
6888 var (tab, post) = this.selectPostChains.Peek();
6889 if (tab == currentTab)
6891 if (post == currentPost) return; //最新の履歴と同一
6892 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
6895 if (count >= 2500) TrimPostChain();
6896 this.selectPostChains.Push((currentTab, currentPost));
6899 private void TrimPostChain()
6901 if (this.selectPostChains.Count <= 2000) return;
6902 var p = new Stack<(TabModel, PostClass?)>(2000);
6903 for (var i = 0; i < 2000; i++)
6905 p.Push(this.selectPostChains.Pop());
6907 this.selectPostChains.Clear();
6908 for (var i = 0; i < 2000; i++)
6910 this.selectPostChains.Push(p.Pop());
6914 private bool GoStatus(long statusId)
6916 if (statusId == 0) return false;
6918 var tab = this._statuses.Tabs
6919 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
6920 .Where(x => x.Contains(statusId))
6926 var index = tab.IndexOf(statusId);
6928 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6929 this.ListTab.SelectedIndex = tabIndex;
6931 var listView = this.CurrentListView;
6932 this.SelectListItem(listView, index);
6933 listView.EnsureVisible(index);
6938 private bool GoDirectMessage(long statusId)
6940 if (statusId == 0) return false;
6942 var tab = this._statuses.DirectMessageTab;
6943 var index = tab.IndexOf(statusId);
6948 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6949 this.ListTab.SelectedIndex = tabIndex;
6951 var listView = this.CurrentListView;
6952 this.SelectListItem(listView, index);
6953 listView.EnsureVisible(index);
6958 private void MyList_MouseClick(object sender, MouseEventArgs e)
6959 => this._anchorFlag = false;
6961 private void StatusText_Enter(object sender, EventArgs e)
6963 // フォーカスの戻り先を StatusText に設定
6964 this.Tag = StatusText;
6965 StatusText.BackColor = _clInputBackcolor;
6968 public Color InputBackColor
6970 get => _clInputBackcolor;
6971 set => _clInputBackcolor = value;
6974 private void StatusText_Leave(object sender, EventArgs e)
6976 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
6977 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
6978 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
6981 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
6983 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
6986 e.SuppressKeyPress = true;
6989 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
6991 if (asyncTask != null)
6995 private void SaveConfigsAll(bool ifModified)
6999 SaveConfigsCommon();
7006 if (ModifySettingCommon) SaveConfigsCommon();
7007 if (ModifySettingLocal) SaveConfigsLocal();
7008 if (ModifySettingAtId) SaveConfigsAtId();
7012 private void SaveConfigsAtId()
7014 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7016 ModifySettingAtId = false;
7017 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7018 SettingManager.SaveAtIdList();
7021 private void SaveConfigsCommon()
7023 if (_ignoreConfigSave) return;
7025 ModifySettingCommon = false;
7028 SettingManager.Common.UserName = tw.Username;
7029 SettingManager.Common.UserId = tw.UserId;
7030 SettingManager.Common.Token = tw.AccessToken;
7031 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7032 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7033 SettingManager.Common.SortColumn = this._statuses.SortMode switch
7035 ComparerMode.Nickname => 1, // ニックネーム
7036 ComparerMode.Data => 2, // 本文
7037 ComparerMode.Id => 3, // 時刻=発言Id
7038 ComparerMode.Name => 4, // 名前
7039 ComparerMode.Source => 7, // Source
7040 _ => throw new InvalidOperationException($"Invalid sort mode: {this._statuses.SortMode}"),
7042 SettingManager.Common.HashTags = HashMgr.HashHistories;
7043 if (HashMgr.IsPermanent)
7045 SettingManager.Common.HashSelected = HashMgr.UseHash;
7049 SettingManager.Common.HashSelected = "";
7051 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7052 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7053 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7054 SettingManager.Common.TrackWord = tw.TrackWord;
7055 SettingManager.Common.AllAtReply = tw.AllAtReply;
7056 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7057 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7059 SettingManager.SaveCommon();
7063 private void SaveConfigsLocal()
7065 if (_ignoreConfigSave) return;
7068 ModifySettingLocal = false;
7069 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7070 SettingManager.Local.FormSize = _mySize;
7071 SettingManager.Local.FormLocation = _myLoc;
7072 SettingManager.Local.SplitterDistance = _mySpDis;
7073 SettingManager.Local.PreviewDistance = _mySpDis3;
7074 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7075 SettingManager.Local.StatusTextHeight = _mySpDis2;
7077 SettingManager.Local.FontUnread = _fntUnread;
7078 SettingManager.Local.ColorUnread = _clUnread;
7079 SettingManager.Local.FontRead = _fntReaded;
7080 SettingManager.Local.ColorRead = _clReaded;
7081 SettingManager.Local.FontDetail = _fntDetail;
7082 SettingManager.Local.ColorDetail = _clDetail;
7083 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7084 SettingManager.Local.ColorDetailLink = _clDetailLink;
7085 SettingManager.Local.ColorFav = _clFav;
7086 SettingManager.Local.ColorOWL = _clOWL;
7087 SettingManager.Local.ColorRetweet = _clRetweet;
7088 SettingManager.Local.ColorSelf = _clSelf;
7089 SettingManager.Local.ColorAtSelf = _clAtSelf;
7090 SettingManager.Local.ColorTarget = _clTarget;
7091 SettingManager.Local.ColorAtTarget = _clAtTarget;
7092 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7093 SettingManager.Local.ColorAtTo = _clAtTo;
7094 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7095 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7096 SettingManager.Local.ColorInputFont = _clInputFont;
7097 SettingManager.Local.FontInputFont = _fntInputFont;
7099 if (_ignoreConfigSave) return;
7100 SettingManager.SaveLocal();
7104 private void SaveConfigsTabs()
7106 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7108 var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7110 foreach (var tab in tabs)
7112 if (!tab.IsPermanentTabType)
7115 var tabSetting = new SettingTabs.SettingTabItem
7117 TabName = tab.TabName,
7118 TabType = tab.TabType,
7119 UnreadManage = tab.UnreadManage,
7120 Protected = tab.Protected,
7121 Notify = tab.Notify,
7122 SoundFile = tab.SoundFile,
7127 case FilterTabModel filterTab:
7128 tabSetting.FilterArray = filterTab.FilterArray;
7130 case UserTimelineTabModel userTab:
7131 tabSetting.User = userTab.ScreenName;
7133 case PublicSearchTabModel searchTab:
7134 tabSetting.SearchWords = searchTab.SearchWords;
7135 tabSetting.SearchLang = searchTab.SearchLang;
7137 case ListTimelineTabModel listTab:
7138 tabSetting.ListInfo = listTab.ListInfo;
7142 tabSettingList.Add(tabSetting);
7145 SettingManager.Tabs.Tabs = tabSettingList;
7146 SettingManager.SaveTabs();
7149 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7151 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7152 if (ret != DialogResult.OK)
7155 var match = Twitter.StatusUrlRegex.Match(inputText);
7158 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7159 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7165 var statusId = long.Parse(match.Groups["StatusId"].Value);
7166 await this.OpenRelatedTab(statusId);
7168 catch (TabException ex)
7170 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7174 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7176 var tab = this.CurrentTab;
7178 var rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7179 Properties.Resources.SaveLogMenuItem_ClickText2,
7180 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7181 if (rslt == DialogResult.Cancel) return;
7183 SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7184 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7185 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7186 SaveFileDialog1.FilterIndex = 0;
7187 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7188 SaveFileDialog1.RestoreDirectory = true;
7190 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7192 if (!SaveFileDialog1.ValidateNames) return;
7193 using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
7194 if (rslt == DialogResult.Yes)
7197 for (var idx = 0; idx < tab.AllCount; idx++)
7199 var post = tab[idx];
7202 protect = "Protect";
7203 sw.WriteLine(post.Nickname + "\t" +
7204 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7205 post.CreatedAt.ToLocalTimeString() + "\t" +
7206 post.ScreenName + "\t" +
7207 post.StatusId + "\t" +
7208 post.ImageUrl + "\t" +
7209 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7215 foreach (var post in this.CurrentTab.SelectedPosts)
7219 protect = "Protect";
7220 sw.WriteLine(post.Nickname + "\t" +
7221 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7222 post.CreatedAt.ToLocalTimeString() + "\t" +
7223 post.ScreenName + "\t" +
7224 post.StatusId + "\t" +
7225 post.ImageUrl + "\t" +
7226 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7231 this.TopMost = SettingManager.Common.AlwaysTop;
7234 public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
7238 using (var inputName = new InputTabName())
7240 inputName.TabName = origTabName;
7241 inputName.ShowDialog();
7242 if (inputName.DialogResult == DialogResult.Cancel) return false;
7243 newTabName = inputName.TabName;
7245 this.TopMost = SettingManager.Common.AlwaysTop;
7246 if (!MyCommon.IsNullOrEmpty(newTabName))
7249 if (this._statuses.ContainsTab(newTabName))
7251 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7252 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7256 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7257 var tabPage = this.ListTab.TabPages[tabIndex];
7260 if (tabPage != null)
7261 tabPage.Text = newTabName;
7263 _statuses.RenameTab(origTabName, newTabName);
7265 SaveConfigsCommon();
7267 _rclickTabName = newTabName;
7276 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7278 if (e.Button == MouseButtons.Middle)
7280 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7282 if (this.ListTab.GetTabRect(index).Contains(e.Location))
7284 this.RemoveSpecifiedTab(tab.TabName, true);
7285 this.SaveConfigsTabs();
7292 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7293 => this.TabRename(this.CurrentTabName, out _);
7295 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7297 if (SettingManager.Common.TabMouseLock) return;
7298 if (e.Button == MouseButtons.Left)
7300 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7302 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7305 _tabMouseDownPoint = e.Location;
7316 private void ListTab_DragEnter(object sender, DragEventArgs e)
7318 if (e.Data.GetDataPresent(typeof(TabPage)))
7319 e.Effect = DragDropEffects.Move;
7321 e.Effect = DragDropEffects.None;
7324 private void ListTab_DragDrop(object sender, DragEventArgs e)
7326 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7331 var cpos = new Point(e.X, e.Y);
7332 var spos = ListTab.PointToClient(cpos);
7333 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7335 var rect = ListTab.GetTabRect(index);
7336 if (rect.Contains(spos))
7339 if (spos.X <= (rect.Left + rect.Right) / 2)
7348 //タブのないところにドロップ->最後尾へ移動
7349 if (MyCommon.IsNullOrEmpty(tn))
7351 var lastTab = this._statuses.Tabs.Last();
7352 tn = lastTab.TabName;
7356 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
7357 if (tp.Text == tn) return;
7359 ReOrderTab(tp.Text, tn, bef);
7362 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7364 var baseIndex = this.GetTabPageIndex(baseTabText);
7365 if (baseIndex == -1)
7368 var targetIndex = this.GetTabPageIndex(targetTabText);
7369 if (targetIndex == -1)
7372 using (ControlTransaction.Layout(this.ListTab))
7374 var tab = this._statuses.Tabs[targetIndex];
7375 var tabPage = this.ListTab.TabPages[targetIndex];
7377 this.ListTab.TabPages.Remove(tabPage);
7379 if (targetIndex < baseIndex)
7382 if (!isBeforeBaseTab)
7385 this._statuses.MoveTab(baseIndex, tab);
7387 ListTab.TabPages.Insert(baseIndex, tabPage);
7393 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7395 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7396 //isReply:true=@,false=DM
7397 if (!StatusText.Enabled) return;
7398 if (!this.ExistCurrentPost) return;
7400 var tab = this.CurrentTab;
7401 var selectedPosts = tab.SelectedPosts;
7403 // 複数あてリプライはReplyではなく通常ポスト
7404 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7405 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7406 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7408 if (selectedPosts.Length > 0)
7411 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7413 var post = selectedPosts.Single();
7416 if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7419 this.inReplyTo = null;
7420 StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7421 StatusText.SelectionStart = StatusText.Text.Length;
7425 if (MyCommon.IsNullOrEmpty(StatusText.Text))
7428 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7429 var inReplyToScreenName = post.ScreenName;
7430 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7432 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7433 StatusText.Text = "@" + post.ScreenName + " ";
7441 //1件選んでEnter or DoubleClick
7442 if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7444 if (this.inReplyTo?.ScreenName == post.ScreenName)
7447 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7448 var inReplyToScreenName = post.ScreenName;
7449 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7453 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7456 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7459 this.inReplyTo = null;
7460 StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7465 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7466 var inReplyToScreenName = post.ScreenName;
7467 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7468 StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7475 this.inReplyTo = null;
7476 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7481 //1件選んでCtrl-Rの場合(返信先操作せず)
7482 var sidx = StatusText.SelectionStart;
7483 var id = "@" + post.ScreenName + " ";
7486 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7491 StatusText.Text = StatusText.Text.Insert(sidx, id);
7493 StatusText.SelectionStart = sidx;
7502 if (!isAuto && !isReply) return;
7504 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7508 //Enter or DoubleClick
7510 var sTxt = StatusText.Text;
7511 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7514 this.inReplyTo = null;
7516 foreach (var post in selectedPosts)
7518 if (!sTxt.Contains("@" + post.ScreenName + " "))
7519 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7521 StatusText.Text = sTxt;
7527 if (selectedPosts.Length > 1)
7532 var sidx = StatusText.SelectionStart;
7533 foreach (var post in selectedPosts)
7535 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7537 ids += "@" + post.ScreenName + " ";
7541 foreach (var (_, screenName) in post.ReplyToList)
7543 if (!ids.Contains("@" + screenName + " ") &&
7544 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7546 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7548 ids += "@" + m.Result("${id}") + " ";
7550 ids += "@" + screenName + " ";
7555 if (ids.Length == 0) return;
7556 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7558 this.inReplyTo = null;
7559 StatusText.Text = ". " + StatusText.Text;
7564 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7569 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7571 StatusText.SelectionStart = sidx;
7577 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7580 var sidx = StatusText.SelectionStart;
7581 var post = selectedPosts.Single();
7582 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7584 ids += "@" + post.ScreenName + " ";
7586 foreach (var (_, screenName) in post.ReplyToList)
7588 if (!ids.Contains("@" + screenName + " ") &&
7589 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7591 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7593 ids += "@" + m.Result("${id}") + " ";
7595 ids += "@" + screenName + " ";
7598 if (!MyCommon.IsNullOrEmpty(post.RetweetedBy))
7600 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7602 ids += "@" + post.RetweetedBy + " ";
7605 if (ids.Length == 0) return;
7606 if (MyCommon.IsNullOrEmpty(StatusText.Text))
7609 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7610 var inReplyToScreenName = post.ScreenName;
7611 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7613 StatusText.Text = ids;
7614 StatusText.SelectionStart = ids.Length;
7621 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7626 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7628 StatusText.SelectionStart = sidx;
7634 StatusText.SelectionStart = StatusText.Text.Length;
7639 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7640 => this._tabDrag = false;
7642 private int iconCnt = 0;
7643 private int blinkCnt = 0;
7644 private bool blink = false;
7646 private void RefreshTasktrayIcon()
7648 void EnableTasktrayAnimation()
7649 => this.TimerRefreshIcon.Enabled = true;
7651 void DisableTasktrayAnimation()
7652 => this.TimerRefreshIcon.Enabled = false;
7654 var busyTasks = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7658 if (iconCnt >= this.NIconRefresh.Length)
7661 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7662 _myStatusError = false;
7663 EnableTasktrayAnimation();
7667 var replyIconType = SettingManager.Common.ReplyIconState;
7669 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
7671 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
7672 if (replyTab != null && replyTab.UnreadCount > 0)
7676 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
7685 NotifyIcon1.Icon = blink ? ReplyIconBlink : ReplyIcon;
7686 EnableTasktrayAnimation();
7690 DisableTasktrayAnimation();
7696 // 優先度:リプライ→エラー→オフライン→アイドル
7697 // エラーは更新アイコンでクリアされる
7698 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
7699 NotifyIcon1.Icon = ReplyIcon;
7700 else if (_myStatusError)
7701 NotifyIcon1.Icon = NIconAtRed;
7702 else if (_myStatusOnline)
7703 NotifyIcon1.Icon = NIconAt;
7705 NotifyIcon1.Icon = NIconAtSmoke;
7708 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
7709 => this.RefreshTasktrayIcon(); // 200ms
7711 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7713 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7714 if (MyCommon.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7715 _rclickTabName = this.CurrentTabName;
7717 if (_statuses == null) return;
7718 if (_statuses.Tabs == null) return;
7720 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7723 NotifyDispMenuItem.Checked = tb.Notify;
7724 this.NotifyTbMenuItem.Checked = tb.Notify;
7726 soundfileListup = true;
7727 SoundFileComboBox.Items.Clear();
7728 this.SoundFileTbComboBox.Items.Clear();
7729 SoundFileComboBox.Items.Add("");
7730 this.SoundFileTbComboBox.Items.Add("");
7731 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7732 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7734 oDir = oDir.GetDirectories("Sounds")[0];
7736 foreach (var oFile in oDir.GetFiles("*.wav"))
7738 SoundFileComboBox.Items.Add(oFile.Name);
7739 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7741 var idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7742 if (idx == -1) idx = 0;
7743 SoundFileComboBox.SelectedIndex = idx;
7744 this.SoundFileTbComboBox.SelectedIndex = idx;
7745 soundfileListup = false;
7746 UreadManageMenuItem.Checked = tb.UnreadManage;
7747 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7749 TabMenuControl(_rclickTabName);
7752 private void TabMenuControl(string tabName)
7754 var tabInfo = _statuses.GetTabByName(tabName)!;
7756 this.FilterEditMenuItem.Enabled = true;
7757 this.EditRuleTbMenuItem.Enabled = true;
7759 if (tabInfo.IsDefaultTabType)
7761 this.ProtectTabMenuItem.Enabled = false;
7762 this.ProtectTbMenuItem.Enabled = false;
7766 this.ProtectTabMenuItem.Enabled = true;
7767 this.ProtectTbMenuItem.Enabled = true;
7770 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7772 this.ProtectTabMenuItem.Checked = true;
7773 this.ProtectTbMenuItem.Checked = true;
7774 this.DeleteTabMenuItem.Enabled = false;
7775 this.DeleteTbMenuItem.Enabled = false;
7779 this.ProtectTabMenuItem.Checked = false;
7780 this.ProtectTbMenuItem.Checked = false;
7781 this.DeleteTabMenuItem.Enabled = true;
7782 this.DeleteTbMenuItem.Enabled = true;
7786 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7788 var checkState = ((ToolStripMenuItem)sender).Checked;
7791 this.ProtectTbMenuItem.Checked = checkState;
7792 this.ProtectTabMenuItem.Checked = checkState;
7795 this.DeleteTabMenuItem.Enabled = !checkState;
7796 this.DeleteTbMenuItem.Enabled = !checkState;
7798 if (MyCommon.IsNullOrEmpty(_rclickTabName)) return;
7799 _statuses.Tabs[_rclickTabName].Protected = checkState;
7804 private void UreadManageMenuItem_Click(object sender, EventArgs e)
7806 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7807 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7809 if (MyCommon.IsNullOrEmpty(_rclickTabName)) return;
7810 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7815 public void ChangeTabUnreadManage(string tabName, bool isManage)
7817 var idx = this.GetTabPageIndex(tabName);
7821 var tab = this._statuses.Tabs[tabName];
7822 tab.UnreadManage = isManage;
7824 if (SettingManager.Common.TabIconDisp)
7826 var tabPage = this.ListTab.TabPages[idx];
7827 if (tab.UnreadCount > 0)
7828 tabPage.ImageIndex = 0;
7830 tabPage.ImageIndex = -1;
7833 if (this.CurrentTabName == tabName)
7835 this.PurgeListViewItemCache();
7836 this.CurrentListView.Refresh();
7839 SetMainWindowTitle();
7840 SetStatusLabelUrl();
7841 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
7844 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
7846 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7847 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
7849 if (MyCommon.IsNullOrEmpty(_rclickTabName)) return;
7851 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
7856 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
7858 if (soundfileListup || MyCommon.IsNullOrEmpty(_rclickTabName)) return;
7860 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
7865 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
7867 if (MyCommon.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
7868 _rclickTabName = this.CurrentTabName;
7870 RemoveSpecifiedTab(_rclickTabName, true);
7874 private void FilterEditMenuItem_Click(object sender, EventArgs e)
7876 if (MyCommon.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.HomeTab.TabName;
7878 using (var fltDialog = new FilterDialog())
7880 fltDialog.Owner = this;
7881 fltDialog.SetCurrent(_rclickTabName);
7882 fltDialog.ShowDialog(this);
7884 this.TopMost = SettingManager.Common.AlwaysTop;
7886 this.ApplyPostFilters();
7890 private async void AddTabMenuItem_Click(object sender, EventArgs e)
7892 string? tabName = null;
7893 MyCommon.TabUsageType tabUsage;
7894 using (var inputName = new InputTabName())
7896 inputName.TabName = _statuses.MakeTabName("MyTab");
7897 inputName.IsShowUsage = true;
7898 inputName.ShowDialog();
7899 if (inputName.DialogResult == DialogResult.Cancel) return;
7900 tabName = inputName.TabName;
7901 tabUsage = inputName.Usage;
7903 this.TopMost = SettingManager.Common.AlwaysTop;
7904 if (!MyCommon.IsNullOrEmpty(tabName))
7907 ListElement? list = null;
7908 if (tabUsage == MyCommon.TabUsageType.Lists)
7910 using var listAvail = new ListAvailable();
7911 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
7913 if (listAvail.SelectedList == null)
7915 list = listAvail.SelectedList;
7921 case MyCommon.TabUsageType.UserDefined:
7922 tab = new FilterTabModel(tabName);
7924 case MyCommon.TabUsageType.PublicSearch:
7925 tab = new PublicSearchTabModel(tabName);
7927 case MyCommon.TabUsageType.Lists:
7928 tab = new ListTimelineTabModel(tabName, list!);
7934 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
7936 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
7937 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7944 var tabIndex = this._statuses.Tabs.Count - 1;
7946 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
7948 ListTab.SelectedIndex = tabIndex;
7949 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
7951 if (tabUsage == MyCommon.TabUsageType.Lists)
7953 ListTab.SelectedIndex = tabIndex;
7954 await this.RefreshTabAsync(this.CurrentTab);
7960 private void TabMenuItem_Click(object sender, EventArgs e)
7962 using (var fltDialog = new FilterDialog())
7964 fltDialog.Owner = this;
7967 foreach (var post in this.CurrentTab.SelectedPosts)
7970 if (!SelectTab(out var tab)) return;
7972 fltDialog.SetCurrent(tab.TabName);
7974 if (post.RetweetedBy == null)
7976 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
7980 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
7982 fltDialog.ShowDialog(this);
7983 this.TopMost = SettingManager.Common.AlwaysTop;
7987 this.ApplyPostFilters();
7991 protected override bool ProcessDialogKey(Keys keyData)
7993 //TextBox1でEnterを押してもビープ音が鳴らないようにする
7994 if ((keyData & Keys.KeyCode) == Keys.Enter)
7996 if (StatusText.Focused)
7998 var _NewLine = false;
8001 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8003 if (StatusText.Multiline)
8005 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8007 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8011 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8015 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8017 if (StatusText.Multiline)
8019 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8021 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8025 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8031 if (StatusText.Multiline)
8033 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8035 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8036 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8040 if (((keyData & Keys.Shift) == Keys.Shift) ||
8041 (((keyData & Keys.Control) != Keys.Control) &&
8042 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8048 var pos1 = StatusText.SelectionStart;
8049 if (StatusText.SelectionLength > 0)
8051 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8053 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8054 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8059 PostButton_Click(this.PostButton, EventArgs.Empty);
8065 var tab = this.CurrentTab;
8066 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8068 var tabPage = this.CurrentTabPage;
8069 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8070 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8072 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
8079 return base.ProcessDialogKey(keyData);
8082 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8083 => this.MakeReplyOrDirectStatus(false, true, true);
8085 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8087 var tab = this.CurrentTab;
8088 var selectedPosts = tab.SelectedPosts;
8091 if (selectedPosts.Length == 0)
8094 var screenNameArray = selectedPosts
8095 .Select(x => x.RetweetedBy ?? x.ScreenName)
8098 this.AddFilterRuleByScreenName(screenNameArray);
8100 if (screenNameArray.Length != 0)
8102 var atids = new List<string>();
8103 foreach (var screenName in screenNameArray)
8105 atids.Add("@" + screenName);
8107 var cnt = AtIdSupl.ItemCount;
8108 AtIdSupl.AddRangeItem(atids.ToArray());
8109 if (AtIdSupl.ItemCount != cnt)
8110 this.MarkSettingAtIdModified();
8114 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8116 var tab = this.CurrentTab;
8117 var selectedPosts = tab.SelectedPosts;
8119 if (selectedPosts.Length == 0)
8122 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8124 this.AddFilterRuleBySource(sourceArray);
8127 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8130 if (!SelectTab(out var tab)) return;
8134 if (tab.TabType != MyCommon.TabUsageType.Mute)
8136 this.MoveOrCopy(out mv, out mk);
8140 // ミュートタブでは常に MoveMatches を true にする
8145 foreach (var screenName in screenNameArray)
8147 tab.AddFilter(new PostFilterRule
8149 FilterName = screenName,
8150 UseNameField = true,
8154 FilterByUrl = false,
8158 this.ApplyPostFilters();
8162 public void AddFilterRuleBySource(params string[] sourceArray)
8164 // タブ選択ダイアログを表示(or追加)
8165 if (!this.SelectTab(out var filterTab))
8170 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8172 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8173 this.MoveOrCopy(out mv, out mk);
8177 // ミュートタブでは常に MoveMatches を true にする
8182 // 振り分けルールに追加するSource
8183 foreach (var source in sourceArray)
8185 filterTab.AddFilter(new PostFilterRule
8187 FilterSource = source,
8191 FilterByUrl = false,
8195 this.ApplyPostFilters();
8196 this.SaveConfigsTabs();
8199 private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
8206 using (var dialog = new TabsDialog(_statuses))
8208 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8210 tab = dialog.SelectedTab;
8213 this.CurrentTabPage.Focus();
8218 using (var inputName = new InputTabName())
8220 inputName.TabName = _statuses.MakeTabName("MyTab");
8221 inputName.ShowDialog();
8222 if (inputName.DialogResult == DialogResult.Cancel) return false;
8223 tabName = inputName.TabName;
8225 this.TopMost = SettingManager.Common.AlwaysTop;
8226 if (!MyCommon.IsNullOrEmpty(tabName))
8228 var newTab = new FilterTabModel(tabName);
8229 if (!_statuses.AddTab(newTab) || !AddNewTab(newTab, startup: false))
8231 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8232 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8251 private void MoveOrCopy(out bool move, out bool mark)
8255 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8256 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8264 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8265 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8276 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8279 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8280 => this.CopyIdUri();
8282 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8284 if (StatusText.Focused)
8287 StatusText.SelectAll();
8291 // ListView上でのCtrl+A
8292 NativeMethods.SelectAllItems(this.CurrentListView);
8296 private void MoveMiddle()
8302 var listView = this.CurrentListView;
8303 if (listView.SelectedIndices.Count == 0) return;
8305 var idx = listView.SelectedIndices[0];
8307 _item = listView.GetItemAt(0, 25);
8313 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8315 idx2 = listView.VirtualListSize - 1;
8319 idx -= Math.Abs(idx1 - idx2) / 2;
8320 if (idx < 0) idx = 0;
8322 listView.EnsureVisible(listView.VirtualListSize - 1);
8323 listView.EnsureVisible(idx);
8326 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8328 var linkElements = this.tweetDetailsView.GetLinkElements();
8330 if (linkElements.Length == 0)
8333 var links = new List<OpenUrlItem>(linkElements.Length);
8335 foreach (var linkElm in linkElements)
8337 var displayUrl = linkElm.GetAttribute("title");
8338 var href = linkElm.GetAttribute("href");
8339 var linkedText = linkElm.InnerText;
8341 if (MyCommon.IsNullOrEmpty(displayUrl))
8344 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
8348 bool isReverseSettings;
8350 if (links.Count == 1)
8352 // ツイートに含まれる URL が 1 つのみの場合
8353 // => OpenURL ダイアログを表示せずにリンクを開く
8354 selectedUrl = links[0].Href;
8356 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8357 isReverseSettings = false;
8361 // ツイートに含まれる URL が複数ある場合
8362 // => OpenURL を表示しユーザーが選択したリンクを開く
8363 this.UrlDialog.ClearUrl();
8365 foreach (var link in links)
8366 this.UrlDialog.AddUrl(link);
8368 if (this.UrlDialog.ShowDialog(this) != DialogResult.OK)
8371 this.TopMost = SettingManager.Common.AlwaysTop;
8373 selectedUrl = this.UrlDialog.SelectedUrl;
8375 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8376 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
8379 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
8382 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8384 if (MyCommon.IsNullOrEmpty(_rclickTabName)) return;
8385 ClearTab(_rclickTabName, true);
8388 private void ClearTab(string tabName, bool showWarning)
8392 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8393 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8399 _statuses.ClearTabIds(tabName);
8400 if (this.CurrentTabName == tabName)
8403 _anchorFlag = false;
8404 this.PurgeListViewItemCache();
8407 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8408 var tabPage = this.ListTab.TabPages[tabIndex];
8409 tabPage.ImageIndex = -1;
8411 var listView = (DetailsListView)tabPage.Tag;
8412 listView.VirtualListSize = 0;
8414 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8416 SetMainWindowTitle();
8417 SetStatusLabelUrl();
8420 private static long followers = 0;
8422 private void SetMainWindowTitle()
8425 var ttl = new StringBuilder(256);
8428 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8429 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8430 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8431 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8433 foreach (var tab in _statuses.Tabs)
8435 ur += tab.UnreadCount;
8440 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8441 ttl.Append(ApplicationSettings.ApplicationName);
8443 switch (SettingManager.Common.DispLatestPost)
8445 case MyCommon.DispTitleEnum.Ver:
8446 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8448 case MyCommon.DispTitleEnum.Post:
8449 if (_history != null && _history.Count > 1)
8450 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8452 case MyCommon.DispTitleEnum.UnreadRepCount:
8453 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8455 case MyCommon.DispTitleEnum.UnreadAllCount:
8456 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8458 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8459 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.MentionTab.UnreadCount + _statuses.DirectMessageTab.UnreadCount);
8461 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8462 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8464 case MyCommon.DispTitleEnum.OwnStatus:
8465 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8466 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8472 this.Text = ttl.ToString();
8474 catch (AccessViolationException)
8476 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8480 private string GetStatusLabelText()
8483 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8484 if (_statuses == null) return "";
8485 var tbRep = _statuses.MentionTab;
8486 var tbDm = _statuses.DirectMessageTab;
8487 if (tbRep == null || tbDm == null) return "";
8488 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
8493 var slbl = new StringBuilder(256);
8496 foreach (var tab in _statuses.Tabs)
8498 ur += tab.UnreadCount;
8500 if (tab.TabName == this.CurrentTabName)
8502 tur = tab.UnreadCount;
8513 UnreadAtCounter = urat;
8515 var homeTab = this._statuses.HomeTab;
8517 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8518 if (SettingManager.Common.TimelinePeriod == 0)
8520 slbl.Append(Properties.Resources.SetStatusLabelText2);
8524 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8526 return slbl.ToString();
8529 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8533 if (this.InvokeRequired && !this.IsDisposed)
8535 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8539 var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
8540 SetApiStatusLabel(endpointName);
8543 catch (ObjectDisposedException)
8547 catch (InvalidOperationException)
8553 private void SetApiStatusLabel(string? endpointName = null)
8555 var tabType = this.CurrentTab.TabType;
8557 if (endpointName == null)
8560 endpointName = tabType switch
8562 MyCommon.TabUsageType.Home => "/statuses/home_timeline",
8563 MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
8564 MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
8565 MyCommon.TabUsageType.Favorites => "/favorites/list",
8566 MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
8567 MyCommon.TabUsageType.UserTimeline => "/statuses/user_timeline",
8568 MyCommon.TabUsageType.Lists => "/lists/statuses",
8569 MyCommon.TabUsageType.PublicSearch => "/search/tweets",
8570 MyCommon.TabUsageType.Related => "/statuses/show/:id",
8573 this.toolStripApiGauge.ApiEndpoint = endpointName;
8577 // 表示中のタブに関連する endpoint であれば更新
8578 var update = endpointName switch
8580 "/statuses/home_timeline" => tabType == MyCommon.TabUsageType.Home || tabType == MyCommon.TabUsageType.UserDefined,
8581 "/statuses/mentions_timeline" => tabType == MyCommon.TabUsageType.Mentions,
8582 "/favorites/list" => tabType == MyCommon.TabUsageType.Favorites,
8583 "/direct_messages/events/list" => tabType == MyCommon.TabUsageType.DirectMessage,
8584 "/statuses/user_timeline" => tabType == MyCommon.TabUsageType.UserTimeline,
8585 "/lists/statuses" => tabType == MyCommon.TabUsageType.Lists,
8586 "/search/tweets" => tabType == MyCommon.TabUsageType.PublicSearch,
8587 "/statuses/show/:id" => tabType == MyCommon.TabUsageType.Related,
8592 this.toolStripApiGauge.ApiEndpoint = endpointName;
8597 private void SetStatusLabelUrl()
8598 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8600 public void SetStatusLabel(string text)
8601 => this.StatusLabel.Text = text;
8603 private void SetNotifyIconText()
8605 var ur = new StringBuilder(64);
8607 // タスクトレイアイコンのツールチップテキスト書き換え
8609 ur.Remove(0, ur.Length);
8610 if (SettingManager.Common.DispUsername)
8612 ur.Append(tw.Username);
8615 ur.Append(ApplicationSettings.ApplicationName);
8617 ur.Append("(Debug Build)");
8619 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8622 ur.Append(UnreadCounter);
8624 ur.Append(UnreadAtCounter);
8627 NotifyIcon1.Text = ur.ToString();
8630 internal void CheckReplyTo(string StatusText)
8634 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8636 foreach (Match hm in m)
8638 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8640 hstr += "#" + hm.Result("$3") + " ";
8641 HashSupl.AddItem("#" + hm.Result("$3"));
8644 if (!MyCommon.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8646 hstr += HashMgr.UseHash;
8648 if (!MyCommon.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8650 // 本当にリプライ先指定すべきかどうかの判定
8651 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8653 if (SettingManager.Common.UseAtIdSupplement)
8655 var bCnt = AtIdSupl.ItemCount;
8656 foreach (Match mid in m)
8658 AtIdSupl.AddItem(mid.Result("${id}"));
8660 if (bCnt != AtIdSupl.ItemCount)
8661 this.MarkSettingAtIdModified();
8664 // リプライ先ステータスIDの指定がない場合は指定しない
8665 if (this.inReplyTo == null)
8669 // 次の条件を満たす場合に in_reply_to_status_id 指定
8670 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8671 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8672 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8676 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8677 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8679 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8683 foreach (Match mid in m)
8685 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8690 this.inReplyTo = null;
8693 private void TweenMain_Resize(object sender, EventArgs e)
8695 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8697 this.Visible = false;
8699 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8701 // 現在の DPI と設定保存時の DPI との比を取得する
8702 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8704 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8707 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8708 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8709 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8711 this.SplitContainer1.SplitterDistance = splitterDistance;
8715 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8716 if (StatusText.Multiline)
8718 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8719 var dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8720 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8722 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8724 StatusText.Height = statusTextHeight;
8728 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8730 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8734 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8735 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8737 this.SplitContainer3.SplitterDistance = previewDistance;
8740 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8741 this.SplitContainer3.Panel2Collapsed = true;
8743 _initialLayout = false;
8745 if (this.WindowState != FormWindowState.Minimized)
8747 _formWindowState = this.WindowState;
8751 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8753 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8754 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8755 if (PlaySoundMenuItem.Checked)
8757 SettingManager.Common.PlaySound = true;
8761 SettingManager.Common.PlaySound = false;
8763 this.MarkSettingCommonModified();
8766 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
8768 if (this._initialLayout)
8771 int splitterDistance;
8772 switch (this.WindowState)
8774 case FormWindowState.Normal:
8775 splitterDistance = this.SplitContainer1.SplitterDistance;
8777 case FormWindowState.Maximized:
8778 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8779 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
8780 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
8781 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
8787 this._mySpDis = splitterDistance;
8788 this.MarkSettingLocalModified();
8791 private async Task doRepliedStatusOpen()
8793 var currentPost = this.CurrentPost;
8794 if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
8796 if (MyCommon.IsKeyDown(Keys.Shift))
8798 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
8801 if (this._statuses.Posts.TryGetValue(currentPost.InReplyToStatusId.Value, out var repPost))
8803 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
8807 foreach (var tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
8809 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
8810 repPost = tb.Posts[currentPost.InReplyToStatusId.Value];
8811 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
8814 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
8819 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
8820 => await this.doRepliedStatusOpen();
8822 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
8824 if (this._initialLayout)
8825 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
8827 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
8828 if (multiline != this.StatusText.Multiline)
8830 this.StatusText.Multiline = multiline;
8831 SettingManager.Local.StatusMultiline = multiline;
8832 this.MarkSettingLocalModified();
8836 private void StatusText_MultilineChanged(object sender, EventArgs e)
8838 if (this.StatusText.Multiline)
8839 this.StatusText.ScrollBars = ScrollBars.Vertical;
8841 this.StatusText.ScrollBars = ScrollBars.None;
8843 if (!this._initialLayout)
8844 this.MarkSettingLocalModified();
8847 private void MultiLineMenuItem_Click(object sender, EventArgs e)
8850 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
8851 StatusText.Multiline = menuItemChecked;
8852 SettingManager.Local.StatusMultiline = menuItemChecked;
8853 if (menuItemChecked)
8855 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
8856 SplitContainer2.SplitterDistance = 0;
8858 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
8862 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8864 this.MarkSettingLocalModified();
8867 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
8869 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
8871 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
8872 if (MyCommon.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
8873 (MyCommon.IsNullOrEmpty(SettingManager.Common.BilyUser) || MyCommon.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
8875 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
8880 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
8881 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
8882 //Appendix A. Collected ABNF for URI
8883 //http://www.ietf.org/rfc/rfc3986.txt
8885 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
8888 if (StatusText.SelectionLength > 0)
8890 var tmp = StatusText.SelectedText;
8891 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
8892 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
8894 // 文字列が選択されている場合はその文字列について処理
8896 //nico.ms使用、nicovideoにマッチしたら変換
8897 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
8899 result = nicoms.Shorten(tmp);
8901 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
8906 var srcUri = new Uri(tmp);
8907 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
8908 result = resultUri.AbsoluteUri;
8910 catch (WebApiException e)
8912 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
8915 catch (UriFormatException e)
8917 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
8926 if (!MyCommon.IsNullOrEmpty(result))
8928 var undotmp = new urlUndo();
8930 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
8931 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
8932 if (origUrlIndex == -1)
8935 StatusText.Select(origUrlIndex, tmp.Length);
8936 StatusText.SelectedText = result;
8939 undotmp.Before = tmp;
8940 undotmp.After = result;
8942 if (urlUndoBuffer == null)
8944 urlUndoBuffer = new List<urlUndo>();
8945 UrlUndoToolStripMenuItem.Enabled = true;
8948 urlUndoBuffer.Add(undotmp);
8954 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
8955 @"(?<url>(?<protocol>https?://)" +
8956 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
8957 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
8958 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
8959 // 正規表現にマッチしたURL文字列をtinyurl化
8960 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
8962 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
8964 var tmp = mt.Result("${url}");
8965 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
8966 tmp = "http://" + tmp;
8967 var undotmp = new urlUndo();
8970 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
8972 //nico.ms使用、nicovideoにマッチしたら変換
8973 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
8975 result = nicoms.Shorten(tmp);
8977 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
8982 var srcUri = new Uri(tmp);
8983 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
8984 result = resultUri.AbsoluteUri;
8986 catch (HttpRequestException e)
8988 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
8989 // のように長いので「:」が含まれていればそれ以降のみを抽出する
8990 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
8992 this.StatusLabel.Text = Converter_Type + ":" + message;
8995 catch (WebApiException e)
8997 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9000 catch (UriFormatException e)
9002 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9011 if (!MyCommon.IsNullOrEmpty(result))
9013 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9014 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9015 if (origUrlIndex == -1)
9018 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9019 StatusText.SelectedText = result;
9021 undotmp.Before = mt.Result("${url}");
9022 undotmp.After = result;
9024 if (urlUndoBuffer == null)
9026 urlUndoBuffer = new List<urlUndo>();
9027 UrlUndoToolStripMenuItem.Enabled = true;
9030 urlUndoBuffer.Add(undotmp);
9038 private void doUrlUndo()
9040 if (urlUndoBuffer != null)
9042 var tmp = StatusText.Text;
9043 foreach (var data in urlUndoBuffer)
9045 tmp = tmp.Replace(data.After, data.Before);
9047 StatusText.Text = tmp;
9048 urlUndoBuffer = null;
9049 UrlUndoToolStripMenuItem.Enabled = false;
9050 StatusText.SelectionStart = 0;
9051 StatusText.SelectionLength = 0;
9055 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9056 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9058 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9059 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9061 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9062 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9064 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9066 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9068 var rnd = new Random();
9070 MyCommon.UrlConverter svc;
9071 // 前回使用した短縮URLサービス以外を選択する
9074 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9076 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9077 await UrlConvertAsync(svc);
9081 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9082 => this.doUrlUndo();
9084 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9086 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9087 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9088 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9089 this.MarkSettingCommonModified();
9092 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9094 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9095 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9096 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9097 this.MarkSettingCommonModified();
9100 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9102 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9103 MenuStrip1.Tag = new object();
9104 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9107 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9109 var currentTabPage = this.CurrentTabPage;
9110 if (this.Tag != null) // 設定された戻り先へ遷移
9112 if (this.Tag == currentTabPage)
9113 ((Control)currentTabPage.Tag).Select();
9115 ((Control)this.Tag).Select();
9117 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9119 this.Tag = currentTabPage.Tag;
9120 ((Control)this.Tag).Select();
9122 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9123 MenuStrip1.Tag = null;
9126 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9128 var lst = (DetailsListView)sender;
9129 if (SettingManager.Local == null) return;
9133 SettingManager.Local.Width1 = lst.Columns[0].Width;
9134 SettingManager.Local.Width3 = lst.Columns[1].Width;
9138 var darr = new int[lst.Columns.Count];
9139 for (var i = 0; i < lst.Columns.Count; i++)
9141 darr[lst.Columns[i].DisplayIndex] = i;
9143 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9145 for (var i = 0; i < lst.Columns.Count; i++)
9150 SettingManager.Local.DisplayIndex1 = i;
9153 SettingManager.Local.DisplayIndex2 = i;
9156 SettingManager.Local.DisplayIndex3 = i;
9159 SettingManager.Local.DisplayIndex4 = i;
9162 SettingManager.Local.DisplayIndex5 = i;
9165 SettingManager.Local.DisplayIndex6 = i;
9168 SettingManager.Local.DisplayIndex7 = i;
9171 SettingManager.Local.DisplayIndex8 = i;
9175 SettingManager.Local.Width1 = lst.Columns[0].Width;
9176 SettingManager.Local.Width2 = lst.Columns[1].Width;
9177 SettingManager.Local.Width3 = lst.Columns[2].Width;
9178 SettingManager.Local.Width4 = lst.Columns[3].Width;
9179 SettingManager.Local.Width5 = lst.Columns[4].Width;
9180 SettingManager.Local.Width6 = lst.Columns[5].Width;
9181 SettingManager.Local.Width7 = lst.Columns[6].Width;
9182 SettingManager.Local.Width8 = lst.Columns[7].Width;
9184 this.MarkSettingLocalModified();
9185 _isColumnChanged = true;
9188 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9190 var lst = (DetailsListView)sender;
9191 if (SettingManager.Local == null) return;
9193 var modified = false;
9196 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9198 SettingManager.Local.Width1 = lst.Columns[0].Width;
9201 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9203 SettingManager.Local.Width3 = lst.Columns[1].Width;
9209 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9211 SettingManager.Local.Width1 = lst.Columns[0].Width;
9214 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9216 SettingManager.Local.Width2 = lst.Columns[1].Width;
9219 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9221 SettingManager.Local.Width3 = lst.Columns[2].Width;
9224 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9226 SettingManager.Local.Width4 = lst.Columns[3].Width;
9229 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9231 SettingManager.Local.Width5 = lst.Columns[4].Width;
9234 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9236 SettingManager.Local.Width6 = lst.Columns[5].Width;
9239 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9241 SettingManager.Local.Width7 = lst.Columns[6].Width;
9244 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9246 SettingManager.Local.Width8 = lst.Columns[7].Width;
9252 this.MarkSettingLocalModified();
9253 this._isColumnChanged = true;
9257 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9259 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9260 this.MarkSettingLocalModified();
9263 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9265 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9267 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9269 SelectMedia_DragDrop(e);
9272 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9274 var (url, title) = GetUrlFromDataObject(e.Data);
9280 appendText = title + " " + url;
9282 if (this.StatusText.TextLength == 0)
9283 this.StatusText.Text = appendText;
9285 this.StatusText.Text += " " + appendText;
9287 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9289 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9291 this.StatusText.Text += text;
9293 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9295 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9296 if (data != null) StatusText.Text += data;
9301 /// IDataObject から URL とタイトルの対を取得します
9304 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9306 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9307 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9308 internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
9310 if (data.GetDataPresent("text/x-moz-url"))
9312 // Firefox, Google Chrome で利用可能
9313 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9315 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
9316 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9317 if (lines.Length < 2)
9318 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9320 return (lines[0], lines[1]);
9322 else if (data.GetDataPresent("IESiteModeToUrl"))
9324 // Internet Exproler 用
9325 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9327 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
9328 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9329 if (lines.Length < 2)
9330 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9332 return (lines[0], lines[1]);
9334 else if (data.GetDataPresent("UniformResourceLocatorW"))
9338 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
9339 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9343 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9346 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9348 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9350 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9352 SelectMedia_DragEnter(e);
9356 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9358 e.Effect = DragDropEffects.Copy;
9361 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9363 e.Effect = DragDropEffects.Copy;
9366 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9368 e.Effect = DragDropEffects.Copy;
9372 e.Effect = DragDropEffects.None;
9375 private void TweenMain_DragOver(object sender, DragEventArgs e)
9379 public bool IsNetworkAvailable()
9381 var nw = MyCommon.IsNetworkAvailable();
9382 _myStatusOnline = nw;
9386 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9388 var uriStr = uri.AbsoluteUri;
9390 // OpenTween 内部で使用する URL
9391 if (uri.Authority == "opentween")
9393 await this.OpenInternalUriAsync(uri);
9397 // ハッシュタグを含む Twitter 検索
9398 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9401 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9402 var pos = unescapedQuery.IndexOf('#');
9403 if (pos == -1) return;
9405 var hash = unescapedQuery.Substring(pos);
9406 this.HashSupl.AddItem(hash);
9407 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9408 this.AddNewTabForSearch(hash);
9413 // フラグが立っている場合は設定と逆の動作をする
9414 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9415 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9417 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9418 if (userUriMatch.Success)
9420 var screenName = userUriMatch.Groups["ScreenName"].Value;
9421 if (this.IsTwitterId(screenName))
9423 await this.AddNewTabForUserTimeline(screenName);
9430 await this.OpenUriInBrowserAsync(uriStr);
9434 /// OpenTween 内部の機能を呼び出すための URL を開きます
9436 private async Task OpenInternalUriAsync(Uri uri)
9438 // ツイートを開く (//opentween/status/:status_id)
9439 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9442 var statusId = long.Parse(match.Groups[1].Value);
9443 await this.OpenRelatedTab(statusId);
9448 public Task OpenUriInBrowserAsync(string UriString)
9450 return Task.Run(() =>
9452 var myPath = UriString;
9456 var configBrowserPath = SettingManager.Local.BrowserPath;
9457 if (!MyCommon.IsNullOrEmpty(configBrowserPath))
9459 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9461 var sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9462 var browserPath = configBrowserPath.Substring(1, sep - 1);
9464 if (sep < configBrowserPath.Length - 1)
9466 arg = configBrowserPath.Substring(sep + 1);
9468 myPath = arg + " " + myPath;
9469 System.Diagnostics.Process.Start(browserPath, myPath);
9473 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9478 System.Diagnostics.Process.Start(myPath);
9487 private void ListTabSelect(TabPage _tab)
9491 this.PurgeListViewItemCache();
9493 this._statuses.SelectTab(_tab.Text);
9495 var listView = this.CurrentListView;
9498 _anchorFlag = false;
9502 listView.Columns[1].Text = ColumnText[2];
9506 for (var i = 0; i < listView.Columns.Count; i++)
9508 listView.Columns[i].Text = ColumnText[i];
9513 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9514 => this.ListTabSelect(e.TabPage);
9516 private void SelectListItem(DetailsListView LView, int Index)
9519 var bnd = new Rectangle();
9521 var item = LView.FocusedItem;
9530 LView.SelectedIndices.Clear();
9532 while (LView.SelectedIndices.Count > 0);
9533 item = LView.Items[Index];
9534 item.Selected = true;
9535 item.Focused = true;
9537 if (flg) LView.Invalidate(bnd);
9540 private void SelectListItem(DetailsListView LView , int[]? Index, int focusedIndex, int selectionMarkIndex)
9543 var bnd = new Rectangle();
9545 var item = LView.FocusedItem;
9556 LView.SelectedIndices.Clear();
9558 while (LView.SelectedIndices.Count > 0);
9559 LView.SelectItems(Index);
9561 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9563 LView.SelectionMark = selectionMarkIndex;
9565 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9567 LView.Items[focusedIndex].Focused = true;
9569 else if (Index != null && Index.Length != 0)
9571 LView.Items[Index.Last()].Focused = true;
9574 if (flg) LView.Invalidate(bnd);
9577 private void StartUserStream()
9579 tw.NewPostFromStream += tw_NewPostFromStream;
9580 tw.UserStreamStarted += tw_UserStreamStarted;
9581 tw.UserStreamStopped += tw_UserStreamStopped;
9582 tw.PostDeleted += tw_PostDeleted;
9583 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9585 this.RefreshUserStreamsMenu();
9587 if (SettingManager.Common.UserstreamStartup)
9588 tw.StartUserStream();
9591 private async void TweenMain_Shown(object sender, EventArgs e)
9593 NotifyIcon1.Visible = true;
9595 if (this.IsNetworkAvailable())
9599 var loadTasks = new List<Task>
9601 this.RefreshMuteUserIdsAsync(),
9602 this.RefreshBlockIdsAsync(),
9603 this.RefreshNoRetweetIdsAsync(),
9604 this.RefreshTwitterConfigurationAsync(),
9605 this.RefreshTabAsync<HomeTabModel>(),
9606 this.RefreshTabAsync<MentionsTabModel>(),
9607 this.RefreshTabAsync<DirectMessagesTabModel>(),
9608 this.RefreshTabAsync<PublicSearchTabModel>(),
9609 this.RefreshTabAsync<UserTimelineTabModel>(),
9610 this.RefreshTabAsync<ListTimelineTabModel>(),
9613 if (SettingManager.Common.StartupFollowers)
9614 loadTasks.Add(this.RefreshFollowerIdsAsync());
9616 if (SettingManager.Common.GetFav)
9617 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9619 var allTasks = Task.WhenAll(loadTasks);
9624 var timeout = Task.Delay(5000);
9625 if (await Task.WhenAny(allTasks, timeout) != timeout)
9629 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9631 if (MyCommon._endingFlag)
9635 if (MyCommon._endingFlag) return;
9637 if (ApplicationSettings.VersionInfoUrl != null)
9639 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9640 if (SettingManager.Common.StartupVersion)
9641 await this.CheckNewVersion(true);
9645 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9646 this.VerUpMenuItem.Enabled = false;
9647 this.VerUpMenuItem.Available = false;
9648 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9651 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9652 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9654 MessageBox.Show(Properties.Resources.ReAuthorizeText);
9655 SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
9659 var reloadTasks = new List<Task>();
9661 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9662 reloadTasks.Add(this.RefreshFollowerIdsAsync());
9664 if (!tw.GetNoRetweetSuccess)
9665 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9667 if (this.tw.Configuration.PhotoSizeLimit == 0)
9668 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9670 await Task.WhenAll(reloadTasks);
9675 this.timelineScheduler.Enabled = true;
9678 private async Task doGetFollowersMenu()
9680 await this.RefreshFollowerIdsAsync();
9681 this.DispSelectedPost(true);
9684 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9685 => await this.doGetFollowersMenu();
9687 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9688 => this.doReTweetUnofficial();
9690 private async Task doReTweetOfficial(bool isConfirm)
9693 if (this.ExistCurrentPost)
9695 var selectedPosts = this.CurrentTab.SelectedPosts;
9697 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9699 if (selectedPosts.Any(x => x.IsProtect))
9700 MessageBox.Show("Protected.");
9702 _DoFavRetweetFlags = false;
9706 if (selectedPosts.Length > 15)
9708 MessageBox.Show(Properties.Resources.RetweetLimitText);
9709 _DoFavRetweetFlags = false;
9712 else if (selectedPosts.Length > 1)
9714 var QuestionText = Properties.Resources.RetweetQuestion2;
9715 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9716 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9718 case DialogResult.Cancel:
9719 case DialogResult.No:
9720 _DoFavRetweetFlags = false;
9726 if (!SettingManager.Common.RetweetNoConfirm)
9728 var Questiontext = Properties.Resources.RetweetQuestion1;
9729 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9730 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9732 _DoFavRetweetFlags = false;
9738 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9740 await this.RetweetAsync(statusIds);
9744 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9745 => await this.doReTweetOfficial(true);
9747 private async Task FavoritesRetweetOfficial()
9749 if (!this.ExistCurrentPost) return;
9750 _DoFavRetweetFlags = true;
9751 var retweetTask = this.doReTweetOfficial(true);
9752 if (_DoFavRetweetFlags)
9754 _DoFavRetweetFlags = false;
9755 var favoriteTask = this.FavoriteChange(true, false);
9757 await Task.WhenAll(retweetTask, favoriteTask);
9765 private async Task FavoritesRetweetUnofficial()
9767 var post = this.CurrentPost;
9768 if (this.ExistCurrentPost && post != null && !post.IsDm)
9770 _DoFavRetweetFlags = true;
9771 var favoriteTask = this.FavoriteChange(true);
9772 if (!post.IsProtect && _DoFavRetweetFlags)
9774 _DoFavRetweetFlags = false;
9775 doReTweetUnofficial();
9783 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
9785 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
9786 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
9787 /// <returns>復元されたツイート本文</returns>
9788 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
9790 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
9793 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
9795 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
9797 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
9799 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
9803 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
9805 statusHtml = statusHtml.Replace("<br>", " ");
9807 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
9808 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
9809 statusHtml = statusHtml.Replace(" ", " ");
9811 return WebUtility.HtmlDecode(statusHtml);
9814 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
9816 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
9818 if (this.CurrentPost != null)
9819 this.DispSelectedPost(true);
9822 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
9824 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
9825 DebugModeToolStripMenuItem.Visible = true;
9827 DebugModeToolStripMenuItem.Visible = false;
9830 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
9831 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
9833 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
9834 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
9836 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
9837 => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
9839 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
9841 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
9842 this.MarkSettingCommonModified();
9845 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
9847 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
9848 this.MarkSettingCommonModified();
9851 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
9853 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
9854 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
9855 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
9856 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
9857 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
9858 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
9861 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
9863 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
9864 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
9865 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
9866 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
9867 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
9868 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
9871 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
9873 if (TraceOutToolStripMenuItem.Checked)
9874 MyCommon.TraceFlag = true;
9876 MyCommon.TraceFlag = false;
9879 private void TweenMain_Deactivate(object sender, EventArgs e)
9880 => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
9882 private void TabRenameMenuItem_Click(object sender, EventArgs e)
9884 if (MyCommon.IsNullOrEmpty(_rclickTabName)) return;
9886 _ = TabRename(_rclickTabName, out _);
9889 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
9890 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
9892 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
9893 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
9895 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
9897 TwitterApiStatus? apiStatus;
9899 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
9901 var cancellationToken = dialog.EnableCancellation();
9905 var task = this.tw.GetInfoApi();
9906 apiStatus = await dialog.WaitForAsync(this, task);
9908 catch (WebApiException)
9913 if (cancellationToken.IsCancellationRequested)
9916 if (apiStatus == null)
9918 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
9923 using var apiDlg = new ApiInfoDialog();
9924 apiDlg.ShowDialog(this);
9927 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
9929 var id = this.CurrentPost?.ScreenName ?? "";
9931 await this.FollowCommand(id);
9934 internal async Task FollowCommand(string id)
9936 using (var inputName = new InputTabName())
9938 inputName.FormTitle = "Follow";
9939 inputName.FormDescription = Properties.Resources.FRMessage1;
9940 inputName.TabName = id;
9942 if (inputName.ShowDialog(this) != DialogResult.OK)
9944 if (string.IsNullOrWhiteSpace(inputName.TabName))
9947 id = inputName.TabName.Trim();
9950 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
9954 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
9955 await dialog.WaitForAsync(this, task);
9957 catch (WebApiException ex)
9959 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
9964 MessageBox.Show(Properties.Resources.FRMessage3);
9967 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
9969 var id = this.CurrentPost?.ScreenName ?? "";
9971 await this.RemoveCommand(id, false);
9974 internal async Task RemoveCommand(string id, bool skipInput)
9978 using var inputName = new InputTabName();
9979 inputName.FormTitle = "Unfollow";
9980 inputName.FormDescription = Properties.Resources.FRMessage1;
9981 inputName.TabName = id;
9983 if (inputName.ShowDialog(this) != DialogResult.OK)
9985 if (string.IsNullOrWhiteSpace(inputName.TabName))
9988 id = inputName.TabName.Trim();
9991 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
9995 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
9996 await dialog.WaitForAsync(this, task);
9998 catch (WebApiException ex)
10000 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10005 MessageBox.Show(Properties.Resources.FRMessage3);
10008 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10010 var id = this.CurrentPost?.ScreenName ?? "";
10012 await this.ShowFriendship(id);
10015 internal async Task ShowFriendship(string id)
10017 using (var inputName = new InputTabName())
10019 inputName.FormTitle = "Show Friendships";
10020 inputName.FormDescription = Properties.Resources.FRMessage1;
10021 inputName.TabName = id;
10023 if (inputName.ShowDialog(this) != DialogResult.OK)
10025 if (string.IsNullOrWhiteSpace(inputName.TabName))
10028 id = inputName.TabName.Trim();
10031 bool isFollowing, isFollowed;
10033 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10035 var cancellationToken = dialog.EnableCancellation();
10039 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10040 var friendship = await dialog.WaitForAsync(this, task);
10042 isFollowing = friendship.Relationship.Source.Following;
10043 isFollowed = friendship.Relationship.Source.FollowedBy;
10045 catch (WebApiException ex)
10047 if (!cancellationToken.IsCancellationRequested)
10048 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10052 if (cancellationToken.IsCancellationRequested)
10059 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10063 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10067 result += Properties.Resources.GetFriendshipInfo3;
10071 result += Properties.Resources.GetFriendshipInfo4;
10073 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10074 MessageBox.Show(result);
10077 internal async Task ShowFriendship(string[] ids)
10079 foreach (var id in ids)
10081 bool isFollowing, isFollowed;
10083 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10085 var cancellationToken = dialog.EnableCancellation();
10089 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10090 var friendship = await dialog.WaitForAsync(this, task);
10092 isFollowing = friendship.Relationship.Source.Following;
10093 isFollowed = friendship.Relationship.Source.FollowedBy;
10095 catch (WebApiException ex)
10097 if (!cancellationToken.IsCancellationRequested)
10098 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10102 if (cancellationToken.IsCancellationRequested)
10112 ff += Properties.Resources.GetFriendshipInfo1;
10116 ff += Properties.Resources.GetFriendshipInfo2;
10119 ff += System.Environment.NewLine + " ";
10122 ff += Properties.Resources.GetFriendshipInfo3;
10126 ff += Properties.Resources.GetFriendshipInfo4;
10128 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10131 if (MessageBox.Show(
10132 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10133 MessageBoxButtons.YesNo,
10134 MessageBoxIcon.Question,
10135 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10137 await this.RemoveCommand(id, true);
10142 MessageBox.Show(result);
10147 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10148 => await this.doShowUserStatus(tw.Username, false);
10150 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10151 // URLから切り出した文字列を渡す
10153 public bool IsTwitterId(string name)
10155 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10156 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10158 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10161 private void doQuoteOfficial()
10163 var post = this.CurrentPost;
10164 if (this.ExistCurrentPost && post != null)
10166 if (post.IsDm || !StatusText.Enabled)
10169 if (post.IsProtect)
10171 MessageBox.Show("Protected.");
10175 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10177 this.inReplyTo = null;
10179 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10181 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10182 StatusText.Focus();
10186 private void doReTweetUnofficial()
10189 var post = this.CurrentPost;
10190 if (this.ExistCurrentPost && post != null)
10192 if (post.IsDm || !StatusText.Enabled)
10195 if (post.IsProtect)
10197 MessageBox.Show("Protected.");
10200 var rtdata = post.Text;
10201 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10203 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10205 // 投稿時に in_reply_to_status_id を付加する
10206 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10207 var inReplyToScreenName = post.ScreenName;
10208 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10210 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10212 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10213 StatusText.Focus();
10217 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10218 => this.doQuoteOfficial();
10220 private async void SearchButton_Click(object sender, EventArgs e)
10223 var pnl = ((Control)sender).Parent;
10224 if (pnl == null) return;
10225 var tbName = pnl.Parent.Text;
10226 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10227 var cmb = (ComboBox)pnl.Controls["comboSearch"];
10228 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
10229 cmb.Text = cmb.Text.Trim();
10230 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10232 var buf = new StringBuilder();
10233 var c = cmb.Text.ToCharArray();
10234 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
10236 if (cnt > cmb.Text.Length - 4)
10238 buf.Append(cmb.Text.Substring(cnt));
10247 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10249 buf.Append(" OR ");
10254 buf.Append(c[cnt]);
10256 cmb.Text = buf.ToString();
10258 var listView = (DetailsListView)pnl.Parent.Tag;
10260 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10262 tb.SearchWords = cmb.Text;
10263 tb.SearchLang = cmbLang.Text;
10264 if (MyCommon.IsNullOrEmpty(cmb.Text))
10272 var idx = cmb.Items.IndexOf(tb.SearchWords);
10273 if (idx > -1) cmb.Items.RemoveAt(idx);
10274 cmb.Items.Insert(0, tb.SearchWords);
10275 cmb.Text = tb.SearchWords;
10277 this.PurgeListViewItemCache();
10278 listView.VirtualListSize = 0;
10279 _statuses.ClearTabIds(tbName);
10280 SaveConfigsTabs(); //検索条件の保存
10284 await this.RefreshTabAsync(tb);
10287 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10288 => await this.DoRefreshMore(); // もっと前を取得
10291 /// 指定されたタブのListTabにおける位置を返します
10294 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10296 public int GetTabPageIndex(string tabName)
10297 => this._statuses.Tabs.IndexOf(tabName);
10299 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10301 if (_statuses.RemovedTab.Count == 0)
10303 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10308 DetailsListView? listView;
10310 var tb = _statuses.RemovedTab.Pop();
10311 if (tb.TabType == MyCommon.TabUsageType.Related)
10313 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10314 if (relatedTab != null)
10316 // 関連発言なら既存のタブを置き換える
10317 tb.TabName = relatedTab.TabName;
10318 this.ClearTab(tb.TabName, false);
10320 this._statuses.ReplaceTab(tb);
10322 var tabIndex = this._statuses.Tabs.IndexOf(tb);
10323 var tabPage = this.ListTab.TabPages[tabIndex];
10324 listView = (DetailsListView)tabPage.Tag;
10325 this.ListTab.SelectedIndex = tabIndex;
10329 const string TabName = "Related Tweets";
10330 var renamed = TabName;
10331 for (var i = 2; i <= 100; i++)
10333 if (!_statuses.ContainsTab(renamed))
10335 renamed = TabName + i;
10337 tb.TabName = renamed;
10339 _statuses.AddTab(tb);
10340 AddNewTab(tb, startup: false);
10342 var tabIndex = this._statuses.Tabs.Count - 1;
10343 var tabPage = this.ListTab.TabPages[tabIndex];
10345 listView = (DetailsListView)tabPage.Tag;
10346 this.ListTab.SelectedIndex = tabIndex;
10351 var renamed = tb.TabName;
10352 for (var i = 1; i < int.MaxValue; i++)
10354 if (!_statuses.ContainsTab(renamed))
10356 renamed = tb.TabName + "(" + i + ")";
10358 tb.TabName = renamed;
10360 _statuses.AddTab(tb);
10361 AddNewTab(tb, startup: false);
10363 var tabIndex = this._statuses.Tabs.Count - 1;
10364 var tabPage = this.ListTab.TabPages[tabIndex];
10366 listView = (DetailsListView)tabPage.Tag;
10367 this.ListTab.SelectedIndex = tabIndex;
10371 if (listView != null)
10373 using (ControlTransaction.Update(listView))
10375 listView.VirtualListSize = tb.AllCount;
10381 private async Task doMoveToRTHome()
10383 var post = this.CurrentPost;
10384 if (post != null && post.RetweetedId != null)
10385 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10388 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10389 => await this.doMoveToRTHome();
10391 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10393 var screenName = this.CurrentPost?.ScreenName;
10394 if (screenName != null)
10395 this.ListManageUserContext(screenName);
10398 public void ListManageUserContext(string screenName)
10400 using var listSelectForm = new MyLists(screenName, this.twitterApi);
10401 listSelectForm.ShowDialog(this);
10404 private void SearchControls_Enter(object sender, EventArgs e)
10406 var pnl = (Control)sender;
10407 foreach (Control ctl in pnl.Controls)
10409 ctl.TabStop = true;
10413 private void SearchControls_Leave(object sender, EventArgs e)
10415 var pnl = (Control)sender;
10416 foreach (Control ctl in pnl.Controls)
10418 ctl.TabStop = false;
10422 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10424 var tab = this.CurrentTab;
10425 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10426 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10429 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10430 => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10432 private void HashManageMenuItem_Click(object sender, EventArgs e)
10437 rslt = HashMgr.ShowDialog();
10443 this.TopMost = SettingManager.Common.AlwaysTop;
10444 if (rslt == DialogResult.Cancel) return;
10445 if (!MyCommon.IsNullOrEmpty(HashMgr.UseHash))
10447 HashStripSplitButton.Text = HashMgr.UseHash;
10448 HashTogglePullDownMenuItem.Checked = true;
10449 HashToggleMenuItem.Checked = true;
10453 HashStripSplitButton.Text = "#[-]";
10454 HashTogglePullDownMenuItem.Checked = false;
10455 HashToggleMenuItem.Checked = false;
10458 this.MarkSettingCommonModified();
10459 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10462 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10464 HashMgr.ToggleHash();
10465 if (!MyCommon.IsNullOrEmpty(HashMgr.UseHash))
10467 HashStripSplitButton.Text = HashMgr.UseHash;
10468 HashToggleMenuItem.Checked = true;
10469 HashTogglePullDownMenuItem.Checked = true;
10473 HashStripSplitButton.Text = "#[-]";
10474 HashToggleMenuItem.Checked = false;
10475 HashTogglePullDownMenuItem.Checked = false;
10477 this.MarkSettingCommonModified();
10478 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10481 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10482 => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
10484 public void SetPermanentHashtag(string hashtag)
10486 HashMgr.SetPermanentHash("#" + hashtag);
10487 HashStripSplitButton.Text = HashMgr.UseHash;
10488 HashTogglePullDownMenuItem.Checked = true;
10489 HashToggleMenuItem.Checked = true;
10491 this.MarkSettingCommonModified();
10494 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10496 if (!this.ExistCurrentPost)
10498 this.ReplyOpMenuItem.Enabled = false;
10499 this.ReplyAllOpMenuItem.Enabled = false;
10500 this.DmOpMenuItem.Enabled = false;
10501 this.ShowProfMenuItem.Enabled = false;
10502 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10503 this.ListManageMenuItem.Enabled = false;
10504 this.OpenFavOpMenuItem.Enabled = false;
10505 this.CreateTabRuleOpMenuItem.Enabled = false;
10506 this.CreateIdRuleOpMenuItem.Enabled = false;
10507 this.CreateSourceRuleOpMenuItem.Enabled = false;
10508 this.ReadOpMenuItem.Enabled = false;
10509 this.UnreadOpMenuItem.Enabled = false;
10513 this.ReplyOpMenuItem.Enabled = true;
10514 this.ReplyAllOpMenuItem.Enabled = true;
10515 this.DmOpMenuItem.Enabled = true;
10516 this.ShowProfMenuItem.Enabled = true;
10517 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10518 this.ListManageMenuItem.Enabled = true;
10519 this.OpenFavOpMenuItem.Enabled = true;
10520 this.CreateTabRuleOpMenuItem.Enabled = true;
10521 this.CreateIdRuleOpMenuItem.Enabled = true;
10522 this.CreateSourceRuleOpMenuItem.Enabled = true;
10523 this.ReadOpMenuItem.Enabled = true;
10524 this.UnreadOpMenuItem.Enabled = true;
10527 var tab = this.CurrentTab;
10528 var post = this.CurrentPost;
10529 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
10531 this.FavOpMenuItem.Enabled = false;
10532 this.UnFavOpMenuItem.Enabled = false;
10533 this.OpenStatusOpMenuItem.Enabled = false;
10534 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10535 this.RtOpMenuItem.Enabled = false;
10536 this.RtUnOpMenuItem.Enabled = false;
10537 this.QtOpMenuItem.Enabled = false;
10538 this.FavoriteRetweetMenuItem.Enabled = false;
10539 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10543 this.FavOpMenuItem.Enabled = true;
10544 this.UnFavOpMenuItem.Enabled = true;
10545 this.OpenStatusOpMenuItem.Enabled = true;
10546 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10548 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10550 this.RtOpMenuItem.Enabled = false;
10551 this.RtUnOpMenuItem.Enabled = false;
10552 this.QtOpMenuItem.Enabled = false;
10553 this.FavoriteRetweetMenuItem.Enabled = false;
10554 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10558 this.RtOpMenuItem.Enabled = true;
10559 this.RtUnOpMenuItem.Enabled = true;
10560 this.QtOpMenuItem.Enabled = true;
10561 this.FavoriteRetweetMenuItem.Enabled = true;
10562 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10566 if (tab.TabType != MyCommon.TabUsageType.Favorites)
10568 this.RefreshPrevOpMenuItem.Enabled = true;
10572 this.RefreshPrevOpMenuItem.Enabled = false;
10574 if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
10576 OpenRepSourceOpMenuItem.Enabled = false;
10580 OpenRepSourceOpMenuItem.Enabled = true;
10582 if (!this.ExistCurrentPost || post == null || MyCommon.IsNullOrEmpty(post.RetweetedBy))
10584 OpenRterHomeMenuItem.Enabled = false;
10588 OpenRterHomeMenuItem.Enabled = true;
10591 if (this.ExistCurrentPost && post != null)
10593 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10597 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10598 => this.ContextMenuTabProperty_Opening(sender, null!);
10600 public Twitter TwitterInstance
10603 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10605 if (this._initialLayout)
10608 int splitterDistance;
10609 switch (this.WindowState)
10611 case FormWindowState.Normal:
10612 splitterDistance = this.SplitContainer3.SplitterDistance;
10614 case FormWindowState.Maximized:
10615 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10616 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10617 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10618 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10624 this._mySpDis3 = splitterDistance;
10625 this.MarkSettingLocalModified();
10628 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10630 if (_statuses.RemovedTab.Count == 0)
10632 UndoRemoveTabMenuItem.Enabled = false;
10636 UndoRemoveTabMenuItem.Enabled = true;
10639 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10640 PublicSearchQueryMenuItem.Enabled = true;
10642 PublicSearchQueryMenuItem.Enabled = false;
10644 var post = this.CurrentPost;
10645 if (!this.ExistCurrentPost || post == null)
10647 this.CopySTOTMenuItem.Enabled = false;
10648 this.CopyURLMenuItem.Enabled = false;
10649 this.CopyUserIdStripMenuItem.Enabled = false;
10653 this.CopySTOTMenuItem.Enabled = true;
10654 this.CopyURLMenuItem.Enabled = true;
10655 this.CopyUserIdStripMenuItem.Enabled = true;
10657 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10658 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10662 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10663 => this.SetNotifyIconText();
10665 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10666 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10668 private async Task doShowUserStatus(string id, bool ShowInputDialog)
10670 TwitterUser? user = null;
10672 if (ShowInputDialog)
10674 using var inputName = new InputTabName();
10675 inputName.FormTitle = "Show UserStatus";
10676 inputName.FormDescription = Properties.Resources.FRMessage1;
10677 inputName.TabName = id;
10679 if (inputName.ShowDialog(this) != DialogResult.OK)
10681 if (string.IsNullOrWhiteSpace(inputName.TabName))
10684 id = inputName.TabName.Trim();
10687 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10689 var cancellationToken = dialog.EnableCancellation();
10693 var task = this.twitterApi.UsersShow(id);
10694 user = await dialog.WaitForAsync(this, task);
10696 catch (WebApiException ex)
10698 if (!cancellationToken.IsCancellationRequested)
10699 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10703 if (cancellationToken.IsCancellationRequested)
10707 await this.doShowUserStatus(user);
10710 private async Task doShowUserStatus(TwitterUser user)
10712 using var userDialog = new UserInfoDialog(this, this.twitterApi);
10713 var showUserTask = userDialog.ShowUserAsync(user);
10714 userDialog.ShowDialog(this);
10717 this.BringToFront();
10719 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10720 await showUserTask;
10723 internal Task ShowUserStatus(string id, bool ShowInputDialog)
10724 => this.doShowUserStatus(id, ShowInputDialog);
10726 internal Task ShowUserStatus(string id)
10727 => this.doShowUserStatus(id, true);
10729 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10731 var post = this.CurrentPost;
10734 await this.ShowUserStatus(post.ScreenName, false);
10738 private async void RtCountMenuItem_Click(object sender, EventArgs e)
10740 var post = this.CurrentPost;
10741 if (!this.ExistCurrentPost || post == null)
10744 var statusId = post.RetweetedId ?? post.StatusId;
10745 TwitterStatus status;
10747 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
10749 var cancellationToken = dialog.EnableCancellation();
10753 var task = this.twitterApi.StatusesShow(statusId);
10754 status = await dialog.WaitForAsync(this, task);
10756 catch (WebApiException ex)
10758 if (!cancellationToken.IsCancellationRequested)
10759 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
10763 if (cancellationToken.IsCancellationRequested)
10767 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
10770 private readonly HookGlobalHotkey _hookGlobalHotkey;
10773 _hookGlobalHotkey = new HookGlobalHotkey(this);
10775 // この呼び出しは、Windows フォーム デザイナで必要です。
10776 InitializeComponent();
10778 // InitializeComponent() 呼び出しの後で初期化を追加します。
10780 if (!this.DesignMode)
10782 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
10783 this.StatusText.Dock = DockStyle.Fill;
10786 this.tweetDetailsView.Owner = this;
10788 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
10789 this.gh.NotifyClicked += GrowlHelper_Callback;
10791 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
10792 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
10794 this.ImageSelector.Visible = false;
10795 this.ImageSelector.Enabled = false;
10796 this.ImageSelector.FilePickDialog = OpenFileDialog1;
10798 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
10800 this.ReplaceAppName();
10801 this.InitializeShortcuts();
10804 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
10806 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
10809 this.Visible = false;
10811 else if (Form.ActiveForm == null)
10813 this.Visible = true;
10814 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
10816 this.BringToFront();
10817 this.StatusText.Focus();
10821 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
10822 => this.MultiLinePullDownMenuItem.PerformClick();
10825 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
10827 if (ImageSelector.Visible)
10828 ImageSelector.EndSelection();
10830 ImageSelector.BeginSelection();
10833 private void SelectMedia_DragEnter(DragEventArgs e)
10835 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
10837 e.Effect = DragDropEffects.Copy;
10840 e.Effect = DragDropEffects.None;
10843 private void SelectMedia_DragDrop(DragEventArgs e)
10846 this.BringToFront();
10847 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
10848 StatusText.Focus();
10851 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
10853 TimelinePanel.Visible = false;
10854 TimelinePanel.Enabled = false;
10857 private void ImageSelector_EndSelecting(object sender, EventArgs e)
10859 TimelinePanel.Visible = true;
10860 TimelinePanel.Enabled = true;
10861 this.CurrentListView.Focus();
10864 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
10865 => this.AllowDrop = false;
10867 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
10868 => this.AllowDrop = true;
10870 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
10872 if (ImageSelector.Visible)
10874 this.MarkSettingCommonModified();
10875 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10879 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
10880 => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
10883 /// StatusTextでCtrl+Vが押下された時の処理
10885 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
10889 if (Clipboard.ContainsText())
10891 // clipboardにテキストがある場合は貼り付け処理
10892 this.StatusText.Paste(Clipboard.GetText());
10894 else if (Clipboard.ContainsImage())
10897 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
10898 Properties.Resources.PostPictureWarn4,
10899 MessageBoxButtons.OKCancel,
10900 MessageBoxIcon.Question,
10901 MessageBoxDefaultButton.Button2)
10902 == DialogResult.OK)
10904 // clipboardから画像を取得
10905 using var image = Clipboard.GetImage();
10906 this.ImageSelector.BeginSelection(image);
10910 catch (ExternalException ex)
10912 MessageBox.Show(ex.Message);
10917 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
10919 using var form = new ListManage(tw);
10920 form.ShowDialog(this);
10923 private bool ModifySettingCommon { get; set; }
10924 private bool ModifySettingLocal { get; set; }
10925 private bool ModifySettingAtId { get; set; }
10927 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
10929 var post = this.CurrentPost;
10930 if (this.ExistCurrentPost && post != null && !post.IsDm)
10931 RtCountMenuItem.Enabled = true;
10933 RtCountMenuItem.Enabled = false;
10936 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
10937 => this.CopyUserId();
10939 private void CopyUserId()
10941 var post = this.CurrentPost;
10942 if (post == null) return;
10943 var clstr = post.ScreenName;
10946 Clipboard.SetDataObject(clstr, false, 5, 100);
10948 catch (Exception ex)
10950 MessageBox.Show(ex.Message);
10954 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
10956 var post = this.CurrentPost;
10957 if (this.ExistCurrentPost && post != null && !post.IsDm)
10961 await this.OpenRelatedTab(post);
10963 catch (TabException ex)
10965 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
10971 /// 指定されたツイートに対する関連発言タブを開きます
10973 /// <param name="statusId">表示するツイートのID</param>
10974 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
10975 public async Task OpenRelatedTab(long statusId)
10977 var post = this._statuses[statusId];
10982 post = await this.tw.GetStatusApi(false, statusId);
10984 catch (WebApiException ex)
10986 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
10991 await this.OpenRelatedTab(post);
10995 /// 指定されたツイートに対する関連発言タブを開きます
10997 /// <param name="post">表示する対象となるツイート</param>
10998 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
10999 private async Task OpenRelatedTab(PostClass post)
11001 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11002 if (tabRelated != null)
11004 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11007 var tabName = this._statuses.MakeTabName("Related Tweets");
11009 tabRelated = new RelatedPostsTabModel(tabName, post)
11011 UnreadManage = false,
11015 this._statuses.AddTab(tabRelated);
11016 this.AddNewTab(tabRelated, startup: false);
11018 this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11020 await this.RefreshTabAsync(tabRelated);
11022 var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11024 if (tabIndex != -1)
11026 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11028 var tabPage = this.ListTab.TabPages[tabIndex];
11029 var listView = (DetailsListView)tabPage.Tag;
11030 var targetPost = tabRelated.TargetPost;
11031 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11033 if (index != -1 && index < listView.Items.Count)
11035 listView.SelectedIndices.Add(index);
11036 listView.Items[index].Focused = true;
11041 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11043 var buf = new StringBuilder();
11044 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11045 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11046 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11049 #region "Userstream"
11050 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11054 if (InvokeRequired && !IsDisposed)
11056 await this.InvokeAsync(() =>
11058 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11059 if (this.CurrentTab.Contains(e.StatusId))
11061 this.PurgeListViewItemCache();
11062 this.CurrentListView.Update();
11063 var post = this.CurrentPost;
11064 if (post != null && post.StatusId == e.StatusId)
11065 this.DispSelectedPost(true);
11071 catch (ObjectDisposedException)
11075 catch (InvalidOperationException)
11081 private void tw_NewPostFromStream(object sender, EventArgs e)
11083 if (SettingManager.Common.ReadOldPosts)
11085 _statuses.SetReadHomeTab(); //新着時未読クリア
11088 this._statuses.DistributePosts();
11090 this.RefreshThrottlingTimer.Call();
11093 private async void tw_UserStreamStarted(object sender, EventArgs e)
11097 if (InvokeRequired && !IsDisposed)
11099 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11103 catch (ObjectDisposedException)
11107 catch (InvalidOperationException)
11112 this.RefreshUserStreamsMenu();
11113 this.MenuItemUserStream.Enabled = true;
11115 StatusLabel.Text = "UserStream Started.";
11118 private async void tw_UserStreamStopped(object sender, EventArgs e)
11122 if (InvokeRequired && !IsDisposed)
11124 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11128 catch (ObjectDisposedException)
11132 catch (InvalidOperationException)
11137 this.RefreshUserStreamsMenu();
11138 this.MenuItemUserStream.Enabled = true;
11140 StatusLabel.Text = "UserStream Stopped.";
11143 private void RefreshUserStreamsMenu()
11145 if (this.tw.UserStreamActive)
11147 this.MenuItemUserStream.Text = "&UserStream ▶";
11148 this.StopToolStripMenuItem.Text = "&Stop";
11152 this.MenuItemUserStream.Text = "&UserStream ■";
11153 this.StopToolStripMenuItem.Text = "&Start";
11157 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11161 if (InvokeRequired && !IsDisposed)
11163 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11167 catch (ObjectDisposedException)
11171 catch (InvalidOperationException)
11175 var ev = e.EventData;
11176 StatusLabel.Text = "Event: " + ev.Event;
11178 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11180 if (this.CurrentTab.Contains(ev.Id))
11182 this.PurgeListViewItemCache();
11183 this.CurrentListView.Update();
11185 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11187 var favTab = this._statuses.FavoriteTab;
11188 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11193 private void NotifyEvent(Twitter.FormattedEvent ev)
11196 if (BalloonRequired(ev))
11198 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11199 var title = new StringBuilder();
11200 if (SettingManager.Common.DispUsername)
11202 title.Append(tw.Username);
11203 title.Append(" - ");
11205 title.Append(ApplicationSettings.ApplicationName);
11206 title.Append(" [");
11207 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11208 title.Append("] by ");
11209 if (!MyCommon.IsNullOrEmpty(ev.Username))
11211 title.Append(ev.Username);
11215 if (!MyCommon.IsNullOrEmpty(ev.Target))
11220 if (SettingManager.Common.IsUseNotifyGrowl)
11222 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11223 ev.Id.ToString(), title.ToString(), text);
11227 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11228 NotifyIcon1.BalloonTipTitle = title.ToString();
11229 NotifyIcon1.BalloonTipText = text;
11230 NotifyIcon1.ShowBalloonTip(500);
11235 var snd = SettingManager.Common.EventSoundFile;
11236 if (!_initial && SettingManager.Common.PlaySound && !MyCommon.IsNullOrEmpty(snd))
11238 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11242 var dir = Application.StartupPath;
11243 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11245 dir = Path.Combine(dir, "Sounds");
11247 using var player = new SoundPlayer(Path.Combine(dir, snd));
11257 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11259 MenuItemUserStream.Enabled = false;
11260 if (StopRefreshAllMenuItem.Checked)
11262 StopRefreshAllMenuItem.Checked = false;
11265 if (this.tw.UserStreamActive)
11267 tw.StopUserStream();
11271 tw.StartUserStream();
11275 private static string inputTrack = "";
11277 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11279 if (TrackToolStripMenuItem.Checked)
11281 using (var inputForm = new InputTabName())
11283 inputForm.TabName = inputTrack;
11284 inputForm.FormTitle = "Input track word";
11285 inputForm.FormDescription = "Track word";
11286 if (inputForm.ShowDialog() != DialogResult.OK)
11288 TrackToolStripMenuItem.Checked = false;
11291 inputTrack = inputForm.TabName.Trim();
11293 if (!inputTrack.Equals(tw.TrackWord))
11295 tw.TrackWord = inputTrack;
11296 this.MarkSettingCommonModified();
11297 TrackToolStripMenuItem.Checked = !MyCommon.IsNullOrEmpty(inputTrack);
11298 tw.ReconnectUserStream();
11304 tw.ReconnectUserStream();
11306 this.MarkSettingCommonModified();
11309 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11311 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11312 this.MarkSettingCommonModified();
11313 tw.ReconnectUserStream();
11316 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11318 if (evtDialog == null || evtDialog.IsDisposed)
11320 this.evtDialog = new EventViewerDialog
11326 this.evtDialog.Location = new Point
11328 X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11329 Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11332 evtDialog.EventSource = tw.StoredEvent;
11333 if (!evtDialog.Visible)
11335 evtDialog.Show(this);
11339 evtDialog.Activate();
11341 this.TopMost = SettingManager.Common.AlwaysTop;
11345 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11347 MyCommon._endingFlag = true;
11351 Application.Restart();
11355 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11359 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11360 => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11362 private bool ExistCurrentPost
11366 var post = this.CurrentPost;
11367 return post != null && !post.IsDeleted;
11371 private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11372 => await this.ShowUserTimeline();
11374 private string GetUserIdFromCurPostOrInput(string caption)
11376 var id = this.CurrentPost?.ScreenName ?? "";
11378 using var inputName = new InputTabName();
11379 inputName.FormTitle = caption;
11380 inputName.FormDescription = Properties.Resources.FRMessage1;
11381 inputName.TabName = id;
11383 if (inputName.ShowDialog() == DialogResult.OK &&
11384 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
11386 id = inputName.TabName.Trim();
11395 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11397 var id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11398 if (!MyCommon.IsNullOrEmpty(id))
11400 await this.AddNewTabForUserTimeline(id);
11404 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11406 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
11407 this.timelineScheduler.SystemResumed();
11410 private void SystemEvents_TimeChanged(object sender, EventArgs e)
11412 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11414 TimeZoneInfo.ClearCachedData();
11416 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11418 if (curTimeOffset != prevTimeOffset)
11421 this.PurgeListViewItemCache();
11422 this.CurrentListView.Refresh();
11424 this.DispSelectedPost(forceupdate: true);
11428 private void TimelineRefreshEnableChange(bool isEnable)
11432 tw.StartUserStream();
11436 tw.StopUserStream();
11438 this.timelineScheduler.Enabled = isEnable;
11441 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11442 => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11444 private async Task OpenUserAppointUrl()
11446 if (SettingManager.Common.UserAppointUrl != null)
11448 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11450 var post = this.CurrentPost;
11453 var xUrl = SettingManager.Common.UserAppointUrl;
11454 xUrl = xUrl.Replace("{ID}", post.ScreenName);
11456 var statusId = post.RetweetedId ?? post.StatusId;
11457 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11459 await this.OpenUriInBrowserAsync(xUrl);
11464 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11469 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11470 => await this.OpenUserAppointUrl();
11472 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11474 if (Form.ActiveForm == null)
11476 await this.InvokeAsync(() =>
11478 this.Visible = true;
11479 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11481 this.BringToFront();
11482 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11484 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11488 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11494 private void ReplaceAppName()
11496 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11497 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11500 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11501 => this.SplitContainer3.Panel2Collapsed = false;
11503 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11504 => await this.OpenThumbnailPicture(e.Thumbnail);
11506 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11507 => await this.OpenUriInBrowserAsync(e.ImageUrl);
11509 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11511 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11513 await this.OpenUriInBrowserAsync(url);
11516 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11517 => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11519 private void PostButton_KeyDown(object sender, KeyEventArgs e)
11521 if (e.KeyCode == Keys.Space)
11523 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
11525 e.SuppressKeyPress = true;
11529 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11531 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11532 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11533 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11534 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11535 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11537 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11540 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11541 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11543 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11544 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11546 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11547 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11549 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11550 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11552 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11553 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11555 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11557 if (SettingManager.Common.IconSize == iconSize) return;
11559 var oldIconCol = _iconCol;
11561 SettingManager.Common.IconSize = iconSize;
11562 ApplyListViewIconSize(iconSize);
11564 if (_iconCol != oldIconCol)
11566 foreach (TabPage tp in ListTab.TabPages)
11568 ResetColumns((DetailsListView)tp.Tag);
11572 this.CurrentListView.Refresh();
11573 this.MarkSettingCommonModified();
11576 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11578 var state = this.LockListSortOrderToolStripMenuItem.Checked;
11579 if (SettingManager.Common.SortOrderLock == state) return;
11581 SettingManager.Common.SortOrderLock = state;
11582 this.MarkSettingCommonModified();
11585 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11587 if (!MyCommon.IsNullOrEmpty(e.StatusText))
11589 this.StatusLabelUrl.Text = e.StatusText;
11593 this.SetStatusLabelUrl();