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.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Runtime.InteropServices;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
60 public partial class TweenMain : OTBaseForm
64 /// <summary>画面サイズ</summary>
67 /// <summary>画面位置</summary>
70 /// <summary>区切り位置</summary>
73 /// <summary>発言欄区切り位置</summary>
74 private int _mySpDis2;
76 /// <summary>プレビュー区切り位置</summary>
77 private int _mySpDis3;
79 /// <summary>アイコンサイズ</summary>
81 /// 現在は16、24、48の3種類。将来直接数字指定可能とする
82 /// 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様
86 private bool _iconCol; // 1列表示の時true(48サイズのとき)
89 private bool _initial; // true:起動時処理中
90 private bool _initialLayout = true;
91 private bool _ignoreConfigSave; // true:起動時処理中
93 /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
94 private bool _tabDrag;
96 private TabPage _beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
97 private Point _tabMouseDownPoint;
99 /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
100 private string _rclickTabName;
102 private readonly object _syncObject = new object(); // ロック用
104 private const string detailHtmlFormatHeaderMono =
105 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
106 + "<style type=\"text/css\"><!-- "
107 + "body, p, pre {margin: 0;} "
108 + "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%);} "
109 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
110 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
111 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
112 + ".quote-tweet.reply {border-color: #f33;} "
113 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
115 + "</head><body><pre>";
116 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
117 private const string detailHtmlFormatHeaderColor =
118 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
119 + "<style type=\"text/css\"><!-- "
120 + "body, p, pre {margin: 0;} "
121 + "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%);} "
122 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
123 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
124 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
125 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
126 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
128 + "</head><body><p>";
129 private const string detailHtmlFormatFooterColor = "</p></body></html>";
130 private string detailHtmlFormatHeader;
131 private string detailHtmlFormatFooter;
133 private bool _myStatusError = false;
134 private bool _myStatusOnline = false;
135 private bool soundfileListup = false;
136 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
139 private readonly TwitterApi twitterApi = new TwitterApi();
143 private readonly GrowlHelper gh = new GrowlHelper(ApplicationSettings.ApplicationName);
147 /// <summary>検索画面インスタンス</summary>
148 internal SearchWordDialog SearchDialog = new SearchWordDialog();
150 private readonly OpenURL UrlDialog = new OpenURL();
152 /// <summary>@id補助</summary>
153 public AtIdSupplement AtIdSupl;
155 /// <summary>Hashtag補助</summary>
156 public AtIdSupplement HashSupl;
158 public HashtagManage HashMgr;
159 private EventViewerDialog evtDialog;
163 /// <summary>未読用フォント</summary>
164 private Font _fntUnread;
166 /// <summary>未読用文字色</summary>
167 private Color _clUnread;
169 /// <summary>既読用フォント</summary>
170 private Font _fntReaded;
172 /// <summary>既読用文字色</summary>
173 private Color _clReaded;
175 /// <summary>Fav用文字色</summary>
176 private Color _clFav;
178 /// <summary>片思い用文字色</summary>
179 private Color _clOWL;
181 /// <summary>Retweet用文字色</summary>
182 private Color _clRetweet;
184 /// <summary>選択中の行用文字色</summary>
185 private readonly Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);
187 /// <summary>発言詳細部用フォント</summary>
188 private Font _fntDetail;
190 /// <summary>発言詳細部用色</summary>
191 private Color _clDetail;
193 /// <summary>発言詳細部用リンク文字色</summary>
194 private Color _clDetailLink;
196 /// <summary>発言詳細部用背景色</summary>
197 private Color _clDetailBackcolor;
199 /// <summary>自分の発言用背景色</summary>
200 private Color _clSelf;
202 /// <summary>自分宛返信用背景色</summary>
203 private Color _clAtSelf;
205 /// <summary>選択発言者の他の発言用背景色</summary>
206 private Color _clTarget;
208 /// <summary>選択発言中の返信先用背景色</summary>
209 private Color _clAtTarget;
211 /// <summary>選択発言者への返信発言用背景色</summary>
212 private Color _clAtFromTarget;
214 /// <summary>選択発言の唯一@先</summary>
215 private Color _clAtTo;
217 /// <summary>リスト部通常発言背景色</summary>
218 private Color _clListBackcolor;
220 /// <summary>入力欄背景色</summary>
221 private Color _clInputBackcolor;
223 /// <summary>入力欄文字色</summary>
224 private Color _clInputFont;
226 /// <summary>入力欄フォント</summary>
227 private Font _fntInputFont;
229 /// <summary>アイコン画像リスト</summary>
230 private ImageCache IconCache;
232 /// <summary>タスクトレイアイコン:通常時 (At.ico)</summary>
233 private Icon NIconAt;
235 /// <summary>タスクトレイアイコン:通信エラー時 (AtRed.ico)</summary>
236 private Icon NIconAtRed;
238 /// <summary>タスクトレイアイコン:オフライン時 (AtSmoke.ico)</summary>
239 private Icon NIconAtSmoke;
241 /// <summary>タスクトレイアイコン:更新中 (Refresh.ico)</summary>
242 private Icon[] NIconRefresh = new Icon[4];
244 /// <summary>未読のあるタブ用アイコン (Tab.ico)</summary>
245 private Icon TabIcon;
247 /// <summary>画面左上のアイコン (Main.ico)</summary>
248 private Icon MainIcon;
250 private Icon ReplyIcon;
251 private Icon ReplyIconBlink;
253 private readonly ImageList _listViewImageList = new ImageList(); // ListViewItemの高さ変更用
255 private PostClass _anchorPost;
256 private bool _anchorFlag; // true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
258 /// <summary>発言履歴</summary>
259 private readonly List<StatusTextHistory> _history = new List<StatusTextHistory>();
261 /// <summary>発言履歴カレントインデックス</summary>
264 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
266 /// <summary>リプライ先のステータスID・スクリーン名</summary>
267 private (long StatusId, string ScreenName)? inReplyTo = null;
270 private readonly List<DateTimeUtc> _postTimestamps = new List<DateTimeUtc>();
271 private readonly List<DateTimeUtc> _favTimestamps = new List<DateTimeUtc>();
274 private readonly SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
275 private SolidBrush _brsBackColorMine;
276 private SolidBrush _brsBackColorAt;
277 private SolidBrush _brsBackColorYou;
278 private SolidBrush _brsBackColorAtYou;
279 private SolidBrush _brsBackColorAtFromTarget;
280 private SolidBrush _brsBackColorAtTo;
281 private SolidBrush _brsBackColorNone;
283 /// <summary>Listにフォーカスないときの選択行の背景色</summary>
284 private readonly SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace));
286 private readonly StringFormat sfTab = new StringFormat();
288 //////////////////////////////////////////////////////////////////////////////////////////////////////////
289 private TabInformations _statuses;
292 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
295 /// キャッシュクリアのために null が代入されることがあるため、
296 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
297 /// 一旦ローカル変数に代入してから参照すること。
299 private ListViewItemCache _listItemCache = null;
301 internal class ListViewItemCache
303 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
304 public ListView TargetList { get; set; }
306 /// <summary>キャッシュする範囲の開始インデックス</summary>
307 public int StartIndex { get; set; }
309 /// <summary>キャッシュする範囲の終了インデックス</summary>
310 public int EndIndex { get; set; }
312 /// <summary>キャッシュされた範囲に対応する <see cref="ListViewItem"/> と <see cref="PostClass"/> の組</summary>
313 public (ListViewItem, PostClass)[] Cache { get; set; }
315 /// <summary>キャッシュされたアイテムの件数</summary>
317 => this.EndIndex - this.StartIndex + 1;
319 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
320 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
321 public bool Contains(int index)
322 => index >= this.StartIndex && index <= this.EndIndex;
324 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
325 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
326 public bool IsSupersetOf(int rangeStart, int rangeEnd)
327 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
329 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
330 /// <returns>取得に成功すれば true、それ以外は false</returns>
331 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
333 if (this.Contains(index))
335 (item, post) = this.Cache[index - this.StartIndex];
347 private bool _isColumnChanged = false;
349 private const int MAX_WORKER_THREADS = 20;
350 private readonly SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
351 private readonly CancellationTokenSource workerCts = new CancellationTokenSource();
352 private readonly IProgress<string> workerProgress;
354 private int UnreadCounter = -1;
355 private int UnreadAtCounter = -1;
357 private readonly string[] ColumnOrgText = new string[9];
358 private readonly string[] ColumnText = new string[9];
360 private bool _DoFavRetweetFlags = false;
362 //////////////////////////////////////////////////////////////////////////////////////////////////////////
364 private readonly TimelineScheduler timelineScheduler = new TimelineScheduler();
365 private ThrottlingTimer RefreshThrottlingTimer;
366 private ThrottlingTimer colorizeDebouncer;
367 private ThrottlingTimer selectionDebouncer;
368 private ThrottlingTimer saveConfigDebouncer;
370 private string recommendedStatusFooter;
371 private bool urlMultibyteSplit = false;
372 private bool preventSmsCommand = true;
375 private struct urlUndo
377 public string Before;
381 private List<urlUndo> urlUndoBuffer = null;
383 private readonly struct ReplyChain
385 public readonly long OriginalId;
386 public readonly long InReplyToId;
387 public readonly TabModel OriginalTab;
389 public ReplyChain(long originalId, long inReplyToId, TabModel originalTab)
391 this.OriginalId = originalId;
392 this.InReplyToId = inReplyToId;
393 this.OriginalTab = originalTab;
397 /// <summary>[, ]でのリプライ移動の履歴</summary>
398 private Stack<ReplyChain> replyChains;
400 /// <summary>ポスト選択履歴</summary>
401 private readonly Stack<(TabModel, PostClass)> selectPostChains = new Stack<(TabModel, PostClass)>();
403 public TabModel CurrentTab
404 => this._statuses.SelectedTab;
406 public string CurrentTabName
407 => this._statuses.SelectedTabName;
409 public TabPage CurrentTabPage
410 => this.ListTab.TabPages[this._statuses.Tabs.IndexOf(this.CurrentTabName)];
412 public DetailsListView CurrentListView
413 => (DetailsListView)this.CurrentTabPage.Tag;
415 public PostClass CurrentPost
416 => this.CurrentTab.SelectedPost;
418 /// <summary>検索処理タイプ</summary>
419 internal enum SEARCHTYPE
426 private class StatusTextHistory
428 public string status = "";
429 public (long StatusId, string ScreenName)? inReplyTo = null;
431 /// <summary>画像投稿サービス名</summary>
432 public string imageService = "";
434 public IMediaItem[] mediaItems = null;
435 public StatusTextHistory()
438 public StatusTextHistory(string status, (long StatusId, string ScreenName)? inReplyTo)
440 this.status = status;
441 this.inReplyTo = inReplyTo;
445 private void TweenMain_Activated(object sender, EventArgs e)
447 //画面がアクティブになったら、発言欄の背景色戻す
448 if (StatusText.Focused)
450 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
454 private bool disposed = false;
457 /// 使用中のリソースをすべてクリーンアップします。
459 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
460 protected override void Dispose(bool disposing)
462 base.Dispose(disposing);
469 this.components?.Dispose();
472 SearchDialog.Dispose();
475 NIconAtRed?.Dispose();
476 NIconAtSmoke?.Dispose();
477 foreach (var iconRefresh in this.NIconRefresh)
479 iconRefresh?.Dispose();
483 ReplyIcon?.Dispose();
484 ReplyIconBlink?.Dispose();
485 _listViewImageList.Dispose();
486 _brsHighLight.Dispose();
487 _brsBackColorMine?.Dispose();
488 _brsBackColorAt?.Dispose();
489 _brsBackColorYou?.Dispose();
490 _brsBackColorAtYou?.Dispose();
491 _brsBackColorAtFromTarget?.Dispose();
492 _brsBackColorAtTo?.Dispose();
493 _brsBackColorNone?.Dispose();
494 _brsDeactiveSelection?.Dispose();
498 this.workerCts.Cancel();
500 if (IconCache != null)
502 this.IconCache.CancelAsync();
503 this.IconCache.Dispose();
506 this.thumbnailTokenSource?.Dispose();
509 this.twitterApi.Dispose();
510 this._hookGlobalHotkey.Dispose();
513 // 終了時にRemoveHandlerしておかないとメモリリークする
514 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
515 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
516 Microsoft.Win32.SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
518 this.disposed = true;
521 private void LoadIcons()
523 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
524 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
527 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
530 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
533 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
536 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
538 // タスクトレイ: オフライン時アイコン
539 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
541 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
542 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
543 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
545 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
546 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
547 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
548 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
549 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
551 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
553 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
554 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
555 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
556 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
557 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
559 if (iconReply != null && iconReplyBlink != null)
561 this.ReplyIcon = iconReply;
562 this.ReplyIconBlink = iconReplyBlink;
566 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
567 this.ReplyIconBlink = this.NIconAt;
570 if (iconRefresh1 == null)
572 this.NIconRefresh = new[] {
573 Properties.Resources.Refresh, Properties.Resources.Refresh2,
574 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
577 else if (iconRefresh2 == null)
579 this.NIconRefresh = new[] { iconRefresh1 };
581 else if (iconRefresh3 == null)
583 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
585 else if (iconRefresh4 == null)
587 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
589 else // iconRefresh1 から iconRefresh4 まで全て揃っている
591 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
595 private Icon LoadIcon(string filePath)
597 if (!File.Exists(filePath))
602 return new Icon(filePath);
610 private void InitColumns(ListView list, bool startup)
612 this.InitColumnText();
614 ColumnHeader[] columns = null;
621 new ColumnHeader(), // アイコン
622 new ColumnHeader(), // 本文
625 columns[0].Text = this.ColumnText[0];
626 columns[1].Text = this.ColumnText[2];
630 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
632 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
633 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
634 columns[0].DisplayIndex = 0;
635 columns[1].DisplayIndex = 1;
640 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
642 columns[idx].Width = curListColumn.Width;
643 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
652 new ColumnHeader(), // アイコン
653 new ColumnHeader(), // ニックネーム
654 new ColumnHeader(), // 本文
655 new ColumnHeader(), // 日付
656 new ColumnHeader(), // ユーザID
657 new ColumnHeader(), // 未読
658 new ColumnHeader(), // マーク&プロテクト
659 new ColumnHeader(), // ソース
662 foreach (var i in Enumerable.Range(0, columns.Length))
663 columns[i].Text = this.ColumnText[i];
667 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
669 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
670 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
671 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
672 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
673 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
674 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
675 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
676 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
678 var displayIndex = new[] {
679 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
680 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
681 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
682 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
685 foreach (var i in Enumerable.Range(0, displayIndex.Length))
687 columns[i].DisplayIndex = displayIndex[i];
693 foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
695 columns[idx].Width = curListColumn.Width;
696 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
702 list.Columns.AddRange(columns);
710 foreach (var column in columns)
716 private void InitColumnText()
719 ColumnText[1] = Properties.Resources.AddNewTabText2;
720 ColumnText[2] = Properties.Resources.AddNewTabText3;
721 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
722 ColumnText[4] = Properties.Resources.AddNewTabText5;
725 ColumnText[7] = "Source";
727 ColumnOrgText[0] = "";
728 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
729 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
730 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
731 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
732 ColumnOrgText[5] = "";
733 ColumnOrgText[6] = "";
734 ColumnOrgText[7] = "Source";
737 switch (_statuses.SortMode)
739 case ComparerMode.Nickname: //ニックネーム
742 case ComparerMode.Data: //本文
745 case ComparerMode.Id: //時刻=発言Id
748 case ComparerMode.Name: //名前
751 case ComparerMode.Source: //Source
758 if (_statuses.SortOrder == SortOrder.Descending)
760 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
761 ColumnText[2] = ColumnOrgText[2] + "▾";
765 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
766 ColumnText[2] = ColumnOrgText[2] + "▴";
771 if (_statuses.SortOrder == SortOrder.Descending)
773 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
774 ColumnText[c] = ColumnOrgText[c] + "▾";
778 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
779 ColumnText[c] = ColumnOrgText[c] + "▴";
784 private void InitializeTraceFrag()
787 TraceOutToolStripMenuItem.Checked = true;
788 MyCommon.TraceFlag = true;
790 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
792 TraceOutToolStripMenuItem.Checked = true;
793 MyCommon.TraceFlag = true;
797 private void TweenMain_Load(object sender, EventArgs e)
799 _ignoreConfigSave = true;
800 this.Visible = false;
802 if (MyApplication.StartupOptions.ContainsKey("d"))
803 MyCommon.TraceFlag = true;
805 InitializeTraceFrag();
807 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
809 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
811 Regex.CacheSize = 100;
814 _statuses = TabInformations.GetInstance();
818 this.Icon = MainIcon; //メインフォーム(TweenMain)
819 NotifyIcon1.Icon = NIconAt; //タスクトレイ
820 TabImage.Images.Add(TabIcon); //タブ見出し
822 //<<<<<<<<<設定関連>>>>>>>>>
826 // 現在の DPI と設定保存時の DPI との比を取得する
827 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
830 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
831 if (fontUIGlobal != null)
833 OTBaseForm.GlobalFont = fontUIGlobal;
834 this.Font = fontUIGlobal;
838 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
840 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
841 SettingManager.Common.TimelinePeriod = 15;
843 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
844 SettingManager.Common.ReplyPeriod = 15;
846 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
847 SettingManager.Common.DMPeriod = 15;
849 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
850 SettingManager.Common.PubSearchPeriod = 30;
852 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
853 SettingManager.Common.UserTimelinePeriod = 15;
855 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
856 SettingManager.Common.ListsPeriod = 15;
859 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
860 SettingManager.Common.CountApi = 60;
861 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
862 SettingManager.Common.CountApiReply = 40;
864 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
865 SettingManager.Common.MoreCountApi = 200;
866 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
867 SettingManager.Common.FirstCountApi = 100;
869 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
870 SettingManager.Common.FavoritesCountApi = 40;
871 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
872 SettingManager.Common.ListCountApi = 100;
873 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
874 SettingManager.Common.SearchCountApi = 100;
875 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
876 SettingManager.Common.UserTimelineCountApi = 20;
878 //廃止サービスが選択されていた場合ux.nuへ読み替え
879 if (SettingManager.Common.AutoShortUrlFirst < 0)
880 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
882 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
883 this.tw = new Twitter(this.twitterApi);
886 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
887 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
891 Networking.Initialize();
893 var saveRequired = false;
894 var firstRun = false;
896 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
897 if (string.IsNullOrEmpty(tw.Username))
902 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
903 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
904 string.IsNullOrEmpty(tw.Username))
906 Application.Exit(); //強制終了
912 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
913 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
914 Networking.SetWebProxy(SettingManager.Local.ProxyType,
915 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
916 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
917 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
919 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
920 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
921 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
922 tw.TrackWord = SettingManager.Common.TrackWord;
923 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(tw.TrackWord);
924 tw.AllAtReply = SettingManager.Common.AllAtReply;
925 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
926 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
927 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
928 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
929 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
931 // アクセストークンが有効であるか確認する
932 // ここが Twitter API への最初のアクセスになるようにすること
935 this.tw.VerifyCredentials();
937 catch (WebApiException ex)
939 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
940 ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
944 //プロキシ設定等の通信まわりの初期化が済んでから処理する
945 ThumbnailGenerator.InitializeGenerator();
947 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
948 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
949 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
951 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
954 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
957 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
958 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
959 HashMgr = new HashtagManage(HashSupl,
960 SettingManager.Common.HashTags.ToArray(),
961 SettingManager.Common.HashSelected,
962 SettingManager.Common.HashIsPermanent,
963 SettingManager.Common.HashIsHead,
964 SettingManager.Common.HashIsNotAddToAtReply);
965 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
968 this.IconCache = new ImageCache();
969 this.tweetDetailsView.IconCache = this.IconCache;
972 _fntUnread = SettingManager.Local.FontUnread;
973 _clUnread = SettingManager.Local.ColorUnread;
974 _fntReaded = SettingManager.Local.FontRead;
975 _clReaded = SettingManager.Local.ColorRead;
976 _clFav = SettingManager.Local.ColorFav;
977 _clOWL = SettingManager.Local.ColorOWL;
978 _clRetweet = SettingManager.Local.ColorRetweet;
979 _fntDetail = SettingManager.Local.FontDetail;
980 _clDetail = SettingManager.Local.ColorDetail;
981 _clDetailLink = SettingManager.Local.ColorDetailLink;
982 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
983 _clSelf = SettingManager.Local.ColorSelf;
984 _clAtSelf = SettingManager.Local.ColorAtSelf;
985 _clTarget = SettingManager.Local.ColorTarget;
986 _clAtTarget = SettingManager.Local.ColorAtTarget;
987 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
988 _clAtTo = SettingManager.Local.ColorAtTo;
989 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
990 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
991 _clInputFont = SettingManager.Local.ColorInputFont;
992 _fntInputFont = SettingManager.Local.FontInputFont;
994 _brsBackColorMine = new SolidBrush(_clSelf);
995 _brsBackColorAt = new SolidBrush(_clAtSelf);
996 _brsBackColorYou = new SolidBrush(_clTarget);
997 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
998 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
999 _brsBackColorAtTo = new SolidBrush(_clAtTo);
1000 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
1001 _brsBackColorNone = new SolidBrush(_clListBackcolor);
1003 // StringFormatオブジェクトへの事前設定
1004 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
1005 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
1006 //sf.FormatFlags = StringFormatFlags.LineLimit; //
1007 sfTab.Alignment = StringAlignment.Center;
1008 sfTab.LineAlignment = StringAlignment.Center;
1010 InitDetailHtmlFormat();
1012 //Regex statregex = new Regex("^0*");
1013 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
1015 _history.Add(new StatusTextHistory());
1017 this.inReplyTo = null;
1020 SearchDialog.Owner = this;
1021 UrlDialog.Owner = this;
1024 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
1025 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
1027 //新着取得時のリストスクロールをするか。trueならスクロールしない
1028 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
1029 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
1031 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1032 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1035 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
1036 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
1037 _myLoc = SettingManager.Local.FormLocation;
1039 if (this.WindowState != FormWindowState.Minimized)
1041 var tbarRect = new Rectangle(this._myLoc, new Size(_mySize.Width, SystemInformation.CaptionHeight));
1042 var outOfScreen = true;
1043 if (Screen.AllScreens.Length == 1) //ハングするとの報告
1045 foreach (var scr in Screen.AllScreens)
1047 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
1049 outOfScreen = false;
1055 this._myLoc = new Point(0, 0);
1057 this.DesktopLocation = this._myLoc;
1059 this.TopMost = SettingManager.Common.AlwaysTop;
1060 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
1061 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
1062 if (SettingManager.Local.PreviewDistance == -1)
1064 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
1065 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
1066 SettingManager.Local.PreviewDistance = _mySpDis3;
1070 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
1072 //this.Tween_ClientSizeChanged(this, null);
1073 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
1074 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
1076 StatusText.Font = _fntInputFont;
1077 StatusText.ForeColor = _clInputFont;
1079 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
1080 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
1081 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
1083 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
1084 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
1086 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
1087 if (SettingManager.Common.UnreadManage == false)
1089 ReadedStripMenuItem.Enabled = false;
1090 UnreadStripMenuItem.Enabled = false;
1093 //リンク先URL表示部の初期化(画面左下)
1094 StatusLabelUrl.Text = "";
1096 StatusLabel.Text = "";
1097 StatusLabel.AutoToolTip = false;
1098 StatusLabel.ToolTipText = "";
1100 lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
1102 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1103 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1104 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1105 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1107 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1108 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1109 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1110 this.SplitContainer2.Panel2.AccessibleName = "";
1112 ////////////////////////////////////////////////////////////////////////////////
1113 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1114 var mode = ComparerMode.Id;
1115 switch (SettingManager.Common.SortColumn)
1117 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1121 mode = ComparerMode.Id; //Idソートに読み替え
1124 mode = ComparerMode.Nickname;
1127 mode = ComparerMode.Data;
1130 mode = ComparerMode.Id;
1133 mode = ComparerMode.Name;
1136 mode = ComparerMode.Source;
1139 _statuses.SetSortMode(mode, sortOrder);
1140 ////////////////////////////////////////////////////////////////////////////////
1142 ApplyListViewIconSize(SettingManager.Common.IconSize);
1144 //<<<<<<<<タブ関連>>>>>>>
1148 //デフォルトタブの存在チェック、ない場合には追加
1149 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1150 this._statuses.AddTab(new HomeTabModel());
1152 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1153 this._statuses.AddTab(new MentionsTabModel());
1155 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1156 this._statuses.AddTab(new DirectMessagesTabModel());
1158 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1159 this._statuses.AddTab(new FavoritesTabModel());
1161 if (this._statuses.MuteTab == null)
1162 this._statuses.AddTab(new MuteTabModel());
1164 foreach (var tab in _statuses.Tabs)
1166 if (!AddNewTab(tab, startup: true))
1167 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1170 this._statuses.SelectTab(this.ListTab.SelectedTab.Text);
1172 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
1173 Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
1175 if (SettingManager.Common.TabIconDisp)
1177 ListTab.DrawMode = TabDrawMode.Normal;
1181 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1182 ListTab.DrawItem += ListTab_DrawItem;
1183 ListTab.ImageList = null;
1186 if (SettingManager.Common.HotkeyEnabled)
1189 var modKey = HookGlobalHotkey.ModKeys.None;
1190 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1191 modKey |= HookGlobalHotkey.ModKeys.Alt;
1192 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1193 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1194 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1195 modKey |= HookGlobalHotkey.ModKeys.Shift;
1196 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1197 modKey |= HookGlobalHotkey.ModKeys.Win;
1199 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1202 if (SettingManager.Common.IsUseNotifyGrowl)
1205 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1207 SetMainWindowTitle();
1208 SetNotifyIconText();
1210 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1212 this.Visible = true;
1217 this.timelineScheduler.UpdateHome = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
1218 this.timelineScheduler.UpdateMention = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
1219 this.timelineScheduler.UpdateDm = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
1220 this.timelineScheduler.UpdatePublicSearch = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
1221 this.timelineScheduler.UpdateUser = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
1222 this.timelineScheduler.UpdateList = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
1223 this.timelineScheduler.UpdateConfig = () => this.InvokeAsync(() => Task.WhenAll(new[]
1225 this.doGetFollowersMenu(),
1226 this.RefreshBlockIdsAsync(),
1227 this.RefreshMuteUserIdsAsync(),
1228 this.RefreshNoRetweetIdsAsync(),
1229 this.RefreshTwitterConfigurationAsync(),
1231 this.RefreshTimelineScheduler();
1233 var streamingRefreshInterval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1234 this.RefreshThrottlingTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), streamingRefreshInterval);
1235 this.colorizeDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.ColorizeList()), TimeSpan.FromMilliseconds(100), leading: true);
1236 this.selectionDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
1237 this.saveConfigDebouncer = ThrottlingTimer.Debounce(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
1240 TimerRefreshIcon.Interval = 200;
1241 TimerRefreshIcon.Enabled = false;
1243 _ignoreConfigSave = false;
1244 this.TweenMain_Resize(null, null);
1245 if (saveRequired) SaveConfigsAll(false);
1247 foreach (var ua in SettingManager.Common.UserAccounts)
1249 if (ua.UserId == 0 && ua.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
1251 ua.UserId = tw.UserId;
1258 // 初回起動時だけ右下のメニューを目立たせる
1259 HashStripSplitButton.ShowDropDown();
1263 private void InitDetailHtmlFormat()
1265 if (SettingManager.Common.IsMonospace)
1267 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1268 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1272 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1273 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1276 detailHtmlFormatHeader = detailHtmlFormatHeader
1277 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1278 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1279 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1280 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1281 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1282 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1285 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1290 txt = this._statuses.Tabs[e.Index].TabName;
1297 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1298 if (e.State == DrawItemState.Selected)
1300 e.DrawFocusRectangle();
1305 if (_statuses.Tabs[txt].UnreadCount > 0)
1308 fore = System.Drawing.SystemBrushes.ControlText;
1312 fore = System.Drawing.SystemBrushes.ControlText;
1314 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1317 private void LoadConfig()
1319 SettingManager.Local = SettingManager.Local;
1321 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1322 if (SettingManager.Local.ScaleDimension.IsEmpty)
1323 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1325 var tabSettings = SettingManager.Tabs;
1326 foreach (var tabSetting in tabSettings.Tabs)
1329 switch (tabSetting.TabType)
1331 case MyCommon.TabUsageType.Home:
1332 tab = new HomeTabModel(tabSetting.TabName);
1334 case MyCommon.TabUsageType.Mentions:
1335 tab = new MentionsTabModel(tabSetting.TabName);
1337 case MyCommon.TabUsageType.DirectMessage:
1338 tab = new DirectMessagesTabModel(tabSetting.TabName);
1340 case MyCommon.TabUsageType.Favorites:
1341 tab = new FavoritesTabModel(tabSetting.TabName);
1343 case MyCommon.TabUsageType.UserDefined:
1344 tab = new FilterTabModel(tabSetting.TabName);
1346 case MyCommon.TabUsageType.UserTimeline:
1347 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1349 case MyCommon.TabUsageType.PublicSearch:
1350 tab = new PublicSearchTabModel(tabSetting.TabName)
1352 SearchWords = tabSetting.SearchWords,
1353 SearchLang = tabSetting.SearchLang,
1356 case MyCommon.TabUsageType.Lists:
1357 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1359 case MyCommon.TabUsageType.Mute:
1360 tab = new MuteTabModel(tabSetting.TabName);
1366 tab.UnreadManage = tabSetting.UnreadManage;
1367 tab.Protected = tabSetting.Protected;
1368 tab.Notify = tabSetting.Notify;
1369 tab.SoundFile = tabSetting.SoundFile;
1371 if (tab.IsDistributableTabType)
1373 var filterTab = (FilterTabModel)tab;
1374 filterTab.FilterArray = tabSetting.FilterArray;
1375 filterTab.FilterModified = false;
1378 if (this._statuses.ContainsTab(tab.TabName))
1379 tab.TabName = this._statuses.MakeTabName("MyTab");
1381 this._statuses.AddTab(tab);
1383 if (_statuses.Tabs.Count == 0)
1385 _statuses.AddTab(new HomeTabModel());
1386 _statuses.AddTab(new MentionsTabModel());
1387 _statuses.AddTab(new DirectMessagesTabModel());
1388 _statuses.AddTab(new FavoritesTabModel());
1392 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1396 var interval = TimeSpan.FromSeconds(SettingManager.Common.UserstreamPeriod);
1397 var newTimer = ThrottlingTimer.Throttle(() => this.InvokeAsync(() => this.RefreshTimeline()), interval);
1398 var oldTimer = Interlocked.Exchange(ref this.RefreshThrottlingTimer, newTimer);
1402 this.RefreshTimelineScheduler();
1405 private void RefreshTimelineScheduler()
1407 this.timelineScheduler.UpdateIntervalHome = TimeSpan.FromSeconds(SettingManager.Common.TimelinePeriod);
1408 this.timelineScheduler.UpdateIntervalMention = TimeSpan.FromSeconds(SettingManager.Common.ReplyPeriod);
1409 this.timelineScheduler.UpdateIntervalDm = TimeSpan.FromSeconds(SettingManager.Common.DMPeriod);
1410 this.timelineScheduler.UpdateIntervalPublicSearch = TimeSpan.FromSeconds(SettingManager.Common.PubSearchPeriod);
1411 this.timelineScheduler.UpdateIntervalUser = TimeSpan.FromSeconds(SettingManager.Common.UserTimelinePeriod);
1412 this.timelineScheduler.UpdateIntervalList = TimeSpan.FromSeconds(SettingManager.Common.ListsPeriod);
1413 this.timelineScheduler.UpdateIntervalConfig = TimeSpan.FromHours(6);
1414 this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
1416 this.timelineScheduler.RefreshSchedule();
1419 private void MarkSettingCommonModified()
1421 if (this.saveConfigDebouncer == null)
1424 this.ModifySettingCommon = true;
1425 this.saveConfigDebouncer.Call();
1428 private void MarkSettingLocalModified()
1430 if (this.saveConfigDebouncer == null)
1433 this.ModifySettingLocal = true;
1434 this.saveConfigDebouncer.Call();
1437 internal void MarkSettingAtIdModified()
1439 if (this.saveConfigDebouncer == null)
1442 this.ModifySettingAtId = true;
1443 this.saveConfigDebouncer.Call();
1446 private void RefreshTimeline()
1448 var curTabModel = this.CurrentTab;
1449 var curListView = this.CurrentListView;
1451 // 現在表示中のタブのスクロール位置を退避
1452 var curListScroll = this.SaveListViewScroll(curListView, curTabModel);
1454 // 各タブのリスト上の選択位置などを退避
1455 var listSelections = this.SaveListViewSelection();
1459 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1460 out var newMentionOrDm, out var isDelete);
1462 if (MyCommon._endingFlag) return;
1465 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1467 var tabPage = this.ListTab.TabPages[index];
1468 var listView = (DetailsListView)tabPage.Tag;
1470 if (listView.VirtualListSize != tab.AllCount || isDelete)
1472 using (ControlTransaction.Update(listView))
1474 if (listView == curListView)
1475 this.PurgeListViewItemCache();
1480 listView.VirtualListSize = tab.AllCount;
1482 catch (NullReferenceException ex)
1484 // WinForms 内部で ListView.set_TopItem が発生させている例外
1485 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1486 MyCommon.TraceOut(ex, $"TabType: {tab.TabType}, Count: {tab.AllCount}, ListSize: {listView.VirtualListSize}");
1490 this.RestoreListViewSelection(listView, tab, listSelections[tab.TabName]);
1497 if (SettingManager.Common.TabIconDisp)
1499 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1501 var tabPage = this.ListTab.TabPages[index];
1502 if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
1503 tabPage.ImageIndex = 0; // 未読アイコン
1508 this.ListTab.Refresh();
1513 this.RestoreListViewScroll(curListView, curTabModel, curListScroll);
1516 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1518 SetMainWindowTitle();
1519 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1521 HashSupl.AddRangeItem(tw.GetHashList());
1525 internal struct ListViewScroll
1527 public ScrollLockMode ScrollLockMode { get; set; }
1528 public long? TopItemStatusId { get; set; }
1531 internal enum ScrollLockMode
1533 /// <summary>固定しない</summary>
1536 /// <summary>最上部に固定する</summary>
1539 /// <summary>最下部に固定する</summary>
1542 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1547 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1549 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1551 var listScroll = new ListViewScroll
1553 ScrollLockMode = this.GetScrollLockMode(listView),
1556 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1558 var topItemIndex = listView.TopItem?.Index ?? -1;
1559 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1560 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1566 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1568 if (this._statuses.SortMode == ComparerMode.Id)
1570 if (this._statuses.SortOrder == SortOrder.Ascending)
1573 if (this.ListLockMenuItem.Checked)
1574 return ScrollLockMode.None;
1576 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1579 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1580 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1581 return ScrollLockMode.FixedToBottom;
1583 return ScrollLockMode.None;
1588 if (this.ListLockMenuItem.Checked)
1589 return ScrollLockMode.FixedToItem;
1591 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1592 var topItem = listView.TopItem;
1593 if (topItem == null || topItem.Index == 0)
1594 return ScrollLockMode.FixedToTop;
1596 return ScrollLockMode.FixedToItem;
1601 return ScrollLockMode.FixedToItem;
1605 internal struct ListViewSelection
1607 public long[] SelectedStatusIds { get; set; }
1608 public long? SelectionMarkStatusId { get; set; }
1609 public long? FocusedStatusId { get; set; }
1613 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1615 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1617 var listsDict = new Dictionary<string, ListViewSelection>();
1619 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
1621 var listView = (DetailsListView)this.ListTab.TabPages[index].Tag;
1622 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1629 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1631 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1633 if (listView.VirtualListSize == 0)
1635 return new ListViewSelection
1637 SelectedStatusIds = Array.Empty<long>(),
1638 SelectionMarkStatusId = null,
1639 FocusedStatusId = null,
1643 return new ListViewSelection
1645 SelectedStatusIds = tab.SelectedStatusIds,
1646 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1647 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1651 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1653 var index = listView.FocusedItem?.Index ?? -1;
1655 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1658 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1660 var index = listView.SelectionMark;
1662 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1666 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1668 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1670 if (listView.VirtualListSize == 0)
1673 switch (listScroll.ScrollLockMode)
1675 case ScrollLockMode.FixedToTop:
1676 listView.EnsureVisible(0);
1678 case ScrollLockMode.FixedToBottom:
1679 listView.EnsureVisible(listView.VirtualListSize - 1);
1681 case ScrollLockMode.FixedToItem:
1682 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1685 var topItem = listView.Items[topIndex];
1688 listView.TopItem = topItem;
1690 catch (NullReferenceException)
1692 listView.EnsureVisible(listView.VirtualListSize - 1);
1693 listView.EnsureVisible(topIndex);
1697 case ScrollLockMode.None:
1704 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1706 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1708 // status_id から ListView 上のインデックスに変換
1709 int[] selectedIndices = null;
1710 if (listSelection.SelectedStatusIds != null)
1711 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1713 var focusedIndex = -1;
1714 if (listSelection.FocusedStatusId != null)
1715 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1717 var selectionMarkIndex = -1;
1718 if (listSelection.SelectionMarkStatusId != null)
1719 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1721 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1724 private bool BalloonRequired()
1726 var ev = new Twitter.FormattedEvent
1728 Eventtype = MyCommon.EVENTTYPE.None,
1731 return BalloonRequired(ev);
1734 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1736 if (type == MyCommon.EVENTTYPE.None)
1739 if (!SettingManager.Common.EventNotifyEnabled)
1742 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1745 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1750 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1753 private bool BalloonRequired(Twitter.FormattedEvent ev)
1758 if (NativeMethods.IsScreenSaverRunning())
1762 if (!this.NewPostPopMenuItem.Checked)
1764 // 「新着通知が無効でもイベントを通知する」にも該当しない
1765 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1769 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1770 if (SettingManager.Common.LimitBalloon)
1772 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1776 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1779 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1781 if (SettingManager.Common.ReadOwnPost)
1783 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1788 if (BalloonRequired())
1790 if (notifyPosts != null && notifyPosts.Length > 0)
1792 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1793 if (SettingManager.Common.IsUseNotifyGrowl)
1795 var sb = new StringBuilder();
1799 foreach (var post in notifyPosts)
1801 if (!(notifyPosts.Length > 3))
1807 if (post.IsReply && !post.IsExcludeReply) reply = true;
1808 if (post.IsDm) dm = true;
1809 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1810 switch (SettingManager.Common.NameBalloon)
1812 case MyCommon.NameBalloonEnum.UserID:
1813 sb.Append(post.ScreenName).Append(" : ");
1815 case MyCommon.NameBalloonEnum.NickName:
1816 sb.Append(post.Nickname).Append(" : ");
1819 sb.Append(post.TextFromApi);
1820 if (notifyPosts.Length > 3)
1822 if (notifyPosts.Last() != post) continue;
1825 var title = new StringBuilder();
1826 GrowlHelper.NotifyType nt;
1827 if (SettingManager.Common.DispUsername)
1829 title.Append(tw.Username);
1830 title.Append(" - ");
1838 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1839 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1840 title.Append(ApplicationSettings.ApplicationName);
1841 title.Append(" [DM] ");
1842 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1843 nt = GrowlHelper.NotifyType.DirectMessage;
1847 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1848 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1849 title.Append(ApplicationSettings.ApplicationName);
1850 title.Append(" [Reply!] ");
1851 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1852 nt = GrowlHelper.NotifyType.Reply;
1856 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1857 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1858 title.Append(ApplicationSettings.ApplicationName);
1860 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1861 nt = GrowlHelper.NotifyType.Notify;
1863 var bText = sb.ToString();
1864 if (string.IsNullOrEmpty(bText)) return;
1866 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1867 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image?.Image, post.ImageUrl);
1872 var sb = new StringBuilder();
1875 foreach (var post in notifyPosts)
1877 if (post.IsReply && !post.IsExcludeReply) reply = true;
1878 if (post.IsDm) dm = true;
1879 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1880 switch (SettingManager.Common.NameBalloon)
1882 case MyCommon.NameBalloonEnum.UserID:
1883 sb.Append(post.ScreenName).Append(" : ");
1885 case MyCommon.NameBalloonEnum.NickName:
1886 sb.Append(post.Nickname).Append(" : ");
1889 sb.Append(post.TextFromApi);
1892 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1893 var title = new StringBuilder();
1895 if (SettingManager.Common.DispUsername)
1897 title.Append(tw.Username);
1898 title.Append(" - ");
1906 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1907 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1908 ntIcon = ToolTipIcon.Warning;
1909 title.Append(ApplicationSettings.ApplicationName);
1910 title.Append(" [DM] ");
1911 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1915 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1916 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1917 ntIcon = ToolTipIcon.Warning;
1918 title.Append(ApplicationSettings.ApplicationName);
1919 title.Append(" [Reply!] ");
1920 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1924 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1925 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1926 ntIcon = ToolTipIcon.Info;
1927 title.Append(ApplicationSettings.ApplicationName);
1929 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1931 var bText = sb.ToString();
1932 if (string.IsNullOrEmpty(bText)) return;
1933 //NotifyIcon1.BalloonTipText = sb.ToString();
1934 //NotifyIcon1.ShowBalloonTip(500);
1935 NotifyIcon1.BalloonTipTitle = title.ToString();
1936 NotifyIcon1.BalloonTipText = bText;
1937 NotifyIcon1.BalloonTipIcon = ntIcon;
1938 NotifyIcon1.ShowBalloonTip(500);
1944 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1948 var dir = Application.StartupPath;
1949 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1951 dir = Path.Combine(dir, "Sounds");
1953 using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1961 //mentions新着時に画面ブリンク
1962 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1964 NativeMethods.FlashMyWindow(this.Handle, 3);
1968 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1970 var listView = this.CurrentListView;
1971 if (listView != sender)
1974 var indices = listView.SelectedIndices.Cast<int>().ToArray();
1975 this.CurrentTab.SelectPosts(indices);
1977 if (listView.SelectedIndices.Count != 1)
1980 var index = listView.SelectedIndices[0];
1981 if (index > listView.VirtualListSize - 1) return;
1983 this.PushSelectPostChain();
1985 var post = this.CurrentPost;
1986 this._statuses.SetReadAllTab(post.StatusId, read: true);
1989 ChangeCacheStyleRead(true, index); // 既読へ(フォント、文字色)
1991 this.colorizeDebouncer.Call();
1992 this.selectionDebouncer.Call();
1995 private void ChangeCacheStyleRead(bool Read, int Index)
1997 var tabInfo = this.CurrentTab;
1998 //Read:true=既読 false=未読
1999 //未読管理していなかったら既読として扱う
2000 if (!tabInfo.UnreadManage ||
2001 !SettingManager.Common.UnreadManage) Read = true;
2003 var listCache = this._listItemCache;
2004 if (listCache == null)
2007 // キャッシュに含まれていないアイテムは対象外
2008 if (!listCache.TryGetValue(Index, out var itm, out var post))
2011 ChangeItemStyleRead(Read, itm, post, (DetailsListView)listCache.TargetList);
2014 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
2029 if (Item.SubItems[5].Text != star)
2030 Item.SubItems[5].Text = star;
2036 else if (Post.RetweetedId != null)
2038 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
2040 else if (Read || !SettingManager.Common.UseUnreadStyle)
2045 if (DList == null || Item.Index == -1)
2047 Item.ForeColor = cl;
2048 if (SettingManager.Common.UseUnreadStyle)
2054 if (SettingManager.Common.UseUnreadStyle)
2055 DList.ChangeItemFontAndColor(Item, cl, fnt);
2057 DList.ChangeItemForeColor(Item, cl);
2058 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2062 private void ColorizeList()
2064 //Index:更新対象のListviewItem.Index。Colorを返す。
2065 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2068 _post = _anchorPost;
2070 _post = this.CurrentPost;
2072 if (_post == null) return;
2074 var listCache = this._listItemCache;
2075 if (listCache == null)
2078 var listView = (DetailsListView)listCache.TargetList;
2080 // ValidateRectが呼ばれる前に選択色などの描画を済ませておく
2083 foreach (var (listViewItem, cachedPost) in listCache.Cache)
2085 var backColor = this.JudgeColor(_post, cachedPost);
2086 listView.ChangeItemBackColor(listViewItem, backColor);
2090 private void ColorizeList(ListViewItem Item, PostClass post)
2092 //Index:更新対象のListviewItem.Index。Colorを返す。
2093 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2096 _post = _anchorPost;
2098 _post = this.CurrentPost;
2100 if (_post == null) return;
2102 if (Item.Index == -1)
2103 Item.BackColor = JudgeColor(_post, post);
2105 this.CurrentListView.ChangeItemBackColor(Item, JudgeColor(_post, post));
2108 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2111 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2114 else if (TargetPost.IsMe)
2117 else if (TargetPost.IsReply)
2120 else if (BasePost.ReplyToList.Any(x => x.UserId == TargetPost.UserId))
2122 cl = _clAtFromTarget;
2123 else if (TargetPost.ReplyToList.Any(x => x.UserId == BasePost.UserId))
2126 else if (TargetPost.UserId == BasePost.UserId)
2131 cl = _clListBackcolor;
2136 private void StatusTextHistoryBack()
2138 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2139 this._history[_hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2142 if (this._hisIdx < 0)
2145 var historyItem = this._history[this._hisIdx];
2146 this.inReplyTo = historyItem.inReplyTo;
2147 this.StatusText.Text = historyItem.status;
2148 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2151 private void StatusTextHistoryForward()
2153 if (!string.IsNullOrWhiteSpace(this.StatusText.Text))
2154 this._history[this._hisIdx] = new StatusTextHistory(this.StatusText.Text, this.inReplyTo);
2157 if (this._hisIdx > this._history.Count - 1)
2158 this._hisIdx = this._history.Count - 1;
2160 var historyItem = this._history[this._hisIdx];
2161 this.inReplyTo = historyItem.inReplyTo;
2162 this.StatusText.Text = historyItem.status;
2163 this.StatusText.SelectionStart = this.StatusText.Text.Length;
2166 private async void PostButton_Click(object sender, EventArgs e)
2168 if (StatusText.Text.Trim().Length == 0)
2170 if (!ImageSelector.Enabled)
2172 await this.DoRefresh();
2177 var currentPost = this.CurrentPost;
2178 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
2180 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2182 MessageBoxButtons.YesNoCancel,
2183 MessageBoxIcon.Question);
2186 case DialogResult.Yes:
2187 StatusText.Text = "";
2188 await this.doReTweetOfficial(false);
2190 case DialogResult.Cancel:
2195 if (TextContainsOnlyMentions(this.StatusText.Text))
2197 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
2198 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
2200 if (ret != DialogResult.OK)
2204 _history[_history.Count - 1] = new StatusTextHistory(StatusText.Text, this.inReplyTo);
2206 if (SettingManager.Common.Nicoms)
2208 StatusText.SelectionStart = StatusText.Text.Length;
2209 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2211 //if (SettingDialog.UrlConvertAuto)
2213 // StatusText.SelectionStart = StatusText.Text.Length;
2214 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2216 //else if (SettingDialog.Nicoms)
2218 // StatusText.SelectionStart = StatusText.Text.Length;
2219 // UrlConvert(UrlConverter.Nicoms);
2221 StatusText.SelectionStart = StatusText.Text.Length;
2222 CheckReplyTo(StatusText.Text);
2224 var status = new PostStatusParams();
2226 var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
2227 if (this.GetRestStatusCount(statusTextCompat) >= 0)
2229 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
2230 // 収まる場合はこれらのオプションを使用せずに投稿する
2231 status.Text = statusTextCompat;
2232 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2236 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
2237 status.InReplyToStatusId = this.inReplyTo?.StatusId;
2239 status.AttachmentUrl = attachmentUrl;
2241 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
2243 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
2244 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
2246 status.AutoPopulateReplyMetadata = true;
2248 // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
2249 status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
2254 if (this.GetRestStatusCount(status.Text) < 0)
2256 // 文字数制限を超えているが強制的に投稿するか
2257 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2258 if (ret != DialogResult.OK)
2262 IMediaUploadService uploadService = null;
2263 IMediaItem[] uploadItems = null;
2264 if (ImageSelector.Visible)
2267 if (!ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
2270 uploadService = this.ImageSelector.GetService(serviceName);
2273 this.inReplyTo = null;
2274 StatusText.Text = "";
2275 _history.Add(new StatusTextHistory());
2276 _hisIdx = _history.Count - 1;
2277 if (!SettingManager.Common.FocusLockToStatusText)
2278 this.CurrentListView.Focus();
2279 urlUndoBuffer = null;
2280 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2283 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2285 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2286 await this.OpenUriInBrowserAsync(tmp);
2289 await this.PostMessageAsync(status, uploadService, uploadItems);
2292 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2294 MyCommon._endingFlag = true;
2298 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2300 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2302 //_endingFlag=false:フォームの×ボタン
2304 this.Visible = false;
2308 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2309 _ignoreConfigSave = true;
2310 MyCommon._endingFlag = true;
2311 this.timelineScheduler.Enabled = false;
2312 TimerRefreshIcon.Enabled = false;
2316 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2318 this.Visible = true;
2319 if (this.WindowState == FormWindowState.Minimized)
2321 this.WindowState = FormWindowState.Normal;
2324 this.BringToFront();
2327 private static int errorCount = 0;
2329 private static bool CheckAccountValid()
2331 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2337 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2346 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2347 private Task RefreshTabAsync<T>() where T : TabModel
2348 => this.RefreshTabAsync<T>(backward: false);
2350 /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
2351 private Task RefreshTabAsync<T>(bool backward) where T : TabModel
2354 from tab in this._statuses.GetTabsByType<T>()
2355 select this.RefreshTabAsync(tab, backward);
2357 return Task.WhenAll(loadTasks);
2360 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2361 private Task RefreshTabAsync(TabModel tab)
2362 => this.RefreshTabAsync(tab, backward: false);
2364 /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
2365 private async Task RefreshTabAsync(TabModel tab, bool backward)
2367 await this.workerSemaphore.WaitAsync();
2368 this.RefreshTasktrayIcon();
2372 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this._initial, this.workerProgress));
2373 this.RefreshTimeline();
2375 catch (WebApiException ex)
2377 this._myStatusError = true;
2382 case HomeTabModel _:
2383 tabType = "GetTimeline";
2385 case MentionsTabModel _:
2386 tabType = "GetTimeline";
2388 case DirectMessagesTabModel _:
2389 tabType = "GetDirectMessage";
2391 case FavoritesTabModel _:
2392 tabType = "GetFavorites";
2394 case PublicSearchTabModel _:
2395 tabType = "GetSearch";
2397 case UserTimelineTabModel _:
2398 tabType = "GetUserTimeline";
2400 case ListTimelineTabModel _:
2401 tabType = "GetListStatus";
2403 case RelatedPostsTabModel _:
2404 tabType = "GetRelatedTweets";
2407 tabType = tab.GetType().Name.Replace("Model", "");
2411 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
2415 this.workerSemaphore.Release();
2419 private async Task FavAddAsync(long statusId, TabModel tab)
2421 await this.workerSemaphore.WaitAsync();
2422 this.RefreshTasktrayIcon();
2426 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2428 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2430 catch (WebApiException ex)
2432 this._myStatusError = true;
2433 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2437 this.workerSemaphore.Release();
2441 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2443 if (ct.IsCancellationRequested)
2446 if (!CheckAccountValid())
2447 throw new WebApiException("Auth error. Check your account");
2449 if (!tab.Posts.TryGetValue(statusId, out var post))
2455 await Task.Run(async () =>
2457 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2463 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2465 .ConfigureAwait(false);
2467 catch (TwitterApiException ex)
2468 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2470 // エラーコード 139 のみの場合は成功と見なす
2473 if (SettingManager.Common.RestrictFavCheck)
2475 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2476 .ConfigureAwait(false);
2478 if (status.Favorited != true)
2479 throw new WebApiException("NG(Restricted?)");
2482 this._favTimestamps.Add(DateTimeUtc.Now);
2485 if (this._statuses.ContainsKey(statusId))
2487 var postTl = this._statuses[statusId];
2488 postTl.IsFav = true;
2490 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2491 favTab.AddPostQueue(postTl);
2494 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2495 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2497 if (tb.Contains(statusId))
2498 tb.Posts[statusId].IsFav = true;
2501 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2503 catch (WebApiException)
2505 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2510 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2511 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2513 if (this._favTimestamps[i] < oneHour)
2514 this._favTimestamps.RemoveAt(i);
2517 this._statuses.DistributePosts();
2520 if (ct.IsCancellationRequested)
2523 this.RefreshTimeline();
2525 if (this.CurrentTabName == tab.TabName)
2527 using (ControlTransaction.Update(this.CurrentListView))
2529 var idx = tab.IndexOf(statusId);
2531 this.ChangeCacheStyleRead(post.IsRead, idx);
2534 var currentPost = this.CurrentPost;
2535 if (currentPost != null && statusId == currentPost.StatusId)
2536 this.DispSelectedPost(true); // 選択アイテム再表示
2540 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2542 await this.workerSemaphore.WaitAsync();
2543 this.RefreshTasktrayIcon();
2547 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2549 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2551 catch (WebApiException ex)
2553 this._myStatusError = true;
2554 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2558 this.workerSemaphore.Release();
2562 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2564 if (ct.IsCancellationRequested)
2567 if (!CheckAccountValid())
2568 throw new WebApiException("Auth error. Check your account");
2570 var successIds = new List<long>();
2572 await Task.Run(async () =>
2576 var failedCount = 0;
2577 foreach (var statusId in statusIds)
2581 var post = tab.Posts[statusId];
2583 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2590 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2592 .ConfigureAwait(false);
2594 catch (WebApiException)
2600 successIds.Add(statusId);
2601 post.IsFav = false; // リスト再描画必要
2603 if (this._statuses.ContainsKey(statusId))
2605 this._statuses[statusId].IsFav = false;
2608 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2609 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2611 if (tb.Contains(statusId))
2612 tb.Posts[statusId].IsFav = false;
2617 if (ct.IsCancellationRequested)
2620 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2621 foreach (var statusId in successIds)
2623 // ツイートが削除された訳ではないので IsDeleted はセットしない
2624 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2627 this.RefreshTimeline();
2629 if (this.CurrentTabName == tab.TabName)
2631 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2637 using (ControlTransaction.Update(this.CurrentListView))
2639 foreach (var statusId in successIds)
2641 var idx = tab.IndexOf(statusId);
2645 var post = tab.Posts[statusId];
2646 this.ChangeCacheStyleRead(post.IsRead, idx);
2650 var currentPost = this.CurrentPost;
2651 if (currentPost != null && successIds.Contains(currentPost.StatusId))
2652 this.DispSelectedPost(true); // 選択アイテム再表示
2657 private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService uploadService, IMediaItem[] uploadItems)
2659 await this.workerSemaphore.WaitAsync();
2660 this.RefreshTasktrayIcon();
2664 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2666 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
2668 catch (WebApiException ex)
2670 this._myStatusError = true;
2671 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2675 this.workerSemaphore.Release();
2679 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostStatusParams postParams,
2680 IMediaUploadService uploadService, IMediaItem[] uploadItems)
2682 if (ct.IsCancellationRequested)
2685 if (!CheckAccountValid())
2686 throw new WebApiException("Auth error. Check your account");
2688 p.Report("Posting...");
2690 PostClass post = null;
2695 await Task.Run(async () =>
2697 var postParamsWithMedia = postParams;
2699 if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
2701 postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
2702 .ConfigureAwait(false);
2705 post = await this.tw.PostStatus(postParamsWithMedia)
2706 .ConfigureAwait(false);
2709 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2711 catch (WebApiException ex)
2713 // 処理は中断せずエラーの表示のみ行う
2714 errMsg = $"Err:{ex.Message}(PostMessage)";
2716 this._myStatusError = true;
2718 catch (UnauthorizedAccessException ex)
2720 // アップロード対象のファイルが開けなかった場合など
2721 errMsg = $"Err:{ex.Message}(PostMessage)";
2723 this._myStatusError = true;
2727 // 使い終わった MediaItem は破棄する
2728 if (uploadItems != null)
2730 foreach (var disposableItem in uploadItems.OfType<IDisposable>())
2732 disposableItem.Dispose();
2737 if (ct.IsCancellationRequested)
2740 if (!string.IsNullOrEmpty(errMsg) &&
2741 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2742 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2744 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
2746 var ret = MessageBox.Show(
2748 "Failed to update status",
2749 MessageBoxButtons.RetryCancel,
2750 MessageBoxIcon.Question);
2752 if (ret == DialogResult.Retry)
2754 await this.PostMessageAsync(postParams, uploadService, uploadItems);
2758 this.StatusTextHistoryBack();
2759 this.StatusText.Focus();
2761 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2762 if (SettingManager.Common.FocusLockToStatusText)
2763 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2768 this._postTimestamps.Add(DateTimeUtc.Now);
2770 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2771 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2773 if (this._postTimestamps[i] < oneHour)
2774 this._postTimestamps.RemoveAt(i);
2777 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2779 this.HashMgr.ClearHashtag();
2780 this.HashStripSplitButton.Text = "#[-]";
2781 this.HashTogglePullDownMenuItem.Checked = false;
2782 this.HashToggleMenuItem.Checked = false;
2785 this.SetMainWindowTitle();
2788 if (!this.tw.UserStreamActive)
2790 if (SettingManager.Common.PostAndGet)
2791 await this.RefreshTabAsync<HomeTabModel>();
2796 this._statuses.AddPost(post);
2797 this._statuses.DistributePosts();
2799 this.RefreshTimeline();
2804 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2806 await this.workerSemaphore.WaitAsync();
2807 this.RefreshTasktrayIcon();
2811 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2813 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2815 catch (WebApiException ex)
2817 this._myStatusError = true;
2818 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2822 this.workerSemaphore.Release();
2826 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2828 if (ct.IsCancellationRequested)
2831 if (!CheckAccountValid())
2832 throw new WebApiException("Auth error. Check your account");
2835 if (!SettingManager.Common.UnreadManage)
2838 read = this._initial && SettingManager.Common.Read;
2840 p.Report("Posting...");
2842 var posts = new List<PostClass>();
2844 await Task.Run(async () =>
2846 foreach (var statusId in statusIds)
2848 var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2849 if (post != null) posts.Add(post);
2853 if (ct.IsCancellationRequested)
2856 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2858 this._postTimestamps.Add(DateTimeUtc.Now);
2860 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
2861 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2863 if (this._postTimestamps[i] < oneHour)
2864 this._postTimestamps.RemoveAt(i);
2868 if (!this.tw.UserStreamActive)
2870 // 自分のRTはTLの更新では取得できない場合があるので、
2871 // 投稿時取得の有無に関わらず追加しておく
2872 posts.ForEach(post => this._statuses.AddPost(post));
2874 if (SettingManager.Common.PostAndGet)
2875 await this.RefreshTabAsync<HomeTabModel>();
2878 this._statuses.DistributePosts();
2879 this.RefreshTimeline();
2884 private async Task RefreshFollowerIdsAsync()
2886 await this.workerSemaphore.WaitAsync();
2887 this.RefreshTasktrayIcon();
2891 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2893 await this.tw.RefreshFollowerIds();
2895 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2897 this.RefreshTimeline();
2898 this.PurgeListViewItemCache();
2899 this.CurrentListView.Refresh();
2901 catch (WebApiException ex)
2903 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2907 this.workerSemaphore.Release();
2911 private async Task RefreshNoRetweetIdsAsync()
2913 await this.workerSemaphore.WaitAsync();
2914 this.RefreshTasktrayIcon();
2918 await this.tw.RefreshNoRetweetIds();
2920 this.StatusLabel.Text = "NoRetweetIds refreshed";
2922 catch (WebApiException ex)
2924 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2928 this.workerSemaphore.Release();
2932 private async Task RefreshBlockIdsAsync()
2934 await this.workerSemaphore.WaitAsync();
2935 this.RefreshTasktrayIcon();
2939 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2941 await this.tw.RefreshBlockIds();
2943 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2945 catch (WebApiException ex)
2947 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2951 this.workerSemaphore.Release();
2955 private async Task RefreshTwitterConfigurationAsync()
2957 await this.workerSemaphore.WaitAsync();
2958 this.RefreshTasktrayIcon();
2962 await this.tw.RefreshConfiguration();
2964 if (this.tw.Configuration.PhotoSizeLimit != 0)
2966 foreach (var service in this.ImageSelector.GetServices())
2968 service.UpdateTwitterConfiguration(this.tw.Configuration);
2972 this.PurgeListViewItemCache();
2973 this.CurrentListView.Refresh();
2975 catch (WebApiException ex)
2977 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2981 this.workerSemaphore.Release();
2985 private async Task RefreshMuteUserIdsAsync()
2987 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2991 await tw.RefreshMuteUserIdsAsync();
2993 catch (WebApiException ex)
2995 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
2999 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3002 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3004 if (e.Button == MouseButtons.Left)
3006 this.Visible = true;
3007 if (this.WindowState == FormWindowState.Minimized)
3009 this.WindowState = _formWindowState;
3012 this.BringToFront();
3016 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3018 switch (SettingManager.Common.ListDoubleClickAction)
3021 MakeReplyOrDirectStatus();
3024 await this.FavoriteChange(true);
3027 var post = this.CurrentPost;
3029 await this.ShowUserStatus(post.ScreenName, false);
3032 await ShowUserTimeline();
3035 ShowRelatedStatusesMenuItem_Click(null, null);
3038 MoveToHomeToolStripMenuItem_Click(null, null);
3041 StatusOpenMenuItem_Click(null, null);
3049 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3050 => await this.FavoriteChange(true);
3052 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3053 => await this.FavoriteChange(false);
3056 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3057 => await this.FavoritesRetweetOfficial();
3059 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3060 => await this.FavoritesRetweetUnofficial();
3062 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3064 var tab = this.CurrentTab;
3065 var posts = tab.SelectedPosts;
3067 //trueでFavAdd,falseでFavRemove
3068 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
3069 || !this.ExistCurrentPost) return;
3071 if (posts.Length > 1)
3076 // https://support.twitter.com/articles/76915#favoriting
3077 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3078 _DoFavRetweetFlags = false;
3083 if (multiFavoriteChangeDialogEnable)
3085 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3086 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3087 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3089 if (confirm == DialogResult.Cancel)
3097 var selectedPost = posts.Single();
3098 if (selectedPost.IsFav)
3100 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3104 await this.FavAddAsync(selectedPost.StatusId, tab);
3108 var selectedPosts = posts.Where(x => x.IsFav);
3109 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3110 if (statusIds.Length == 0)
3112 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3116 await this.FavRemoveAsync(statusIds, tab);
3120 private PostClass GetCurTabPost(int Index)
3122 var listCache = this._listItemCache;
3123 if (listCache != null)
3125 if (listCache.TryGetValue(Index, out _, out var post))
3129 return this.CurrentTab[Index];
3132 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3134 var post = this.CurrentPost;
3136 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + post.ScreenName);
3138 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3141 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3143 var post = this.CurrentPost;
3145 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + post.ScreenName + "/favorites");
3148 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3150 if ((!_initialLayout) && this.Visible)
3152 if (this.WindowState == FormWindowState.Normal)
3154 _mySize = this.ClientSize;
3155 _mySpDis = this.SplitContainer1.SplitterDistance;
3156 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3157 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3158 this.MarkSettingLocalModified();
3163 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3165 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3166 if (comparerMode == null)
3169 this.SetSortColumn(comparerMode.Value);
3173 /// 列インデックスからソートを行う ComparerMode を求める
3175 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3176 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3177 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3180 return ComparerMode.Id;
3182 switch (columnIndex)
3185 return ComparerMode.Nickname;
3187 return ComparerMode.Data;
3189 return ComparerMode.Id;
3191 return ComparerMode.Name;
3193 return ComparerMode.Source;
3195 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3201 /// 発言一覧の指定した位置の列でソートする
3203 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3204 private void SetSortColumnByDisplayIndex(int columnIndex)
3206 // 表示上の列の位置から ColumnHeader を求める
3207 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3208 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3213 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3214 if (comparerMode == null)
3217 this.SetSortColumn(comparerMode.Value);
3221 /// 発言一覧の最後列の項目でソートする
3223 private void SetSortLastColumn()
3225 // 表示上の最後列にある ColumnHeader を求める
3226 var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
3227 .OrderByDescending(x => x.DisplayIndex)
3230 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3231 if (comparerMode == null)
3234 this.SetSortColumn(comparerMode.Value);
3238 /// 発言一覧を指定された ComparerMode に基づいてソートする
3240 private void SetSortColumn(ComparerMode sortColumn)
3242 if (SettingManager.Common.SortOrderLock)
3245 this._statuses.ToggleSortOrder(sortColumn);
3246 this.InitColumnText();
3248 var list = this.CurrentListView;
3251 list.Columns[0].Text = this.ColumnText[0];
3252 list.Columns[1].Text = this.ColumnText[2];
3256 for (var i = 0; i <= 7; i++)
3258 list.Columns[i].Text = this.ColumnText[i];
3262 this.PurgeListViewItemCache();
3264 var tab = this.CurrentTab;
3265 var post = this.CurrentPost;
3266 if (tab.AllCount > 0 && post != null)
3268 var idx = tab.IndexOf(post.StatusId);
3271 this.SelectListItem(list, idx);
3272 list.EnsureVisible(idx);
3277 this.MarkSettingCommonModified();
3280 private void TweenMain_LocationChanged(object sender, EventArgs e)
3282 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3284 _myLoc = this.DesktopLocation;
3285 this.MarkSettingLocalModified();
3289 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3291 if (!this.ExistCurrentPost)
3293 ReplyStripMenuItem.Enabled = false;
3294 ReplyAllStripMenuItem.Enabled = false;
3295 DMStripMenuItem.Enabled = false;
3296 ShowProfileMenuItem.Enabled = false;
3297 ShowUserTimelineContextMenuItem.Enabled = false;
3298 ListManageUserContextToolStripMenuItem2.Enabled = false;
3299 MoveToFavToolStripMenuItem.Enabled = false;
3300 TabMenuItem.Enabled = false;
3301 IDRuleMenuItem.Enabled = false;
3302 SourceRuleMenuItem.Enabled = false;
3303 ReadedStripMenuItem.Enabled = false;
3304 UnreadStripMenuItem.Enabled = false;
3308 ShowProfileMenuItem.Enabled = true;
3309 ListManageUserContextToolStripMenuItem2.Enabled = true;
3310 ReplyStripMenuItem.Enabled = true;
3311 ReplyAllStripMenuItem.Enabled = true;
3312 DMStripMenuItem.Enabled = true;
3313 ShowUserTimelineContextMenuItem.Enabled = true;
3314 MoveToFavToolStripMenuItem.Enabled = true;
3315 TabMenuItem.Enabled = true;
3316 IDRuleMenuItem.Enabled = true;
3317 SourceRuleMenuItem.Enabled = true;
3318 ReadedStripMenuItem.Enabled = true;
3319 UnreadStripMenuItem.Enabled = true;
3321 var tab = this.CurrentTab;
3322 var post = this.CurrentPost;
3323 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
3325 FavAddToolStripMenuItem.Enabled = false;
3326 FavRemoveToolStripMenuItem.Enabled = false;
3327 StatusOpenMenuItem.Enabled = false;
3328 ShowRelatedStatusesMenuItem.Enabled = false;
3330 ReTweetStripMenuItem.Enabled = false;
3331 ReTweetUnofficialStripMenuItem.Enabled = false;
3332 QuoteStripMenuItem.Enabled = false;
3333 FavoriteRetweetContextMenu.Enabled = false;
3334 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3338 FavAddToolStripMenuItem.Enabled = true;
3339 FavRemoveToolStripMenuItem.Enabled = true;
3340 StatusOpenMenuItem.Enabled = true;
3341 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3343 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
3345 ReTweetStripMenuItem.Enabled = false;
3346 ReTweetUnofficialStripMenuItem.Enabled = false;
3347 QuoteStripMenuItem.Enabled = false;
3348 FavoriteRetweetContextMenu.Enabled = false;
3349 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3353 ReTweetStripMenuItem.Enabled = true;
3354 ReTweetUnofficialStripMenuItem.Enabled = true;
3355 QuoteStripMenuItem.Enabled = true;
3356 FavoriteRetweetContextMenu.Enabled = true;
3357 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3360 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3362 // RefreshMoreStripMenuItem.Enabled = true;
3366 // RefreshMoreStripMenuItem.Enabled = false;
3368 if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
3370 RepliedStatusOpenMenuItem.Enabled = false;
3374 RepliedStatusOpenMenuItem.Enabled = true;
3376 if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
3378 MoveToRTHomeMenuItem.Enabled = false;
3382 MoveToRTHomeMenuItem.Enabled = true;
3385 if (this.ExistCurrentPost)
3387 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
3388 if (post.RetweetedByUserId == this.tw.UserId)
3389 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3391 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3395 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3396 => this.MakeReplyOrDirectStatus(false, true);
3398 private void DMStripMenuItem_Click(object sender, EventArgs e)
3399 => this.MakeReplyOrDirectStatus(false, false);
3401 private async Task doStatusDelete()
3403 var posts = this.CurrentTab.SelectedPosts;
3404 if (posts.Length == 0)
3407 // 選択されたツイートの中に削除可能なものが一つでもあるか
3408 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3411 var ret = MessageBox.Show(this,
3412 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3413 Properties.Resources.DeleteStripMenuItem_ClickText2,
3414 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3416 if (ret != DialogResult.OK)
3419 var currentListView = this.CurrentListView;
3420 var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
3422 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3424 Exception lastException = null;
3425 foreach (var post in posts)
3427 if (!post.CanDeleteBy(this.tw.UserId))
3434 await this.twitterApi.DirectMessagesEventsDestroy(post.StatusId.ToString(CultureInfo.InvariantCulture));
3438 if (post.RetweetedByUserId == this.tw.UserId)
3440 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3442 await this.twitterApi.StatusesDestroy(post.StatusId)
3447 if (post.UserId == this.tw.UserId)
3449 if (post.RetweetedId != null)
3450 // 他人に RT された自分のツイート
3451 // => RT 元の自分のツイートを削除
3452 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3457 await this.twitterApi.StatusesDestroy(post.StatusId)
3463 catch (WebApiException ex)
3469 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3472 if (lastException == null)
3473 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3475 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3477 this.PurgeListViewItemCache();
3479 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3481 var tabPage = this.ListTab.TabPages[index];
3482 var listView = (DetailsListView)tabPage.Tag;
3484 using (ControlTransaction.Update(listView))
3486 listView.VirtualListSize = tab.AllCount;
3488 if (tab.TabName == this.CurrentTabName)
3490 listView.SelectedIndices.Clear();
3492 if (tab.AllCount != 0)
3495 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3496 selectedIndex = focusedIndex;
3498 selectedIndex = tab.AllCount - 1;
3500 listView.SelectedIndices.Add(selectedIndex);
3501 listView.EnsureVisible(selectedIndex);
3502 listView.FocusedItem = listView.Items[selectedIndex];
3507 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3509 if (tabPage.ImageIndex == 0)
3510 tabPage.ImageIndex = -1; // タブアイコン
3514 if (!SettingManager.Common.TabIconDisp)
3515 this.ListTab.Refresh();
3519 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3520 => await this.doStatusDelete();
3522 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3524 using (ControlTransaction.Update(this.CurrentListView))
3526 var tab = this.CurrentTab;
3527 foreach (var statusId in tab.SelectedStatusIds)
3529 this._statuses.SetReadAllTab(statusId, read: true);
3530 var idx = tab.IndexOf(statusId);
3531 ChangeCacheStyleRead(true, idx);
3535 if (SettingManager.Common.TabIconDisp)
3537 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3539 if (tab.UnreadCount == 0)
3541 var tabPage = this.ListTab.TabPages[index];
3542 if (tabPage.ImageIndex == 0)
3543 tabPage.ImageIndex = -1; // タブアイコン
3547 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3550 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3552 using (ControlTransaction.Update(this.CurrentListView))
3554 var tab = this.CurrentTab;
3555 foreach (var statusId in tab.SelectedStatusIds)
3557 this._statuses.SetReadAllTab(statusId, read: false);
3558 var idx = tab.IndexOf(statusId);
3559 ChangeCacheStyleRead(false, idx);
3563 if (SettingManager.Common.TabIconDisp)
3565 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3567 if (tab.UnreadCount > 0)
3569 var tabPage = this.ListTab.TabPages[index];
3570 if (tabPage.ImageIndex == -1)
3571 tabPage.ImageIndex = 0; // タブアイコン
3575 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3578 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3579 => await this.DoRefresh();
3581 private async Task DoRefresh()
3582 => await this.RefreshTabAsync(this.CurrentTab);
3584 private async Task DoRefreshMore()
3585 => await this.RefreshTabAsync(this.CurrentTab, backward: true);
3587 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3589 var result = DialogResult.Abort;
3591 using var settingDialog = new AppendSettingDialog();
3592 settingDialog.Icon = this.MainIcon;
3593 settingDialog.Owner = this;
3594 settingDialog.ShowInTaskbar = showTaskbarIcon;
3595 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3597 settingDialog.tw = this.tw;
3598 settingDialog.twitterApi = this.twitterApi;
3600 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3604 result = settingDialog.ShowDialog(this);
3608 return DialogResult.Abort;
3611 if (result == DialogResult.OK)
3615 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3622 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3625 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3627 var oldIconSz = SettingManager.Common.IconSize;
3629 if (ShowSettingDialog() == DialogResult.OK)
3633 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3634 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3635 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3636 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3637 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3638 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3639 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3641 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3642 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3643 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3644 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3645 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3646 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3648 ImageSelector.Reset(tw, this.tw.Configuration);
3652 if (SettingManager.Common.TabIconDisp)
3654 ListTab.DrawItem -= ListTab_DrawItem;
3655 ListTab.DrawMode = TabDrawMode.Normal;
3656 ListTab.ImageList = this.TabImage;
3660 ListTab.DrawItem -= ListTab_DrawItem;
3661 ListTab.DrawItem += ListTab_DrawItem;
3662 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3663 ListTab.ImageList = null;
3666 catch (Exception ex)
3668 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3669 ex.Data["IsTerminatePermission"] = false;
3675 if (!SettingManager.Common.UnreadManage)
3677 ReadedStripMenuItem.Enabled = false;
3678 UnreadStripMenuItem.Enabled = false;
3679 if (SettingManager.Common.TabIconDisp)
3681 foreach (TabPage myTab in ListTab.TabPages)
3683 myTab.ImageIndex = -1;
3689 ReadedStripMenuItem.Enabled = true;
3690 UnreadStripMenuItem.Enabled = true;
3693 catch (Exception ex)
3695 ex.Data["Instance"] = "ListTab(UnreadManage)";
3696 ex.Data["IsTerminatePermission"] = false;
3703 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3705 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3706 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3707 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3709 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3710 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3711 _fntUnread = SettingManager.Local.FontUnread;
3712 _clUnread = SettingManager.Local.ColorUnread;
3713 _fntReaded = SettingManager.Local.FontRead;
3714 _clReaded = SettingManager.Local.ColorRead;
3715 _clFav = SettingManager.Local.ColorFav;
3716 _clOWL = SettingManager.Local.ColorOWL;
3717 _clRetweet = SettingManager.Local.ColorRetweet;
3718 _fntDetail = SettingManager.Local.FontDetail;
3719 _clDetail = SettingManager.Local.ColorDetail;
3720 _clDetailLink = SettingManager.Local.ColorDetailLink;
3721 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3722 _clSelf = SettingManager.Local.ColorSelf;
3723 _clAtSelf = SettingManager.Local.ColorAtSelf;
3724 _clTarget = SettingManager.Local.ColorTarget;
3725 _clAtTarget = SettingManager.Local.ColorAtTarget;
3726 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3727 _clAtTo = SettingManager.Local.ColorAtTo;
3728 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3729 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3730 _clInputFont = SettingManager.Local.ColorInputFont;
3731 _fntInputFont = SettingManager.Local.FontInputFont;
3732 _brsBackColorMine.Dispose();
3733 _brsBackColorAt.Dispose();
3734 _brsBackColorYou.Dispose();
3735 _brsBackColorAtYou.Dispose();
3736 _brsBackColorAtFromTarget.Dispose();
3737 _brsBackColorAtTo.Dispose();
3738 _brsBackColorNone.Dispose();
3739 _brsBackColorMine = new SolidBrush(_clSelf);
3740 _brsBackColorAt = new SolidBrush(_clAtSelf);
3741 _brsBackColorYou = new SolidBrush(_clTarget);
3742 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3743 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3744 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3745 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3749 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3750 StatusText.Font = _fntInputFont;
3751 StatusText.ForeColor = _clInputFont;
3753 catch (Exception ex)
3755 MessageBox.Show(ex.Message);
3760 InitDetailHtmlFormat();
3762 catch (Exception ex)
3764 ex.Data["Instance"] = "Font";
3765 ex.Data["IsTerminatePermission"] = false;
3771 if (SettingManager.Common.TabIconDisp)
3773 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3775 var tabPage = this.ListTab.TabPages[index];
3776 if (tab.UnreadCount == 0)
3777 tabPage.ImageIndex = -1;
3779 tabPage.ImageIndex = 0;
3783 catch (Exception ex)
3785 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3786 ex.Data["IsTerminatePermission"] = false;
3792 var oldIconCol = _iconCol;
3794 if (SettingManager.Common.IconSize != oldIconSz)
3795 ApplyListViewIconSize(SettingManager.Common.IconSize);
3797 foreach (TabPage tp in ListTab.TabPages)
3799 var lst = (DetailsListView)tp.Tag;
3801 using (ControlTransaction.Update(lst))
3803 lst.GridLines = SettingManager.Common.ShowGrid;
3804 lst.Font = _fntReaded;
3805 lst.BackColor = _clListBackcolor;
3807 if (_iconCol != oldIconCol)
3812 catch (Exception ex)
3814 ex.Data["Instance"] = "ListView(IconSize)";
3815 ex.Data["IsTerminatePermission"] = false;
3819 SetMainWindowTitle();
3820 SetNotifyIconText();
3822 this.PurgeListViewItemCache();
3823 this.CurrentListView.Refresh();
3826 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3827 if (SettingManager.Common.HotkeyEnabled)
3829 ///グローバルホットキーの登録。設定で変更可能にするかも
3830 var modKey = HookGlobalHotkey.ModKeys.None;
3831 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3832 modKey |= HookGlobalHotkey.ModKeys.Alt;
3833 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3834 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3835 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3836 modKey |= HookGlobalHotkey.ModKeys.Shift;
3837 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3838 modKey |= HookGlobalHotkey.ModKeys.Win;
3840 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3843 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3846 StatusText_TextChanged(null, null);
3855 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3856 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3859 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3861 this.TopMost = SettingManager.Common.AlwaysTop;
3862 SaveConfigsAll(false);
3864 if (tw.UserId != oldUser.UserId)
3865 await this.doGetFollowersMenu();
3871 private void SetTabAlignment()
3873 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3874 if (ListTab.Alignment == newAlignment) return;
3876 // 各タブのリスト上の選択位置などを退避
3877 var listSelections = this.SaveListViewSelection();
3879 ListTab.Alignment = newAlignment;
3881 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
3883 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
3884 using (ControlTransaction.Update(lst))
3887 this.RestoreListViewSelection(lst, tab, listSelections[tab.TabName]);
3892 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3898 case MyCommon.IconSizes.IconNone:
3901 case MyCommon.IconSizes.Icon16:
3904 case MyCommon.IconSizes.Icon24:
3907 case MyCommon.IconSizes.Icon48:
3910 case MyCommon.IconSizes.Icon48_2:
3918 // ディスプレイの DPI 設定を考慮したサイズを設定する
3919 _listViewImageList.ImageSize = new Size(
3921 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
3925 _listViewImageList.ImageSize = new Size(1, 1);
3929 private void ResetColumns(DetailsListView list)
3931 using (ControlTransaction.Update(list))
3932 using (ControlTransaction.Layout(list, false))
3935 list.ColumnClick -= MyList_ColumnClick;
3936 list.DrawColumnHeader -= MyList_DrawColumnHeader;
3937 list.ColumnReordered -= MyList_ColumnReordered;
3938 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
3940 var cols = list.Columns.Cast<ColumnHeader>().ToList();
3941 list.Columns.Clear();
3942 cols.ForEach(col => col.Dispose());
3945 InitColumns(list, true);
3947 list.ColumnClick += MyList_ColumnClick;
3948 list.DrawColumnHeader += MyList_DrawColumnHeader;
3949 list.ColumnReordered += MyList_ColumnReordered;
3950 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
3954 public void AddNewTabForSearch(string searchWord)
3956 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
3957 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
3959 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
3961 var tabIndex = this._statuses.Tabs.IndexOf(tb);
3962 this.ListTab.SelectedIndex = tabIndex;
3967 var tabName = searchWord;
3968 for (var i = 0; i <= 100; i++)
3970 if (_statuses.ContainsTab(tabName))
3976 var tab = new PublicSearchTabModel(tabName);
3977 _statuses.AddTab(tab);
3978 AddNewTab(tab, startup: false);
3980 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
3982 var tabPage = this.CurrentTabPage;
3983 var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
3984 cmb.Items.Add(searchWord);
3985 cmb.Text = searchWord;
3988 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
3991 private async Task ShowUserTimeline()
3993 if (!this.ExistCurrentPost) return;
3994 await this.AddNewTabForUserTimeline(this.CurrentPost.ScreenName);
3997 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
3999 if (e.KeyCode == Keys.Escape)
4001 RemoveSpecifiedTab(this.CurrentTabName, false);
4003 e.SuppressKeyPress = true;
4007 public async Task AddNewTabForUserTimeline(string user)
4009 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4010 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4012 if (tb.ScreenName == user)
4014 var tabIndex = this._statuses.Tabs.IndexOf(tb);
4015 this.ListTab.SelectedIndex = tabIndex;
4020 var tabName = "user:" + user;
4021 while (_statuses.ContainsTab(tabName))
4026 var tab = new UserTimelineTabModel(tabName, user);
4027 this._statuses.AddTab(tab);
4028 this.AddNewTab(tab, startup: false);
4030 ListTab.SelectedIndex = this._statuses.Tabs.Count - 1;
4033 await this.RefreshTabAsync(tab);
4036 public bool AddNewTab(TabModel tab, bool startup)
4039 if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
4043 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4045 var _tabPage = new TabPage();
4046 var _listCustom = new DetailsListView();
4048 var cnt = this._statuses.Tabs.Count;
4050 ///ToDo:Create and set controls follow tabtypes
4052 using (ControlTransaction.Update(_listCustom))
4053 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4054 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4055 using (ControlTransaction.Layout(this.SplitContainer1, false))
4056 using (ControlTransaction.Layout(this.ListTab, false))
4057 using (ControlTransaction.Layout(this))
4058 using (ControlTransaction.Layout(_tabPage, false))
4060 _tabPage.Controls.Add(_listCustom);
4063 var userTab = tab as UserTimelineTabModel;
4064 var listTab = tab as ListTimelineTabModel;
4065 var searchTab = tab as PublicSearchTabModel;
4067 if (userTab != null || listTab != null)
4069 var label = new Label
4071 Dock = DockStyle.Top,
4076 if (listTab != null)
4078 label.Text = listTab.ListInfo.ToString();
4080 else if (userTab != null)
4082 label.Text = userTab.ScreenName + "'s Timeline";
4084 label.TextAlign = ContentAlignment.MiddleLeft;
4085 using (var tmpComboBox = new ComboBox())
4087 label.Height = tmpComboBox.Height;
4089 _tabPage.Controls.Add(label);
4092 else if (searchTab != null)
4094 var pnl = new Panel();
4096 var lbl = new Label();
4097 var cmb = new ComboBox();
4098 var btn = new Button();
4099 var cmbLang = new ComboBox();
4101 using (ControlTransaction.Layout(pnl, false))
4103 pnl.Controls.Add(cmb);
4104 pnl.Controls.Add(cmbLang);
4105 pnl.Controls.Add(btn);
4106 pnl.Controls.Add(lbl);
4107 pnl.Name = "panelSearch";
4109 pnl.Dock = DockStyle.Top;
4110 pnl.Height = cmb.Height;
4111 pnl.Enter += SearchControls_Enter;
4112 pnl.Leave += SearchControls_Leave;
4115 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4116 cmb.Dock = DockStyle.Fill;
4117 cmb.Name = "comboSearch";
4118 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4119 cmb.ImeMode = ImeMode.NoControl;
4120 cmb.TabStop = false;
4122 cmb.AutoCompleteMode = AutoCompleteMode.None;
4123 cmb.KeyDown += SearchComboBox_KeyDown;
4126 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4127 cmbLang.Dock = DockStyle.Right;
4129 cmbLang.Name = "comboLang";
4130 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4131 cmbLang.TabStop = false;
4132 cmbLang.TabIndex = 2;
4133 cmbLang.Items.Add("");
4134 cmbLang.Items.Add("ja");
4135 cmbLang.Items.Add("en");
4136 cmbLang.Items.Add("ar");
4137 cmbLang.Items.Add("da");
4138 cmbLang.Items.Add("nl");
4139 cmbLang.Items.Add("fa");
4140 cmbLang.Items.Add("fi");
4141 cmbLang.Items.Add("fr");
4142 cmbLang.Items.Add("de");
4143 cmbLang.Items.Add("hu");
4144 cmbLang.Items.Add("is");
4145 cmbLang.Items.Add("it");
4146 cmbLang.Items.Add("no");
4147 cmbLang.Items.Add("pl");
4148 cmbLang.Items.Add("pt");
4149 cmbLang.Items.Add("ru");
4150 cmbLang.Items.Add("es");
4151 cmbLang.Items.Add("sv");
4152 cmbLang.Items.Add("th");
4154 lbl.Text = "Search(C-S-f)";
4155 lbl.Name = "label1";
4156 lbl.Dock = DockStyle.Left;
4158 lbl.Height = cmb.Height;
4159 lbl.TextAlign = ContentAlignment.MiddleLeft;
4162 btn.Text = "Search";
4163 btn.Name = "buttonSearch";
4164 btn.UseVisualStyleBackColor = true;
4165 btn.Dock = DockStyle.Right;
4166 btn.TabStop = false;
4168 btn.Click += SearchButton_Click;
4170 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4172 cmb.Items.Add(searchTab.SearchWords);
4173 cmb.Text = searchTab.SearchWords;
4176 cmbLang.Text = searchTab.SearchLang;
4178 _tabPage.Controls.Add(pnl);
4182 _tabPage.Tag = _listCustom;
4183 this.ListTab.Controls.Add(_tabPage);
4185 _tabPage.Location = new Point(4, 4);
4186 _tabPage.Name = "CTab" + cnt;
4187 _tabPage.Size = new Size(380, 260);
4188 _tabPage.TabIndex = 2 + cnt;
4189 _tabPage.Text = tab.TabName;
4190 _tabPage.UseVisualStyleBackColor = true;
4191 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4193 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4194 _listCustom.TabIndex = 1;
4195 _listCustom.AllowColumnReorder = true;
4196 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4197 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4198 _listCustom.Dock = DockStyle.Fill;
4199 _listCustom.FullRowSelect = true;
4200 _listCustom.HideSelection = false;
4201 _listCustom.Location = new Point(0, 0);
4202 _listCustom.Margin = new Padding(0);
4203 _listCustom.Name = "CList" + Environment.TickCount;
4204 _listCustom.ShowItemToolTips = true;
4205 _listCustom.Size = new Size(380, 260);
4206 _listCustom.UseCompatibleStateImageBehavior = false;
4207 _listCustom.View = View.Details;
4208 _listCustom.OwnerDraw = true;
4209 _listCustom.VirtualMode = true;
4210 _listCustom.Font = _fntReaded;
4211 _listCustom.BackColor = _clListBackcolor;
4213 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4214 _listCustom.AllowDrop = true;
4216 _listCustom.SmallImageList = _listViewImageList;
4218 InitColumns(_listCustom, startup);
4220 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4221 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4222 _listCustom.ColumnClick += MyList_ColumnClick;
4223 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4224 _listCustom.DragDrop += TweenMain_DragDrop;
4225 _listCustom.DragEnter += TweenMain_DragEnter;
4226 _listCustom.DragOver += TweenMain_DragOver;
4227 _listCustom.DrawItem += MyList_DrawItem;
4228 _listCustom.MouseClick += MyList_MouseClick;
4229 _listCustom.ColumnReordered += MyList_ColumnReordered;
4230 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4231 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4232 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4233 _listCustom.DrawSubItem += MyList_DrawSubItem;
4234 _listCustom.HScrolled += MyList_HScrolled;
4240 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4242 var tabInfo = _statuses.GetTabByName(TabName);
4243 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4247 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4248 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4249 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4255 var tabIndex = this._statuses.Tabs.IndexOf(TabName);
4259 var _tabPage = this.ListTab.TabPages[tabIndex];
4261 SetListProperty(); //他のタブに列幅等を反映
4264 var _listCustom = (DetailsListView)_tabPage.Tag;
4265 _tabPage.Tag = null;
4267 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4268 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4269 using (ControlTransaction.Layout(this.SplitContainer1, false))
4270 using (ControlTransaction.Layout(this.ListTab, false))
4271 using (ControlTransaction.Layout(this))
4272 using (ControlTransaction.Layout(_tabPage, false))
4274 if (this.CurrentTabName == TabName)
4276 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4277 this._beforeSelectedTab = null;
4279 this.ListTab.Controls.Remove(_tabPage);
4282 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4284 using var label = _tabPage.Controls["labelUser"];
4285 _tabPage.Controls.Remove(label);
4287 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4289 using var pnl = _tabPage.Controls["panelSearch"];
4291 pnl.Enter -= SearchControls_Enter;
4292 pnl.Leave -= SearchControls_Leave;
4293 _tabPage.Controls.Remove(pnl);
4295 foreach (Control ctrl in pnl.Controls)
4297 if (ctrl.Name == "buttonSearch")
4299 ctrl.Click -= SearchButton_Click;
4301 else if (ctrl.Name == "comboSearch")
4303 ctrl.KeyDown -= SearchComboBox_KeyDown;
4305 pnl.Controls.Remove(ctrl);
4310 _tabPage.Controls.Remove(_listCustom);
4312 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4313 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4314 _listCustom.ColumnClick -= MyList_ColumnClick;
4315 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4316 _listCustom.DragDrop -= TweenMain_DragDrop;
4317 _listCustom.DragEnter -= TweenMain_DragEnter;
4318 _listCustom.DragOver -= TweenMain_DragOver;
4319 _listCustom.DrawItem -= MyList_DrawItem;
4320 _listCustom.MouseClick -= MyList_MouseClick;
4321 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4322 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4323 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4324 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4325 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4326 _listCustom.HScrolled -= MyList_HScrolled;
4328 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4329 _listCustom.Columns.Clear();
4330 cols.ForEach(col => col.Dispose());
4333 _listCustom.ContextMenuStrip = null;
4334 _listCustom.ColumnHeaderContextMenuStrip = null;
4335 _listCustom.Font = null;
4337 _listCustom.SmallImageList = null;
4338 _listCustom.ListViewItemSorter = null;
4341 this.PurgeListViewItemCache();
4345 _listCustom.Dispose();
4346 _statuses.RemoveTab(TabName);
4348 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4350 var lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
4351 lst.VirtualListSize = tab.AllCount;
4357 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4359 this.PurgeListViewItemCache();
4360 _beforeSelectedTab = e.TabPage;
4363 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4367 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4370 var dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4371 if (!dragEnableRectangle.Contains(e.Location))
4373 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4374 tn = this.CurrentTabName;
4377 if (string.IsNullOrEmpty(tn)) return;
4379 var tabIndex = this._statuses.Tabs.IndexOf(tn);
4382 var tabPage = this.ListTab.TabPages[tabIndex];
4383 ListTab.DoDragDrop(tabPage, DragDropEffects.All);
4391 var cpos = new Point(e.X, e.Y);
4392 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4394 var rect = ListTab.GetTabRect(index);
4395 if (rect.Contains(cpos))
4397 _rclickTabName = tab.TabName;
4403 private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4405 //_curList.Refresh();
4406 SetMainWindowTitle();
4407 SetStatusLabelUrl();
4408 SetApiStatusLabel();
4409 if (ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
4410 this.Tag = ListTab.Tag;
4411 TabMenuControl(this.CurrentTabName);
4412 this.PushSelectPostChain();
4416 private void SetListProperty()
4418 if (!_isColumnChanged) return;
4420 var currentListView = this.CurrentListView;
4422 var dispOrder = new int[currentListView.Columns.Count];
4423 for (var i = 0; i < currentListView.Columns.Count; i++)
4425 for (var j = 0; j < currentListView.Columns.Count; j++)
4427 if (currentListView.Columns[j].DisplayIndex == i)
4436 foreach (TabPage tb in ListTab.TabPages)
4438 if (tb.Text == this.CurrentTabName)
4441 if (tb.Tag != null && tb.Controls.Count > 0)
4443 var lst = (DetailsListView)tb.Tag;
4444 for (var i = 0; i < lst.Columns.Count; i++)
4446 lst.Columns[dispOrder[i]].DisplayIndex = i;
4447 lst.Columns[i].Width = currentListView.Columns[i].Width;
4452 _isColumnChanged = false;
4455 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4457 if (e.KeyChar == '@')
4459 if (!SettingManager.Common.UseAtIdSupplement) return;
4461 var cnt = AtIdSupl.ItemCount;
4462 ShowSuplDialog(StatusText, AtIdSupl);
4463 if (cnt != AtIdSupl.ItemCount)
4464 this.MarkSettingAtIdModified();
4467 else if (e.KeyChar == '#')
4469 if (!SettingManager.Common.UseHashSupplement) return;
4470 ShowSuplDialog(StatusText, HashSupl);
4475 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4476 => this.ShowSuplDialog(owner, dialog, 0, "");
4478 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4479 => this.ShowSuplDialog(owner, dialog, offset, "");
4481 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4483 dialog.StartsWith = startswith;
4490 dialog.ShowDialog();
4492 this.TopMost = SettingManager.Common.AlwaysTop;
4493 var selStart = owner.SelectionStart;
4496 if (dialog.DialogResult == DialogResult.OK)
4498 if (!string.IsNullOrEmpty(dialog.inputText))
4502 fHalf = owner.Text.Substring(0, selStart - offset);
4504 if (selStart < owner.Text.Length)
4506 eHalf = owner.Text.Substring(selStart);
4508 owner.Text = fHalf + dialog.inputText + eHalf;
4509 owner.SelectionStart = selStart + dialog.inputText.Length;
4516 fHalf = owner.Text.Substring(0, selStart);
4518 if (selStart < owner.Text.Length)
4520 eHalf = owner.Text.Substring(selStart);
4522 owner.Text = fHalf + eHalf;
4525 owner.SelectionStart = selStart;
4531 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4534 if (!e.Alt && !e.Control && !e.Shift)
4536 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4538 var isSpace = false;
4539 foreach (var c in StatusText.Text)
4541 if (c == ' ' || c == ' ')
4554 StatusText.Text = "";
4555 JumpUnreadMenuItem_Click(null, null);
4559 this.StatusText_TextChanged(null, null);
4562 private void StatusText_TextChanged(object sender, EventArgs e)
4565 var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
4566 lblLen.Text = pLen.ToString();
4569 StatusText.ForeColor = Color.Red;
4573 StatusText.ForeColor = _clInputFont;
4576 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4578 if (string.IsNullOrEmpty(StatusText.Text))
4580 this.inReplyTo = null;
4585 /// メンション以外の文字列が含まれていないテキストであるか判定します
4587 internal static bool TextContainsOnlyMentions(string text)
4589 var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
4592 foreach (var mention in mentions)
4594 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
4596 if (!string.IsNullOrWhiteSpace(textPart))
4599 startIndex = mention.Indices[1];
4602 var textPartLast = text.Substring(startIndex);
4604 if (!string.IsNullOrWhiteSpace(textPartLast))
4611 /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
4613 private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
4615 var _autoPopulatedUserIds = new List<long>();
4617 var replyToPost = this.inReplyTo != null ? this._statuses[this.inReplyTo.Value.StatusId] : null;
4618 if (replyToPost != null)
4620 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
4622 statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
4623 _autoPopulatedUserIds.Add(replyToPost.UserId);
4625 foreach (var (userId, screenName) in replyToPost.ReplyToList)
4627 if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
4629 statusText = statusText.Substring(screenName.Length + 2);
4630 _autoPopulatedUserIds.Add(userId);
4636 autoPopulatedUserIds = _autoPopulatedUserIds.ToArray();
4642 /// attachment_url に指定可能な URL が含まれていれば除去
4644 private string RemoveAttachmentUrl(string statusText, out string attachmentUrl)
4646 attachmentUrl = null;
4648 // attachment_url は media_id と同時に使用できない
4649 if (this.ImageSelector.Visible && this.ImageSelector.SelectedService is TwitterPhoto)
4652 var match = Twitter.AttachmentUrlRegex.Match(statusText);
4656 attachmentUrl = match.Value;
4659 statusText = statusText.Substring(0, match.Index);
4661 // テキストと URL の間にスペースが含まれていれば除去
4662 return statusText.TrimEnd(' ');
4665 private string FormatStatusTextExtended(string statusText)
4666 => this.FormatStatusTextExtended(statusText, out _, out _);
4669 /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
4671 private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string attachmentUrl)
4673 statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
4675 statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
4677 return this.FormatStatusText(statusText);
4681 /// ツイート投稿前のフッター付与などの前処理を行います
4683 private string FormatStatusText(string statusText)
4685 statusText = statusText.Replace("\r\n", "\n");
4687 if (this.urlMultibyteSplit)
4690 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4693 if (SettingManager.Common.WideSpaceConvert)
4695 // 文中の全角スペースを半角スペース1個にする
4696 statusText = statusText.Replace(" ", " ");
4699 // DM の場合はこれ以降の処理を行わない
4700 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4704 if (SettingManager.Common.PostShiftEnter)
4706 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4710 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4711 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4713 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4716 if (statusText.Contains("RT @"))
4717 disableFooter = true;
4719 // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
4720 if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
4722 var mentionSelf = $"@{this.tw.Username} ";
4723 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
4725 if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
4726 statusText = statusText.Substring(mentionSelf.Length);
4733 var hashtag = this.HashMgr.UseHash;
4734 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4737 header = HashMgr.UseHash + " ";
4739 footer = " " + HashMgr.UseHash;
4744 if (SettingManager.Local.UseRecommendStatus)
4747 footer += this.recommendedStatusFooter;
4749 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4751 // テキストボックスに入力されている文字列を使用する
4752 footer += " " + SettingManager.Local.StatusText.Trim();
4756 statusText = header + statusText + footer;
4758 if (this.preventSmsCommand)
4760 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4761 // 参照: https://support.twitter.com/articles/14020
4763 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4764 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4766 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4767 statusText = '\u200b' + statusText;
4775 /// 投稿欄に表示する入力可能な文字数を計算します
4777 private int GetRestStatusCount(string statusText)
4779 var remainCount = this.tw.GetTextLengthRemain(statusText);
4781 var uploadService = this.GetSelectedImageService();
4782 if (uploadService != null)
4784 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4785 remainCount -= uploadService.GetReservedTextLength(1);
4791 private IMediaUploadService GetSelectedImageService()
4792 => this.ImageSelector.Visible ? this.ImageSelector.SelectedService : null;
4794 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4796 if (sender != this.CurrentListView)
4799 var listCache = this._listItemCache;
4800 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4802 // If the newly requested cache is a subset of the old cache,
4803 // no need to rebuild everything, so do nothing.
4807 // Now we need to rebuild the cache.
4808 this.CreateCache(e.StartIndex, e.EndIndex);
4811 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4813 var listCache = this._listItemCache;
4814 if (listCache?.TargetList == sender)
4816 if (listCache.TryGetValue(e.ItemIndex, out var item, out _))
4823 // A cache miss, so create a new ListViewItem and pass it back.
4824 var tabPage = (TabPage)((DetailsListView)sender).Parent;
4825 var tab = this._statuses.Tabs[tabPage.Text];
4828 e.Item = this.CreateItem(tab, tab[e.ItemIndex]);
4832 // 不正な要求に対する間に合わせの応答
4833 string[] sitem = {"", "", "", "", "", "", "", ""};
4834 e.Item = new ImageListViewItem(sitem);
4838 private void CreateCache(int startIndex, int endIndex)
4840 var tabInfo = this.CurrentTab;
4842 if (tabInfo.AllCount == 0)
4845 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4846 int FilterRange(int index)
4847 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4849 // キャッシュ要求(要求範囲±30を作成)
4850 startIndex = FilterRange(startIndex - 30);
4851 endIndex = FilterRange(endIndex + 30);
4853 var cacheLength = endIndex - startIndex + 1;
4855 var tab = this.CurrentTab;
4856 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4857 var listItems = Enumerable.Range(0, cacheLength)
4858 .Select(x => this.CreateItem(tab, posts[x]))
4861 var listCache = new ListViewItemCache
4863 TargetList = this.CurrentListView,
4864 StartIndex = startIndex,
4865 EndIndex = endIndex,
4866 Cache = Enumerable.Zip(listItems, posts, (x, y) => (x, y)).ToArray(),
4869 Interlocked.Exchange(ref this._listItemCache, listCache);
4873 /// DetailsListView のための ListViewItem のキャッシュを消去する
4875 private void PurgeListViewItemCache()
4876 => Interlocked.Exchange(ref this._listItemCache, null);
4878 private ListViewItem CreateItem(TabModel tab, PostClass Post)
4880 var mk = new StringBuilder();
4881 //if (Post.IsDeleted) mk.Append("×");
4882 //if (Post.IsMark) mk.Append("♪");
4883 //if (Post.IsProtect) mk.Append("Ю");
4884 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4885 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4886 ImageListViewItem itm;
4887 if (Post.RetweetedId == null)
4889 string[] sitem= {"",
4891 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4892 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4897 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4901 string[] sitem = {"",
4903 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4904 Post.CreatedAt.ToLocalTimeString(SettingManager.Common.DateTimeFormat),
4905 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4909 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4911 itm.StateIndex = Post.StateIndex;
4914 var read = Post.IsRead;
4915 // 未読管理していなかったら既読として扱う
4916 if (!tab.UnreadManage || !SettingManager.Common.UnreadManage)
4919 ChangeItemStyleRead(read, itm, Post, null);
4921 if (tab.TabName == this.CurrentTabName)
4922 this.ColorizeList(itm, Post);
4928 /// 全てのタブの振り分けルールを反映し直します
4930 private void ApplyPostFilters()
4932 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4934 this.PurgeListViewItemCache();
4935 this._statuses.FilterAll();
4937 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
4939 var tabPage = this.ListTab.TabPages[index];
4940 var listview = (DetailsListView)tabPage.Tag;
4941 using (ControlTransaction.Update(listview))
4943 listview.VirtualListSize = tab.AllCount;
4946 if (SettingManager.Common.TabIconDisp)
4948 if (tab.UnreadCount > 0)
4949 tabPage.ImageIndex = 0;
4951 tabPage.ImageIndex = -1;
4955 if (!SettingManager.Common.TabIconDisp)
4956 this.ListTab.Refresh();
4958 SetMainWindowTitle();
4959 SetStatusLabelUrl();
4963 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4964 => e.DrawDefault = true;
4966 private void MyList_HScrolled(object sender, EventArgs e)
4967 => ((DetailsListView)sender).Refresh();
4969 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4971 if (e.State == 0) return;
4972 e.DrawDefault = false;
4975 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4977 if (e.Item.BackColor == _clSelf)
4978 brs2 = _brsBackColorMine;
4979 else if (e.Item.BackColor == _clAtSelf)
4980 brs2 = _brsBackColorAt;
4981 else if (e.Item.BackColor == _clTarget)
4982 brs2 = _brsBackColorYou;
4983 else if (e.Item.BackColor == _clAtTarget)
4984 brs2 = _brsBackColorAtYou;
4985 else if (e.Item.BackColor == _clAtFromTarget)
4986 brs2 = _brsBackColorAtFromTarget;
4987 else if (e.Item.BackColor == _clAtTo)
4988 brs2 = _brsBackColorAtTo;
4990 brs2 = _brsBackColorNone;
4995 if (((Control)sender).Focused)
4996 brs2 = _brsHighLight;
4998 brs2 = _brsDeactiveSelection;
5000 e.Graphics.FillRectangle(brs2, e.Bounds);
5001 e.DrawFocusRectangle();
5002 this.DrawListViewItemIcon(e);
5005 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5007 if (e.ItemState == 0) return;
5009 if (e.ColumnIndex > 0)
5012 var post = (PostClass)e.Item.Tag;
5014 RectangleF rct = e.Bounds;
5015 rct.Width = e.Header.Width;
5016 var fontHeight = e.Item.Font.Height;
5019 rct.Y += fontHeight;
5020 rct.Height -= fontHeight;
5023 var drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5025 //if (heightDiff > fontHeight * 0.7)
5027 // rct.Height += fontHeight;
5028 // drawLineCount += 1;
5031 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5032 if (!_iconCol && drawLineCount <= 1)
5034 //rct.Inflate(0, heightDiff / -2);
5035 //rct.Height += fontHeight / 2;
5037 else if (heightDiff < fontHeight * 0.7)
5039 //最終行が70%以上欠けていたら、最終行は表示しない
5040 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5041 rct.Height = (fontHeight * drawLineCount) - 1;
5048 //if (!_iconCol && drawLineCount > 1)
5050 // rct.Y += fontHeight * 0.2;
5051 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5056 var color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5057 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5062 var rctB = e.Bounds;
5063 rctB.Width = e.Header.Width;
5064 rctB.Height = fontHeight;
5066 using var fnt = new Font(e.Item.Font, FontStyle.Bold);
5068 TextRenderer.DrawText(e.Graphics,
5069 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5071 Rectangle.Round(rct),
5073 TextFormatFlags.WordBreak |
5074 TextFormatFlags.EndEllipsis |
5075 TextFormatFlags.GlyphOverhangPadding |
5076 TextFormatFlags.NoPrefix);
5077 TextRenderer.DrawText(e.Graphics,
5078 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 + "]",
5082 TextFormatFlags.SingleLine |
5083 TextFormatFlags.EndEllipsis |
5084 TextFormatFlags.GlyphOverhangPadding |
5085 TextFormatFlags.NoPrefix);
5090 if (e.ColumnIndex != 2)
5091 text = e.SubItem.Text;
5093 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5095 if (drawLineCount == 1)
5097 TextRenderer.DrawText(e.Graphics,
5100 Rectangle.Round(rct),
5102 TextFormatFlags.SingleLine |
5103 TextFormatFlags.EndEllipsis |
5104 TextFormatFlags.GlyphOverhangPadding |
5105 TextFormatFlags.NoPrefix |
5106 TextFormatFlags.VerticalCenter);
5110 TextRenderer.DrawText(e.Graphics,
5113 Rectangle.Round(rct),
5115 TextFormatFlags.WordBreak |
5116 TextFormatFlags.EndEllipsis |
5117 TextFormatFlags.GlyphOverhangPadding |
5118 TextFormatFlags.NoPrefix);
5121 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5126 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5128 if (_iconSz == 0) return;
5130 var item = (ImageListViewItem)e.Item;
5132 //e.Bounds.Leftが常に0を指すから自前で計算
5133 var itemRect = item.Bounds;
5134 var col0 = e.Item.ListView.Columns[0];
5135 itemRect.Width = col0.Width;
5137 if (col0.DisplayIndex > 0)
5139 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5141 if (clm.DisplayIndex < col0.DisplayIndex)
5142 itemRect.X += clm.Width;
5146 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5147 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5148 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5151 var img = item.Image;
5154 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5155 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5157 if (iconRect.Width > 0)
5159 e.Graphics.FillRectangle(Brushes.White, iconRect);
5160 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5163 e.Graphics.DrawImage(img.Image, iconRect);
5165 catch (ArgumentException)
5167 item.RefreshImageAsync();
5173 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5174 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5176 item.GetImageAsync();
5179 if (item.StateIndex > -1)
5181 var stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5182 if (stateRect.Width > 0)
5184 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5185 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5186 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5191 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5193 base.ScaleControl(factor, specified);
5195 ScaleChildControl(this.TabImage, factor);
5197 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5198 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5200 foreach (var listview in listviews)
5202 ScaleChildControl(listview, factor);
5206 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5208 // ImageListViewItem item = (ImageListViewItem)e.Item;
5209 // if (item.StateImageIndex > -1)
5211 // ////e.Bounds.Leftが常に0を指すから自前で計算
5212 // //Rectangle itemRect = item.Bounds;
5213 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5215 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5217 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5219 // // itemRect.X += clm.Width;
5223 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5224 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5226 // if (rct.Width > 0)
5228 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5229 // //e.Graphics.FillRectangle(Brushes.White, rct);
5230 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5231 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5236 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5238 var tab = this.CurrentTab;
5240 if (tab.AllCount == 0)
5242 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5246 var selectedIndex = tab.SelectedIndex;
5251 case SEARCHTYPE.NextSearch: // 次を検索
5252 if (selectedIndex != -1)
5253 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5257 case SEARCHTYPE.PrevSearch: // 前を検索
5258 if (selectedIndex != -1)
5259 startIndex = Math.Max(selectedIndex - 1, 0);
5261 startIndex = tab.AllCount - 1;
5263 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5265 if (selectedIndex != -1)
5266 startIndex = selectedIndex;
5272 Func<string, bool> stringComparer;
5275 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5277 catch (ArgumentException)
5279 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5283 var reverse = searchType == SEARCHTYPE.PrevSearch;
5284 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5285 .DefaultIfEmpty(-1).First();
5287 if (foundIndex == -1)
5289 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5293 var listView = this.CurrentListView;
5294 this.SelectListItem(listView, foundIndex);
5295 listView.EnsureVisible(foundIndex);
5298 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5299 => this.ShowSearchDialog(); // 検索メニュー
5301 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5303 var previousSearch = this.SearchDialog.ResultOptions;
5304 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5306 this.SearchDialog.Reset();
5307 this.ShowSearchDialog();
5313 previousSearch.Query,
5314 previousSearch.CaseSensitive,
5315 previousSearch.UseRegex,
5316 SEARCHTYPE.NextSearch);
5319 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5321 var previousSearch = this.SearchDialog.ResultOptions;
5322 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5324 this.SearchDialog.Reset();
5325 this.ShowSearchDialog();
5331 previousSearch.Query,
5332 previousSearch.CaseSensitive,
5333 previousSearch.UseRegex,
5334 SEARCHTYPE.PrevSearch);
5338 /// 検索ダイアログを表示し、検索を実行します
5340 private void ShowSearchDialog()
5342 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5344 this.TopMost = SettingManager.Common.AlwaysTop;
5347 this.TopMost = SettingManager.Common.AlwaysTop;
5349 var searchOptions = this.SearchDialog.ResultOptions;
5350 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5352 if (searchOptions.NewTab)
5354 var tabName = Properties.Resources.SearchResults_TabName;
5358 tabName = this._statuses.MakeTabName(tabName);
5360 catch (TabException ex)
5362 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5365 var resultTab = new LocalSearchTabModel(tabName);
5366 this.AddNewTab(resultTab, startup: false);
5367 this._statuses.AddTab(resultTab);
5369 var targetTab = this.CurrentTab;
5371 Func<string, bool> stringComparer;
5374 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5376 catch (ArgumentException)
5378 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5382 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5383 if (foundIndices.Length == 0)
5385 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5389 var foundPosts = foundIndices.Select(x => targetTab[x]);
5390 foreach (var post in foundPosts)
5392 resultTab.AddPostQueue(post);
5395 this._statuses.DistributePosts();
5396 this.RefreshTimeline();
5398 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
5399 this.ListTab.SelectedIndex = tabIndex;
5404 searchOptions.Query,
5405 searchOptions.CaseSensitive,
5406 searchOptions.UseRegex,
5407 SEARCHTYPE.DialogSearch);
5410 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5412 this.AddNewTabForSearch(searchOptions.Query);
5416 /// <summary>発言検索に使用するメソッドを生成します</summary>
5417 /// <exception cref="ArgumentException">
5418 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5420 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5424 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5425 var regex = new Regex(query, regexOption);
5427 return x => regex.IsMatch(x);
5431 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5433 return x => x.IndexOf(query, comparisonType) != -1;
5437 private void AboutMenuItem_Click(object sender, EventArgs e)
5439 using (var about = new TweenAboutBox())
5441 about.ShowDialog(this);
5443 this.TopMost = SettingManager.Common.AlwaysTop;
5446 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5448 var bgnIdx = this._statuses.SelectedTabIndex;
5450 if (ImageSelector.Enabled)
5453 TabModel foundTab = null;
5456 DetailsListView lst = null;
5459 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Skip(bgnIdx))
5461 var unreadIndex = tab.NextUnreadIndex;
5462 if (unreadIndex != -1)
5464 ListTab.SelectedIndex = index;
5466 foundIndex = unreadIndex;
5467 lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5472 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5473 if (foundTab == null && bgnIdx > 0)
5475 foreach (var (tab, index) in this._statuses.Tabs.WithIndex().Take(bgnIdx))
5477 var unreadIndex = tab.NextUnreadIndex;
5478 if (unreadIndex != -1)
5480 ListTab.SelectedIndex = index;
5482 foundIndex = unreadIndex;
5483 lst = (DetailsListView)this.ListTab.TabPages[index].Tag;
5489 if (foundTab == null)
5491 //全部調べたが未読見つからず→先頭タブの最新発言へ
5492 ListTab.SelectedIndex = 0;
5493 var tabPage = this.ListTab.TabPages[0];
5494 var tab = this._statuses.Tabs[0];
5496 if (tab.AllCount == 0)
5499 if (_statuses.SortOrder == SortOrder.Ascending)
5500 foundIndex = tab.AllCount - 1;
5504 lst = (DetailsListView)tabPage.Tag;
5507 SelectListItem(lst, foundIndex);
5509 if (_statuses.SortMode == ComparerMode.Id)
5511 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5512 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5518 lst.EnsureVisible(foundIndex);
5523 lst.EnsureVisible(foundIndex);
5529 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5531 var tab = this.CurrentTab;
5532 var post = this.CurrentPost;
5533 if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
5534 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5537 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5538 => await this.CheckNewVersion(false);
5540 private void RunTweenUp()
5542 var pinfo = new ProcessStartInfo
5544 UseShellExecute = true,
5545 WorkingDirectory = MyCommon.settingPath,
5546 FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe"),
5547 Arguments = "\"" + Application.StartupPath + "\"",
5552 Process.Start(pinfo);
5556 MessageBox.Show("Failed to execute TweenUp3.exe.");
5560 public class VersionInfo
5562 public Version Version { get; set; }
5563 public Uri DownloadUri { get; set; }
5564 public string ReleaseNote { get; set; }
5568 /// OpenTween の最新バージョンの情報を取得します
5570 public async Task<VersionInfo> GetVersionInfoAsync()
5572 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5573 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5575 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5576 .ConfigureAwait(false);
5578 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5579 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5581 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5582 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5584 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5586 return new VersionInfo
5588 Version = Version.Parse(msgHeader[0]),
5589 DownloadUri = new Uri(msgHeader[1]),
5590 ReleaseNote = msgBody,
5594 private async Task CheckNewVersion(bool startup = false)
5596 if (ApplicationSettings.VersionInfoUrl == null)
5597 return; // 更新チェック無効化
5601 var versionInfo = await this.GetVersionInfoAsync();
5603 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5608 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5609 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5610 msgtext = MyCommon.ReplaceAppName(msgtext);
5612 MessageBox.Show(msgtext,
5613 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5614 MessageBoxButtons.OK, MessageBoxIcon.Information);
5619 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
5622 using var dialog = new UpdateDialog();
5624 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5625 MyCommon.GetReadableVersion(versionInfo.Version));
5626 dialog.DetailsText = versionInfo.ReleaseNote;
5628 if (dialog.ShowDialog(this) == DialogResult.Yes)
5630 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5632 else if (dialog.SkipButtonPressed)
5634 SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
5635 this.MarkSettingCommonModified();
5640 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5643 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5644 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5645 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5650 private void UpdateSelectedPost()
5652 //件数関連の場合、タイトル即時書き換え
5653 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5654 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5655 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5656 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5658 SetMainWindowTitle();
5660 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5661 SetStatusLabelUrl();
5663 if (SettingManager.Common.TabIconDisp)
5665 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
5667 if (tab.UnreadCount == 0)
5669 var tabPage = this.ListTab.TabPages[index];
5670 if (tabPage.ImageIndex == 0)
5671 tabPage.ImageIndex = -1;
5677 this.ListTab.Refresh();
5680 this.DispSelectedPost();
5683 public string createDetailHtml(string orgdata)
5684 => detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5686 private void DispSelectedPost()
5687 => this.DispSelectedPost(false);
5689 private PostClass displayPost = new PostClass();
5692 /// サムネイル表示に使用する CancellationToken の生成元
5694 private CancellationTokenSource thumbnailTokenSource = null;
5696 private void DispSelectedPost(bool forceupdate)
5698 var currentPost = this.CurrentPost;
5699 if (currentPost == null)
5702 var oldDisplayPost = this.displayPost;
5703 this.displayPost = currentPost;
5705 if (!forceupdate && currentPost.Equals(oldDisplayPost))
5708 var loadTasks = new List<Task>
5710 this.tweetDetailsView.ShowPostDetails(currentPost),
5713 this.SplitContainer3.Panel2Collapsed = true;
5715 if (SettingManager.Common.PreviewEnable)
5717 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5718 oldTokenSource?.Cancel();
5720 var token = this.thumbnailTokenSource.Token;
5721 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(currentPost, token));
5724 async Task delayedTasks()
5728 await Task.WhenAll(loadTasks);
5730 catch (OperationCanceledException) { }
5733 // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
5737 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5738 => await this.OpenApplicationWebsite();
5740 private async Task OpenApplicationWebsite()
5741 => await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5743 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5744 => await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5746 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5748 var tab = this.CurrentTab;
5749 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
5751 var pnl = this.CurrentTabPage.Controls["panelSearch"];
5752 if (pnl.Controls["comboSearch"].Focused ||
5753 pnl.Controls["comboLang"].Focused ||
5754 pnl.Controls["buttonSearch"].Focused) return;
5757 if (e.Control || e.Shift || e.Alt)
5758 this._anchorFlag = false;
5760 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5763 e.SuppressKeyPress = true;
5766 if (asyncTask != null)
5770 private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
5772 private void InitializeShortcuts()
5774 this.shortcutCommands = new[]
5776 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5777 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5778 .FocusedOn(FocusedControl.ListTab)
5779 .Do(() => SendKeys.Send("{DOWN}")),
5781 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5782 .FocusedOn(FocusedControl.ListTab)
5783 .Do(() => SendKeys.Send("{UP}")),
5785 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5786 .FocusedOn(FocusedControl.ListTab)
5787 .Do(() => SendKeys.Send("{PGDN}")),
5789 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5790 .FocusedOn(FocusedControl.ListTab)
5791 .Do(() => SendKeys.Send("{PGUP}")),
5793 ShortcutCommand.Create(Keys.F1)
5794 .Do(() => this.OpenApplicationWebsite()),
5796 ShortcutCommand.Create(Keys.F3)
5797 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5799 ShortcutCommand.Create(Keys.F5)
5800 .Do(() => this.DoRefresh()),
5802 ShortcutCommand.Create(Keys.F6)
5803 .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
5805 ShortcutCommand.Create(Keys.F7)
5806 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
5808 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5809 .NotFocusedOn(FocusedControl.StatusText)
5810 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5812 ShortcutCommand.Create(Keys.G)
5813 .NotFocusedOn(FocusedControl.StatusText)
5814 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5816 ShortcutCommand.Create(Keys.Right, Keys.N)
5817 .FocusedOn(FocusedControl.ListTab)
5818 .Do(() => this.GoRelPost(forward: true)),
5820 ShortcutCommand.Create(Keys.Left, Keys.P)
5821 .FocusedOn(FocusedControl.ListTab)
5822 .Do(() => this.GoRelPost(forward: false)),
5824 ShortcutCommand.Create(Keys.OemPeriod)
5825 .FocusedOn(FocusedControl.ListTab)
5826 .Do(() => this.GoAnchor()),
5828 ShortcutCommand.Create(Keys.I)
5829 .FocusedOn(FocusedControl.ListTab)
5830 .OnlyWhen(() => this.StatusText.Enabled)
5831 .Do(() => this.StatusText.Focus()),
5833 ShortcutCommand.Create(Keys.Enter)
5834 .FocusedOn(FocusedControl.ListTab)
5835 .Do(() => this.MakeReplyOrDirectStatus()),
5837 ShortcutCommand.Create(Keys.R)
5838 .FocusedOn(FocusedControl.ListTab)
5839 .Do(() => this.DoRefresh()),
5841 ShortcutCommand.Create(Keys.L)
5842 .FocusedOn(FocusedControl.ListTab)
5843 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5845 ShortcutCommand.Create(Keys.H)
5846 .FocusedOn(FocusedControl.ListTab)
5847 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5849 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5850 .FocusedOn(FocusedControl.ListTab)
5851 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5853 ShortcutCommand.Create(Keys.S)
5854 .FocusedOn(FocusedControl.ListTab)
5855 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5857 ShortcutCommand.Create(Keys.A)
5858 .FocusedOn(FocusedControl.ListTab)
5859 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5861 // ] in_reply_to参照元へ戻る
5862 ShortcutCommand.Create(Keys.Oem4)
5863 .FocusedOn(FocusedControl.ListTab)
5864 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5866 // [ in_reply_toへジャンプ
5867 ShortcutCommand.Create(Keys.Oem6)
5868 .FocusedOn(FocusedControl.ListTab)
5869 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5871 ShortcutCommand.Create(Keys.Escape)
5872 .FocusedOn(FocusedControl.ListTab)
5874 this._anchorFlag = false;
5875 var tab = this.CurrentTab;
5876 var tabtype = tab.TabType;
5877 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5879 RemoveSpecifiedTab(tab.TabName, false);
5884 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5885 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5886 .FocusedOn(FocusedControl.ListTab)
5887 .Do(() => this._anchorFlag = false, preventDefault: false),
5889 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5890 ShortcutCommand.Create(Keys.Up, Keys.Down)
5891 .FocusedOn(FocusedControl.PostBrowser)
5894 ShortcutCommand.Create(Keys.Control | Keys.R)
5895 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5897 ShortcutCommand.Create(Keys.Control | Keys.D)
5898 .Do(() => this.doStatusDelete()),
5900 ShortcutCommand.Create(Keys.Control | Keys.M)
5901 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5903 ShortcutCommand.Create(Keys.Control | Keys.S)
5904 .Do(() => this.FavoriteChange(FavAdd: true)),
5906 ShortcutCommand.Create(Keys.Control | Keys.I)
5907 .Do(() => this.doRepliedStatusOpen()),
5909 ShortcutCommand.Create(Keys.Control | Keys.Q)
5910 .Do(() => this.doQuoteOfficial()),
5912 ShortcutCommand.Create(Keys.Control | Keys.B)
5913 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5915 ShortcutCommand.Create(Keys.Control | Keys.T)
5916 .Do(() => this.HashManageMenuItem_Click(null, null)),
5918 ShortcutCommand.Create(Keys.Control | Keys.L)
5919 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5921 ShortcutCommand.Create(Keys.Control | Keys.Y)
5922 .NotFocusedOn(FocusedControl.PostBrowser)
5923 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5925 ShortcutCommand.Create(Keys.Control | Keys.F)
5926 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5928 ShortcutCommand.Create(Keys.Control | Keys.U)
5929 .Do(() => this.ShowUserTimeline()),
5931 ShortcutCommand.Create(Keys.Control | Keys.H)
5932 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5934 ShortcutCommand.Create(Keys.Control | Keys.G)
5935 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5937 ShortcutCommand.Create(Keys.Control | Keys.O)
5938 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5940 ShortcutCommand.Create(Keys.Control | Keys.E)
5941 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5943 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5944 .FocusedOn(FocusedControl.ListTab)
5945 .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
5947 ShortcutCommand.Create(Keys.Control | Keys.N)
5948 .FocusedOn(FocusedControl.ListTab)
5949 .Do(() => this.GoNextTab(forward: true)),
5951 ShortcutCommand.Create(Keys.Control | Keys.P)
5952 .FocusedOn(FocusedControl.ListTab)
5953 .Do(() => this.GoNextTab(forward: false)),
5955 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5956 .FocusedOn(FocusedControl.ListTab)
5957 .Do(() => this.CopyStot()),
5959 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5960 ShortcutCommand.Create(Keys.Control | Keys.D1)
5961 .FocusedOn(FocusedControl.ListTab)
5962 .OnlyWhen(() => this._statuses.Tabs.Count >= 1)
5963 .Do(() => this.ListTab.SelectedIndex = 0),
5965 ShortcutCommand.Create(Keys.Control | Keys.D2)
5966 .FocusedOn(FocusedControl.ListTab)
5967 .OnlyWhen(() => this._statuses.Tabs.Count >= 2)
5968 .Do(() => this.ListTab.SelectedIndex = 1),
5970 ShortcutCommand.Create(Keys.Control | Keys.D3)
5971 .FocusedOn(FocusedControl.ListTab)
5972 .OnlyWhen(() => this._statuses.Tabs.Count >= 3)
5973 .Do(() => this.ListTab.SelectedIndex = 2),
5975 ShortcutCommand.Create(Keys.Control | Keys.D4)
5976 .FocusedOn(FocusedControl.ListTab)
5977 .OnlyWhen(() => this._statuses.Tabs.Count >= 4)
5978 .Do(() => this.ListTab.SelectedIndex = 3),
5980 ShortcutCommand.Create(Keys.Control | Keys.D5)
5981 .FocusedOn(FocusedControl.ListTab)
5982 .OnlyWhen(() => this._statuses.Tabs.Count >= 5)
5983 .Do(() => this.ListTab.SelectedIndex = 4),
5985 ShortcutCommand.Create(Keys.Control | Keys.D6)
5986 .FocusedOn(FocusedControl.ListTab)
5987 .OnlyWhen(() => this._statuses.Tabs.Count >= 6)
5988 .Do(() => this.ListTab.SelectedIndex = 5),
5990 ShortcutCommand.Create(Keys.Control | Keys.D7)
5991 .FocusedOn(FocusedControl.ListTab)
5992 .OnlyWhen(() => this._statuses.Tabs.Count >= 7)
5993 .Do(() => this.ListTab.SelectedIndex = 6),
5995 ShortcutCommand.Create(Keys.Control | Keys.D8)
5996 .FocusedOn(FocusedControl.ListTab)
5997 .OnlyWhen(() => this._statuses.Tabs.Count >= 8)
5998 .Do(() => this.ListTab.SelectedIndex = 7),
6000 ShortcutCommand.Create(Keys.Control | Keys.D9)
6001 .FocusedOn(FocusedControl.ListTab)
6002 .Do(() => this.ListTab.SelectedIndex = this._statuses.Tabs.Count - 1),
6004 ShortcutCommand.Create(Keys.Control | Keys.A)
6005 .FocusedOn(FocusedControl.StatusText)
6006 .Do(() => this.StatusText.SelectAll()),
6008 ShortcutCommand.Create(Keys.Control | Keys.V)
6009 .FocusedOn(FocusedControl.StatusText)
6010 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6012 ShortcutCommand.Create(Keys.Control | Keys.Up)
6013 .FocusedOn(FocusedControl.StatusText)
6014 .Do(() => this.StatusTextHistoryBack()),
6016 ShortcutCommand.Create(Keys.Control | Keys.Down)
6017 .FocusedOn(FocusedControl.StatusText)
6018 .Do(() => this.StatusTextHistoryForward()),
6020 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6021 .FocusedOn(FocusedControl.StatusText)
6023 if (ListTab.SelectedIndex == 0)
6025 ListTab.SelectedIndex = ListTab.TabCount - 1;
6029 ListTab.SelectedIndex -= 1;
6034 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6035 .FocusedOn(FocusedControl.StatusText)
6037 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6039 ListTab.SelectedIndex = 0;
6043 ListTab.SelectedIndex += 1;
6048 ShortcutCommand.Create(Keys.Control | Keys.Y)
6049 .FocusedOn(FocusedControl.PostBrowser)
6051 var multiline = !SettingManager.Local.StatusMultiline;
6052 SettingManager.Local.StatusMultiline = multiline;
6053 MultiLineMenuItem.Checked = multiline;
6054 MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6057 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6058 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6060 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6061 .Do(() => this.DoRefreshMore()),
6063 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6064 .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
6066 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6067 .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
6069 ShortcutCommand.Create(Keys.Shift | Keys.R)
6070 .NotFocusedOn(FocusedControl.StatusText)
6071 .Do(() => this.DoRefreshMore()),
6073 ShortcutCommand.Create(Keys.Shift | Keys.H)
6074 .FocusedOn(FocusedControl.ListTab)
6075 .Do(() => this.GoTopEnd(GoTop: true)),
6077 ShortcutCommand.Create(Keys.Shift | Keys.L)
6078 .FocusedOn(FocusedControl.ListTab)
6079 .Do(() => this.GoTopEnd(GoTop: false)),
6081 ShortcutCommand.Create(Keys.Shift | Keys.M)
6082 .FocusedOn(FocusedControl.ListTab)
6083 .Do(() => this.GoMiddle()),
6085 ShortcutCommand.Create(Keys.Shift | Keys.G)
6086 .FocusedOn(FocusedControl.ListTab)
6087 .Do(() => this.GoLast()),
6089 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6090 .FocusedOn(FocusedControl.ListTab)
6091 .Do(() => this.MoveMiddle()),
6093 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6094 .FocusedOn(FocusedControl.ListTab)
6095 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6097 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6098 .FocusedOn(FocusedControl.ListTab)
6099 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6101 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6102 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6103 .FocusedOn(FocusedControl.ListTab)
6104 .Do(() => this.GoFav(forward: true)),
6106 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6107 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6108 .FocusedOn(FocusedControl.ListTab)
6109 .Do(() => this.GoFav(forward: false)),
6111 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6112 .FocusedOn(FocusedControl.ListTab)
6113 .Do(() => this.GoBackSelectPostChain()),
6115 ShortcutCommand.Create(Keys.Alt | Keys.R)
6116 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6118 ShortcutCommand.Create(Keys.Alt | Keys.P)
6119 .OnlyWhen(() => this.CurrentPost != null)
6120 .Do(() => this.doShowUserStatus(this.CurrentPost.ScreenName, ShowInputDialog: false)),
6122 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6123 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6125 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6126 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6128 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6129 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6131 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6132 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6134 // 別タブの同じ書き込みへ(ALT+←/→)
6135 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6136 .FocusedOn(FocusedControl.ListTab)
6137 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6139 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6140 .FocusedOn(FocusedControl.ListTab)
6141 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6143 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6144 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6146 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6147 .Do(() => this.CopyIdUri()),
6149 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6150 .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
6151 .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6153 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6154 .Do(() => this.FavoriteChange(FavAdd: false)),
6156 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6157 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6159 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6160 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6162 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6163 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6165 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6166 .Do(() => this.doMoveToRTHome()),
6168 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6169 .FocusedOn(FocusedControl.StatusText)
6171 var tab = this.CurrentTab;
6172 var selectedIndex = tab.SelectedIndex;
6173 if (selectedIndex != -1 && selectedIndex > 0)
6175 var listView = this.CurrentListView;
6176 var idx = selectedIndex - 1;
6177 SelectListItem(listView, idx);
6178 listView.EnsureVisible(idx);
6182 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6183 .FocusedOn(FocusedControl.StatusText)
6185 var tab = this.CurrentTab;
6186 var selectedIndex = tab.SelectedIndex;
6187 if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
6189 var listView = this.CurrentListView;
6190 var idx = selectedIndex + 1;
6191 SelectListItem(listView, idx);
6192 listView.EnsureVisible(idx);
6196 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6197 .FocusedOn(FocusedControl.StatusText)
6199 if (StatusText.SelectionStart > 0)
6201 var endidx = StatusText.SelectionStart - 1;
6203 for (var i = StatusText.SelectionStart - 1; i >= 0; i--)
6205 var c = StatusText.Text[i];
6206 if (char.IsLetterOrDigit(c) || c == '_')
6212 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6213 var cnt = AtIdSupl.ItemCount;
6214 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6215 if (AtIdSupl.ItemCount != cnt)
6216 this.MarkSettingAtIdModified();
6220 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6221 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6231 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6232 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6233 .FocusedOn(FocusedControl.ListTab)
6234 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6236 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6237 .FocusedOn(FocusedControl.ListTab)
6238 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6240 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6241 .FocusedOn(FocusedControl.ListTab)
6242 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6244 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6245 .FocusedOn(FocusedControl.ListTab)
6246 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6248 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6249 .FocusedOn(FocusedControl.ListTab)
6250 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6252 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6253 .FocusedOn(FocusedControl.ListTab)
6254 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6256 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6257 .FocusedOn(FocusedControl.ListTab)
6258 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6260 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6261 .FocusedOn(FocusedControl.ListTab)
6262 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6264 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6265 .FocusedOn(FocusedControl.ListTab)
6266 .Do(() => this.SetSortLastColumn()),
6268 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6269 .FocusedOn(FocusedControl.ListTab)
6270 .Do(() => this.FavoritesRetweetOfficial()),
6272 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6273 .FocusedOn(FocusedControl.ListTab)
6274 .Do(() => this.FavoritesRetweetUnofficial()),
6276 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6277 .FocusedOn(FocusedControl.ListTab)
6278 .Do(() => this.OpenUserAppointUrl()),
6280 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6281 .FocusedOn(FocusedControl.PostBrowser)
6282 .Do(() => this.doReTweetUnofficial()),
6284 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6285 .OnlyWhen(() => this.ExistCurrentPost)
6286 .Do(() => this.tweetDetailsView.DoTranslation()),
6288 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6289 .Do(() => this.doReTweetUnofficial()),
6291 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6292 .Do(() => this.CopyUserId()),
6294 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6295 .Do(() => this.tweetThumbnail1.ScrollUp()),
6297 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6298 .Do(() => this.tweetThumbnail1.ScrollDown()),
6300 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6301 .FocusedOn(FocusedControl.ListTab)
6302 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6303 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6307 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6309 // Task を返す非同期処理があれば asyncTask に代入する
6312 // ShortcutCommand に対応しているコマンドはここで処理される
6313 foreach (var command in this.shortcutCommands)
6315 if (command.IsMatch(keyData, focusedOn))
6317 asyncTask = command.RunCommand();
6318 return command.PreventDefault;
6325 private void GoNextTab(bool forward)
6327 var idx = this._statuses.SelectedTabIndex;
6328 var tabCount = this._statuses.Tabs.Count;
6332 if (idx > tabCount - 1) idx = 0;
6337 if (idx < 0) idx = tabCount - 1;
6339 ListTab.SelectedIndex = idx;
6342 private void CopyStot()
6344 var sb = new StringBuilder();
6345 var tab = this.CurrentTab;
6346 var IsProtected = false;
6347 var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
6348 foreach (var post in tab.SelectedPosts)
6350 if (post.IsDeleted) continue;
6353 if (post.RetweetedId != null)
6354 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6356 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6360 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6365 MessageBox.Show(Properties.Resources.CopyStotText1);
6369 var clstr = sb.ToString();
6372 Clipboard.SetDataObject(clstr, false, 5, 100);
6374 catch (Exception ex)
6376 MessageBox.Show(ex.Message);
6381 private void CopyIdUri()
6383 var tab = this.CurrentTab;
6384 if (tab == null || tab is DirectMessagesTabModel)
6387 var copyUrls = new List<string>();
6388 foreach (var post in tab.SelectedPosts)
6389 copyUrls.Add(MyCommon.GetStatusUrl(post));
6391 if (copyUrls.Count == 0)
6396 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6398 catch (ExternalException ex)
6400 MessageBox.Show(ex.Message);
6404 private void GoFav(bool forward)
6406 var tab = this.CurrentTab;
6407 if (tab.AllCount == 0)
6410 var selectedIndex = tab.SelectedIndex;
6418 if (selectedIndex == -1)
6424 fIdx = selectedIndex + 1;
6425 if (fIdx > tab.AllCount - 1)
6428 toIdx = tab.AllCount;
6433 if (selectedIndex == -1)
6435 fIdx = tab.AllCount - 1;
6439 fIdx = selectedIndex - 1;
6447 for (var idx = fIdx; idx != toIdx; idx += stp)
6451 var listView = this.CurrentListView;
6452 SelectListItem(listView, idx);
6453 listView.EnsureVisible(idx);
6459 private void GoSamePostToAnotherTab(bool left)
6461 var tab = this.CurrentTab;
6463 // Directタブは対象外(見つかるはずがない)
6464 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6467 var selectedStatusId = tab.SelectedStatusId;
6468 if (selectedStatusId == -1)
6471 int fIdx, toIdx, stp;
6476 if (ListTab.SelectedIndex == 0)
6482 fIdx = ListTab.SelectedIndex - 1;
6490 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6496 fIdx = ListTab.SelectedIndex + 1;
6498 toIdx = ListTab.TabCount;
6502 for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6504 var targetTab = this._statuses.Tabs[tabidx];
6507 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6510 var foundIndex = targetTab.IndexOf(selectedStatusId);
6511 if (foundIndex != -1)
6513 ListTab.SelectedIndex = tabidx;
6514 var listView = this.CurrentListView;
6515 SelectListItem(listView, foundIndex);
6516 listView.EnsureVisible(foundIndex);
6522 private void GoPost(bool forward)
6524 var tab = this.CurrentTab;
6525 var currentPost = this.CurrentPost;
6527 if (currentPost == null)
6530 var selectedIndex = tab.SelectedIndex;
6532 int fIdx, toIdx, stp;
6536 fIdx = selectedIndex + 1;
6537 if (fIdx > tab.AllCount - 1) return;
6538 toIdx = tab.AllCount;
6543 fIdx = selectedIndex - 1;
6544 if (fIdx < 0) return;
6550 if (currentPost.RetweetedId == null)
6552 name = currentPost.ScreenName;
6556 name = currentPost.RetweetedBy;
6558 for (var idx = fIdx; idx != toIdx; idx += stp)
6560 var post = tab[idx];
6561 if (post.RetweetedId == null)
6563 if (post.ScreenName == name)
6565 var listView = this.CurrentListView;
6566 SelectListItem(listView, idx);
6567 listView.EnsureVisible(idx);
6573 if (post.RetweetedBy == name)
6575 var listView = this.CurrentListView;
6576 SelectListItem(listView, idx);
6577 listView.EnsureVisible(idx);
6584 private void GoRelPost(bool forward)
6586 var tab = this.CurrentTab;
6587 var selectedIndex = tab.SelectedIndex;
6589 if (selectedIndex == -1)
6592 int fIdx, toIdx, stp;
6596 fIdx = selectedIndex + 1;
6597 if (fIdx > tab.AllCount - 1) return;
6598 toIdx = tab.AllCount;
6603 fIdx = selectedIndex - 1;
6604 if (fIdx < 0) return;
6611 var currentPost = this.CurrentPost;
6612 if (currentPost == null) return;
6613 _anchorPost = currentPost;
6618 if (_anchorPost == null) return;
6621 for (var idx = fIdx; idx != toIdx; idx += stp)
6623 var post = tab[idx];
6624 if (post.ScreenName == _anchorPost.ScreenName ||
6625 post.RetweetedBy == _anchorPost.ScreenName ||
6626 post.ScreenName == _anchorPost.RetweetedBy ||
6627 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6628 _anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
6629 _anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
6630 post.ReplyToList.Any(x => x.UserId == _anchorPost.UserId) ||
6631 post.ReplyToList.Any(x => x.UserId == _anchorPost.RetweetedByUserId))
6633 var listView = this.CurrentListView;
6634 SelectListItem(listView, idx);
6635 listView.EnsureVisible(idx);
6641 private void GoAnchor()
6643 if (_anchorPost == null) return;
6644 var idx = this.CurrentTab.IndexOf(_anchorPost.StatusId);
6645 if (idx == -1) return;
6647 var listView = this.CurrentListView;
6648 SelectListItem(listView, idx);
6649 listView.EnsureVisible(idx);
6652 private void GoTopEnd(bool GoTop)
6654 var listView = this.CurrentListView;
6655 if (listView.VirtualListSize == 0)
6663 _item = listView.GetItemAt(0, 25);
6671 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6673 idx = listView.VirtualListSize - 1;
6677 SelectListItem(listView, idx);
6680 private void GoMiddle()
6682 var listView = this.CurrentListView;
6683 if (listView.VirtualListSize == 0)
6691 _item = listView.GetItemAt(0, 0);
6701 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6704 idx2 = listView.VirtualListSize - 1;
6710 idx3 = (idx1 + idx2) / 2;
6712 SelectListItem(listView, idx3);
6715 private void GoLast()
6717 var listView = this.CurrentListView;
6718 if (listView.VirtualListSize == 0) return;
6720 if (_statuses.SortOrder == SortOrder.Ascending)
6722 SelectListItem(listView, listView.VirtualListSize - 1);
6723 listView.EnsureVisible(listView.VirtualListSize - 1);
6727 SelectListItem(listView, 0);
6728 listView.EnsureVisible(0);
6732 private void MoveTop()
6734 var listView = this.CurrentListView;
6735 if (listView.SelectedIndices.Count == 0) return;
6736 var idx = listView.SelectedIndices[0];
6737 if (_statuses.SortOrder == SortOrder.Ascending)
6739 listView.EnsureVisible(listView.VirtualListSize - 1);
6743 listView.EnsureVisible(0);
6745 listView.EnsureVisible(idx);
6748 private async Task GoInReplyToPostTree()
6750 var curTabClass = this.CurrentTab;
6751 var currentPost = this.CurrentPost;
6753 if (currentPost == null)
6756 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
6760 var post = await tw.GetStatusApi(false, currentPost.StatusId);
6762 currentPost.InReplyToStatusId = post.InReplyToStatusId;
6763 currentPost.InReplyToUser = post.InReplyToUser;
6764 currentPost.IsReply = post.IsReply;
6765 this.PurgeListViewItemCache();
6767 var index = curTabClass.SelectedIndex;
6768 this.CurrentListView.RedrawItems(index, index, false);
6770 catch (WebApiException ex)
6772 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6776 if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
6778 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != currentPost.StatusId))
6780 replyChains = new Stack<ReplyChain>();
6782 replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId.Value, curTabClass));
6785 string inReplyToTabName;
6786 var inReplyToId = currentPost.InReplyToStatusId.Value;
6787 var inReplyToUser = currentPost.InReplyToUser;
6789 var inReplyToPosts = from tab in _statuses.Tabs
6790 orderby tab != curTabClass
6791 from post in tab.Posts.Values
6792 where post.StatusId == inReplyToId
6793 let index = tab.IndexOf(post.StatusId)
6795 select new {Tab = tab, Index = index};
6797 var inReplyPost = inReplyToPosts.FirstOrDefault();
6798 if (inReplyPost == null)
6802 await Task.Run(async () =>
6804 var post = await tw.GetStatusApi(false, currentPost.InReplyToStatusId.Value)
6805 .ConfigureAwait(false);
6808 _statuses.AddPost(post);
6809 _statuses.DistributePosts();
6812 catch (WebApiException ex)
6814 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6815 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6819 this.RefreshTimeline();
6821 inReplyPost = inReplyToPosts.FirstOrDefault();
6822 if (inReplyPost == null)
6824 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6828 inReplyToTabName = inReplyPost.Tab.TabName;
6829 inReplyToIndex = inReplyPost.Index;
6831 var tabIndex = this._statuses.Tabs.IndexOf(inReplyToTabName);
6832 var tabPage = this.ListTab.TabPages[tabIndex];
6833 var listView = (DetailsListView)tabPage.Tag;
6835 if (this.CurrentTabName != inReplyToTabName)
6837 this.ListTab.SelectedIndex = tabIndex;
6840 this.SelectListItem(listView, inReplyToIndex);
6841 listView.EnsureVisible(inReplyToIndex);
6844 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6846 var curTabClass = this.CurrentTab;
6847 var currentPost = this.CurrentPost;
6849 if (currentPost == null)
6854 if (currentPost.InReplyToStatusId != null)
6856 var posts = from t in _statuses.Tabs
6858 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
6859 let indexOf = t.IndexOf(p.Value.StatusId)
6861 orderby isForward ? indexOf : indexOf * -1
6862 orderby t != curTabClass
6863 select new {Tab = t, Post = p.Value, Index = indexOf};
6866 var postList = posts.ToList();
6867 for (var i = postList.Count - 1; i >= 0; i--)
6870 if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
6872 postList.RemoveAt(index);
6875 var currentIndex = this.CurrentTab.SelectedIndex;
6876 var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
6877 if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
6878 if (post == null) post = postList.First();
6879 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6880 this.ListTab.SelectedIndex = tabIndex;
6881 var listView = this.CurrentListView;
6882 SelectListItem(listView, post.Index);
6883 listView.EnsureVisible(post.Index);
6885 catch (InvalidOperationException)
6893 if (replyChains == null || replyChains.Count < 1)
6895 var posts = from t in _statuses.Tabs
6897 where p.Value.InReplyToStatusId == currentPost.StatusId
6898 let indexOf = t.IndexOf(p.Value.StatusId)
6901 orderby t != curTabClass
6902 select new {Tab = t, Index = indexOf};
6905 var post = posts.First();
6906 var tabIndex = this._statuses.Tabs.IndexOf(post.Tab);
6907 this.ListTab.SelectedIndex = tabIndex;
6908 var listView = this.CurrentListView;
6909 SelectListItem(listView, post.Index);
6910 listView.EnsureVisible(post.Index);
6912 catch (InvalidOperationException)
6919 var chainHead = replyChains.Pop();
6920 if (chainHead.InReplyToId == currentPost.StatusId)
6922 var tab = chainHead.OriginalTab;
6923 if (!this._statuses.Tabs.Contains(tab))
6929 var idx = tab.IndexOf(chainHead.OriginalId);
6936 var tabIndex = this._statuses.Tabs.IndexOf(tab);
6939 this.ListTab.SelectedIndex = tabIndex;
6945 var listView = this.CurrentListView;
6946 SelectListItem(listView, idx);
6947 listView.EnsureVisible(idx);
6954 this.GoBackInReplyToPostTree(parallel);
6960 private void GoBackSelectPostChain()
6962 if (this.selectPostChains.Count > 1)
6965 TabModel foundTab = null;
6971 this.selectPostChains.Pop();
6972 var (tab, post) = this.selectPostChains.Peek();
6974 if (!this._statuses.Tabs.Contains(tab))
6975 continue; // 該当タブが存在しないので無視
6979 idx = tab.IndexOf(post.StatusId);
6980 if (idx == -1) continue; //該当ポストが存在しないので無視
6985 this.selectPostChains.Pop();
6987 catch (InvalidOperationException)
6993 while (this.selectPostChains.Count > 1);
6995 if (foundTab == null)
6998 //履歴が残り1つであればクリアしておく
6999 if (this.selectPostChains.Count == 1)
7000 this.selectPostChains.Clear();
7004 var tabIndex = this._statuses.Tabs.IndexOf(foundTab);
7005 var tabPage = this.ListTab.TabPages[tabIndex];
7006 var lst = (DetailsListView)tabPage.Tag;
7007 this.ListTab.SelectedIndex = tabIndex;
7011 SelectListItem(lst, idx);
7012 lst.EnsureVisible(idx);
7018 private void PushSelectPostChain()
7020 var currentTab = this.CurrentTab;
7021 var currentPost = this.CurrentPost;
7023 var count = this.selectPostChains.Count;
7026 var (tab, post) = this.selectPostChains.Peek();
7027 if (tab == currentTab)
7029 if (post == currentPost) return; //最新の履歴と同一
7030 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7033 if (count >= 2500) TrimPostChain();
7034 this.selectPostChains.Push((currentTab, currentPost));
7037 private void TrimPostChain()
7039 if (this.selectPostChains.Count <= 2000) return;
7040 var p = new Stack<(TabModel, PostClass)>(2000);
7041 for (var i = 0; i < 2000; i++)
7043 p.Push(this.selectPostChains.Pop());
7045 this.selectPostChains.Clear();
7046 for (var i = 0; i < 2000; i++)
7048 this.selectPostChains.Push(p.Pop());
7052 private bool GoStatus(long statusId)
7054 if (statusId == 0) return false;
7056 var tab = this._statuses.Tabs
7057 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
7058 .Where(x => x.Contains(statusId))
7064 var index = tab.IndexOf(statusId);
7066 var tabIndex = this._statuses.Tabs.IndexOf(tab);
7067 this.ListTab.SelectedIndex = tabIndex;
7069 var listView = this.CurrentListView;
7070 this.SelectListItem(listView, index);
7071 listView.EnsureVisible(index);
7076 private bool GoDirectMessage(long statusId)
7078 if (statusId == 0) return false;
7080 var tab = this._statuses.GetTabByType<DirectMessagesTabModel>();
7081 var index = tab.IndexOf(statusId);
7086 var tabIndex = this._statuses.Tabs.IndexOf(tab);
7087 this.ListTab.SelectedIndex = tabIndex;
7089 var listView = this.CurrentListView;
7090 this.SelectListItem(listView, index);
7091 listView.EnsureVisible(index);
7096 private void MyList_MouseClick(object sender, MouseEventArgs e)
7097 => this._anchorFlag = false;
7099 private void StatusText_Enter(object sender, EventArgs e)
7101 // フォーカスの戻り先を StatusText に設定
7102 this.Tag = StatusText;
7103 StatusText.BackColor = _clInputBackcolor;
7106 public Color InputBackColor
7108 get => _clInputBackcolor;
7109 set => _clInputBackcolor = value;
7112 private void StatusText_Leave(object sender, EventArgs e)
7114 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7115 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7116 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7119 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7121 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7124 e.SuppressKeyPress = true;
7127 this.StatusText_TextChanged(null, null);
7129 if (asyncTask != null)
7133 private void SaveConfigsAll(bool ifModified)
7137 SaveConfigsCommon();
7144 if (ModifySettingCommon) SaveConfigsCommon();
7145 if (ModifySettingLocal) SaveConfigsLocal();
7146 if (ModifySettingAtId) SaveConfigsAtId();
7150 private void SaveConfigsAtId()
7152 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7154 ModifySettingAtId = false;
7155 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7156 SettingManager.SaveAtIdList();
7159 private void SaveConfigsCommon()
7161 if (_ignoreConfigSave) return;
7163 ModifySettingCommon = false;
7166 SettingManager.Common.UserName = tw.Username;
7167 SettingManager.Common.UserId = tw.UserId;
7168 SettingManager.Common.Token = tw.AccessToken;
7169 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7170 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7171 switch (_statuses.SortMode)
7173 case ComparerMode.Nickname: //ニックネーム
7174 SettingManager.Common.SortColumn = 1;
7176 case ComparerMode.Data: //本文
7177 SettingManager.Common.SortColumn = 2;
7179 case ComparerMode.Id: //時刻=発言Id
7180 SettingManager.Common.SortColumn = 3;
7182 case ComparerMode.Name: //名前
7183 SettingManager.Common.SortColumn = 4;
7185 case ComparerMode.Source: //Source
7186 SettingManager.Common.SortColumn = 7;
7190 SettingManager.Common.HashTags = HashMgr.HashHistories;
7191 if (HashMgr.IsPermanent)
7193 SettingManager.Common.HashSelected = HashMgr.UseHash;
7197 SettingManager.Common.HashSelected = "";
7199 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7200 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7201 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7202 SettingManager.Common.TrackWord = tw.TrackWord;
7203 SettingManager.Common.AllAtReply = tw.AllAtReply;
7204 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7205 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7207 SettingManager.SaveCommon();
7211 private void SaveConfigsLocal()
7213 if (_ignoreConfigSave) return;
7216 ModifySettingLocal = false;
7217 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7218 SettingManager.Local.FormSize = _mySize;
7219 SettingManager.Local.FormLocation = _myLoc;
7220 SettingManager.Local.SplitterDistance = _mySpDis;
7221 SettingManager.Local.PreviewDistance = _mySpDis3;
7222 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7223 SettingManager.Local.StatusTextHeight = _mySpDis2;
7225 SettingManager.Local.FontUnread = _fntUnread;
7226 SettingManager.Local.ColorUnread = _clUnread;
7227 SettingManager.Local.FontRead = _fntReaded;
7228 SettingManager.Local.ColorRead = _clReaded;
7229 SettingManager.Local.FontDetail = _fntDetail;
7230 SettingManager.Local.ColorDetail = _clDetail;
7231 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7232 SettingManager.Local.ColorDetailLink = _clDetailLink;
7233 SettingManager.Local.ColorFav = _clFav;
7234 SettingManager.Local.ColorOWL = _clOWL;
7235 SettingManager.Local.ColorRetweet = _clRetweet;
7236 SettingManager.Local.ColorSelf = _clSelf;
7237 SettingManager.Local.ColorAtSelf = _clAtSelf;
7238 SettingManager.Local.ColorTarget = _clTarget;
7239 SettingManager.Local.ColorAtTarget = _clAtTarget;
7240 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7241 SettingManager.Local.ColorAtTo = _clAtTo;
7242 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7243 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7244 SettingManager.Local.ColorInputFont = _clInputFont;
7245 SettingManager.Local.FontInputFont = _fntInputFont;
7247 if (_ignoreConfigSave) return;
7248 SettingManager.SaveLocal();
7252 private void SaveConfigsTabs()
7254 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7256 var tabs = this._statuses.Tabs.Append(this._statuses.MuteTab);
7258 foreach (var tab in tabs)
7260 if (!tab.IsPermanentTabType)
7263 var tabSetting = new SettingTabs.SettingTabItem
7265 TabName = tab.TabName,
7266 TabType = tab.TabType,
7267 UnreadManage = tab.UnreadManage,
7268 Protected = tab.Protected,
7269 Notify = tab.Notify,
7270 SoundFile = tab.SoundFile,
7275 case FilterTabModel filterTab:
7276 tabSetting.FilterArray = filterTab.FilterArray;
7278 case UserTimelineTabModel userTab:
7279 tabSetting.User = userTab.ScreenName;
7281 case PublicSearchTabModel searchTab:
7282 tabSetting.SearchWords = searchTab.SearchWords;
7283 tabSetting.SearchLang = searchTab.SearchLang;
7285 case ListTimelineTabModel listTab:
7286 tabSetting.ListInfo = listTab.ListInfo;
7290 tabSettingList.Add(tabSetting);
7293 SettingManager.Tabs.Tabs = tabSettingList;
7294 SettingManager.SaveTabs();
7297 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7299 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7300 if (ret != DialogResult.OK)
7303 var match = Twitter.StatusUrlRegex.Match(inputText);
7306 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7307 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7313 var statusId = long.Parse(match.Groups["StatusId"].Value);
7314 await this.OpenRelatedTab(statusId);
7316 catch (TabException ex)
7318 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7322 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7324 var tab = this.CurrentTab;
7326 var rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7327 Properties.Resources.SaveLogMenuItem_ClickText2,
7328 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7329 if (rslt == DialogResult.Cancel) return;
7331 SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
7332 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7333 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7334 SaveFileDialog1.FilterIndex = 0;
7335 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7336 SaveFileDialog1.RestoreDirectory = true;
7338 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7340 if (!SaveFileDialog1.ValidateNames) return;
7341 using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
7342 if (rslt == DialogResult.Yes)
7345 for (var idx = 0; idx < tab.AllCount; idx++)
7347 var post = tab[idx];
7350 protect = "Protect";
7351 sw.WriteLine(post.Nickname + "\t" +
7352 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7353 post.CreatedAt.ToLocalTimeString() + "\t" +
7354 post.ScreenName + "\t" +
7355 post.StatusId + "\t" +
7356 post.ImageUrl + "\t" +
7357 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7363 foreach (var post in this.CurrentTab.SelectedPosts)
7367 protect = "Protect";
7368 sw.WriteLine(post.Nickname + "\t" +
7369 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7370 post.CreatedAt.ToLocalTimeString() + "\t" +
7371 post.ScreenName + "\t" +
7372 post.StatusId + "\t" +
7373 post.ImageUrl + "\t" +
7374 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7379 this.TopMost = SettingManager.Common.AlwaysTop;
7382 public bool TabRename(string origTabName, out string newTabName)
7386 using (var inputName = new InputTabName())
7388 inputName.TabName = origTabName;
7389 inputName.ShowDialog();
7390 if (inputName.DialogResult == DialogResult.Cancel) return false;
7391 newTabName = inputName.TabName;
7393 this.TopMost = SettingManager.Common.AlwaysTop;
7394 if (!string.IsNullOrEmpty(newTabName))
7397 if (this._statuses.ContainsTab(newTabName))
7399 var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7400 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7404 var tabIndex = this._statuses.Tabs.IndexOf(origTabName);
7405 var tabPage = this.ListTab.TabPages[tabIndex];
7408 if (tabPage != null)
7409 tabPage.Text = newTabName;
7411 _statuses.RenameTab(origTabName, newTabName);
7413 SaveConfigsCommon();
7415 _rclickTabName = newTabName;
7424 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7426 if (e.Button == MouseButtons.Middle)
7428 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7430 if (this.ListTab.GetTabRect(index).Contains(e.Location))
7432 this.RemoveSpecifiedTab(tab.TabName, true);
7433 this.SaveConfigsTabs();
7440 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7441 => this.TabRename(this.CurrentTabName, out _);
7443 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7445 if (SettingManager.Common.TabMouseLock) return;
7446 if (e.Button == MouseButtons.Left)
7448 foreach (var i in Enumerable.Range(0, this._statuses.Tabs.Count))
7450 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7453 _tabMouseDownPoint = e.Location;
7464 private void ListTab_DragEnter(object sender, DragEventArgs e)
7466 if (e.Data.GetDataPresent(typeof(TabPage)))
7467 e.Effect = DragDropEffects.Move;
7469 e.Effect = DragDropEffects.None;
7472 private void ListTab_DragDrop(object sender, DragEventArgs e)
7474 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7479 var cpos = new Point(e.X, e.Y);
7480 var spos = ListTab.PointToClient(cpos);
7481 foreach (var (tab, index) in this._statuses.Tabs.WithIndex())
7483 var rect = ListTab.GetTabRect(index);
7484 if (rect.Contains(spos))
7487 if (spos.X <= (rect.Left + rect.Right) / 2)
7496 //タブのないところにドロップ->最後尾へ移動
7497 if (string.IsNullOrEmpty(tn))
7499 var lastTab = this._statuses.Tabs.Last();
7500 tn = lastTab.TabName;
7504 var tp = (TabPage)e.Data.GetData(typeof(TabPage));
7505 if (tp.Text == tn) return;
7507 ReOrderTab(tp.Text, tn, bef);
7510 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7512 var baseIndex = this.GetTabPageIndex(baseTabText);
7513 if (baseIndex == -1)
7516 var targetIndex = this.GetTabPageIndex(targetTabText);
7517 if (targetIndex == -1)
7520 using (ControlTransaction.Layout(this.ListTab))
7522 var tab = this._statuses.Tabs[targetIndex];
7523 var tabPage = this.ListTab.TabPages[targetIndex];
7525 this.ListTab.TabPages.Remove(tabPage);
7527 if (targetIndex < baseIndex)
7530 if (!isBeforeBaseTab)
7533 this._statuses.MoveTab(baseIndex, tab);
7535 ListTab.TabPages.Insert(baseIndex, tabPage);
7541 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7543 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7544 //isReply:true=@,false=DM
7545 if (!StatusText.Enabled) return;
7546 if (!this.ExistCurrentPost) return;
7548 var tab = this.CurrentTab;
7549 var selectedPosts = tab.SelectedPosts;
7551 // 複数あてリプライはReplyではなく通常ポスト
7552 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7553 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7554 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7556 if (selectedPosts.Length > 0)
7559 if (selectedPosts.Length == 1 && !isAll && this.ExistCurrentPost)
7561 var post = selectedPosts.Single();
7564 if ((tab.TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7567 this.inReplyTo = null;
7568 StatusText.Text = "D " + post.ScreenName + " " + StatusText.Text;
7569 StatusText.SelectionStart = StatusText.Text.Length;
7573 if (string.IsNullOrEmpty(StatusText.Text))
7576 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7577 var inReplyToScreenName = post.ScreenName;
7578 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7580 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7581 StatusText.Text = "@" + post.ScreenName + " ";
7589 //1件選んでEnter or DoubleClick
7590 if (StatusText.Text.Contains("@" + post.ScreenName + " "))
7592 if (this.inReplyTo?.ScreenName == post.ScreenName)
7595 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7596 var inReplyToScreenName = post.ScreenName;
7597 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7601 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7604 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7607 this.inReplyTo = null;
7608 StatusText.Text = StatusText.Text.Insert(2, "@" + post.ScreenName + " ");
7613 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7614 var inReplyToScreenName = post.ScreenName;
7615 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7616 StatusText.Text = "@" + post.ScreenName + " " + StatusText.Text;
7623 this.inReplyTo = null;
7624 StatusText.Text = ". @" + post.ScreenName + " " + StatusText.Text;
7629 //1件選んでCtrl-Rの場合(返信先操作せず)
7630 var sidx = StatusText.SelectionStart;
7631 var id = "@" + post.ScreenName + " ";
7634 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7639 StatusText.Text = StatusText.Text.Insert(sidx, id);
7641 //if (StatusText.Text.StartsWith("@"))
7644 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7645 // sidx += 5 + _curPost.ScreenName.Length;
7650 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7651 // sidx += 3 + _curPost.ScreenName.Length;
7653 StatusText.SelectionStart = sidx;
7656 //_reply_to_name = null;
7664 if (!isAuto && !isReply) return;
7666 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7670 //Enter or DoubleClick
7672 var sTxt = StatusText.Text;
7673 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7676 this.inReplyTo = null;
7678 foreach (var post in selectedPosts)
7680 if (!sTxt.Contains("@" + post.ScreenName + " "))
7682 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7683 //sTxt = "@" + post.ScreenName + " " + sTxt;
7686 StatusText.Text = sTxt;
7692 if (selectedPosts.Length > 1)
7697 var sidx = StatusText.SelectionStart;
7698 foreach (var post in selectedPosts)
7700 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7702 ids += "@" + post.ScreenName + " ";
7706 foreach (var (_, screenName) in post.ReplyToList)
7708 if (!ids.Contains("@" + screenName + " ") &&
7709 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7711 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7713 ids += "@" + m.Result("${id}") + " ";
7715 ids += "@" + screenName + " ";
7720 if (ids.Length == 0) return;
7721 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7723 this.inReplyTo = null;
7724 StatusText.Text = ". " + StatusText.Text;
7729 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7734 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7736 //if (StatusText.Text.StartsWith("@"))
7738 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7739 // sidx += 2 + ids.Length;
7743 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7744 // sidx += 1 + ids.Length;
7746 StatusText.SelectionStart = sidx;
7752 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7755 var sidx = StatusText.SelectionStart;
7756 var post = selectedPosts.Single();
7757 if (!ids.Contains("@" + post.ScreenName + " ") && post.UserId != tw.UserId)
7759 ids += "@" + post.ScreenName + " ";
7761 foreach (var (_, screenName) in post.ReplyToList)
7763 if (!ids.Contains("@" + screenName + " ") &&
7764 !screenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7766 var m = Regex.Match(post.TextFromApi, "[@@](?<id>" + screenName + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7768 ids += "@" + m.Result("${id}") + " ";
7770 ids += "@" + screenName + " ";
7773 if (!string.IsNullOrEmpty(post.RetweetedBy))
7775 if (!ids.Contains("@" + post.RetweetedBy + " ") && post.RetweetedByUserId != tw.UserId)
7777 ids += "@" + post.RetweetedBy + " ";
7780 if (ids.Length == 0) return;
7781 if (string.IsNullOrEmpty(StatusText.Text))
7784 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
7785 var inReplyToScreenName = post.ScreenName;
7786 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
7788 StatusText.Text = ids;
7789 StatusText.SelectionStart = ids.Length;
7796 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7801 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7803 StatusText.SelectionStart = sidx;
7809 StatusText.SelectionStart = StatusText.Text.Length;
7814 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7815 => this._tabDrag = false;
7817 private int iconCnt = 0;
7818 private int blinkCnt = 0;
7819 private bool blink = false;
7821 private void RefreshTasktrayIcon()
7823 void EnableTasktrayAnimation()
7824 => this.TimerRefreshIcon.Enabled = true;
7826 void DisableTasktrayAnimation()
7827 => this.TimerRefreshIcon.Enabled = false;
7829 var busyTasks = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7833 if (iconCnt >= this.NIconRefresh.Length)
7836 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7837 _myStatusError = false;
7838 EnableTasktrayAnimation();
7842 var replyIconType = SettingManager.Common.ReplyIconState;
7844 if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
7846 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
7847 if (replyTab != null && replyTab.UnreadCount > 0)
7851 if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
7860 NotifyIcon1.Icon = blink ? ReplyIconBlink : ReplyIcon;
7861 EnableTasktrayAnimation();
7865 DisableTasktrayAnimation();
7871 // 優先度:リプライ→エラー→オフライン→アイドル
7872 // エラーは更新アイコンでクリアされる
7873 if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
7874 NotifyIcon1.Icon = ReplyIcon;
7875 else if (_myStatusError)
7876 NotifyIcon1.Icon = NIconAtRed;
7877 else if (_myStatusOnline)
7878 NotifyIcon1.Icon = NIconAt;
7880 NotifyIcon1.Icon = NIconAtSmoke;
7883 private void TimerRefreshIcon_Tick(object sender, EventArgs e)
7884 => this.RefreshTasktrayIcon(); // 200ms
7886 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7888 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7889 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7890 _rclickTabName = this.CurrentTabName;
7892 if (_statuses == null) return;
7893 if (_statuses.Tabs == null) return;
7895 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7898 NotifyDispMenuItem.Checked = tb.Notify;
7899 this.NotifyTbMenuItem.Checked = tb.Notify;
7901 soundfileListup = true;
7902 SoundFileComboBox.Items.Clear();
7903 this.SoundFileTbComboBox.Items.Clear();
7904 SoundFileComboBox.Items.Add("");
7905 this.SoundFileTbComboBox.Items.Add("");
7906 var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7907 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7909 oDir = oDir.GetDirectories("Sounds")[0];
7911 foreach (var oFile in oDir.GetFiles("*.wav"))
7913 SoundFileComboBox.Items.Add(oFile.Name);
7914 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7916 var idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7917 if (idx == -1) idx = 0;
7918 SoundFileComboBox.SelectedIndex = idx;
7919 this.SoundFileTbComboBox.SelectedIndex = idx;
7920 soundfileListup = false;
7921 UreadManageMenuItem.Checked = tb.UnreadManage;
7922 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7924 TabMenuControl(_rclickTabName);
7927 private void TabMenuControl(string tabName)
7929 var tabInfo = _statuses.GetTabByName(tabName);
7931 this.FilterEditMenuItem.Enabled = true;
7932 this.EditRuleTbMenuItem.Enabled = true;
7934 if (tabInfo.IsDefaultTabType)
7936 this.ProtectTabMenuItem.Enabled = false;
7937 this.ProtectTbMenuItem.Enabled = false;
7941 this.ProtectTabMenuItem.Enabled = true;
7942 this.ProtectTbMenuItem.Enabled = true;
7945 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
7947 this.ProtectTabMenuItem.Checked = true;
7948 this.ProtectTbMenuItem.Checked = true;
7949 this.DeleteTabMenuItem.Enabled = false;
7950 this.DeleteTbMenuItem.Enabled = false;
7954 this.ProtectTabMenuItem.Checked = false;
7955 this.ProtectTbMenuItem.Checked = false;
7956 this.DeleteTabMenuItem.Enabled = true;
7957 this.DeleteTbMenuItem.Enabled = true;
7961 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
7963 var checkState = ((ToolStripMenuItem)sender).Checked;
7966 this.ProtectTbMenuItem.Checked = checkState;
7967 this.ProtectTabMenuItem.Checked = checkState;
7970 this.DeleteTabMenuItem.Enabled = !checkState;
7971 this.DeleteTbMenuItem.Enabled = !checkState;
7973 if (string.IsNullOrEmpty(_rclickTabName)) return;
7974 _statuses.Tabs[_rclickTabName].Protected = checkState;
7979 private void UreadManageMenuItem_Click(object sender, EventArgs e)
7981 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7982 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
7984 if (string.IsNullOrEmpty(_rclickTabName)) return;
7985 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
7990 public void ChangeTabUnreadManage(string tabName, bool isManage)
7992 var idx = this.GetTabPageIndex(tabName);
7996 var tab = this._statuses.Tabs[tabName];
7997 tab.UnreadManage = isManage;
7999 if (SettingManager.Common.TabIconDisp)
8001 var tabPage = this.ListTab.TabPages[idx];
8002 if (tab.UnreadCount > 0)
8003 tabPage.ImageIndex = 0;
8005 tabPage.ImageIndex = -1;
8008 if (this.CurrentTabName == tabName)
8010 this.PurgeListViewItemCache();
8011 this.CurrentListView.Refresh();
8014 SetMainWindowTitle();
8015 SetStatusLabelUrl();
8016 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8019 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8021 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8022 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8024 if (string.IsNullOrEmpty(_rclickTabName)) return;
8026 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8031 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8033 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8035 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8040 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8042 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem)
8043 _rclickTabName = this.CurrentTabName;
8045 RemoveSpecifiedTab(_rclickTabName, true);
8049 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8051 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8053 using (var fltDialog = new FilterDialog())
8055 fltDialog.Owner = this;
8056 fltDialog.SetCurrent(_rclickTabName);
8057 fltDialog.ShowDialog(this);
8059 this.TopMost = SettingManager.Common.AlwaysTop;
8061 this.ApplyPostFilters();
8065 private async void AddTabMenuItem_Click(object sender, EventArgs e)
8067 string tabName = null;
8068 MyCommon.TabUsageType tabUsage;
8069 using (var inputName = new InputTabName())
8071 inputName.TabName = _statuses.MakeTabName("MyTab");
8072 inputName.IsShowUsage = true;
8073 inputName.ShowDialog();
8074 if (inputName.DialogResult == DialogResult.Cancel) return;
8075 tabName = inputName.TabName;
8076 tabUsage = inputName.Usage;
8078 this.TopMost = SettingManager.Common.AlwaysTop;
8079 if (!string.IsNullOrEmpty(tabName))
8082 ListElement list = null;
8083 if (tabUsage == MyCommon.TabUsageType.Lists)
8085 using var listAvail = new ListAvailable();
8086 if (listAvail.ShowDialog(this) == DialogResult.Cancel)
8088 if (listAvail.SelectedList == null)
8090 list = listAvail.SelectedList;
8096 case MyCommon.TabUsageType.UserDefined:
8097 tab = new FilterTabModel(tabName);
8099 case MyCommon.TabUsageType.PublicSearch:
8100 tab = new PublicSearchTabModel(tabName);
8102 case MyCommon.TabUsageType.Lists:
8103 tab = new ListTimelineTabModel(tabName, list);
8109 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8111 var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8112 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8119 var tabIndex = this._statuses.Tabs.Count - 1;
8121 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8123 ListTab.SelectedIndex = tabIndex;
8124 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8126 if (tabUsage == MyCommon.TabUsageType.Lists)
8128 ListTab.SelectedIndex = tabIndex;
8129 await this.RefreshTabAsync(this.CurrentTab);
8135 private void TabMenuItem_Click(object sender, EventArgs e)
8137 using (var fltDialog = new FilterDialog())
8139 fltDialog.Owner = this;
8142 foreach (var post in this.CurrentTab.SelectedPosts)
8145 if (!SelectTab(out var tabName)) return;
8147 fltDialog.SetCurrent(tabName);
8149 if (post.RetweetedId == null)
8151 fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
8155 fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
8157 fltDialog.ShowDialog(this);
8158 this.TopMost = SettingManager.Common.AlwaysTop;
8162 this.ApplyPostFilters();
8166 protected override bool ProcessDialogKey(Keys keyData)
8168 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8169 if ((keyData & Keys.KeyCode) == Keys.Enter)
8171 if (StatusText.Focused)
8173 var _NewLine = false;
8176 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8178 if (StatusText.Multiline)
8180 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8182 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8186 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8190 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8192 if (StatusText.Multiline)
8194 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8196 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8200 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8206 if (StatusText.Multiline)
8208 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8210 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8211 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8215 if (((keyData & Keys.Shift) == Keys.Shift) ||
8216 (((keyData & Keys.Control) != Keys.Control) &&
8217 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8223 var pos1 = StatusText.SelectionStart;
8224 if (StatusText.SelectionLength > 0)
8226 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8228 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8229 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8234 PostButton_Click(null, null);
8240 var tab = this.CurrentTab;
8241 if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
8243 var tabPage = this.CurrentTabPage;
8244 if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8245 tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
8247 this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], null);
8254 return base.ProcessDialogKey(keyData);
8257 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8258 => this.MakeReplyOrDirectStatus(false, true, true);
8260 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8262 var tab = this.CurrentTab;
8263 var selectedPosts = tab.SelectedPosts;
8266 if (selectedPosts.Length == 0)
8269 var screenNameArray = selectedPosts
8270 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8273 this.AddFilterRuleByScreenName(screenNameArray);
8275 if (screenNameArray.Length != 0)
8277 var atids = new List<string>();
8278 foreach (var screenName in screenNameArray)
8280 atids.Add("@" + screenName);
8282 var cnt = AtIdSupl.ItemCount;
8283 AtIdSupl.AddRangeItem(atids.ToArray());
8284 if (AtIdSupl.ItemCount != cnt)
8285 this.MarkSettingAtIdModified();
8289 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8291 var tab = this.CurrentTab;
8292 var selectedPosts = tab.SelectedPosts;
8294 if (selectedPosts.Length == 0)
8297 var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
8299 this.AddFilterRuleBySource(sourceArray);
8302 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8305 if (!SelectTab(out var tabName)) return;
8307 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8311 if (tab.TabType != MyCommon.TabUsageType.Mute)
8313 this.MoveOrCopy(out mv, out mk);
8317 // ミュートタブでは常に MoveMatches を true にする
8322 foreach (var screenName in screenNameArray)
8324 tab.AddFilter(new PostFilterRule
8326 FilterName = screenName,
8327 UseNameField = true,
8331 FilterByUrl = false,
8335 this.ApplyPostFilters();
8339 public void AddFilterRuleBySource(params string[] sourceArray)
8341 // タブ選択ダイアログを表示(or追加)
8342 if (!this.SelectTab(out var tabName))
8345 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8349 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8351 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8352 this.MoveOrCopy(out mv, out mk);
8356 // ミュートタブでは常に MoveMatches を true にする
8361 // 振り分けルールに追加するSource
8362 foreach (var source in sourceArray)
8364 filterTab.AddFilter(new PostFilterRule
8366 FilterSource = source,
8370 FilterByUrl = false,
8374 this.ApplyPostFilters();
8375 this.SaveConfigsTabs();
8378 private bool SelectTab(out string tabName)
8385 using (var dialog = new TabsDialog(_statuses))
8387 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8389 tabName = dialog.SelectedTab?.TabName;
8392 this.CurrentTabPage.Focus();
8394 if (tabName == null)
8396 using (var inputName = new InputTabName())
8398 inputName.TabName = _statuses.MakeTabName("MyTab");
8399 inputName.ShowDialog();
8400 if (inputName.DialogResult == DialogResult.Cancel) return false;
8401 tabName = inputName.TabName;
8403 this.TopMost = SettingManager.Common.AlwaysTop;
8404 if (!string.IsNullOrEmpty(tabName))
8406 var tab = new FilterTabModel(tabName);
8407 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8409 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8410 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8428 private void MoveOrCopy(out bool move, out bool mark)
8432 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8433 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8441 var _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8442 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8453 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8456 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8457 => this.CopyIdUri();
8459 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8461 if (StatusText.Focused)
8464 StatusText.SelectAll();
8468 // ListView上でのCtrl+A
8469 NativeMethods.SelectAllItems(this.CurrentListView);
8473 private void MoveMiddle()
8479 var listView = this.CurrentListView;
8480 if (listView.SelectedIndices.Count == 0) return;
8482 var idx = listView.SelectedIndices[0];
8484 _item = listView.GetItemAt(0, 25);
8490 _item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
8492 idx2 = listView.VirtualListSize - 1;
8496 idx -= Math.Abs(idx1 - idx2) / 2;
8497 if (idx < 0) idx = 0;
8499 listView.EnsureVisible(listView.VirtualListSize - 1);
8500 listView.EnsureVisible(idx);
8503 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8505 var linkElements = this.tweetDetailsView.GetLinkElements();
8507 if (linkElements.Length == 0)
8510 var links = new List<OpenUrlItem>(linkElements.Length);
8512 foreach (var linkElm in linkElements)
8514 var displayUrl = linkElm.GetAttribute("title");
8515 var href = linkElm.GetAttribute("href");
8516 var linkedText = linkElm.InnerText;
8518 if (string.IsNullOrEmpty(displayUrl))
8521 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
8525 bool isReverseSettings;
8527 if (links.Count == 1)
8529 // ツイートに含まれる URL が 1 つのみの場合
8530 // => OpenURL ダイアログを表示せずにリンクを開く
8531 selectedUrl = links[0].Href;
8533 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8534 isReverseSettings = false;
8538 // ツイートに含まれる URL が複数ある場合
8539 // => OpenURL を表示しユーザーが選択したリンクを開く
8540 this.UrlDialog.ClearUrl();
8542 foreach (var link in links)
8543 this.UrlDialog.AddUrl(link);
8545 if (this.UrlDialog.ShowDialog(this) != DialogResult.OK)
8548 this.TopMost = SettingManager.Common.AlwaysTop;
8550 selectedUrl = this.UrlDialog.SelectedUrl;
8552 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8553 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
8556 await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
8559 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8561 if (string.IsNullOrEmpty(_rclickTabName)) return;
8562 ClearTab(_rclickTabName, true);
8565 private void ClearTab(string tabName, bool showWarning)
8569 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8570 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8576 _statuses.ClearTabIds(tabName);
8577 if (this.CurrentTabName == tabName)
8580 _anchorFlag = false;
8581 this.PurgeListViewItemCache();
8584 var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8585 var tabPage = this.ListTab.TabPages[tabIndex];
8586 tabPage.ImageIndex = -1;
8588 var listView = (DetailsListView)tabPage.Tag;
8589 listView.VirtualListSize = 0;
8591 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8593 SetMainWindowTitle();
8594 SetStatusLabelUrl();
8597 private static long followers = 0;
8599 private void SetMainWindowTitle()
8602 var ttl = new StringBuilder(256);
8605 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8606 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8607 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8608 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8610 foreach (var tab in _statuses.Tabs)
8612 ur += tab.UnreadCount;
8617 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8618 ttl.Append(ApplicationSettings.ApplicationName);
8620 switch (SettingManager.Common.DispLatestPost)
8622 case MyCommon.DispTitleEnum.Ver:
8623 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8625 case MyCommon.DispTitleEnum.Post:
8626 if (_history != null && _history.Count > 1)
8627 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8629 case MyCommon.DispTitleEnum.UnreadRepCount:
8630 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8632 case MyCommon.DispTitleEnum.UnreadAllCount:
8633 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8635 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8636 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8638 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8639 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8641 case MyCommon.DispTitleEnum.OwnStatus:
8642 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8643 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8649 this.Text = ttl.ToString();
8651 catch (AccessViolationException)
8653 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8657 private string GetStatusLabelText()
8660 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8661 if (_statuses == null) return "";
8662 var tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8663 var tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8664 if (tbRep == null || tbDm == null) return "";
8665 var urat = tbRep.UnreadCount + tbDm.UnreadCount;
8670 var slbl = new StringBuilder(256);
8673 foreach (var tab in _statuses.Tabs)
8675 ur += tab.UnreadCount;
8677 if (tab.TabName == this.CurrentTabName)
8679 tur = tab.UnreadCount;
8690 UnreadAtCounter = urat;
8692 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8694 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8695 if (SettingManager.Common.TimelinePeriod == 0)
8697 slbl.Append(Properties.Resources.SetStatusLabelText2);
8701 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8703 return slbl.ToString();
8706 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8710 if (this.InvokeRequired && !this.IsDisposed)
8712 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8716 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8717 SetApiStatusLabel(endpointName);
8720 catch (ObjectDisposedException)
8724 catch (InvalidOperationException)
8730 private void SetApiStatusLabel(string endpointName = null)
8732 var tabType = this.CurrentTab.TabType;
8734 if (endpointName == null)
8739 case MyCommon.TabUsageType.Home:
8740 case MyCommon.TabUsageType.UserDefined:
8741 endpointName = "/statuses/home_timeline";
8744 case MyCommon.TabUsageType.Mentions:
8745 endpointName = "/statuses/mentions_timeline";
8748 case MyCommon.TabUsageType.Favorites:
8749 endpointName = "/favorites/list";
8752 case MyCommon.TabUsageType.DirectMessage:
8753 endpointName = "/direct_messages/events/list";
8756 case MyCommon.TabUsageType.UserTimeline:
8757 endpointName = "/statuses/user_timeline";
8760 case MyCommon.TabUsageType.Lists:
8761 endpointName = "/lists/statuses";
8764 case MyCommon.TabUsageType.PublicSearch:
8765 endpointName = "/search/tweets";
8768 case MyCommon.TabUsageType.Related:
8769 endpointName = "/statuses/show/:id";
8776 this.toolStripApiGauge.ApiEndpoint = endpointName;
8780 // 表示中のタブに関連する endpoint であれば更新
8783 switch (endpointName)
8785 case "/statuses/home_timeline":
8786 update = tabType == MyCommon.TabUsageType.Home ||
8787 tabType == MyCommon.TabUsageType.UserDefined;
8790 case "/statuses/mentions_timeline":
8791 update = tabType == MyCommon.TabUsageType.Mentions;
8794 case "/favorites/list":
8795 update = tabType == MyCommon.TabUsageType.Favorites;
8798 case "/direct_messages/events/list":
8799 update = tabType == MyCommon.TabUsageType.DirectMessage;
8802 case "/statuses/user_timeline":
8803 update = tabType == MyCommon.TabUsageType.UserTimeline;
8806 case "/lists/statuses":
8807 update = tabType == MyCommon.TabUsageType.Lists;
8810 case "/search/tweets":
8811 update = tabType == MyCommon.TabUsageType.PublicSearch;
8814 case "/statuses/show/:id":
8815 update = tabType == MyCommon.TabUsageType.Related;
8824 this.toolStripApiGauge.ApiEndpoint = endpointName;
8829 private void SetStatusLabelUrl()
8830 => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8832 public void SetStatusLabel(string text)
8833 => this.StatusLabel.Text = text;
8835 private void SetNotifyIconText()
8837 var ur = new StringBuilder(64);
8839 // タスクトレイアイコンのツールチップテキスト書き換え
8841 ur.Remove(0, ur.Length);
8842 if (SettingManager.Common.DispUsername)
8844 ur.Append(tw.Username);
8847 ur.Append(ApplicationSettings.ApplicationName);
8849 ur.Append("(Debug Build)");
8851 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8854 ur.Append(UnreadCounter);
8856 ur.Append(UnreadAtCounter);
8859 NotifyIcon1.Text = ur.ToString();
8862 internal void CheckReplyTo(string StatusText)
8866 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8868 foreach (Match hm in m)
8870 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8872 hstr += "#" + hm.Result("$3") + " ";
8873 HashSupl.AddItem("#" + hm.Result("$3"));
8876 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8878 hstr += HashMgr.UseHash;
8880 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8882 // 本当にリプライ先指定すべきかどうかの判定
8883 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8885 if (SettingManager.Common.UseAtIdSupplement)
8887 var bCnt = AtIdSupl.ItemCount;
8888 foreach (Match mid in m)
8890 AtIdSupl.AddItem(mid.Result("${id}"));
8892 if (bCnt != AtIdSupl.ItemCount)
8893 this.MarkSettingAtIdModified();
8896 // リプライ先ステータスIDの指定がない場合は指定しない
8897 if (this.inReplyTo == null)
8901 // 次の条件を満たす場合に in_reply_to_status_id 指定
8902 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8903 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8904 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8908 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8909 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8911 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8915 foreach (Match mid in m)
8917 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8922 this.inReplyTo = null;
8925 private void TweenMain_Resize(object sender, EventArgs e)
8927 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8929 this.Visible = false;
8931 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8933 // 現在の DPI と設定保存時の DPI との比を取得する
8934 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8936 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8939 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8940 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8941 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8943 this.SplitContainer1.SplitterDistance = splitterDistance;
8947 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8948 if (StatusText.Multiline)
8950 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8951 var dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8952 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8954 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8956 StatusText.Height = statusTextHeight;
8960 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8962 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8966 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8967 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8969 this.SplitContainer3.SplitterDistance = previewDistance;
8972 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8973 this.SplitContainer3.Panel2Collapsed = true;
8975 _initialLayout = false;
8977 if (this.WindowState != FormWindowState.Minimized)
8979 _formWindowState = this.WindowState;
8983 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8985 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8986 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8987 if (PlaySoundMenuItem.Checked)
8989 SettingManager.Common.PlaySound = true;
8993 SettingManager.Common.PlaySound = false;
8995 this.MarkSettingCommonModified();
8998 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9000 if (this._initialLayout)
9003 int splitterDistance;
9004 switch (this.WindowState)
9006 case FormWindowState.Normal:
9007 splitterDistance = this.SplitContainer1.SplitterDistance;
9009 case FormWindowState.Maximized:
9010 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9011 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9012 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9013 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9019 this._mySpDis = splitterDistance;
9020 this.MarkSettingLocalModified();
9023 private async Task doRepliedStatusOpen()
9025 var currentPost = this.CurrentPost;
9026 if (this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
9028 if (MyCommon.IsKeyDown(Keys.Shift))
9030 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9033 if (_statuses.ContainsKey(currentPost.InReplyToStatusId.Value))
9035 var repPost = _statuses[currentPost.InReplyToStatusId.Value];
9036 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9040 foreach (var tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9042 if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
9043 var repPost = _statuses[currentPost.InReplyToStatusId.Value];
9044 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9047 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9052 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9053 => await this.doRepliedStatusOpen();
9055 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9057 if (this._initialLayout)
9058 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9060 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9061 if (multiline != this.StatusText.Multiline)
9063 this.StatusText.Multiline = multiline;
9064 SettingManager.Local.StatusMultiline = multiline;
9065 this.MarkSettingLocalModified();
9069 private void StatusText_MultilineChanged(object sender, EventArgs e)
9071 if (this.StatusText.Multiline)
9072 this.StatusText.ScrollBars = ScrollBars.Vertical;
9074 this.StatusText.ScrollBars = ScrollBars.None;
9076 if (!this._initialLayout)
9077 this.MarkSettingLocalModified();
9080 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9083 var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9084 StatusText.Multiline = menuItemChecked;
9085 SettingManager.Local.StatusMultiline = menuItemChecked;
9086 if (menuItemChecked)
9088 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9089 SplitContainer2.SplitterDistance = 0;
9091 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9095 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9097 this.MarkSettingLocalModified();
9100 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9102 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9104 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9105 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9106 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9108 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9113 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9114 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9116 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9117 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9118 //Appendix A. Collected ABNF for URI
9119 //http://www.ietf.org/rfc/rfc3986.txt
9121 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9124 if (StatusText.SelectionLength > 0)
9126 var tmp = StatusText.SelectedText;
9127 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9128 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9130 // 文字列が選択されている場合はその文字列について処理
9132 //nico.ms使用、nicovideoにマッチしたら変換
9133 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9135 result = nicoms.Shorten(tmp);
9137 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9142 var srcUri = new Uri(tmp);
9143 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9144 result = resultUri.AbsoluteUri;
9146 catch (WebApiException e)
9148 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9151 catch (UriFormatException e)
9153 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9162 if (!string.IsNullOrEmpty(result))
9164 var undotmp = new urlUndo();
9166 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9167 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9168 if (origUrlIndex == -1)
9171 StatusText.Select(origUrlIndex, tmp.Length);
9172 StatusText.SelectedText = result;
9175 undotmp.Before = tmp;
9176 undotmp.After = result;
9178 if (urlUndoBuffer == null)
9180 urlUndoBuffer = new List<urlUndo>();
9181 UrlUndoToolStripMenuItem.Enabled = true;
9184 urlUndoBuffer.Add(undotmp);
9190 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9191 @"(?<url>(?<protocol>https?://)" +
9192 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9193 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9194 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9195 // 正規表現にマッチしたURL文字列をtinyurl化
9196 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9198 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
9200 var tmp = mt.Result("${url}");
9201 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
9202 tmp = "http://" + tmp;
9203 var undotmp = new urlUndo();
9206 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9208 //nico.ms使用、nicovideoにマッチしたら変換
9209 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9211 result = nicoms.Shorten(tmp);
9213 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9218 var srcUri = new Uri(tmp);
9219 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9220 result = resultUri.AbsoluteUri;
9222 catch (HttpRequestException e)
9224 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9225 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9226 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9228 this.StatusLabel.Text = Converter_Type + ":" + message;
9231 catch (WebApiException e)
9233 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9236 catch (UriFormatException e)
9238 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9247 if (!string.IsNullOrEmpty(result))
9249 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9250 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9251 if (origUrlIndex == -1)
9254 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9255 StatusText.SelectedText = result;
9257 undotmp.Before = mt.Result("${url}");
9258 undotmp.After = result;
9260 if (urlUndoBuffer == null)
9262 urlUndoBuffer = new List<urlUndo>();
9263 UrlUndoToolStripMenuItem.Enabled = true;
9266 urlUndoBuffer.Add(undotmp);
9274 private void doUrlUndo()
9276 if (urlUndoBuffer != null)
9278 var tmp = StatusText.Text;
9279 foreach (var data in urlUndoBuffer)
9281 tmp = tmp.Replace(data.After, data.Before);
9283 StatusText.Text = tmp;
9284 urlUndoBuffer = null;
9285 UrlUndoToolStripMenuItem.Enabled = false;
9286 StatusText.SelectionStart = 0;
9287 StatusText.SelectionLength = 0;
9291 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9292 => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9294 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9295 => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9297 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9298 => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9300 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9302 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9304 var rnd = new Random();
9306 MyCommon.UrlConverter svc;
9307 // 前回使用した短縮URLサービス以外を選択する
9310 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9312 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9313 await UrlConvertAsync(svc);
9317 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9318 => this.doUrlUndo();
9320 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9322 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9323 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9324 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9325 this.MarkSettingCommonModified();
9328 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9330 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9331 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9332 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9333 this.MarkSettingCommonModified();
9336 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9338 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9339 MenuStrip1.Tag = new object();
9340 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9343 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9345 var currentTabPage = this.CurrentTabPage;
9346 if (this.Tag != null) // 設定された戻り先へ遷移
9348 if (this.Tag == currentTabPage)
9349 ((Control)currentTabPage.Tag).Select();
9351 ((Control)this.Tag).Select();
9353 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9355 this.Tag = currentTabPage.Tag;
9356 ((Control)this.Tag).Select();
9358 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9359 MenuStrip1.Tag = null;
9362 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9364 var lst = (DetailsListView)sender;
9365 if (SettingManager.Local == null) return;
9369 SettingManager.Local.Width1 = lst.Columns[0].Width;
9370 SettingManager.Local.Width3 = lst.Columns[1].Width;
9374 var darr = new int[lst.Columns.Count];
9375 for (var i = 0; i < lst.Columns.Count; i++)
9377 darr[lst.Columns[i].DisplayIndex] = i;
9379 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9381 for (var i = 0; i < lst.Columns.Count; i++)
9386 SettingManager.Local.DisplayIndex1 = i;
9389 SettingManager.Local.DisplayIndex2 = i;
9392 SettingManager.Local.DisplayIndex3 = i;
9395 SettingManager.Local.DisplayIndex4 = i;
9398 SettingManager.Local.DisplayIndex5 = i;
9401 SettingManager.Local.DisplayIndex6 = i;
9404 SettingManager.Local.DisplayIndex7 = i;
9407 SettingManager.Local.DisplayIndex8 = i;
9411 SettingManager.Local.Width1 = lst.Columns[0].Width;
9412 SettingManager.Local.Width2 = lst.Columns[1].Width;
9413 SettingManager.Local.Width3 = lst.Columns[2].Width;
9414 SettingManager.Local.Width4 = lst.Columns[3].Width;
9415 SettingManager.Local.Width5 = lst.Columns[4].Width;
9416 SettingManager.Local.Width6 = lst.Columns[5].Width;
9417 SettingManager.Local.Width7 = lst.Columns[6].Width;
9418 SettingManager.Local.Width8 = lst.Columns[7].Width;
9420 this.MarkSettingLocalModified();
9421 _isColumnChanged = true;
9424 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9426 var lst = (DetailsListView)sender;
9427 if (SettingManager.Local == null) return;
9429 var modified = false;
9432 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9434 SettingManager.Local.Width1 = lst.Columns[0].Width;
9437 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9439 SettingManager.Local.Width3 = lst.Columns[1].Width;
9445 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9447 SettingManager.Local.Width1 = lst.Columns[0].Width;
9450 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9452 SettingManager.Local.Width2 = lst.Columns[1].Width;
9455 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9457 SettingManager.Local.Width3 = lst.Columns[2].Width;
9460 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9462 SettingManager.Local.Width4 = lst.Columns[3].Width;
9465 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9467 SettingManager.Local.Width5 = lst.Columns[4].Width;
9470 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9472 SettingManager.Local.Width6 = lst.Columns[5].Width;
9475 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9477 SettingManager.Local.Width7 = lst.Columns[6].Width;
9480 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9482 SettingManager.Local.Width8 = lst.Columns[7].Width;
9488 this.MarkSettingLocalModified();
9489 this._isColumnChanged = true;
9491 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9494 // SaveConfigsLocal();
9498 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9500 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9501 this.MarkSettingLocalModified();
9504 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9506 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9508 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9510 SelectMedia_DragDrop(e);
9513 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9515 var (url, title) = GetUrlFromDataObject(e.Data);
9521 appendText = title + " " + url;
9523 if (this.StatusText.TextLength == 0)
9524 this.StatusText.Text = appendText;
9526 this.StatusText.Text += " " + appendText;
9528 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9530 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9532 this.StatusText.Text += text;
9534 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9536 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9537 if (data != null) StatusText.Text += data;
9542 /// IDataObject から URL とタイトルの対を取得します
9545 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9547 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9548 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9549 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9551 if (data.GetDataPresent("text/x-moz-url"))
9553 // Firefox, Google Chrome で利用可能
9554 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9556 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
9557 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9558 if (lines.Length < 2)
9559 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9561 return (lines[0], lines[1]);
9563 else if (data.GetDataPresent("IESiteModeToUrl"))
9565 // Internet Exproler 用
9566 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9568 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
9569 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9570 if (lines.Length < 2)
9571 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9573 return (lines[0], lines[1]);
9575 else if (data.GetDataPresent("UniformResourceLocatorW"))
9579 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
9580 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9584 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9587 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9589 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9591 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9593 SelectMedia_DragEnter(e);
9597 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9599 e.Effect = DragDropEffects.Copy;
9602 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9604 e.Effect = DragDropEffects.Copy;
9607 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9609 e.Effect = DragDropEffects.Copy;
9613 e.Effect = DragDropEffects.None;
9616 private void TweenMain_DragOver(object sender, DragEventArgs e)
9620 public bool IsNetworkAvailable()
9622 var nw = MyCommon.IsNetworkAvailable();
9623 _myStatusOnline = nw;
9627 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9629 var uriStr = uri.AbsoluteUri;
9631 // OpenTween 内部で使用する URL
9632 if (uri.Authority == "opentween")
9634 await this.OpenInternalUriAsync(uri);
9638 // ハッシュタグを含む Twitter 検索
9639 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9642 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9643 var pos = unescapedQuery.IndexOf('#');
9644 if (pos == -1) return;
9646 var hash = unescapedQuery.Substring(pos);
9647 this.HashSupl.AddItem(hash);
9648 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9649 this.AddNewTabForSearch(hash);
9654 // フラグが立っている場合は設定と逆の動作をする
9655 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9656 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9658 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9659 if (userUriMatch.Success)
9661 var screenName = userUriMatch.Groups["ScreenName"].Value;
9662 if (this.IsTwitterId(screenName))
9664 await this.AddNewTabForUserTimeline(screenName);
9671 await this.OpenUriInBrowserAsync(uriStr);
9675 /// OpenTween 内部の機能を呼び出すための URL を開きます
9677 private async Task OpenInternalUriAsync(Uri uri)
9679 // ツイートを開く (//opentween/status/:status_id)
9680 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9683 var statusId = long.Parse(match.Groups[1].Value);
9684 await this.OpenRelatedTab(statusId);
9689 public Task OpenUriInBrowserAsync(string UriString)
9691 return Task.Run(() =>
9693 var myPath = UriString;
9697 var configBrowserPath = SettingManager.Local.BrowserPath;
9698 if (!string.IsNullOrEmpty(configBrowserPath))
9700 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9702 var sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9703 var browserPath = configBrowserPath.Substring(1, sep - 1);
9705 if (sep < configBrowserPath.Length - 1)
9707 arg = configBrowserPath.Substring(sep + 1);
9709 myPath = arg + " " + myPath;
9710 System.Diagnostics.Process.Start(browserPath, myPath);
9714 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9719 System.Diagnostics.Process.Start(myPath);
9724 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9729 private void ListTabSelect(TabPage _tab)
9733 this.PurgeListViewItemCache();
9735 this._statuses.SelectTab(_tab.Text);
9737 var listView = this.CurrentListView;
9740 _anchorFlag = false;
9744 listView.Columns[1].Text = ColumnText[2];
9748 for (var i = 0; i < listView.Columns.Count; i++)
9750 listView.Columns[i].Text = ColumnText[i];
9755 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9756 => this.ListTabSelect(e.TabPage);
9758 private void SelectListItem(DetailsListView LView, int Index)
9761 var bnd = new Rectangle();
9763 var item = LView.FocusedItem;
9772 LView.SelectedIndices.Clear();
9774 while (LView.SelectedIndices.Count > 0);
9775 item = LView.Items[Index];
9776 item.Selected = true;
9777 item.Focused = true;
9779 if (flg) LView.Invalidate(bnd);
9782 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9785 var bnd = new Rectangle();
9787 var item = LView.FocusedItem;
9798 LView.SelectedIndices.Clear();
9800 while (LView.SelectedIndices.Count > 0);
9801 LView.SelectItems(Index);
9803 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9805 LView.SelectionMark = selectionMarkIndex;
9807 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9809 LView.Items[focusedIndex].Focused = true;
9811 else if (Index != null && Index.Length != 0)
9813 LView.Items[Index.Last()].Focused = true;
9816 if (flg) LView.Invalidate(bnd);
9819 private void StartUserStream()
9821 tw.NewPostFromStream += tw_NewPostFromStream;
9822 tw.UserStreamStarted += tw_UserStreamStarted;
9823 tw.UserStreamStopped += tw_UserStreamStopped;
9824 tw.PostDeleted += tw_PostDeleted;
9825 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9827 this.RefreshUserStreamsMenu();
9829 if (SettingManager.Common.UserstreamStartup)
9830 tw.StartUserStream();
9833 private async void TweenMain_Shown(object sender, EventArgs e)
9835 NotifyIcon1.Visible = true;
9837 if (this.IsNetworkAvailable())
9841 var loadTasks = new List<Task>
9843 this.RefreshMuteUserIdsAsync(),
9844 this.RefreshBlockIdsAsync(),
9845 this.RefreshNoRetweetIdsAsync(),
9846 this.RefreshTwitterConfigurationAsync(),
9847 this.RefreshTabAsync<HomeTabModel>(),
9848 this.RefreshTabAsync<MentionsTabModel>(),
9849 this.RefreshTabAsync<DirectMessagesTabModel>(),
9850 this.RefreshTabAsync<PublicSearchTabModel>(),
9851 this.RefreshTabAsync<UserTimelineTabModel>(),
9852 this.RefreshTabAsync<ListTimelineTabModel>(),
9855 if (SettingManager.Common.StartupFollowers)
9856 loadTasks.Add(this.RefreshFollowerIdsAsync());
9858 if (SettingManager.Common.GetFav)
9859 loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9861 var allTasks = Task.WhenAll(loadTasks);
9866 var timeout = Task.Delay(5000);
9867 if (await Task.WhenAny(allTasks, timeout) != timeout)
9871 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9873 if (MyCommon._endingFlag)
9877 if (MyCommon._endingFlag) return;
9879 if (ApplicationSettings.VersionInfoUrl != null)
9881 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9882 if (SettingManager.Common.StartupVersion)
9883 await this.CheckNewVersion(true);
9887 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9888 this.VerUpMenuItem.Enabled = false;
9889 this.VerUpMenuItem.Available = false;
9890 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9893 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9894 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9896 MessageBox.Show(Properties.Resources.ReAuthorizeText);
9897 SettingStripMenuItem_Click(null, null);
9901 var reloadTasks = new List<Task>();
9903 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9904 reloadTasks.Add(this.RefreshFollowerIdsAsync());
9906 if (!tw.GetNoRetweetSuccess)
9907 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9909 if (this.tw.Configuration.PhotoSizeLimit == 0)
9910 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9912 await Task.WhenAll(reloadTasks);
9917 this.timelineScheduler.Enabled = true;
9920 private async Task doGetFollowersMenu()
9922 await this.RefreshFollowerIdsAsync();
9923 this.DispSelectedPost(true);
9926 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9927 => await this.doGetFollowersMenu();
9929 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9930 => this.doReTweetUnofficial();
9932 private async Task doReTweetOfficial(bool isConfirm)
9935 if (this.ExistCurrentPost)
9937 var selectedPosts = this.CurrentTab.SelectedPosts;
9939 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9941 if (selectedPosts.Any(x => x.IsProtect))
9942 MessageBox.Show("Protected.");
9944 _DoFavRetweetFlags = false;
9948 if (selectedPosts.Length > 15)
9950 MessageBox.Show(Properties.Resources.RetweetLimitText);
9951 _DoFavRetweetFlags = false;
9954 else if (selectedPosts.Length > 1)
9956 var QuestionText = Properties.Resources.RetweetQuestion2;
9957 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9958 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9960 case DialogResult.Cancel:
9961 case DialogResult.No:
9962 _DoFavRetweetFlags = false;
9968 if (!SettingManager.Common.RetweetNoConfirm)
9970 var Questiontext = Properties.Resources.RetweetQuestion1;
9971 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9972 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9974 _DoFavRetweetFlags = false;
9980 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9982 await this.RetweetAsync(statusIds);
9986 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9987 => await this.doReTweetOfficial(true);
9989 private async Task FavoritesRetweetOfficial()
9991 if (!this.ExistCurrentPost) return;
9992 _DoFavRetweetFlags = true;
9993 var retweetTask = this.doReTweetOfficial(true);
9994 if (_DoFavRetweetFlags)
9996 _DoFavRetweetFlags = false;
9997 var favoriteTask = this.FavoriteChange(true, false);
9999 await Task.WhenAll(retweetTask, favoriteTask);
10007 private async Task FavoritesRetweetUnofficial()
10009 var post = this.CurrentPost;
10010 if (this.ExistCurrentPost && !post.IsDm)
10012 _DoFavRetweetFlags = true;
10013 var favoriteTask = this.FavoriteChange(true);
10014 if (!post.IsProtect && _DoFavRetweetFlags)
10016 _DoFavRetweetFlags = false;
10017 doReTweetUnofficial();
10020 await favoriteTask;
10025 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10027 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10028 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10029 /// <returns>復元されたツイート本文</returns>
10030 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10032 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10035 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10037 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10039 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10041 statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
10045 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10047 statusHtml = statusHtml.Replace("<br>", " ");
10049 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10050 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10051 statusHtml = statusHtml.Replace(" ", " ");
10053 return WebUtility.HtmlDecode(statusHtml);
10056 private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10058 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10060 if (this.CurrentPost != null)
10061 this.DispSelectedPost(true);
10064 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10066 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10067 DebugModeToolStripMenuItem.Visible = true;
10069 DebugModeToolStripMenuItem.Visible = false;
10072 private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10073 => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10075 private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10076 => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10078 private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10079 => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10081 private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10083 SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10084 this.MarkSettingCommonModified();
10087 private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10089 SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10090 this.MarkSettingCommonModified();
10093 private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10095 UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10096 PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10097 UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10098 IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10099 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10100 FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10103 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10105 UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10106 PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10107 UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10108 IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10109 MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10110 FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10113 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10115 if (TraceOutToolStripMenuItem.Checked)
10116 MyCommon.TraceFlag = true;
10118 MyCommon.TraceFlag = false;
10121 private void TweenMain_Deactivate(object sender, EventArgs e)
10122 => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10124 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10126 if (string.IsNullOrEmpty(_rclickTabName)) return;
10128 _ = TabRename(_rclickTabName, out _);
10131 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10132 => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10134 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10135 => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10137 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10139 TwitterApiStatus apiStatus;
10141 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10143 var cancellationToken = dialog.EnableCancellation();
10147 var task = this.tw.GetInfoApi();
10148 apiStatus = await dialog.WaitForAsync(this, task);
10150 catch (WebApiException)
10155 if (cancellationToken.IsCancellationRequested)
10158 if (apiStatus == null)
10160 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10165 using var apiDlg = new ApiInfoDialog();
10166 apiDlg.ShowDialog(this);
10169 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10171 var id = this.CurrentPost?.ScreenName ?? "";
10173 await this.FollowCommand(id);
10176 internal async Task FollowCommand(string id)
10178 using (var inputName = new InputTabName())
10180 inputName.FormTitle = "Follow";
10181 inputName.FormDescription = Properties.Resources.FRMessage1;
10182 inputName.TabName = id;
10184 if (inputName.ShowDialog(this) != DialogResult.OK)
10186 if (string.IsNullOrWhiteSpace(inputName.TabName))
10189 id = inputName.TabName.Trim();
10192 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10196 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10197 await dialog.WaitForAsync(this, task);
10199 catch (WebApiException ex)
10201 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10206 MessageBox.Show(Properties.Resources.FRMessage3);
10209 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10211 var id = this.CurrentPost?.ScreenName ?? "";
10213 await this.RemoveCommand(id, false);
10216 internal async Task RemoveCommand(string id, bool skipInput)
10220 using var inputName = new InputTabName();
10221 inputName.FormTitle = "Unfollow";
10222 inputName.FormDescription = Properties.Resources.FRMessage1;
10223 inputName.TabName = id;
10225 if (inputName.ShowDialog(this) != DialogResult.OK)
10227 if (string.IsNullOrWhiteSpace(inputName.TabName))
10230 id = inputName.TabName.Trim();
10233 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10237 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10238 await dialog.WaitForAsync(this, task);
10240 catch (WebApiException ex)
10242 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10247 MessageBox.Show(Properties.Resources.FRMessage3);
10250 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10252 var id = this.CurrentPost?.ScreenName ?? "";
10254 await this.ShowFriendship(id);
10257 internal async Task ShowFriendship(string id)
10259 using (var inputName = new InputTabName())
10261 inputName.FormTitle = "Show Friendships";
10262 inputName.FormDescription = Properties.Resources.FRMessage1;
10263 inputName.TabName = id;
10265 if (inputName.ShowDialog(this) != DialogResult.OK)
10267 if (string.IsNullOrWhiteSpace(inputName.TabName))
10270 id = inputName.TabName.Trim();
10273 bool isFollowing, isFollowed;
10275 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10277 var cancellationToken = dialog.EnableCancellation();
10281 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10282 var friendship = await dialog.WaitForAsync(this, task);
10284 isFollowing = friendship.Relationship.Source.Following;
10285 isFollowed = friendship.Relationship.Source.FollowedBy;
10287 catch (WebApiException ex)
10289 if (!cancellationToken.IsCancellationRequested)
10290 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10294 if (cancellationToken.IsCancellationRequested)
10301 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10305 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10309 result += Properties.Resources.GetFriendshipInfo3;
10313 result += Properties.Resources.GetFriendshipInfo4;
10315 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10316 MessageBox.Show(result);
10319 internal async Task ShowFriendship(string[] ids)
10321 foreach (var id in ids)
10323 bool isFollowing, isFollowed;
10325 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10327 var cancellationToken = dialog.EnableCancellation();
10331 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10332 var friendship = await dialog.WaitForAsync(this, task);
10334 isFollowing = friendship.Relationship.Source.Following;
10335 isFollowed = friendship.Relationship.Source.FollowedBy;
10337 catch (WebApiException ex)
10339 if (!cancellationToken.IsCancellationRequested)
10340 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10344 if (cancellationToken.IsCancellationRequested)
10354 ff += Properties.Resources.GetFriendshipInfo1;
10358 ff += Properties.Resources.GetFriendshipInfo2;
10361 ff += System.Environment.NewLine + " ";
10364 ff += Properties.Resources.GetFriendshipInfo3;
10368 ff += Properties.Resources.GetFriendshipInfo4;
10370 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10373 if (MessageBox.Show(
10374 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10375 MessageBoxButtons.YesNo,
10376 MessageBoxIcon.Question,
10377 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10379 await this.RemoveCommand(id, true);
10384 MessageBox.Show(result);
10389 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10390 => await this.doShowUserStatus(tw.Username, false);
10392 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10393 // URLから切り出した文字列を渡す
10395 public bool IsTwitterId(string name)
10397 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10398 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10400 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10403 private void doQuoteOfficial()
10405 if (this.ExistCurrentPost)
10407 var post = this.CurrentPost;
10408 if (post.IsDm || !StatusText.Enabled)
10411 if (post.IsProtect)
10413 MessageBox.Show("Protected.");
10417 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10419 this.inReplyTo = null;
10421 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10423 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10424 StatusText.Focus();
10428 private void doReTweetUnofficial()
10431 if (this.ExistCurrentPost)
10433 var post = this.CurrentPost;
10434 if (post.IsDm || !StatusText.Enabled)
10437 if (post.IsProtect)
10439 MessageBox.Show("Protected.");
10442 var rtdata = post.Text;
10443 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10445 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10447 // 投稿時に in_reply_to_status_id を付加する
10448 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10449 var inReplyToScreenName = post.ScreenName;
10450 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10452 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10454 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10455 StatusText.Focus();
10459 private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10460 => this.doQuoteOfficial();
10462 private async void SearchButton_Click(object sender, EventArgs e)
10465 var pnl = ((Control)sender).Parent;
10466 if (pnl == null) return;
10467 var tbName = pnl.Parent.Text;
10468 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10469 var cmb = (ComboBox)pnl.Controls["comboSearch"];
10470 var cmbLang = (ComboBox)pnl.Controls["comboLang"];
10471 cmb.Text = cmb.Text.Trim();
10472 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10474 var buf = new StringBuilder();
10475 var c = cmb.Text.ToCharArray();
10476 for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
10478 if (cnt > cmb.Text.Length - 4)
10480 buf.Append(cmb.Text.Substring(cnt));
10489 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10491 buf.Append(" OR ");
10496 buf.Append(c[cnt]);
10498 cmb.Text = buf.ToString();
10500 var listView = (DetailsListView)pnl.Parent.Tag;
10502 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10504 tb.SearchWords = cmb.Text;
10505 tb.SearchLang = cmbLang.Text;
10506 if (string.IsNullOrEmpty(cmb.Text))
10514 var idx = cmb.Items.IndexOf(tb.SearchWords);
10515 if (idx > -1) cmb.Items.RemoveAt(idx);
10516 cmb.Items.Insert(0, tb.SearchWords);
10517 cmb.Text = tb.SearchWords;
10519 this.PurgeListViewItemCache();
10520 listView.VirtualListSize = 0;
10521 _statuses.ClearTabIds(tbName);
10522 SaveConfigsTabs(); //検索条件の保存
10526 await this.RefreshTabAsync(tb);
10529 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10530 => await this.DoRefreshMore(); // もっと前を取得
10533 /// 指定されたタブのListTabにおける位置を返します
10536 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10538 public int GetTabPageIndex(string tabName)
10539 => this._statuses.Tabs.IndexOf(tabName);
10541 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10543 if (_statuses.RemovedTab.Count == 0)
10545 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10550 var tb = _statuses.RemovedTab.Pop();
10551 DetailsListView listView;
10552 if (tb.TabType == MyCommon.TabUsageType.Related)
10554 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10555 if (relatedTab != null)
10557 // 関連発言なら既存のタブを置き換える
10558 tb.TabName = relatedTab.TabName;
10559 this.ClearTab(tb.TabName, false);
10561 this._statuses.ReplaceTab(tb);
10563 var tabIndex = this._statuses.Tabs.IndexOf(tb);
10564 var tabPage = this.ListTab.TabPages[tabIndex];
10565 listView = (DetailsListView)tabPage.Tag;
10566 this.ListTab.SelectedIndex = tabIndex;
10570 const string TabName = "Related Tweets";
10571 var renamed = TabName;
10572 for (var i = 2; i <= 100; i++)
10574 if (!_statuses.ContainsTab(renamed))
10576 renamed = TabName + i;
10578 tb.TabName = renamed;
10580 _statuses.AddTab(tb);
10581 AddNewTab(tb, startup: false);
10583 var tabIndex = this._statuses.Tabs.Count - 1;
10584 var tabPage = this.ListTab.TabPages[tabIndex];
10586 listView = (DetailsListView)tabPage.Tag;
10587 this.ListTab.SelectedIndex = tabIndex;
10592 var renamed = tb.TabName;
10593 for (var i = 1; i < int.MaxValue; i++)
10595 if (!_statuses.ContainsTab(renamed))
10597 renamed = tb.TabName + "(" + i + ")";
10599 tb.TabName = renamed;
10601 _statuses.AddTab(tb);
10602 AddNewTab(tb, startup: false);
10604 var tabIndex = this._statuses.Tabs.Count - 1;
10605 var tabPage = this.ListTab.TabPages[tabIndex];
10607 listView = (DetailsListView)tabPage.Tag;
10608 this.ListTab.SelectedIndex = tabIndex;
10612 if (listView != null)
10614 using (ControlTransaction.Update(listView))
10616 listView.VirtualListSize = tb.AllCount;
10622 private async Task doMoveToRTHome()
10624 var post = this.CurrentPost;
10625 if (post != null && post.RetweetedId != null)
10626 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10629 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10630 => await this.doMoveToRTHome();
10632 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10634 var screenName = this.CurrentPost?.ScreenName;
10635 if (screenName != null)
10636 this.ListManageUserContext(screenName);
10639 public void ListManageUserContext(string screenName)
10641 using var listSelectForm = new MyLists(screenName, this.twitterApi);
10642 listSelectForm.ShowDialog(this);
10645 private void SearchControls_Enter(object sender, EventArgs e)
10647 var pnl = (Control)sender;
10648 foreach (Control ctl in pnl.Controls)
10650 ctl.TabStop = true;
10654 private void SearchControls_Leave(object sender, EventArgs e)
10656 var pnl = (Control)sender;
10657 foreach (Control ctl in pnl.Controls)
10659 ctl.TabStop = false;
10663 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10665 var tab = this.CurrentTab;
10666 if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10667 this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10670 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10671 => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10673 private void HashManageMenuItem_Click(object sender, EventArgs e)
10678 rslt = HashMgr.ShowDialog();
10684 this.TopMost = SettingManager.Common.AlwaysTop;
10685 if (rslt == DialogResult.Cancel) return;
10686 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10688 HashStripSplitButton.Text = HashMgr.UseHash;
10689 HashTogglePullDownMenuItem.Checked = true;
10690 HashToggleMenuItem.Checked = true;
10694 HashStripSplitButton.Text = "#[-]";
10695 HashTogglePullDownMenuItem.Checked = false;
10696 HashToggleMenuItem.Checked = false;
10698 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10700 // int sidx = StatusText.SelectionStart;
10701 // string hash = HashMgr.UseHash + " ";
10704 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10705 // hash = " " + hash;
10707 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10708 // sidx += hash.Length;
10709 // StatusText.SelectionStart = sidx;
10710 // StatusText.Focus();
10712 this.MarkSettingCommonModified();
10713 this.StatusText_TextChanged(null, null);
10716 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10718 HashMgr.ToggleHash();
10719 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10721 HashStripSplitButton.Text = HashMgr.UseHash;
10722 HashToggleMenuItem.Checked = true;
10723 HashTogglePullDownMenuItem.Checked = true;
10727 HashStripSplitButton.Text = "#[-]";
10728 HashToggleMenuItem.Checked = false;
10729 HashTogglePullDownMenuItem.Checked = false;
10731 this.MarkSettingCommonModified();
10732 this.StatusText_TextChanged(null, null);
10735 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10736 => this.HashToggleMenuItem_Click(null, null);
10738 public void SetPermanentHashtag(string hashtag)
10740 HashMgr.SetPermanentHash("#" + hashtag);
10741 HashStripSplitButton.Text = HashMgr.UseHash;
10742 HashTogglePullDownMenuItem.Checked = true;
10743 HashToggleMenuItem.Checked = true;
10745 this.MarkSettingCommonModified();
10748 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10750 if (!this.ExistCurrentPost)
10752 this.ReplyOpMenuItem.Enabled = false;
10753 this.ReplyAllOpMenuItem.Enabled = false;
10754 this.DmOpMenuItem.Enabled = false;
10755 this.ShowProfMenuItem.Enabled = false;
10756 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10757 this.ListManageMenuItem.Enabled = false;
10758 this.OpenFavOpMenuItem.Enabled = false;
10759 this.CreateTabRuleOpMenuItem.Enabled = false;
10760 this.CreateIdRuleOpMenuItem.Enabled = false;
10761 this.CreateSourceRuleOpMenuItem.Enabled = false;
10762 this.ReadOpMenuItem.Enabled = false;
10763 this.UnreadOpMenuItem.Enabled = false;
10767 this.ReplyOpMenuItem.Enabled = true;
10768 this.ReplyAllOpMenuItem.Enabled = true;
10769 this.DmOpMenuItem.Enabled = true;
10770 this.ShowProfMenuItem.Enabled = true;
10771 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10772 this.ListManageMenuItem.Enabled = true;
10773 this.OpenFavOpMenuItem.Enabled = true;
10774 this.CreateTabRuleOpMenuItem.Enabled = true;
10775 this.CreateIdRuleOpMenuItem.Enabled = true;
10776 this.CreateSourceRuleOpMenuItem.Enabled = true;
10777 this.ReadOpMenuItem.Enabled = true;
10778 this.UnreadOpMenuItem.Enabled = true;
10781 var tab = this.CurrentTab;
10782 var post = this.CurrentPost;
10783 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
10785 this.FavOpMenuItem.Enabled = false;
10786 this.UnFavOpMenuItem.Enabled = false;
10787 this.OpenStatusOpMenuItem.Enabled = false;
10788 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10789 this.RtOpMenuItem.Enabled = false;
10790 this.RtUnOpMenuItem.Enabled = false;
10791 this.QtOpMenuItem.Enabled = false;
10792 this.FavoriteRetweetMenuItem.Enabled = false;
10793 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10797 this.FavOpMenuItem.Enabled = true;
10798 this.UnFavOpMenuItem.Enabled = true;
10799 this.OpenStatusOpMenuItem.Enabled = true;
10800 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10802 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10804 this.RtOpMenuItem.Enabled = false;
10805 this.RtUnOpMenuItem.Enabled = false;
10806 this.QtOpMenuItem.Enabled = false;
10807 this.FavoriteRetweetMenuItem.Enabled = false;
10808 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10812 this.RtOpMenuItem.Enabled = true;
10813 this.RtUnOpMenuItem.Enabled = true;
10814 this.QtOpMenuItem.Enabled = true;
10815 this.FavoriteRetweetMenuItem.Enabled = true;
10816 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10820 if (tab.TabType != MyCommon.TabUsageType.Favorites)
10822 this.RefreshPrevOpMenuItem.Enabled = true;
10826 this.RefreshPrevOpMenuItem.Enabled = false;
10828 if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
10830 OpenRepSourceOpMenuItem.Enabled = false;
10834 OpenRepSourceOpMenuItem.Enabled = true;
10836 if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
10838 OpenRterHomeMenuItem.Enabled = false;
10842 OpenRterHomeMenuItem.Enabled = true;
10845 if (this.ExistCurrentPost)
10847 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10851 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10852 => this.ContextMenuTabProperty_Opening(sender, null);
10854 public Twitter TwitterInstance
10857 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10859 if (this._initialLayout)
10862 int splitterDistance;
10863 switch (this.WindowState)
10865 case FormWindowState.Normal:
10866 splitterDistance = this.SplitContainer3.SplitterDistance;
10868 case FormWindowState.Maximized:
10869 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10870 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10871 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10872 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10878 this._mySpDis3 = splitterDistance;
10879 this.MarkSettingLocalModified();
10882 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10884 if (_statuses.RemovedTab.Count == 0)
10886 UndoRemoveTabMenuItem.Enabled = false;
10890 UndoRemoveTabMenuItem.Enabled = true;
10893 if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10894 PublicSearchQueryMenuItem.Enabled = true;
10896 PublicSearchQueryMenuItem.Enabled = false;
10898 if (!this.ExistCurrentPost)
10900 this.CopySTOTMenuItem.Enabled = false;
10901 this.CopyURLMenuItem.Enabled = false;
10902 this.CopyUserIdStripMenuItem.Enabled = false;
10906 this.CopySTOTMenuItem.Enabled = true;
10907 this.CopyURLMenuItem.Enabled = true;
10908 this.CopyUserIdStripMenuItem.Enabled = true;
10910 var post = this.CurrentPost;
10911 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10912 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10916 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10917 => this.SetNotifyIconText();
10919 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10920 => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10922 private async Task doShowUserStatus(string id, bool ShowInputDialog)
10924 TwitterUser user = null;
10926 if (ShowInputDialog)
10928 using var inputName = new InputTabName();
10929 inputName.FormTitle = "Show UserStatus";
10930 inputName.FormDescription = Properties.Resources.FRMessage1;
10931 inputName.TabName = id;
10933 if (inputName.ShowDialog(this) != DialogResult.OK)
10935 if (string.IsNullOrWhiteSpace(inputName.TabName))
10938 id = inputName.TabName.Trim();
10941 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10943 var cancellationToken = dialog.EnableCancellation();
10947 var task = this.twitterApi.UsersShow(id);
10948 user = await dialog.WaitForAsync(this, task);
10950 catch (WebApiException ex)
10952 if (!cancellationToken.IsCancellationRequested)
10953 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10957 if (cancellationToken.IsCancellationRequested)
10961 await this.doShowUserStatus(user);
10964 private async Task doShowUserStatus(TwitterUser user)
10966 using var userDialog = new UserInfoDialog(this, this.twitterApi);
10967 var showUserTask = userDialog.ShowUserAsync(user);
10968 userDialog.ShowDialog(this);
10971 this.BringToFront();
10973 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10974 await showUserTask;
10977 internal Task ShowUserStatus(string id, bool ShowInputDialog)
10978 => this.doShowUserStatus(id, ShowInputDialog);
10980 internal Task ShowUserStatus(string id)
10981 => this.doShowUserStatus(id, true);
10983 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10985 var post = this.CurrentPost;
10988 await this.ShowUserStatus(post.ScreenName, false);
10992 private async void RtCountMenuItem_Click(object sender, EventArgs e)
10994 if (!this.ExistCurrentPost)
10997 var post = this.CurrentPost;
10998 var statusId = post.RetweetedId ?? post.StatusId;
10999 TwitterStatus status;
11001 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11003 var cancellationToken = dialog.EnableCancellation();
11007 var task = this.twitterApi.StatusesShow(statusId);
11008 status = await dialog.WaitForAsync(this, task);
11010 catch (WebApiException ex)
11012 if (!cancellationToken.IsCancellationRequested)
11013 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11017 if (cancellationToken.IsCancellationRequested)
11021 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11024 private readonly HookGlobalHotkey _hookGlobalHotkey;
11027 _hookGlobalHotkey = new HookGlobalHotkey(this);
11029 // この呼び出しは、Windows フォーム デザイナで必要です。
11030 InitializeComponent();
11032 // InitializeComponent() 呼び出しの後で初期化を追加します。
11034 if (!this.DesignMode)
11036 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11037 this.StatusText.Dock = DockStyle.Fill;
11040 this.tweetDetailsView.Owner = this;
11042 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11043 this.gh.NotifyClicked += GrowlHelper_Callback;
11045 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11046 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11048 this.ImageSelector.Visible = false;
11049 this.ImageSelector.Enabled = false;
11050 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11052 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11054 this.ReplaceAppName();
11055 this.InitializeShortcuts();
11058 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11060 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11063 this.Visible = false;
11065 else if (Form.ActiveForm == null)
11067 this.Visible = true;
11068 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11070 this.BringToFront();
11071 this.StatusText.Focus();
11075 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11076 => this.MultiLinePullDownMenuItem.PerformClick();
11079 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11081 if (ImageSelector.Visible)
11082 ImageSelector.EndSelection();
11084 ImageSelector.BeginSelection();
11087 private void SelectMedia_DragEnter(DragEventArgs e)
11089 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11091 e.Effect = DragDropEffects.Copy;
11094 e.Effect = DragDropEffects.None;
11097 private void SelectMedia_DragDrop(DragEventArgs e)
11100 this.BringToFront();
11101 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11102 StatusText.Focus();
11105 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11107 TimelinePanel.Visible = false;
11108 TimelinePanel.Enabled = false;
11111 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11113 TimelinePanel.Visible = true;
11114 TimelinePanel.Enabled = true;
11115 this.CurrentListView.Focus();
11118 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11119 => this.AllowDrop = false;
11121 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11122 => this.AllowDrop = true;
11124 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11126 if (ImageSelector.Visible)
11128 this.MarkSettingCommonModified();
11129 this.StatusText_TextChanged(null, null);
11133 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11134 => this.StatusText_TextChanged(null, null);
11137 /// StatusTextでCtrl+Vが押下された時の処理
11139 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11143 if (Clipboard.ContainsText())
11145 // clipboardにテキストがある場合は貼り付け処理
11146 this.StatusText.Paste(Clipboard.GetText());
11148 else if (Clipboard.ContainsImage())
11151 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11152 Properties.Resources.PostPictureWarn4,
11153 MessageBoxButtons.OKCancel,
11154 MessageBoxIcon.Question,
11155 MessageBoxDefaultButton.Button2)
11156 == DialogResult.OK)
11158 // clipboardから画像を取得
11159 using var image = Clipboard.GetImage();
11160 this.ImageSelector.BeginSelection(image);
11164 catch (ExternalException ex)
11166 MessageBox.Show(ex.Message);
11171 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11173 using var form = new ListManage(tw);
11174 form.ShowDialog(this);
11177 private bool ModifySettingCommon { get; set; }
11178 private bool ModifySettingLocal { get; set; }
11179 private bool ModifySettingAtId { get; set; }
11181 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11183 var post = this.CurrentPost;
11184 if (this.ExistCurrentPost && !post.IsDm)
11185 RtCountMenuItem.Enabled = true;
11187 RtCountMenuItem.Enabled = false;
11189 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11190 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11192 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11195 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11196 => this.CopyUserId();
11198 private void CopyUserId()
11200 var post = this.CurrentPost;
11201 if (post == null) return;
11202 var clstr = post.ScreenName;
11205 Clipboard.SetDataObject(clstr, false, 5, 100);
11207 catch (Exception ex)
11209 MessageBox.Show(ex.Message);
11213 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11215 var post = this.CurrentPost;
11216 if (this.ExistCurrentPost && !post.IsDm)
11220 await this.OpenRelatedTab(post);
11222 catch (TabException ex)
11224 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11230 /// 指定されたツイートに対する関連発言タブを開きます
11232 /// <param name="statusId">表示するツイートのID</param>
11233 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11234 public async Task OpenRelatedTab(long statusId)
11236 var post = this._statuses[statusId];
11241 post = await this.tw.GetStatusApi(false, statusId);
11243 catch (WebApiException ex)
11245 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11250 await this.OpenRelatedTab(post);
11254 /// 指定されたツイートに対する関連発言タブを開きます
11256 /// <param name="post">表示する対象となるツイート</param>
11257 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11258 private async Task OpenRelatedTab(PostClass post)
11260 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11261 if (tabRelated != null)
11263 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11266 var tabName = this._statuses.MakeTabName("Related Tweets");
11268 tabRelated = new RelatedPostsTabModel(tabName, post)
11270 UnreadManage = false,
11274 this._statuses.AddTab(tabRelated);
11275 this.AddNewTab(tabRelated, startup: false);
11277 this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11279 await this.RefreshTabAsync(tabRelated);
11281 var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11283 if (tabIndex != -1)
11285 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11287 var tabPage = this.ListTab.TabPages[tabIndex];
11288 var listView = (DetailsListView)tabPage.Tag;
11289 var targetPost = tabRelated.TargetPost;
11290 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11292 if (index != -1 && index < listView.Items.Count)
11294 listView.SelectedIndices.Add(index);
11295 listView.Items[index].Focused = true;
11300 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11302 var buf = new StringBuilder();
11303 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11304 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11305 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11306 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11307 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11310 #region "Userstream"
11311 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11315 if (InvokeRequired && !IsDisposed)
11317 await this.InvokeAsync(() =>
11319 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11320 if (this.CurrentTab.Contains(e.StatusId))
11322 this.PurgeListViewItemCache();
11323 this.CurrentListView.Update();
11324 var post = this.CurrentPost;
11325 if (post != null && post.StatusId == e.StatusId)
11326 this.DispSelectedPost(true);
11332 catch (ObjectDisposedException)
11336 catch (InvalidOperationException)
11342 private void tw_NewPostFromStream(object sender, EventArgs e)
11344 if (SettingManager.Common.ReadOldPosts)
11346 _statuses.SetReadHomeTab(); //新着時未読クリア
11349 this._statuses.DistributePosts();
11351 this.RefreshThrottlingTimer.Call();
11354 private async void tw_UserStreamStarted(object sender, EventArgs e)
11358 if (InvokeRequired && !IsDisposed)
11360 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11364 catch (ObjectDisposedException)
11368 catch (InvalidOperationException)
11373 this.RefreshUserStreamsMenu();
11374 this.MenuItemUserStream.Enabled = true;
11376 StatusLabel.Text = "UserStream Started.";
11379 private async void tw_UserStreamStopped(object sender, EventArgs e)
11383 if (InvokeRequired && !IsDisposed)
11385 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11389 catch (ObjectDisposedException)
11393 catch (InvalidOperationException)
11398 this.RefreshUserStreamsMenu();
11399 this.MenuItemUserStream.Enabled = true;
11401 StatusLabel.Text = "UserStream Stopped.";
11404 private void RefreshUserStreamsMenu()
11406 if (this.tw.UserStreamActive)
11408 this.MenuItemUserStream.Text = "&UserStream ▶";
11409 this.StopToolStripMenuItem.Text = "&Stop";
11413 this.MenuItemUserStream.Text = "&UserStream ■";
11414 this.StopToolStripMenuItem.Text = "&Start";
11418 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11422 if (InvokeRequired && !IsDisposed)
11424 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11428 catch (ObjectDisposedException)
11432 catch (InvalidOperationException)
11436 var ev = e.EventData;
11437 StatusLabel.Text = "Event: " + ev.Event;
11438 //if (ev.Event == "favorite")
11440 // NotifyFavorite(ev);
11443 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11445 if (this.CurrentTab.Contains(ev.Id))
11447 this.PurgeListViewItemCache();
11448 this.CurrentListView.Update();
11450 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11452 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11453 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11458 private void NotifyEvent(Twitter.FormattedEvent ev)
11461 if (BalloonRequired(ev))
11463 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11464 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11465 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11466 var title = new StringBuilder();
11467 if (SettingManager.Common.DispUsername)
11469 title.Append(tw.Username);
11470 title.Append(" - ");
11476 title.Append(ApplicationSettings.ApplicationName);
11477 title.Append(" [");
11478 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11479 title.Append("] by ");
11480 if (!string.IsNullOrEmpty(ev.Username))
11482 title.Append(ev.Username);
11486 //title.Append("");
11489 if (!string.IsNullOrEmpty(ev.Target))
11491 //NotifyIcon1.BalloonTipText = ev.Target;
11496 //NotifyIcon1.BalloonTipText = " ";
11499 //NotifyIcon1.ShowBalloonTip(500);
11500 if (SettingManager.Common.IsUseNotifyGrowl)
11502 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11503 ev.Id.ToString(), title.ToString(), text);
11507 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11508 NotifyIcon1.BalloonTipTitle = title.ToString();
11509 NotifyIcon1.BalloonTipText = text;
11510 NotifyIcon1.ShowBalloonTip(500);
11515 var snd = SettingManager.Common.EventSoundFile;
11516 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11518 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11522 var dir = Application.StartupPath;
11523 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11525 dir = Path.Combine(dir, "Sounds");
11527 using var player = new SoundPlayer(Path.Combine(dir, snd));
11537 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11539 MenuItemUserStream.Enabled = false;
11540 if (StopRefreshAllMenuItem.Checked)
11542 StopRefreshAllMenuItem.Checked = false;
11545 if (this.tw.UserStreamActive)
11547 tw.StopUserStream();
11551 tw.StartUserStream();
11555 private static string inputTrack = "";
11557 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11559 if (TrackToolStripMenuItem.Checked)
11561 using (var inputForm = new InputTabName())
11563 inputForm.TabName = inputTrack;
11564 inputForm.FormTitle = "Input track word";
11565 inputForm.FormDescription = "Track word";
11566 if (inputForm.ShowDialog() != DialogResult.OK)
11568 TrackToolStripMenuItem.Checked = false;
11571 inputTrack = inputForm.TabName.Trim();
11573 if (!inputTrack.Equals(tw.TrackWord))
11575 tw.TrackWord = inputTrack;
11576 this.MarkSettingCommonModified();
11577 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11578 tw.ReconnectUserStream();
11584 tw.ReconnectUserStream();
11586 this.MarkSettingCommonModified();
11589 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11591 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11592 this.MarkSettingCommonModified();
11593 tw.ReconnectUserStream();
11596 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11598 if (evtDialog == null || evtDialog.IsDisposed)
11600 this.evtDialog = new EventViewerDialog
11606 this.evtDialog.Location = new Point
11608 X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11609 Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11612 evtDialog.EventSource = tw.StoredEvent;
11613 if (!evtDialog.Visible)
11615 evtDialog.Show(this);
11619 evtDialog.Activate();
11621 this.TopMost = SettingManager.Common.AlwaysTop;
11625 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11627 MyCommon._endingFlag = true;
11631 Application.Restart();
11635 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11639 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11640 => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11642 private bool ExistCurrentPost
11646 var post = this.CurrentPost;
11647 return post != null && !post.IsDeleted;
11651 private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11652 => await this.ShowUserTimeline();
11654 private string GetUserIdFromCurPostOrInput(string caption)
11656 var id = this.CurrentPost?.ScreenName ?? "";
11658 using var inputName = new InputTabName();
11659 inputName.FormTitle = caption;
11660 inputName.FormDescription = Properties.Resources.FRMessage1;
11661 inputName.TabName = id;
11663 if (inputName.ShowDialog() == DialogResult.OK &&
11664 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11666 id = inputName.TabName.Trim();
11675 private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11677 var id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11678 if (!string.IsNullOrEmpty(id))
11680 await this.AddNewTabForUserTimeline(id);
11684 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11686 if (e.Mode == Microsoft.Win32.PowerModes.Resume)
11687 this.timelineScheduler.SystemResumed();
11690 private void SystemEvents_TimeChanged(object sender, EventArgs e)
11692 var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11694 TimeZoneInfo.ClearCachedData();
11696 var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11698 if (curTimeOffset != prevTimeOffset)
11701 this.PurgeListViewItemCache();
11702 this.CurrentListView.Refresh();
11704 this.DispSelectedPost(forceupdate: true);
11708 private void TimelineRefreshEnableChange(bool isEnable)
11712 tw.StartUserStream();
11716 tw.StopUserStream();
11718 this.timelineScheduler.Enabled = isEnable;
11721 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11722 => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11724 private async Task OpenUserAppointUrl()
11726 if (SettingManager.Common.UserAppointUrl != null)
11728 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11730 var post = this.CurrentPost;
11733 var xUrl = SettingManager.Common.UserAppointUrl;
11734 xUrl = xUrl.Replace("{ID}", post.ScreenName);
11736 var statusId = post.RetweetedId ?? post.StatusId;
11737 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11739 await this.OpenUriInBrowserAsync(xUrl);
11744 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11749 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11750 => await this.OpenUserAppointUrl();
11752 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11754 if (Form.ActiveForm == null)
11756 await this.InvokeAsync(() =>
11758 this.Visible = true;
11759 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11761 this.BringToFront();
11762 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11764 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11768 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11774 private void ReplaceAppName()
11776 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11777 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11780 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11781 => this.SplitContainer3.Panel2Collapsed = false;
11783 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11784 => await this.OpenThumbnailPicture(e.Thumbnail);
11786 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11787 => await this.OpenUriInBrowserAsync(e.ImageUrl);
11789 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11791 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11793 await this.OpenUriInBrowserAsync(url);
11796 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11797 => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11799 private void PostButton_KeyDown(object sender, KeyEventArgs e)
11801 if (e.KeyCode == Keys.Space)
11803 this.JumpUnreadMenuItem_Click(null, null);
11805 e.SuppressKeyPress = true;
11809 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11811 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11812 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11813 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11814 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11815 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11817 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11820 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11821 => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11823 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11824 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11826 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11827 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11829 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11830 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11832 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11833 => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11835 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11837 if (SettingManager.Common.IconSize == iconSize) return;
11839 var oldIconCol = _iconCol;
11841 SettingManager.Common.IconSize = iconSize;
11842 ApplyListViewIconSize(iconSize);
11844 if (_iconCol != oldIconCol)
11846 foreach (TabPage tp in ListTab.TabPages)
11848 ResetColumns((DetailsListView)tp.Tag);
11852 this.CurrentListView.Refresh();
11853 this.MarkSettingCommonModified();
11856 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11858 var state = this.LockListSortOrderToolStripMenuItem.Checked;
11859 if (SettingManager.Common.SortOrderLock == state) return;
11861 SettingManager.Common.SortOrderLock = state;
11862 this.MarkSettingCommonModified();
11865 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11867 if (!string.IsNullOrEmpty(e.StatusText))
11869 this.StatusLabelUrl.Text = e.StatusText;
11873 this.SetStatusLabelUrl();