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
63 private Size _mySize; //画面サイズ
64 private Point _myLoc; //画面位置
65 private int _mySpDis; //区切り位置
66 private int _mySpDis2; //発言欄区切り位置
67 private int _mySpDis3; //プレビュー区切り位置
68 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69 private bool _iconCol; //1列表示の時true(48サイズのとき)
72 private bool _initial; //true:起動時処理中
73 private bool _initialLayout = true;
74 private bool _ignoreConfigSave; //true:起動時処理中
75 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77 private Point _tabMouseDownPoint;
78 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
79 private readonly object _syncObject = new object(); //ロック用
81 private const string detailHtmlFormatHeaderMono =
82 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83 + "<style type=\"text/css\"><!-- "
84 + "body, p, pre {margin: 0;} "
85 + "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%);} "
86 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89 + ".quote-tweet.reply {border-color: #f33;} "
90 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
92 + "</head><body><pre>";
93 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94 private const string detailHtmlFormatHeaderColor =
95 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96 + "<style type=\"text/css\"><!-- "
97 + "body, p, pre {margin: 0;} "
98 + "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%);} "
99 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
105 + "</head><body><p>";
106 private const string detailHtmlFormatFooterColor = "</p></body></html>";
107 private string detailHtmlFormatHeader;
108 private string detailHtmlFormatFooter;
110 private bool _myStatusError = false;
111 private bool _myStatusOnline = false;
112 private bool soundfileListup = false;
113 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
116 private TwitterApi twitterApi = new TwitterApi();
120 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
124 private OpenURL UrlDialog = new OpenURL();
125 public AtIdSupplement AtIdSupl; //@id補助
126 public AtIdSupplement HashSupl; //Hashtag補助
127 public HashtagManage HashMgr;
128 private EventViewerDialog evtDialog;
131 private Font _fntUnread; //未読用フォント
132 private Color _clUnread; //未読用文字色
133 private Font _fntReaded; //既読用フォント
134 private Color _clReaded; //既読用文字色
135 private Color _clFav; //Fav用文字色
136 private Color _clOWL; //片思い用文字色
137 private Color _clRetweet; //Retweet用文字色
138 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
139 private Font _fntDetail; //発言詳細部用フォント
140 private Color _clDetail; //発言詳細部用色
141 private Color _clDetailLink; //発言詳細部用リンク文字色
142 private Color _clDetailBackcolor; //発言詳細部用背景色
143 private Color _clSelf; //自分の発言用背景色
144 private Color _clAtSelf; //自分宛返信用背景色
145 private Color _clTarget; //選択発言者の他の発言用背景色
146 private Color _clAtTarget; //選択発言中の返信先用背景色
147 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
148 private Color _clAtTo; //選択発言の唯一@先
149 private Color _clListBackcolor; //リスト部通常発言背景色
150 private Color _clInputBackcolor; //入力欄背景色
151 private Color _clInputFont; //入力欄文字色
152 private Font _fntInputFont; //入力欄フォント
153 private ImageCache IconCache; //アイコン画像リスト
154 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
155 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
156 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
157 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
158 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
159 private Icon MainIcon; //Main.ico 画面左上のアイコン
160 private Icon ReplyIcon; //5g
161 private Icon ReplyIconBlink; //6g
163 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
165 private PostClass _anchorPost;
166 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
168 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
169 private int _hisIdx; //発言履歴カレントインデックス
171 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
172 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175 private List<DateTime> _postTimestamps = new List<DateTime>();
176 private List<DateTime> _favTimestamps = new List<DateTime>();
179 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
180 private SolidBrush _brsBackColorMine;
181 private SolidBrush _brsBackColorAt;
182 private SolidBrush _brsBackColorYou;
183 private SolidBrush _brsBackColorAtYou;
184 private SolidBrush _brsBackColorAtFromTarget;
185 private SolidBrush _brsBackColorAtTo;
186 private SolidBrush _brsBackColorNone;
187 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
188 private StringFormat sfTab = new StringFormat();
190 //////////////////////////////////////////////////////////////////////////////////////////////////////////
191 private TabInformations _statuses;
194 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
197 /// キャッシュクリアのために null が代入されることがあるため、
198 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
199 /// 一旦ローカル変数に代入してから参照すること。
201 private ListViewItemCache _listItemCache = null;
203 internal class ListViewItemCache
205 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
206 public ListView TargetList { get; set; }
208 /// <summary>キャッシュする範囲の開始インデックス</summary>
209 public int StartIndex { get; set; }
211 /// <summary>キャッシュする範囲の終了インデックス</summary>
212 public int EndIndex { get; set; }
214 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
215 public ListViewItem[] ListItem { get; set; }
217 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
218 public PostClass[] Post { get; set; }
220 /// <summary>キャッシュされたアイテムの件数</summary>
222 => this.EndIndex - this.StartIndex + 1;
224 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
225 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
226 public bool Contains(int index)
227 => index >= this.StartIndex && index <= this.EndIndex;
229 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool IsSupersetOf(int rangeStart, int rangeEnd)
232 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
234 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
235 /// <returns>取得に成功すれば true、それ以外は false</returns>
236 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
238 if (this.Contains(index))
240 item = this.ListItem[index - this.StartIndex];
241 post = this.Post[index - this.StartIndex];
253 private TabPage _curTab;
254 private int _curItemIndex;
255 private DetailsListView _curList;
256 private PostClass _curPost;
257 private bool _isColumnChanged = false;
259 private const int MAX_WORKER_THREADS = 20;
260 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
261 private CancellationTokenSource workerCts = new CancellationTokenSource();
262 private IProgress<string> workerProgress;
264 private int UnreadCounter = -1;
265 private int UnreadAtCounter = -1;
267 private string[] ColumnOrgText = new string[9];
268 private string[] ColumnText = new string[9];
270 private bool _DoFavRetweetFlags = false;
271 private bool osResumed = false;
273 //////////////////////////////////////////////////////////////////////////////////////////////////////////
274 private bool _colorize = false;
276 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
278 private string recommendedStatusFooter;
281 private struct urlUndo
283 public string Before;
287 private List<urlUndo> urlUndoBuffer = null;
289 private struct ReplyChain
291 public long OriginalId;
292 public long InReplyToId;
293 public TabPage OriginalTab;
295 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
297 this.OriginalId = originalId;
298 this.InReplyToId = inReplyToId;
299 this.OriginalTab = originalTab;
303 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
304 private Stack<ValueTuple<TabPage, PostClass>> selectPostChains = new Stack<ValueTuple<TabPage, PostClass>>(); //ポスト選択履歴
307 internal enum SEARCHTYPE
314 private class PostingStatus
316 public string status = "";
317 public long? inReplyToId = null;
318 public string inReplyToName = null;
319 public string imageService = ""; //画像投稿サービス名
320 public IMediaItem[] mediaItems = null;
321 public PostingStatus()
324 public PostingStatus(string status, long? replyToId, string replyToName)
326 this.status = status;
327 this.inReplyToId = replyToId;
328 this.inReplyToName = replyToName;
332 private void TweenMain_Activated(object sender, EventArgs e)
334 //画面がアクティブになったら、発言欄の背景色戻す
335 if (StatusText.Focused)
337 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
341 private bool disposed = false;
344 /// 使用中のリソースをすべてクリーンアップします。
346 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
347 protected override void Dispose(bool disposing)
349 base.Dispose(disposing);
356 this.components?.Dispose();
359 SearchDialog.Dispose();
362 NIconAtRed?.Dispose();
363 NIconAtSmoke?.Dispose();
364 foreach (var iconRefresh in this.NIconRefresh)
366 iconRefresh?.Dispose();
370 ReplyIcon?.Dispose();
371 ReplyIconBlink?.Dispose();
372 _listViewImageList.Dispose();
373 _brsHighLight.Dispose();
374 _brsBackColorMine?.Dispose();
375 _brsBackColorAt?.Dispose();
376 _brsBackColorYou?.Dispose();
377 _brsBackColorAtYou?.Dispose();
378 _brsBackColorAtFromTarget?.Dispose();
379 _brsBackColorAtTo?.Dispose();
380 _brsBackColorNone?.Dispose();
381 _brsDeactiveSelection?.Dispose();
385 this.workerCts.Cancel();
387 if (IconCache != null)
389 this.IconCache.CancelAsync();
390 this.IconCache.Dispose();
393 this.thumbnailTokenSource?.Dispose();
396 this.twitterApi.Dispose();
397 this._hookGlobalHotkey.Dispose();
400 // 終了時にRemoveHandlerしておかないとメモリリークする
401 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
402 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
404 this.disposed = true;
407 private void LoadIcons()
409 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
410 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
413 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
416 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
419 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
422 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
424 // タスクトレイ: オフライン時アイコン
425 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
427 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
428 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
429 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
431 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
432 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
433 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
434 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
435 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
437 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
439 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
440 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
441 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
442 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
443 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
445 if (iconReply != null && iconReplyBlink != null)
447 this.ReplyIcon = iconReply;
448 this.ReplyIconBlink = iconReplyBlink;
452 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
453 this.ReplyIconBlink = this.NIconAt;
456 if (iconRefresh1 == null)
458 this.NIconRefresh = new[] {
459 Properties.Resources.Refresh, Properties.Resources.Refresh2,
460 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
463 else if (iconRefresh2 == null)
465 this.NIconRefresh = new[] { iconRefresh1 };
467 else if (iconRefresh3 == null)
469 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
471 else if (iconRefresh4 == null)
473 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
475 else // iconRefresh1 から iconRefresh4 まで全て揃っている
477 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
481 private Icon LoadIcon(string filePath)
483 if (!File.Exists(filePath))
488 return new Icon(filePath);
496 private void InitColumns(ListView list, bool startup)
498 this.InitColumnText();
500 ColumnHeader[] columns = null;
507 new ColumnHeader(), // アイコン
508 new ColumnHeader(), // 本文
511 columns[0].Text = this.ColumnText[0];
512 columns[1].Text = this.ColumnText[2];
516 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
518 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
519 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
520 columns[0].DisplayIndex = 0;
521 columns[1].DisplayIndex = 1;
526 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
528 columns[idx].Width = curListColumn.Width;
529 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
538 new ColumnHeader(), // アイコン
539 new ColumnHeader(), // ニックネーム
540 new ColumnHeader(), // 本文
541 new ColumnHeader(), // 日付
542 new ColumnHeader(), // ユーザID
543 new ColumnHeader(), // 未読
544 new ColumnHeader(), // マーク&プロテクト
545 new ColumnHeader(), // ソース
548 foreach (var i in Enumerable.Range(0, columns.Length))
549 columns[i].Text = this.ColumnText[i];
553 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
555 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
556 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
557 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
558 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
559 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
560 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
561 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
562 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
564 var displayIndex = new[] {
565 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
566 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
567 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
568 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
571 foreach (var i in Enumerable.Range(0, displayIndex.Length))
573 columns[i].DisplayIndex = displayIndex[i];
579 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
581 columns[idx].Width = curListColumn.Width;
582 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
588 list.Columns.AddRange(columns);
596 foreach (var column in columns)
602 private void InitColumnText()
605 ColumnText[1] = Properties.Resources.AddNewTabText2;
606 ColumnText[2] = Properties.Resources.AddNewTabText3;
607 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
608 ColumnText[4] = Properties.Resources.AddNewTabText5;
611 ColumnText[7] = "Source";
613 ColumnOrgText[0] = "";
614 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
615 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
616 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
617 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
618 ColumnOrgText[5] = "";
619 ColumnOrgText[6] = "";
620 ColumnOrgText[7] = "Source";
623 switch (_statuses.SortMode)
625 case ComparerMode.Nickname: //ニックネーム
628 case ComparerMode.Data: //本文
631 case ComparerMode.Id: //時刻=発言Id
634 case ComparerMode.Name: //名前
637 case ComparerMode.Source: //Source
644 if (_statuses.SortOrder == SortOrder.Descending)
646 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
647 ColumnText[2] = ColumnOrgText[2] + "▾";
651 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
652 ColumnText[2] = ColumnOrgText[2] + "▴";
657 if (_statuses.SortOrder == SortOrder.Descending)
659 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
660 ColumnText[c] = ColumnOrgText[c] + "▾";
664 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
665 ColumnText[c] = ColumnOrgText[c] + "▴";
670 private void InitializeTraceFrag()
673 TraceOutToolStripMenuItem.Checked = true;
674 MyCommon.TraceFlag = true;
676 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
678 TraceOutToolStripMenuItem.Checked = true;
679 MyCommon.TraceFlag = true;
683 private void TweenMain_Load(object sender, EventArgs e)
685 _ignoreConfigSave = true;
686 this.Visible = false;
688 if (MyApplication.StartupOptions.ContainsKey("d"))
689 MyCommon.TraceFlag = true;
691 InitializeTraceFrag();
693 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
695 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
696 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
698 Regex.CacheSize = 100;
701 _statuses = TabInformations.GetInstance();
705 this.Icon = MainIcon; //メインフォーム(TweenMain)
706 NotifyIcon1.Icon = NIconAt; //タスクトレイ
707 TabImage.Images.Add(TabIcon); //タブ見出し
709 //<<<<<<<<<設定関連>>>>>>>>>
713 // 現在の DPI と設定保存時の DPI との比を取得する
714 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
717 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
718 if (fontUIGlobal != null)
720 OTBaseForm.GlobalFont = fontUIGlobal;
721 this.Font = fontUIGlobal;
725 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
727 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
728 SettingManager.Common.TimelinePeriod = 15;
730 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
731 SettingManager.Common.ReplyPeriod = 15;
733 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
734 SettingManager.Common.DMPeriod = 15;
736 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
737 SettingManager.Common.PubSearchPeriod = 30;
739 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
740 SettingManager.Common.UserTimelinePeriod = 15;
742 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
743 SettingManager.Common.ListsPeriod = 15;
746 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
747 SettingManager.Common.CountApi = 60;
748 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
749 SettingManager.Common.CountApiReply = 40;
751 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
752 SettingManager.Common.MoreCountApi = 200;
753 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
754 SettingManager.Common.FirstCountApi = 100;
756 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
757 SettingManager.Common.FavoritesCountApi = 40;
758 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
759 SettingManager.Common.ListCountApi = 100;
760 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
761 SettingManager.Common.SearchCountApi = 100;
762 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
763 SettingManager.Common.UserTimelineCountApi = 20;
765 //廃止サービスが選択されていた場合ux.nuへ読み替え
766 if (SettingManager.Common.AutoShortUrlFirst < 0)
767 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
769 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
770 this.tw = new Twitter(this.twitterApi);
773 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
774 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
778 Networking.Initialize();
780 bool saveRequired = false;
781 bool firstRun = false;
783 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
784 if (string.IsNullOrEmpty(tw.Username))
789 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
790 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
791 string.IsNullOrEmpty(tw.Username))
793 Application.Exit(); //強制終了
799 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
800 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
801 Networking.SetWebProxy(SettingManager.Local.ProxyType,
802 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
803 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
804 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
806 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
807 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
808 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
809 tw.TrackWord = SettingManager.Common.TrackWord;
810 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
811 tw.AllAtReply = SettingManager.Common.AllAtReply;
812 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
813 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
814 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
815 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
816 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
818 // アクセストークンが有効であるか確認する
819 // ここが Twitter API への最初のアクセスになるようにすること
822 this.tw.VerifyCredentials();
824 catch (WebApiException ex)
826 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
827 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
831 //プロキシ設定等の通信まわりの初期化が済んでから処理する
832 ThumbnailGenerator.InitializeGenerator();
834 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
835 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
836 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
838 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
841 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
844 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
845 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
846 HashMgr = new HashtagManage(HashSupl,
847 SettingManager.Common.HashTags.ToArray(),
848 SettingManager.Common.HashSelected,
849 SettingManager.Common.HashIsPermanent,
850 SettingManager.Common.HashIsHead,
851 SettingManager.Common.HashIsNotAddToAtReply);
852 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
855 this.IconCache = new ImageCache();
856 this.tweetDetailsView.IconCache = this.IconCache;
859 _fntUnread = SettingManager.Local.FontUnread;
860 _clUnread = SettingManager.Local.ColorUnread;
861 _fntReaded = SettingManager.Local.FontRead;
862 _clReaded = SettingManager.Local.ColorRead;
863 _clFav = SettingManager.Local.ColorFav;
864 _clOWL = SettingManager.Local.ColorOWL;
865 _clRetweet = SettingManager.Local.ColorRetweet;
866 _fntDetail = SettingManager.Local.FontDetail;
867 _clDetail = SettingManager.Local.ColorDetail;
868 _clDetailLink = SettingManager.Local.ColorDetailLink;
869 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
870 _clSelf = SettingManager.Local.ColorSelf;
871 _clAtSelf = SettingManager.Local.ColorAtSelf;
872 _clTarget = SettingManager.Local.ColorTarget;
873 _clAtTarget = SettingManager.Local.ColorAtTarget;
874 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
875 _clAtTo = SettingManager.Local.ColorAtTo;
876 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
877 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
878 _clInputFont = SettingManager.Local.ColorInputFont;
879 _fntInputFont = SettingManager.Local.FontInputFont;
881 _brsBackColorMine = new SolidBrush(_clSelf);
882 _brsBackColorAt = new SolidBrush(_clAtSelf);
883 _brsBackColorYou = new SolidBrush(_clTarget);
884 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
885 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
886 _brsBackColorAtTo = new SolidBrush(_clAtTo);
887 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
888 _brsBackColorNone = new SolidBrush(_clListBackcolor);
890 // StringFormatオブジェクトへの事前設定
891 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
892 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
893 //sf.FormatFlags = StringFormatFlags.LineLimit; //
894 sfTab.Alignment = StringAlignment.Center;
895 sfTab.LineAlignment = StringAlignment.Center;
897 InitDetailHtmlFormat();
899 //Regex statregex = new Regex("^0*");
900 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
902 _history.Add(new PostingStatus());
904 this.inReplyTo = null;
907 SearchDialog.Owner = this;
908 UrlDialog.Owner = this;
911 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
912 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
914 //新着取得時のリストスクロールをするか。trueならスクロールしない
915 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
916 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
918 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
919 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
921 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
922 this.ToolStripFocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
925 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
926 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
927 _myLoc = SettingManager.Local.FormLocation;
929 if (this.WindowState != FormWindowState.Minimized)
931 this.DesktopLocation = SettingManager.Local.FormLocation;
932 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
933 bool outOfScreen = true;
934 if (Screen.AllScreens.Length == 1) //ハングするとの報告
936 foreach (Screen scr in Screen.AllScreens)
938 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
946 this.DesktopLocation = new Point(0, 0);
947 _myLoc = this.DesktopLocation;
951 this.TopMost = SettingManager.Common.AlwaysTop;
952 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
953 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
954 if (SettingManager.Local.PreviewDistance == -1)
956 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
957 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
958 SettingManager.Local.PreviewDistance = _mySpDis3;
962 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
964 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
965 //this.Tween_ClientSizeChanged(this, null);
966 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
967 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
969 StatusText.Font = _fntInputFont;
970 StatusText.ForeColor = _clInputFont;
972 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
973 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
974 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
976 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
977 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
979 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
980 if (SettingManager.Common.UnreadManage == false)
982 ReadedStripMenuItem.Enabled = false;
983 UnreadStripMenuItem.Enabled = false;
986 //リンク先URL表示部の初期化(画面左下)
987 StatusLabelUrl.Text = "";
989 StatusLabel.Text = "";
990 StatusLabel.AutoToolTip = false;
991 StatusLabel.ToolTipText = "";
993 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
995 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
996 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
997 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
998 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1000 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1001 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1002 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1003 this.SplitContainer2.Panel2.AccessibleName = "";
1005 ////////////////////////////////////////////////////////////////////////////////
1006 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1007 var mode = ComparerMode.Id;
1008 switch (SettingManager.Common.SortColumn)
1010 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1014 mode = ComparerMode.Id; //Idソートに読み替え
1017 mode = ComparerMode.Nickname;
1020 mode = ComparerMode.Data;
1023 mode = ComparerMode.Id;
1026 mode = ComparerMode.Name;
1029 mode = ComparerMode.Source;
1032 _statuses.SetSortMode(mode, sortOrder);
1033 ////////////////////////////////////////////////////////////////////////////////
1035 ApplyListViewIconSize(SettingManager.Common.IconSize);
1037 //<<<<<<<<タブ関連>>>>>>>
1041 //デフォルトタブの存在チェック、ない場合には追加
1042 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1043 this._statuses.AddTab(new HomeTabModel());
1045 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1046 this._statuses.AddTab(new MentionsTabModel());
1048 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1049 this._statuses.AddTab(new DirectMessagesTabModel());
1051 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1052 this._statuses.AddTab(new FavoritesTabModel());
1054 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1055 this._statuses.AddTab(new MuteTabModel());
1057 foreach (var tab in _statuses.Tabs.Values)
1060 if (tab.TabType == MyCommon.TabUsageType.Mute)
1063 if (!AddNewTab(tab, startup: true))
1064 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1067 _curTab = ListTab.SelectedTab;
1069 _curList = (DetailsListView)_curTab.Tag;
1071 if (SettingManager.Common.TabIconDisp)
1073 ListTab.DrawMode = TabDrawMode.Normal;
1077 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1078 ListTab.DrawItem += ListTab_DrawItem;
1079 ListTab.ImageList = null;
1082 if (SettingManager.Common.HotkeyEnabled)
1085 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1086 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1087 modKey |= HookGlobalHotkey.ModKeys.Alt;
1088 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1089 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1090 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1091 modKey |= HookGlobalHotkey.ModKeys.Shift;
1092 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1093 modKey |= HookGlobalHotkey.ModKeys.Win;
1095 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1098 if (SettingManager.Common.IsUseNotifyGrowl)
1101 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1103 SetMainWindowTitle();
1104 SetNotifyIconText();
1106 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1108 this.Visible = true;
1112 TimerTimeline.AutoReset = true;
1113 TimerTimeline.SynchronizingObject = this;
1115 TimerTimeline.Interval = 1000;
1116 TimerTimeline.Enabled = true;
1118 TimerRefreshIcon.Interval = 200;
1119 TimerRefreshIcon.Enabled = true;
1121 _ignoreConfigSave = false;
1122 this.TweenMain_Resize(null, null);
1123 if (saveRequired) SaveConfigsAll(false);
1125 foreach (var ua in SettingManager.Common.UserAccounts)
1127 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1129 ua.UserId = tw.UserId;
1136 // 初回起動時だけ右下のメニューを目立たせる
1137 HashStripSplitButton.ShowDropDown();
1141 private void InitDetailHtmlFormat()
1143 if (SettingManager.Common.IsMonospace)
1145 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1146 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1150 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1151 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1154 detailHtmlFormatHeader = detailHtmlFormatHeader
1155 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1156 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1157 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1158 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1159 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1160 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1163 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1168 txt = ListTab.TabPages[e.Index].Text;
1175 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1176 if (e.State == DrawItemState.Selected)
1178 e.DrawFocusRectangle();
1183 if (_statuses.Tabs[txt].UnreadCount > 0)
1186 fore = System.Drawing.SystemBrushes.ControlText;
1190 fore = System.Drawing.SystemBrushes.ControlText;
1192 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1195 private void LoadConfig()
1197 SettingManager.Local = SettingManager.Local;
1199 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1200 if (SettingManager.Local.ScaleDimension.IsEmpty)
1201 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1203 var tabSettings = SettingManager.Tabs;
1204 foreach (var tabSetting in tabSettings.Tabs)
1207 switch (tabSetting.TabType)
1209 case MyCommon.TabUsageType.Home:
1210 tab = new HomeTabModel(tabSetting.TabName);
1212 case MyCommon.TabUsageType.Mentions:
1213 tab = new MentionsTabModel(tabSetting.TabName);
1215 case MyCommon.TabUsageType.DirectMessage:
1216 tab = new DirectMessagesTabModel(tabSetting.TabName);
1218 case MyCommon.TabUsageType.Favorites:
1219 tab = new FavoritesTabModel(tabSetting.TabName);
1221 case MyCommon.TabUsageType.UserDefined:
1222 tab = new FilterTabModel(tabSetting.TabName);
1224 case MyCommon.TabUsageType.UserTimeline:
1225 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1227 case MyCommon.TabUsageType.PublicSearch:
1228 tab = new PublicSearchTabModel(tabSetting.TabName)
1230 SearchWords = tabSetting.SearchWords,
1231 SearchLang = tabSetting.SearchLang,
1234 case MyCommon.TabUsageType.Lists:
1235 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1237 case MyCommon.TabUsageType.Mute:
1238 tab = new MuteTabModel(tabSetting.TabName);
1244 tab.UnreadManage = tabSetting.UnreadManage;
1245 tab.Protected = tabSetting.Protected;
1246 tab.Notify = tabSetting.Notify;
1247 tab.SoundFile = tabSetting.SoundFile;
1249 if (tab.IsDistributableTabType)
1251 var filterTab = (FilterTabModel)tab;
1252 filterTab.FilterArray = tabSetting.FilterArray;
1253 filterTab.FilterModified = false;
1256 if (this._statuses.ContainsTab(tab.TabName))
1257 tab.TabName = this._statuses.MakeTabName("MyTab");
1259 this._statuses.AddTab(tab);
1261 if (_statuses.Tabs.Count == 0)
1263 _statuses.AddTab(new HomeTabModel());
1264 _statuses.AddTab(new MentionsTabModel());
1265 _statuses.AddTab(new DirectMessagesTabModel());
1266 _statuses.AddTab(new FavoritesTabModel());
1270 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1272 if (!TimerTimeline.Enabled) return;
1276 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1278 private static int homeCounter = 0;
1279 private static int mentionCounter = 0;
1280 private static int dmCounter = 0;
1281 private static int pubSearchCounter = 0;
1282 private static int userTimelineCounter = 0;
1283 private static int listsCounter = 0;
1284 private static int usCounter = 0;
1285 private static int ResumeWait = 0;
1286 private static int refreshFollowers = 0;
1288 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1290 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1291 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1292 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1293 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1294 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1295 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1296 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1297 Interlocked.Increment(ref refreshFollowers);
1299 var refreshTasks = new List<Task>();
1302 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1304 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1305 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1306 refreshTasks.Add(this.GetHomeTimelineAsync());
1307 ResetTimers.Timeline = false;
1309 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1311 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1312 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1313 refreshTasks.Add(this.GetReplyAsync());
1314 ResetTimers.Reply = false;
1316 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1318 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1319 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1320 refreshTasks.Add(this.GetDirectMessagesAsync());
1321 ResetTimers.DirectMessage = false;
1323 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1325 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1326 if (!ResetTimers.PublicSearch)
1327 refreshTasks.Add(this.GetPublicSearchAllAsync());
1328 ResetTimers.PublicSearch = false;
1330 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1332 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1333 if (!ResetTimers.UserTimeline)
1334 refreshTasks.Add(this.GetUserTimelineAllAsync());
1335 ResetTimers.UserTimeline = false;
1337 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1339 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1340 if (!ResetTimers.Lists)
1341 refreshTasks.Add(this.GetListTimelineAllAsync());
1342 ResetTimers.Lists = false;
1344 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1346 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1347 if (this.tw.UserStreamActive)
1348 this.RefreshTimeline();
1349 ResetTimers.UserStream = false;
1351 if (refreshFollowers > 6 * 3600)
1353 Interlocked.Exchange(ref refreshFollowers, 0);
1354 refreshTasks.AddRange(new[]
1356 this.doGetFollowersMenu(),
1357 this.RefreshNoRetweetIdsAsync(),
1358 this.RefreshTwitterConfigurationAsync(),
1363 Interlocked.Increment(ref ResumeWait);
1364 if (ResumeWait > 30)
1367 Interlocked.Exchange(ref ResumeWait, 0);
1368 refreshTasks.AddRange(new[]
1370 this.GetHomeTimelineAsync(),
1371 this.GetReplyAsync(),
1372 this.GetDirectMessagesAsync(),
1373 this.GetPublicSearchAllAsync(),
1374 this.GetUserTimelineAllAsync(),
1375 this.GetListTimelineAllAsync(),
1376 this.doGetFollowersMenu(),
1377 this.RefreshTwitterConfigurationAsync(),
1382 await Task.WhenAll(refreshTasks);
1385 private void RefreshTimeline()
1387 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1389 // 現在表示中のタブのスクロール位置を退避
1390 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1392 // 各タブのリスト上の選択位置などを退避
1393 var listSelections = this.SaveListViewSelection();
1397 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1398 out var newMentionOrDm, out var isDelete);
1400 if (MyCommon._endingFlag) return;
1403 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1405 var listView = (DetailsListView)tabPage.Tag;
1406 var tabModel = this._statuses.Tabs[tabPage.Text];
1408 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1410 using (ControlTransaction.Update(listView))
1412 if (listView == this._curList)
1413 this.PurgeListViewItemCache();
1418 listView.VirtualListSize = tabModel.AllCount;
1420 catch (NullReferenceException ex)
1422 // WinForms 内部で ListView.set_TopItem が発生させている例外
1423 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1424 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1428 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1435 if (SettingManager.Common.TabIconDisp)
1437 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1439 var tabModel = this._statuses.Tabs[tabPage.Text];
1440 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1441 tabPage.ImageIndex = 0; // 未読アイコン
1446 this.ListTab.Refresh();
1451 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1454 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1456 SetMainWindowTitle();
1457 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1459 HashSupl.AddRangeItem(tw.GetHashList());
1463 internal struct ListViewScroll
1465 public ScrollLockMode ScrollLockMode { get; set; }
1466 public long? TopItemStatusId { get; set; }
1469 internal enum ScrollLockMode
1471 /// <summary>固定しない</summary>
1474 /// <summary>最上部に固定する</summary>
1477 /// <summary>最下部に固定する</summary>
1480 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1485 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1487 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1489 var listScroll = new ListViewScroll
1491 ScrollLockMode = this.GetScrollLockMode(listView),
1494 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1496 var topItemIndex = listView.TopItem?.Index ?? -1;
1497 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1498 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1504 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1506 if (this._statuses.SortMode == ComparerMode.Id)
1508 if (this._statuses.SortOrder == SortOrder.Ascending)
1511 if (this.ListLockMenuItem.Checked)
1512 return ScrollLockMode.None;
1514 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1517 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1518 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1519 return ScrollLockMode.FixedToBottom;
1521 return ScrollLockMode.None;
1526 if (this.ListLockMenuItem.Checked)
1527 return ScrollLockMode.FixedToItem;
1529 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1530 var topItem = listView.TopItem;
1531 if (topItem == null || topItem.Index == 0)
1532 return ScrollLockMode.FixedToTop;
1534 return ScrollLockMode.FixedToItem;
1539 return ScrollLockMode.FixedToItem;
1543 internal struct ListViewSelection
1545 public long[] SelectedStatusIds { get; set; }
1546 public long? SelectionMarkStatusId { get; set; }
1547 public long? FocusedStatusId { get; set; }
1551 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1553 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1555 var listsDict = new Dictionary<string, ListViewSelection>();
1557 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1559 var listView = (DetailsListView)tabPage.Tag;
1560 var tab = _statuses.Tabs[tabPage.Text];
1562 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1569 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1571 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1573 if (listView.VirtualListSize == 0)
1575 return new ListViewSelection
1577 SelectedStatusIds = new long[0],
1578 SelectionMarkStatusId = null,
1579 FocusedStatusId = null,
1583 return new ListViewSelection
1585 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1586 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1587 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1591 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1593 var selectedIndices = listView.SelectedIndices;
1594 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1595 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1600 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1602 var index = listView.FocusedItem?.Index ?? -1;
1604 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1607 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1609 var index = listView.SelectionMark;
1611 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1615 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1617 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1619 if (listView.VirtualListSize == 0)
1622 switch (listScroll.ScrollLockMode)
1624 case ScrollLockMode.FixedToTop:
1625 listView.EnsureVisible(0);
1627 case ScrollLockMode.FixedToBottom:
1628 listView.EnsureVisible(listView.VirtualListSize - 1);
1630 case ScrollLockMode.FixedToItem:
1631 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1634 var topItem = listView.Items[topIndex];
1637 listView.TopItem = topItem;
1639 catch (NullReferenceException)
1641 listView.EnsureVisible(listView.VirtualListSize - 1);
1642 listView.EnsureVisible(topIndex);
1646 case ScrollLockMode.None:
1653 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1655 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1657 // status_id から ListView 上のインデックスに変換
1658 int[] selectedIndices = null;
1659 if (listSelection.SelectedStatusIds != null)
1660 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1662 var focusedIndex = -1;
1663 if (listSelection.FocusedStatusId != null)
1664 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1666 var selectionMarkIndex = -1;
1667 if (listSelection.SelectionMarkStatusId != null)
1668 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1670 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1673 private bool BalloonRequired()
1675 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1676 ev.Eventtype = MyCommon.EVENTTYPE.None;
1678 return BalloonRequired(ev);
1681 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1683 if (type == MyCommon.EVENTTYPE.None)
1686 if (!SettingManager.Common.EventNotifyEnabled)
1689 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1692 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1697 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1700 private bool BalloonRequired(Twitter.FormattedEvent ev)
1705 if (NativeMethods.IsScreenSaverRunning())
1709 if (!this.NewPostPopMenuItem.Checked)
1711 // 「新着通知が無効でもイベントを通知する」にも該当しない
1712 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1716 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1717 if (SettingManager.Common.LimitBalloon)
1719 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1723 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1726 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1728 if (SettingManager.Common.ReadOwnPost)
1730 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1735 if (BalloonRequired())
1737 if (notifyPosts != null && notifyPosts.Length > 0)
1739 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1740 if (SettingManager.Common.IsUseNotifyGrowl)
1742 StringBuilder sb = new StringBuilder();
1746 foreach (PostClass post in notifyPosts)
1748 if (!(notifyPosts.Length > 3))
1754 if (post.IsReply && !post.IsExcludeReply) reply = true;
1755 if (post.IsDm) dm = true;
1756 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1757 switch (SettingManager.Common.NameBalloon)
1759 case MyCommon.NameBalloonEnum.UserID:
1760 sb.Append(post.ScreenName).Append(" : ");
1762 case MyCommon.NameBalloonEnum.NickName:
1763 sb.Append(post.Nickname).Append(" : ");
1766 sb.Append(post.TextFromApi);
1767 if (notifyPosts.Length > 3)
1769 if (notifyPosts.Last() != post) continue;
1772 StringBuilder title = new StringBuilder();
1773 GrowlHelper.NotifyType nt;
1774 if (SettingManager.Common.DispUsername)
1776 title.Append(tw.Username);
1777 title.Append(" - ");
1785 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1786 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1787 title.Append(Application.ProductName);
1788 title.Append(" [DM] ");
1789 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1790 nt = GrowlHelper.NotifyType.DirectMessage;
1794 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1795 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1796 title.Append(Application.ProductName);
1797 title.Append(" [Reply!] ");
1798 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1799 nt = GrowlHelper.NotifyType.Reply;
1803 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1804 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1805 title.Append(Application.ProductName);
1807 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1808 nt = GrowlHelper.NotifyType.Notify;
1810 string bText = sb.ToString();
1811 if (string.IsNullOrEmpty(bText)) return;
1813 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1814 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1819 StringBuilder sb = new StringBuilder();
1822 foreach (PostClass post in notifyPosts)
1824 if (post.IsReply && !post.IsExcludeReply) reply = true;
1825 if (post.IsDm) dm = true;
1826 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1827 switch (SettingManager.Common.NameBalloon)
1829 case MyCommon.NameBalloonEnum.UserID:
1830 sb.Append(post.ScreenName).Append(" : ");
1832 case MyCommon.NameBalloonEnum.NickName:
1833 sb.Append(post.Nickname).Append(" : ");
1836 sb.Append(post.TextFromApi);
1839 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1840 StringBuilder title = new StringBuilder();
1842 if (SettingManager.Common.DispUsername)
1844 title.Append(tw.Username);
1845 title.Append(" - ");
1853 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1854 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1855 ntIcon = ToolTipIcon.Warning;
1856 title.Append(Application.ProductName);
1857 title.Append(" [DM] ");
1858 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1862 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1863 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1864 ntIcon = ToolTipIcon.Warning;
1865 title.Append(Application.ProductName);
1866 title.Append(" [Reply!] ");
1867 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1871 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1872 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1873 ntIcon = ToolTipIcon.Info;
1874 title.Append(Application.ProductName);
1876 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1878 string bText = sb.ToString();
1879 if (string.IsNullOrEmpty(bText)) return;
1880 //NotifyIcon1.BalloonTipText = sb.ToString();
1881 //NotifyIcon1.ShowBalloonTip(500);
1882 NotifyIcon1.BalloonTipTitle = title.ToString();
1883 NotifyIcon1.BalloonTipText = bText;
1884 NotifyIcon1.BalloonTipIcon = ntIcon;
1885 NotifyIcon1.ShowBalloonTip(500);
1891 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1895 string dir = Application.StartupPath;
1896 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1898 dir = Path.Combine(dir, "Sounds");
1900 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1910 //mentions新着時に画面ブリンク
1911 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1913 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1917 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1919 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1921 _curItemIndex = _curList.SelectedIndices[0];
1922 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1926 this._curPost = GetCurTabPost(_curItemIndex);
1928 catch (ArgumentException)
1933 this.PushSelectPostChain();
1935 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1937 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1943 private void ChangeCacheStyleRead(bool Read, int Index)
1945 var tabInfo = _statuses.Tabs[_curTab.Text];
1946 //Read:true=既読 false=未読
1947 //未読管理していなかったら既読として扱う
1948 if (!tabInfo.UnreadManage ||
1949 !SettingManager.Common.UnreadManage) Read = true;
1951 var listCache = this._listItemCache;
1952 if (listCache == null)
1955 // キャッシュに含まれていないアイテムは対象外
1956 if (!listCache.TryGetValue(Index, out var itm, out var post))
1959 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1962 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1969 Item.SubItems[5].Text = "";
1974 Item.SubItems[5].Text = "★";
1980 else if (Post.RetweetedId != null)
1982 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1984 else if (Read || !SettingManager.Common.UseUnreadStyle)
1989 if (DList == null || Item.Index == -1)
1991 Item.ForeColor = cl;
1992 if (SettingManager.Common.UseUnreadStyle)
1998 if (SettingManager.Common.UseUnreadStyle)
1999 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2001 DList.ChangeItemForeColor(Item.Index, cl);
2002 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2006 private void ColorizeList()
2008 //Index:更新対象のListviewItem.Index。Colorを返す。
2009 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2012 _post = _anchorPost;
2016 if (_post == null) return;
2018 var listCache = this._listItemCache;
2019 if (listCache == null)
2022 var index = listCache.StartIndex;
2023 foreach (var cachedPost in listCache.Post)
2025 var backColor = this.JudgeColor(_post, cachedPost);
2026 this._curList.ChangeItemBackColor(index++, backColor);
2030 private void ColorizeList(ListViewItem Item, int Index)
2032 //Index:更新対象のListviewItem.Index。Colorを返す。
2033 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2036 _post = _anchorPost;
2040 PostClass tPost = GetCurTabPost(Index);
2042 if (_post == null) return;
2044 if (Item.Index == -1)
2045 Item.BackColor = JudgeColor(_post, tPost);
2047 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2050 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2053 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2056 else if (TargetPost.IsMe)
2059 else if (TargetPost.IsReply)
2062 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2064 cl = _clAtFromTarget;
2065 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2068 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2073 cl = _clListBackcolor;
2078 private async void PostButton_Click(object sender, EventArgs e)
2080 if (StatusText.Text.Trim().Length == 0)
2082 if (!ImageSelector.Enabled)
2084 await this.DoRefresh();
2089 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2091 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2093 MessageBoxButtons.YesNoCancel,
2094 MessageBoxIcon.Question);
2097 case DialogResult.Yes:
2098 StatusText.Text = "";
2099 await this.doReTweetOfficial(false);
2101 case DialogResult.Cancel:
2106 var inReplyToStatusId = this.inReplyTo?.Item1;
2107 var inReplyToScreenName = this.inReplyTo?.Item2;
2108 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2110 if (SettingManager.Common.Nicoms)
2112 StatusText.SelectionStart = StatusText.Text.Length;
2113 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2115 //if (SettingDialog.UrlConvertAuto)
2117 // StatusText.SelectionStart = StatusText.Text.Length;
2118 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2120 //else if (SettingDialog.Nicoms)
2122 // StatusText.SelectionStart = StatusText.Text.Length;
2123 // UrlConvert(UrlConverter.Nicoms);
2125 StatusText.SelectionStart = StatusText.Text.Length;
2126 CheckReplyTo(StatusText.Text);
2128 var statusText = this.FormatStatusText(this.StatusText.Text);
2130 if (this.GetRestStatusCount(statusText) < 0)
2132 // 文字数制限を超えているが強制的に投稿するか
2133 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2134 if (ret != DialogResult.OK)
2138 var status = new PostingStatus();
2139 status.status = statusText;
2141 status.inReplyToId = this.inReplyTo?.Item1;
2142 status.inReplyToName = this.inReplyTo?.Item2;
2143 if (ImageSelector.Visible)
2146 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2150 this.inReplyTo = null;
2151 StatusText.Text = "";
2152 _history.Add(new PostingStatus());
2153 _hisIdx = _history.Count - 1;
2154 if (!ToolStripFocusLockMenuItem.Checked)
2155 ((Control)ListTab.SelectedTab.Tag).Focus();
2156 urlUndoBuffer = null;
2157 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2160 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2162 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2163 await this.OpenUriInBrowserAsync(tmp);
2166 await this.PostMessageAsync(status);
2169 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2171 MyCommon._endingFlag = true;
2175 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2177 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2179 //_endingFlag=false:フォームの×ボタン
2181 this.Visible = false;
2185 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2186 _ignoreConfigSave = true;
2187 MyCommon._endingFlag = true;
2188 TimerTimeline.Enabled = false;
2189 TimerRefreshIcon.Enabled = false;
2193 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2195 this.Visible = true;
2196 if (this.WindowState == FormWindowState.Minimized)
2198 this.WindowState = FormWindowState.Normal;
2201 this.BringToFront();
2204 private static int errorCount = 0;
2206 private static bool CheckAccountValid()
2208 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2214 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2223 private Task GetHomeTimelineAsync()
2225 return this.GetHomeTimelineAsync(loadMore: false);
2228 private async Task GetHomeTimelineAsync(bool loadMore)
2230 await this.workerSemaphore.WaitAsync();
2234 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2235 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2237 this.RefreshTimeline();
2239 catch (WebApiException ex)
2241 this._myStatusError = true;
2242 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2246 this.workerSemaphore.Release();
2250 private Task GetReplyAsync()
2252 return this.GetReplyAsync(loadMore: false);
2255 private async Task GetReplyAsync(bool loadMore)
2257 await this.workerSemaphore.WaitAsync();
2261 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2262 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2264 this.RefreshTimeline();
2266 catch (WebApiException ex)
2268 this._myStatusError = true;
2269 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2273 this.workerSemaphore.Release();
2277 private Task GetDirectMessagesAsync()
2279 return this.GetDirectMessagesAsync(loadMore: false);
2282 private async Task GetDirectMessagesAsync(bool loadMore)
2284 await this.workerSemaphore.WaitAsync();
2288 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2289 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2291 this.RefreshTimeline();
2293 catch (WebApiException ex)
2295 this._myStatusError = true;
2296 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2300 this.workerSemaphore.Release();
2304 private Task GetFavoritesAsync()
2306 return this.GetFavoritesAsync(loadMore: false);
2309 private async Task GetFavoritesAsync(bool loadMore)
2311 await this.workerSemaphore.WaitAsync();
2315 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2316 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2318 this.RefreshTimeline();
2320 catch (WebApiException ex)
2322 this._myStatusError = true;
2323 this.StatusLabel.Text = ex.Message;
2327 this.workerSemaphore.Release();
2331 private Task GetPublicSearchAllAsync()
2333 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2335 return this.GetPublicSearchAsync(tabs, loadMore: false);
2338 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2340 return this.GetPublicSearchAsync(tab, loadMore: false);
2343 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2345 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2348 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2350 await this.workerSemaphore.WaitAsync();
2354 foreach (var tab in tabs)
2358 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2360 catch (WebApiException ex)
2362 this._myStatusError = true;
2363 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2367 this.RefreshTimeline();
2371 this.workerSemaphore.Release();
2375 private Task GetUserTimelineAllAsync()
2377 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2379 return this.GetUserTimelineAsync(tabs, loadMore: false);
2382 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2384 return this.GetUserTimelineAsync(tab, loadMore: false);
2387 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2389 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2392 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2394 await this.workerSemaphore.WaitAsync();
2398 foreach (var tab in tabs)
2402 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2404 catch (WebApiException ex)
2406 this._myStatusError = true;
2407 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2411 this.RefreshTimeline();
2415 this.workerSemaphore.Release();
2419 private Task GetListTimelineAllAsync()
2421 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2423 return this.GetListTimelineAsync(tabs, loadMore: false);
2426 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2428 return this.GetListTimelineAsync(tab, loadMore: false);
2431 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2433 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2436 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2438 await this.workerSemaphore.WaitAsync();
2442 foreach (var tab in tabs)
2446 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2448 catch (WebApiException ex)
2450 this._myStatusError = true;
2451 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2455 this.RefreshTimeline();
2459 this.workerSemaphore.Release();
2463 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2465 await this.workerSemaphore.WaitAsync();
2469 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2471 this.RefreshTimeline();
2473 catch (WebApiException ex)
2475 this._myStatusError = true;
2476 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2480 this.workerSemaphore.Release();
2484 private async Task FavAddAsync(long statusId, TabModel tab)
2486 await this.workerSemaphore.WaitAsync();
2490 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2492 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2494 catch (WebApiException ex)
2496 this._myStatusError = true;
2497 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2501 this.workerSemaphore.Release();
2505 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2507 if (ct.IsCancellationRequested)
2510 if (!CheckAccountValid())
2511 throw new WebApiException("Auth error. Check your account");
2513 if (!tab.Posts.TryGetValue(statusId, out var post))
2519 await Task.Run(async () =>
2521 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2527 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2529 .ConfigureAwait(false);
2531 catch (TwitterApiException ex)
2532 when (ex.ErrorResponse.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
2534 // エラーコード 139 のみの場合は成功と見なす
2537 if (SettingManager.Common.RestrictFavCheck)
2539 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2540 .ConfigureAwait(false);
2542 if (status.Favorited != true)
2543 throw new WebApiException("NG(Restricted?)");
2546 this._favTimestamps.Add(DateTime.Now);
2549 if (this._statuses.ContainsKey(statusId))
2551 var postTl = this._statuses[statusId];
2552 postTl.IsFav = true;
2554 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2555 favTab.AddPostQueue(postTl);
2558 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2559 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2561 if (tb.Contains(statusId))
2562 tb.Posts[statusId].IsFav = true;
2565 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2567 catch (WebApiException)
2569 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2574 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2575 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2577 if (this._favTimestamps[i] < oneHour)
2578 this._favTimestamps.RemoveAt(i);
2581 this._statuses.DistributePosts();
2584 if (ct.IsCancellationRequested)
2587 this.RefreshTimeline();
2589 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2591 using (ControlTransaction.Update(this._curList))
2593 var idx = tab.IndexOf(statusId);
2595 this.ChangeCacheStyleRead(post.IsRead, idx);
2598 if (statusId == this._curPost.StatusId)
2599 await this.DispSelectedPost(true); // 選択アイテム再表示
2603 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2605 await this.workerSemaphore.WaitAsync();
2609 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2611 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2613 catch (WebApiException ex)
2615 this._myStatusError = true;
2616 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2620 this.workerSemaphore.Release();
2624 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2626 if (ct.IsCancellationRequested)
2629 if (!CheckAccountValid())
2630 throw new WebApiException("Auth error. Check your account");
2632 var successIds = new List<long>();
2634 await Task.Run(async () =>
2638 var failedCount = 0;
2639 foreach (var statusId in statusIds)
2643 var post = tab.Posts[statusId];
2645 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2652 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2654 .ConfigureAwait(false);
2656 catch (WebApiException)
2662 successIds.Add(statusId);
2663 post.IsFav = false; // リスト再描画必要
2665 if (this._statuses.ContainsKey(statusId))
2667 this._statuses[statusId].IsFav = false;
2670 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2671 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2673 if (tb.Contains(statusId))
2674 tb.Posts[statusId].IsFav = false;
2679 if (ct.IsCancellationRequested)
2682 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2683 foreach (var statusId in successIds)
2685 // ツイートが削除された訳ではないので IsDeleted はセットしない
2686 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2689 this.RefreshTimeline();
2691 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2693 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2699 using (ControlTransaction.Update(this._curList))
2701 foreach (var statusId in successIds)
2703 var idx = tab.IndexOf(statusId);
2707 var post = tab.Posts[statusId];
2708 this.ChangeCacheStyleRead(post.IsRead, idx);
2712 if (successIds.Contains(this._curPost.StatusId))
2713 await this.DispSelectedPost(true); // 選択アイテム再表示
2718 private async Task PostMessageAsync(PostingStatus status)
2720 await this.workerSemaphore.WaitAsync();
2724 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2726 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2728 catch (WebApiException ex)
2730 this._myStatusError = true;
2731 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2735 this.workerSemaphore.Release();
2739 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2741 if (ct.IsCancellationRequested)
2744 if (!CheckAccountValid())
2745 throw new WebApiException("Auth error. Check your account");
2747 p.Report("Posting...");
2753 await Task.Run(async () =>
2755 if (status.mediaItems == null || status.mediaItems.Length == 0)
2757 await this.tw.PostStatus(status.status, status.inReplyToId)
2758 .ConfigureAwait(false);
2762 var service = ImageSelector.GetService(status.imageService);
2763 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2764 .ConfigureAwait(false);
2768 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2770 catch (WebApiException ex)
2772 // 処理は中断せずエラーの表示のみ行う
2773 errMsg = $"Err:{ex.Message}(PostMessage)";
2775 this._myStatusError = true;
2777 catch (UnauthorizedAccessException ex)
2779 // アップロード対象のファイルが開けなかった場合など
2780 errMsg = $"Err:{ex.Message}(PostMessage)";
2782 this._myStatusError = true;
2786 // 使い終わった MediaItem は破棄する
2787 if (status.mediaItems != null)
2789 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2791 disposableItem.Dispose();
2796 if (ct.IsCancellationRequested)
2799 if (!string.IsNullOrEmpty(errMsg) &&
2800 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2801 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2803 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2805 var ret = MessageBox.Show(
2807 "Failed to update status",
2808 MessageBoxButtons.RetryCancel,
2809 MessageBoxIcon.Question);
2811 if (ret == DialogResult.Retry)
2813 await this.PostMessageAsync(status);
2817 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2818 if (this.ToolStripFocusLockMenuItem.Checked)
2819 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2824 this._postTimestamps.Add(DateTime.Now);
2826 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2827 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2829 if (this._postTimestamps[i] < oneHour)
2830 this._postTimestamps.RemoveAt(i);
2833 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2835 this.HashMgr.ClearHashtag();
2836 this.HashStripSplitButton.Text = "#[-]";
2837 this.HashToggleMenuItem.Checked = false;
2838 this.HashToggleToolStripMenuItem.Checked = false;
2841 this.SetMainWindowTitle();
2843 if (SettingManager.Common.PostAndGet)
2845 if (this.tw.UserStreamActive)
2846 this.RefreshTimeline();
2848 await this.GetHomeTimelineAsync();
2852 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2854 await this.workerSemaphore.WaitAsync();
2858 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2860 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2862 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2863 await this.GetHomeTimelineAsync();
2865 catch (WebApiException ex)
2867 this._myStatusError = true;
2868 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2872 this.workerSemaphore.Release();
2876 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2878 if (ct.IsCancellationRequested)
2881 if (!CheckAccountValid())
2882 throw new WebApiException("Auth error. Check your account");
2885 if (!SettingManager.Common.UnreadManage)
2888 read = this._initial && SettingManager.Common.Read;
2890 p.Report("Posting...");
2892 foreach (var statusId in statusIds)
2894 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2897 if (ct.IsCancellationRequested)
2900 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2902 this._postTimestamps.Add(DateTime.Now);
2904 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2905 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2907 if (this._postTimestamps[i] < oneHour)
2908 this._postTimestamps.RemoveAt(i);
2912 private async Task RefreshFollowerIdsAsync()
2914 await this.workerSemaphore.WaitAsync();
2917 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2919 await this.tw.RefreshFollowerIds();
2921 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2923 this.RefreshTimeline();
2924 this.PurgeListViewItemCache();
2925 this._curList?.Refresh();
2927 catch (WebApiException ex)
2929 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2933 this.workerSemaphore.Release();
2937 private async Task RefreshNoRetweetIdsAsync()
2939 await this.workerSemaphore.WaitAsync();
2942 await this.tw.RefreshNoRetweetIds();
2944 this.StatusLabel.Text = "NoRetweetIds refreshed";
2946 catch (WebApiException ex)
2948 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2952 this.workerSemaphore.Release();
2956 private async Task RefreshBlockIdsAsync()
2958 await this.workerSemaphore.WaitAsync();
2961 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2963 await this.tw.RefreshBlockIds();
2965 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2967 catch (WebApiException ex)
2969 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2973 this.workerSemaphore.Release();
2977 private async Task RefreshTwitterConfigurationAsync()
2979 await this.workerSemaphore.WaitAsync();
2982 await this.tw.RefreshConfiguration();
2984 if (this.tw.Configuration.PhotoSizeLimit != 0)
2986 foreach (var service in this.ImageSelector.GetServices())
2988 service.UpdateTwitterConfiguration(this.tw.Configuration);
2992 this.PurgeListViewItemCache();
2994 this._curList?.Refresh();
2996 catch (WebApiException ex)
2998 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3002 this.workerSemaphore.Release();
3006 private async Task RefreshMuteUserIdsAsync()
3008 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3012 await tw.RefreshMuteUserIdsAsync();
3014 catch (WebApiException ex)
3016 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3020 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3023 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3025 if (e.Button == MouseButtons.Left)
3027 this.Visible = true;
3028 if (this.WindowState == FormWindowState.Minimized)
3030 this.WindowState = _formWindowState;
3033 this.BringToFront();
3037 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3039 switch (SettingManager.Common.ListDoubleClickAction)
3042 MakeReplyOrDirectStatus();
3045 await this.FavoriteChange(true);
3048 if (_curPost != null)
3049 await this.ShowUserStatus(_curPost.ScreenName, false);
3055 ShowRelatedStatusesMenuItem_Click(null, null);
3058 MoveToHomeToolStripMenuItem_Click(null, null);
3061 StatusOpenMenuItem_Click(null, null);
3069 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3071 await this.FavoriteChange(true);
3074 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3076 await this.FavoriteChange(false);
3080 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3082 await this.FavoritesRetweetOfficial();
3085 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3087 await this.FavoritesRetweetUnofficial();
3090 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3092 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3095 //trueでFavAdd,falseでFavRemove
3096 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3097 || !this.ExistCurrentPost) return;
3099 if (this._curList.SelectedIndices.Count > 1)
3104 // https://support.twitter.com/articles/76915#favoriting
3105 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3106 _DoFavRetweetFlags = false;
3111 if (multiFavoriteChangeDialogEnable)
3113 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3114 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3115 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3117 if (confirm == DialogResult.Cancel)
3125 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3126 if (selectedPost.IsFav)
3128 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3132 await this.FavAddAsync(selectedPost.StatusId, tab);
3136 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3137 .Select(x => this.GetCurTabPost(x))
3138 .Where(x => x.IsFav);
3140 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3141 if (statusIds.Length == 0)
3143 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3147 await this.FavRemoveAsync(statusIds, tab);
3151 private PostClass GetCurTabPost(int Index)
3153 var listCache = this._listItemCache;
3154 if (listCache != null)
3156 if (listCache.TryGetValue(Index, out var item, out var post))
3160 return _statuses.Tabs[_curTab.Text][Index];
3163 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3165 if (_curList.SelectedIndices.Count > 0)
3166 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3167 else if (_curList.SelectedIndices.Count == 0)
3168 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3171 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3173 if (_curList.SelectedIndices.Count > 0)
3174 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3177 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3179 if ((!_initialLayout) && this.Visible)
3181 if (this.WindowState == FormWindowState.Normal)
3183 _mySize = this.ClientSize;
3184 _mySpDis = this.SplitContainer1.SplitterDistance;
3185 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3186 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3187 ModifySettingLocal = true;
3192 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3194 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3195 if (comparerMode == null)
3198 this.SetSortColumn(comparerMode.Value);
3202 /// 列インデックスからソートを行う ComparerMode を求める
3204 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3205 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3206 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3209 return ComparerMode.Id;
3211 switch (columnIndex)
3214 return ComparerMode.Nickname;
3216 return ComparerMode.Data;
3218 return ComparerMode.Id;
3220 return ComparerMode.Name;
3222 return ComparerMode.Source;
3224 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3230 /// 発言一覧の指定した位置の列でソートする
3232 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3233 private void SetSortColumnByDisplayIndex(int columnIndex)
3235 // 表示上の列の位置から ColumnHeader を求める
3236 var col = this._curList.Columns.Cast<ColumnHeader>()
3237 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3242 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3243 if (comparerMode == null)
3246 this.SetSortColumn(comparerMode.Value);
3250 /// 発言一覧の最後列の項目でソートする
3252 private void SetSortLastColumn()
3254 // 表示上の最後列にある ColumnHeader を求める
3255 var col = this._curList.Columns.Cast<ColumnHeader>()
3256 .OrderByDescending(x => x.DisplayIndex)
3259 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3260 if (comparerMode == null)
3263 this.SetSortColumn(comparerMode.Value);
3267 /// 発言一覧を指定された ComparerMode に基づいてソートする
3269 private void SetSortColumn(ComparerMode sortColumn)
3271 if (SettingManager.Common.SortOrderLock)
3274 this._statuses.ToggleSortOrder(sortColumn);
3275 this.InitColumnText();
3277 var list = this._curList;
3280 list.Columns[0].Text = this.ColumnText[0];
3281 list.Columns[1].Text = this.ColumnText[2];
3285 for (var i = 0; i <= 7; i++)
3287 list.Columns[i].Text = this.ColumnText[i];
3291 this.PurgeListViewItemCache();
3293 var tab = this._statuses.Tabs[this._curTab.Text];
3294 if (tab.AllCount > 0 && this._curPost != null)
3296 var idx = tab.IndexOf(this._curPost.StatusId);
3299 this.SelectListItem(list, idx);
3300 list.EnsureVisible(idx);
3305 this.ModifySettingCommon = true;
3308 private void TweenMain_LocationChanged(object sender, EventArgs e)
3310 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3312 _myLoc = this.DesktopLocation;
3313 ModifySettingLocal = true;
3317 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3319 if (ListTab.SelectedTab == null) return;
3320 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3321 if (!this.ExistCurrentPost)
3323 ReplyStripMenuItem.Enabled = false;
3324 ReplyAllStripMenuItem.Enabled = false;
3325 DMStripMenuItem.Enabled = false;
3326 ShowProfileMenuItem.Enabled = false;
3327 ShowUserTimelineContextMenuItem.Enabled = false;
3328 ListManageUserContextToolStripMenuItem2.Enabled = false;
3329 MoveToFavToolStripMenuItem.Enabled = false;
3330 TabMenuItem.Enabled = false;
3331 IDRuleMenuItem.Enabled = false;
3332 SourceRuleMenuItem.Enabled = false;
3333 ReadedStripMenuItem.Enabled = false;
3334 UnreadStripMenuItem.Enabled = false;
3338 ShowProfileMenuItem.Enabled = true;
3339 ListManageUserContextToolStripMenuItem2.Enabled = true;
3340 ReplyStripMenuItem.Enabled = true;
3341 ReplyAllStripMenuItem.Enabled = true;
3342 DMStripMenuItem.Enabled = true;
3343 ShowUserTimelineContextMenuItem.Enabled = true;
3344 MoveToFavToolStripMenuItem.Enabled = true;
3345 TabMenuItem.Enabled = true;
3346 IDRuleMenuItem.Enabled = true;
3347 SourceRuleMenuItem.Enabled = true;
3348 ReadedStripMenuItem.Enabled = true;
3349 UnreadStripMenuItem.Enabled = true;
3351 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3353 FavAddToolStripMenuItem.Enabled = false;
3354 FavRemoveToolStripMenuItem.Enabled = false;
3355 StatusOpenMenuItem.Enabled = false;
3356 FavorareMenuItem.Enabled = false;
3357 ShowRelatedStatusesMenuItem.Enabled = false;
3359 ReTweetStripMenuItem.Enabled = false;
3360 ReTweetUnofficialStripMenuItem.Enabled = false;
3361 QuoteStripMenuItem.Enabled = false;
3362 FavoriteRetweetContextMenu.Enabled = false;
3363 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3367 FavAddToolStripMenuItem.Enabled = true;
3368 FavRemoveToolStripMenuItem.Enabled = true;
3369 StatusOpenMenuItem.Enabled = true;
3370 FavorareMenuItem.Enabled = true;
3371 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3373 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3375 ReTweetStripMenuItem.Enabled = false;
3376 ReTweetUnofficialStripMenuItem.Enabled = false;
3377 QuoteStripMenuItem.Enabled = false;
3378 FavoriteRetweetContextMenu.Enabled = false;
3379 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3383 ReTweetStripMenuItem.Enabled = true;
3384 ReTweetUnofficialStripMenuItem.Enabled = true;
3385 QuoteStripMenuItem.Enabled = true;
3386 FavoriteRetweetContextMenu.Enabled = true;
3387 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3390 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3392 // RefreshMoreStripMenuItem.Enabled = true;
3396 // RefreshMoreStripMenuItem.Enabled = false;
3398 if (!this.ExistCurrentPost
3399 || _curPost.InReplyToStatusId == null)
3401 RepliedStatusOpenMenuItem.Enabled = false;
3405 RepliedStatusOpenMenuItem.Enabled = true;
3407 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3409 MoveToRTHomeMenuItem.Enabled = false;
3413 MoveToRTHomeMenuItem.Enabled = true;
3416 if (this.ExistCurrentPost)
3418 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3419 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3420 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3422 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3426 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3428 MakeReplyOrDirectStatus(false, true);
3431 private void DMStripMenuItem_Click(object sender, EventArgs e)
3433 MakeReplyOrDirectStatus(false, false);
3436 private async Task doStatusDelete()
3438 if (this._curTab == null || this._curList == null)
3441 if (this._curList.SelectedIndices.Count == 0)
3444 var posts = this._curList.SelectedIndices.Cast<int>()
3445 .Select(x => this.GetCurTabPost(x))
3448 // 選択されたツイートの中に削除可能なものが一つでもあるか
3449 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3452 var ret = MessageBox.Show(this,
3453 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3454 Properties.Resources.DeleteStripMenuItem_ClickText2,
3455 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3457 if (ret != DialogResult.OK)
3460 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3462 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3464 Exception lastException = null;
3465 foreach (var post in posts)
3467 if (!post.CanDeleteBy(this.tw.UserId))
3474 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3479 if (post.RetweetedByUserId == this.tw.UserId)
3481 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3483 await this.twitterApi.StatusesDestroy(post.StatusId)
3488 if (post.UserId == this.tw.UserId)
3490 if (post.RetweetedId != null)
3491 // 他人に RT された自分のツイート
3492 // => RT 元の自分のツイートを削除
3493 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3498 await this.twitterApi.StatusesDestroy(post.StatusId)
3504 catch (WebApiException ex)
3510 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3513 if (lastException == null)
3514 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3516 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3518 this.PurgeListViewItemCache();
3519 this._curPost = null;
3520 this._curItemIndex = -1;
3522 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3524 var listView = (DetailsListView)tabPage.Tag;
3525 var tab = this._statuses.Tabs[tabPage.Text];
3527 using (ControlTransaction.Update(listView))
3529 listView.VirtualListSize = tab.AllCount;
3531 if (tabPage == this._curTab)
3533 listView.SelectedIndices.Clear();
3535 if (tab.AllCount != 0)
3538 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3539 selectedIndex = focusedIndex;
3541 selectedIndex = tab.AllCount - 1;
3543 listView.SelectedIndices.Add(selectedIndex);
3544 listView.EnsureVisible(selectedIndex);
3545 listView.FocusedItem = listView.Items[selectedIndex];
3550 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3552 if (tabPage.ImageIndex == 0)
3553 tabPage.ImageIndex = -1; // タブアイコン
3557 if (!SettingManager.Common.TabIconDisp)
3558 this.ListTab.Refresh();
3562 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3564 await this.doStatusDelete();
3567 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3569 using (ControlTransaction.Update(this._curList))
3571 foreach (int idx in _curList.SelectedIndices)
3573 var post = this._statuses.Tabs[this._curTab.Text][idx];
3574 this._statuses.SetReadAllTab(post.StatusId, read: true);
3575 ChangeCacheStyleRead(true, idx);
3579 foreach (TabPage tb in ListTab.TabPages)
3581 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3583 if (SettingManager.Common.TabIconDisp)
3585 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3589 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3592 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3594 using (ControlTransaction.Update(this._curList))
3596 foreach (int idx in _curList.SelectedIndices)
3598 var post = this._statuses.Tabs[this._curTab.Text][idx];
3599 this._statuses.SetReadAllTab(post.StatusId, read: false);
3600 ChangeCacheStyleRead(false, idx);
3604 foreach (TabPage tb in ListTab.TabPages)
3606 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3608 if (SettingManager.Common.TabIconDisp)
3610 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3614 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3617 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3619 await this.DoRefresh();
3622 private async Task DoRefresh()
3624 if (_curTab != null)
3626 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3631 case MentionsTabModel replyTab:
3632 await this.GetReplyAsync();
3634 case DirectMessagesTabModel dmTab:
3635 await this.GetDirectMessagesAsync();
3637 case FavoritesTabModel favTab:
3638 await this.GetFavoritesAsync();
3640 case PublicSearchTabModel searchTab:
3641 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3642 await this.GetPublicSearchAsync(searchTab);
3644 case UserTimelineTabModel userTab:
3645 await this.GetUserTimelineAsync(userTab);
3647 case ListTimelineTabModel listTab:
3648 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3649 await this.GetListTimelineAsync(listTab);
3652 await this.GetHomeTimelineAsync();
3658 await this.GetHomeTimelineAsync();
3662 private async Task DoRefreshMore()
3665 if (_curTab != null)
3667 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3672 case MentionsTabModel replyTab:
3673 await this.GetReplyAsync(loadMore: true);
3675 case DirectMessagesTabModel dmTab:
3676 await this.GetDirectMessagesAsync(loadMore: true);
3678 case FavoritesTabModel favTab:
3679 await this.GetFavoritesAsync(loadMore: true);
3681 case PublicSearchTabModel searchTab:
3682 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3683 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3685 case UserTimelineTabModel userTab:
3686 await this.GetUserTimelineAsync(userTab, loadMore: true);
3688 case ListTimelineTabModel listTab:
3689 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3690 await this.GetListTimelineAsync(listTab, loadMore: true);
3693 await this.GetHomeTimelineAsync(loadMore: true);
3699 await this.GetHomeTimelineAsync(loadMore: true);
3703 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3705 DialogResult result = DialogResult.Abort;
3707 using (var settingDialog = new AppendSettingDialog())
3709 settingDialog.Icon = this.MainIcon;
3710 settingDialog.Owner = this;
3711 settingDialog.ShowInTaskbar = showTaskbarIcon;
3712 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3714 settingDialog.tw = this.tw;
3715 settingDialog.twitterApi = this.twitterApi;
3717 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3721 result = settingDialog.ShowDialog(this);
3725 return DialogResult.Abort;
3728 if (result == DialogResult.OK)
3732 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3740 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3743 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3745 var oldIconSz = SettingManager.Common.IconSize;
3747 if (ShowSettingDialog() == DialogResult.OK)
3751 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3752 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3753 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3754 ShortUrl.Instance.BitlyAccessToken = SettingManager.Common.BitlyAccessToken;
3755 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3756 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3757 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3759 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3760 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3761 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3762 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3763 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3764 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3766 ImageSelector.Reset(tw, this.tw.Configuration);
3770 if (SettingManager.Common.TabIconDisp)
3772 ListTab.DrawItem -= ListTab_DrawItem;
3773 ListTab.DrawMode = TabDrawMode.Normal;
3774 ListTab.ImageList = this.TabImage;
3778 ListTab.DrawItem -= ListTab_DrawItem;
3779 ListTab.DrawItem += ListTab_DrawItem;
3780 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3781 ListTab.ImageList = null;
3784 catch (Exception ex)
3786 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3787 ex.Data["IsTerminatePermission"] = false;
3793 if (!SettingManager.Common.UnreadManage)
3795 ReadedStripMenuItem.Enabled = false;
3796 UnreadStripMenuItem.Enabled = false;
3797 if (SettingManager.Common.TabIconDisp)
3799 foreach (TabPage myTab in ListTab.TabPages)
3801 myTab.ImageIndex = -1;
3807 ReadedStripMenuItem.Enabled = true;
3808 UnreadStripMenuItem.Enabled = true;
3811 catch (Exception ex)
3813 ex.Data["Instance"] = "ListTab(UnreadManage)";
3814 ex.Data["IsTerminatePermission"] = false;
3821 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3823 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3824 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3825 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3827 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3828 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3829 _fntUnread = SettingManager.Local.FontUnread;
3830 _clUnread = SettingManager.Local.ColorUnread;
3831 _fntReaded = SettingManager.Local.FontRead;
3832 _clReaded = SettingManager.Local.ColorRead;
3833 _clFav = SettingManager.Local.ColorFav;
3834 _clOWL = SettingManager.Local.ColorOWL;
3835 _clRetweet = SettingManager.Local.ColorRetweet;
3836 _fntDetail = SettingManager.Local.FontDetail;
3837 _clDetail = SettingManager.Local.ColorDetail;
3838 _clDetailLink = SettingManager.Local.ColorDetailLink;
3839 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3840 _clSelf = SettingManager.Local.ColorSelf;
3841 _clAtSelf = SettingManager.Local.ColorAtSelf;
3842 _clTarget = SettingManager.Local.ColorTarget;
3843 _clAtTarget = SettingManager.Local.ColorAtTarget;
3844 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3845 _clAtTo = SettingManager.Local.ColorAtTo;
3846 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3847 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3848 _clInputFont = SettingManager.Local.ColorInputFont;
3849 _fntInputFont = SettingManager.Local.FontInputFont;
3850 _brsBackColorMine.Dispose();
3851 _brsBackColorAt.Dispose();
3852 _brsBackColorYou.Dispose();
3853 _brsBackColorAtYou.Dispose();
3854 _brsBackColorAtFromTarget.Dispose();
3855 _brsBackColorAtTo.Dispose();
3856 _brsBackColorNone.Dispose();
3857 _brsBackColorMine = new SolidBrush(_clSelf);
3858 _brsBackColorAt = new SolidBrush(_clAtSelf);
3859 _brsBackColorYou = new SolidBrush(_clTarget);
3860 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3861 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3862 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3863 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3867 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3868 StatusText.Font = _fntInputFont;
3869 StatusText.ForeColor = _clInputFont;
3871 catch (Exception ex)
3873 MessageBox.Show(ex.Message);
3878 InitDetailHtmlFormat();
3880 catch (Exception ex)
3882 ex.Data["Instance"] = "Font";
3883 ex.Data["IsTerminatePermission"] = false;
3889 foreach (TabPage tb in ListTab.TabPages)
3891 if (SettingManager.Common.TabIconDisp)
3893 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3900 catch (Exception ex)
3902 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3903 ex.Data["IsTerminatePermission"] = false;
3909 var oldIconCol = _iconCol;
3911 if (SettingManager.Common.IconSize != oldIconSz)
3912 ApplyListViewIconSize(SettingManager.Common.IconSize);
3914 foreach (TabPage tp in ListTab.TabPages)
3916 DetailsListView lst = (DetailsListView)tp.Tag;
3918 using (ControlTransaction.Update(lst))
3920 lst.GridLines = SettingManager.Common.ShowGrid;
3921 lst.Font = _fntReaded;
3922 lst.BackColor = _clListBackcolor;
3924 if (_iconCol != oldIconCol)
3929 catch (Exception ex)
3931 ex.Data["Instance"] = "ListView(IconSize)";
3932 ex.Data["IsTerminatePermission"] = false;
3936 SetMainWindowTitle();
3937 SetNotifyIconText();
3939 this.PurgeListViewItemCache();
3940 _curList?.Refresh();
3943 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3944 if (SettingManager.Common.HotkeyEnabled)
3946 ///グローバルホットキーの登録。設定で変更可能にするかも
3947 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3948 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3949 modKey |= HookGlobalHotkey.ModKeys.Alt;
3950 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3951 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3952 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3953 modKey |= HookGlobalHotkey.ModKeys.Shift;
3954 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3955 modKey |= HookGlobalHotkey.ModKeys.Win;
3957 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3960 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3963 StatusText_TextChanged(null, null);
3972 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3973 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3976 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3978 this.TopMost = SettingManager.Common.AlwaysTop;
3979 SaveConfigsAll(false);
3981 if (tw.Username != oldUser.Username)
3982 await this.doGetFollowersMenu();
3988 private void SetTabAlignment()
3990 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3991 if (ListTab.Alignment == newAlignment) return;
3993 // 各タブのリスト上の選択位置などを退避
3994 var listSelections = this.SaveListViewSelection();
3996 ListTab.Alignment = newAlignment;
3998 foreach (TabPage tab in ListTab.TabPages)
4000 DetailsListView lst = (DetailsListView)tab.Tag;
4001 TabModel tabInfo = _statuses.Tabs[tab.Text];
4002 using (ControlTransaction.Update(lst))
4005 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4010 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4016 case MyCommon.IconSizes.IconNone:
4019 case MyCommon.IconSizes.Icon16:
4022 case MyCommon.IconSizes.Icon24:
4025 case MyCommon.IconSizes.Icon48:
4028 case MyCommon.IconSizes.Icon48_2:
4036 // ディスプレイの DPI 設定を考慮したサイズを設定する
4037 _listViewImageList.ImageSize = new Size(
4039 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4043 _listViewImageList.ImageSize = new Size(1, 1);
4047 private void ResetColumns(DetailsListView list)
4049 using (ControlTransaction.Update(list))
4050 using (ControlTransaction.Layout(list, false))
4053 list.ColumnClick -= MyList_ColumnClick;
4054 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4055 list.ColumnReordered -= MyList_ColumnReordered;
4056 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4058 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4059 list.Columns.Clear();
4060 cols.ForEach(col => col.Dispose());
4063 InitColumns(list, true);
4065 list.ColumnClick += MyList_ColumnClick;
4066 list.DrawColumnHeader += MyList_DrawColumnHeader;
4067 list.ColumnReordered += MyList_ColumnReordered;
4068 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4072 public void AddNewTabForSearch(string searchWord)
4074 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4075 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4077 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4079 foreach (TabPage tp in ListTab.TabPages)
4081 if (tb.TabName == tp.Text)
4083 ListTab.SelectedTab = tp;
4090 string tabName = searchWord;
4091 for (int i = 0; i <= 100; i++)
4093 if (_statuses.ContainsTab(tabName))
4099 var tab = new PublicSearchTabModel(tabName);
4100 _statuses.AddTab(tab);
4101 AddNewTab(tab, startup: false);
4103 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4105 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4106 cmb.Items.Add(searchWord);
4107 cmb.Text = searchWord;
4110 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4113 private void ShowUserTimeline()
4115 if (!this.ExistCurrentPost) return;
4116 AddNewTabForUserTimeline(_curPost.ScreenName);
4119 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4121 if (e.KeyCode == Keys.Escape)
4123 TabPage relTp = ListTab.SelectedTab;
4124 RemoveSpecifiedTab(relTp.Text, false);
4126 e.SuppressKeyPress = true;
4130 public void AddNewTabForUserTimeline(string user)
4132 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4133 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4135 if (tb.ScreenName == user)
4137 foreach (TabPage tp in ListTab.TabPages)
4139 if (tb.TabName == tp.Text)
4141 ListTab.SelectedTab = tp;
4148 string tabName = "user:" + user;
4149 while (_statuses.ContainsTab(tabName))
4154 var tab = new UserTimelineTabModel(tabName, user);
4155 this._statuses.AddTab(tab);
4156 this.AddNewTab(tab, startup: false);
4158 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4161 this.GetUserTimelineAsync(tab);
4164 public bool AddNewTab(TabModel tab, bool startup)
4167 foreach (TabPage tb in ListTab.TabPages)
4169 if (tb.Text == tab.TabName) return false;
4173 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4175 var _tabPage = new TabPage();
4176 var _listCustom = new DetailsListView();
4178 int cnt = ListTab.TabPages.Count;
4180 ///ToDo:Create and set controls follow tabtypes
4182 using (ControlTransaction.Update(_listCustom))
4183 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4184 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4185 using (ControlTransaction.Layout(this.SplitContainer1, false))
4186 using (ControlTransaction.Layout(this.ListTab, false))
4187 using (ControlTransaction.Layout(this))
4188 using (ControlTransaction.Layout(_tabPage, false))
4190 _tabPage.Controls.Add(_listCustom);
4193 var userTab = tab as UserTimelineTabModel;
4194 var listTab = tab as ListTimelineTabModel;
4195 var searchTab = tab as PublicSearchTabModel;
4197 if (userTab != null || listTab != null)
4199 var label = new Label();
4200 label.Dock = DockStyle.Top;
4201 label.Name = "labelUser";
4204 if (listTab != null)
4206 label.Text = listTab.ListInfo.ToString();
4208 else if (userTab != null)
4210 label.Text = userTab.ScreenName + "'s Timeline";
4212 label.TextAlign = ContentAlignment.MiddleLeft;
4213 using (ComboBox tmpComboBox = new ComboBox())
4215 label.Height = tmpComboBox.Height;
4217 _tabPage.Controls.Add(label);
4220 else if (searchTab != null)
4222 var pnl = new Panel();
4224 var lbl = new Label();
4225 var cmb = new ComboBox();
4226 var btn = new Button();
4227 var cmbLang = new ComboBox();
4229 using (ControlTransaction.Layout(pnl, false))
4231 pnl.Controls.Add(cmb);
4232 pnl.Controls.Add(cmbLang);
4233 pnl.Controls.Add(btn);
4234 pnl.Controls.Add(lbl);
4235 pnl.Name = "panelSearch";
4237 pnl.Dock = DockStyle.Top;
4238 pnl.Height = cmb.Height;
4239 pnl.Enter += SearchControls_Enter;
4240 pnl.Leave += SearchControls_Leave;
4243 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4244 cmb.Dock = DockStyle.Fill;
4245 cmb.Name = "comboSearch";
4246 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4247 cmb.ImeMode = ImeMode.NoControl;
4248 cmb.TabStop = false;
4250 cmb.AutoCompleteMode = AutoCompleteMode.None;
4251 cmb.KeyDown += SearchComboBox_KeyDown;
4254 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4255 cmbLang.Dock = DockStyle.Right;
4257 cmbLang.Name = "comboLang";
4258 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4259 cmbLang.TabStop = false;
4260 cmbLang.TabIndex = 2;
4261 cmbLang.Items.Add("");
4262 cmbLang.Items.Add("ja");
4263 cmbLang.Items.Add("en");
4264 cmbLang.Items.Add("ar");
4265 cmbLang.Items.Add("da");
4266 cmbLang.Items.Add("nl");
4267 cmbLang.Items.Add("fa");
4268 cmbLang.Items.Add("fi");
4269 cmbLang.Items.Add("fr");
4270 cmbLang.Items.Add("de");
4271 cmbLang.Items.Add("hu");
4272 cmbLang.Items.Add("is");
4273 cmbLang.Items.Add("it");
4274 cmbLang.Items.Add("no");
4275 cmbLang.Items.Add("pl");
4276 cmbLang.Items.Add("pt");
4277 cmbLang.Items.Add("ru");
4278 cmbLang.Items.Add("es");
4279 cmbLang.Items.Add("sv");
4280 cmbLang.Items.Add("th");
4282 lbl.Text = "Search(C-S-f)";
4283 lbl.Name = "label1";
4284 lbl.Dock = DockStyle.Left;
4286 lbl.Height = cmb.Height;
4287 lbl.TextAlign = ContentAlignment.MiddleLeft;
4290 btn.Text = "Search";
4291 btn.Name = "buttonSearch";
4292 btn.UseVisualStyleBackColor = true;
4293 btn.Dock = DockStyle.Right;
4294 btn.TabStop = false;
4296 btn.Click += SearchButton_Click;
4298 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4300 cmb.Items.Add(searchTab.SearchWords);
4301 cmb.Text = searchTab.SearchWords;
4304 cmbLang.Text = searchTab.SearchLang;
4306 _tabPage.Controls.Add(pnl);
4310 _tabPage.Tag = _listCustom;
4311 this.ListTab.Controls.Add(_tabPage);
4313 _tabPage.Location = new Point(4, 4);
4314 _tabPage.Name = "CTab" + cnt;
4315 _tabPage.Size = new Size(380, 260);
4316 _tabPage.TabIndex = 2 + cnt;
4317 _tabPage.Text = tab.TabName;
4318 _tabPage.UseVisualStyleBackColor = true;
4319 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4321 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4322 _listCustom.TabIndex = 1;
4323 _listCustom.AllowColumnReorder = true;
4324 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4325 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4326 _listCustom.Dock = DockStyle.Fill;
4327 _listCustom.FullRowSelect = true;
4328 _listCustom.HideSelection = false;
4329 _listCustom.Location = new Point(0, 0);
4330 _listCustom.Margin = new Padding(0);
4331 _listCustom.Name = "CList" + Environment.TickCount;
4332 _listCustom.ShowItemToolTips = true;
4333 _listCustom.Size = new Size(380, 260);
4334 _listCustom.UseCompatibleStateImageBehavior = false;
4335 _listCustom.View = View.Details;
4336 _listCustom.OwnerDraw = true;
4337 _listCustom.VirtualMode = true;
4338 _listCustom.Font = _fntReaded;
4339 _listCustom.BackColor = _clListBackcolor;
4341 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4342 _listCustom.AllowDrop = true;
4344 _listCustom.SmallImageList = _listViewImageList;
4346 InitColumns(_listCustom, startup);
4348 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4349 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4350 _listCustom.ColumnClick += MyList_ColumnClick;
4351 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4352 _listCustom.DragDrop += TweenMain_DragDrop;
4353 _listCustom.DragEnter += TweenMain_DragEnter;
4354 _listCustom.DragOver += TweenMain_DragOver;
4355 _listCustom.DrawItem += MyList_DrawItem;
4356 _listCustom.MouseClick += MyList_MouseClick;
4357 _listCustom.ColumnReordered += MyList_ColumnReordered;
4358 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4359 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4360 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4361 _listCustom.DrawSubItem += MyList_DrawSubItem;
4362 _listCustom.HScrolled += MyList_HScrolled;
4368 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4370 var tabInfo = _statuses.GetTabByName(TabName);
4371 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4375 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4376 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4377 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4383 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4384 if (_tabPage == null) return false;
4386 SetListProperty(); //他のタブに列幅等を反映
4389 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4390 _tabPage.Tag = null;
4392 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4393 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4394 using (ControlTransaction.Layout(this.SplitContainer1, false))
4395 using (ControlTransaction.Layout(this.ListTab, false))
4396 using (ControlTransaction.Layout(this))
4397 using (ControlTransaction.Layout(_tabPage, false))
4399 if (this.ListTab.SelectedTab == _tabPage)
4401 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4402 this._beforeSelectedTab = null;
4404 this.ListTab.Controls.Remove(_tabPage);
4407 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4409 using (Control label = _tabPage.Controls["labelUser"])
4411 _tabPage.Controls.Remove(label);
4414 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4416 using (Control pnl = _tabPage.Controls["panelSearch"])
4418 pnl.Enter -= SearchControls_Enter;
4419 pnl.Leave -= SearchControls_Leave;
4420 _tabPage.Controls.Remove(pnl);
4422 foreach (Control ctrl in pnl.Controls)
4424 if (ctrl.Name == "buttonSearch")
4426 ctrl.Click -= SearchButton_Click;
4428 else if (ctrl.Name == "comboSearch")
4430 ctrl.KeyDown -= SearchComboBox_KeyDown;
4432 pnl.Controls.Remove(ctrl);
4438 _tabPage.Controls.Remove(_listCustom);
4440 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4441 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4442 _listCustom.ColumnClick -= MyList_ColumnClick;
4443 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4444 _listCustom.DragDrop -= TweenMain_DragDrop;
4445 _listCustom.DragEnter -= TweenMain_DragEnter;
4446 _listCustom.DragOver -= TweenMain_DragOver;
4447 _listCustom.DrawItem -= MyList_DrawItem;
4448 _listCustom.MouseClick -= MyList_MouseClick;
4449 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4450 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4451 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4452 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4453 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4454 _listCustom.HScrolled -= MyList_HScrolled;
4456 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4457 _listCustom.Columns.Clear();
4458 cols.ForEach(col => col.Dispose());
4461 _listCustom.ContextMenuStrip = null;
4462 _listCustom.ColumnHeaderContextMenuStrip = null;
4463 _listCustom.Font = null;
4465 _listCustom.SmallImageList = null;
4466 _listCustom.ListViewItemSorter = null;
4469 if (_curTab.Equals(_tabPage))
4476 this.PurgeListViewItemCache();
4480 _listCustom.Dispose();
4481 _statuses.RemoveTab(TabName);
4483 foreach (TabPage tp in ListTab.TabPages)
4485 DetailsListView lst = (DetailsListView)tp.Tag;
4486 var count = _statuses.Tabs[tp.Text].AllCount;
4487 lst.VirtualListSize = count;
4493 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4495 this.PurgeListViewItemCache();
4496 _beforeSelectedTab = e.TabPage;
4499 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4503 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4506 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4507 if (!dragEnableRectangle.Contains(e.Location))
4509 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4510 tn = ListTab.SelectedTab.Text;
4513 if (string.IsNullOrEmpty(tn)) return;
4515 foreach (TabPage tb in ListTab.TabPages)
4519 ListTab.DoDragDrop(tb, DragDropEffects.All);
4529 Point cpos = new Point(e.X, e.Y);
4530 for (int i = 0; i < ListTab.TabPages.Count; i++)
4532 Rectangle rect = ListTab.GetTabRect(i);
4533 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4534 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4536 _rclickTabName = ListTab.TabPages[i].Text;
4542 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4544 //_curList.Refresh();
4545 SetMainWindowTitle();
4546 SetStatusLabelUrl();
4547 SetApiStatusLabel();
4548 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4549 TabMenuControl(ListTab.SelectedTab.Text);
4550 this.PushSelectPostChain();
4551 await DispSelectedPost();
4554 private void SetListProperty()
4556 //削除などで見つからない場合は処理せず
4557 if (_curList == null) return;
4558 if (!_isColumnChanged) return;
4560 int[] dispOrder = new int[_curList.Columns.Count];
4561 for (int i = 0; i < _curList.Columns.Count; i++)
4563 for (int j = 0; j < _curList.Columns.Count; j++)
4565 if (_curList.Columns[j].DisplayIndex == i)
4574 foreach (TabPage tb in ListTab.TabPages)
4576 if (!tb.Equals(_curTab))
4578 if (tb.Tag != null && tb.Controls.Count > 0)
4580 DetailsListView lst = (DetailsListView)tb.Tag;
4581 for (int i = 0; i < lst.Columns.Count; i++)
4583 lst.Columns[dispOrder[i]].DisplayIndex = i;
4584 lst.Columns[i].Width = _curList.Columns[i].Width;
4590 _isColumnChanged = false;
4593 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4595 if (e.KeyChar == '@')
4597 if (!SettingManager.Common.UseAtIdSupplement) return;
4599 int cnt = AtIdSupl.ItemCount;
4600 ShowSuplDialog(StatusText, AtIdSupl);
4601 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4604 else if (e.KeyChar == '#')
4606 if (!SettingManager.Common.UseHashSupplement) return;
4607 ShowSuplDialog(StatusText, HashSupl);
4612 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4614 ShowSuplDialog(owner, dialog, 0, "");
4617 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4619 ShowSuplDialog(owner, dialog, offset, "");
4622 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4624 dialog.StartsWith = startswith;
4631 dialog.ShowDialog();
4633 this.TopMost = SettingManager.Common.AlwaysTop;
4634 int selStart = owner.SelectionStart;
4637 if (dialog.DialogResult == DialogResult.OK)
4639 if (!string.IsNullOrEmpty(dialog.inputText))
4643 fHalf = owner.Text.Substring(0, selStart - offset);
4645 if (selStart < owner.Text.Length)
4647 eHalf = owner.Text.Substring(selStart);
4649 owner.Text = fHalf + dialog.inputText + eHalf;
4650 owner.SelectionStart = selStart + dialog.inputText.Length;
4657 fHalf = owner.Text.Substring(0, selStart);
4659 if (selStart < owner.Text.Length)
4661 eHalf = owner.Text.Substring(selStart);
4663 owner.Text = fHalf + eHalf;
4666 owner.SelectionStart = selStart;
4672 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4675 if (!e.Alt && !e.Control && !e.Shift)
4677 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4679 bool isSpace = false;
4680 foreach (char c in StatusText.Text)
4682 if (c == ' ' || c == ' ')
4695 StatusText.Text = "";
4696 JumpUnreadMenuItem_Click(null, null);
4700 this.StatusText_TextChanged(null, null);
4703 private void StatusText_TextChanged(object sender, EventArgs e)
4706 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4707 lblLen.Text = pLen.ToString();
4710 StatusText.ForeColor = Color.Red;
4714 StatusText.ForeColor = _clInputFont;
4717 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4719 if (string.IsNullOrEmpty(StatusText.Text))
4721 this.inReplyTo = null;
4726 /// ツイート投稿前のフッター付与などの前処理を行います
4728 private string FormatStatusText(string statusText)
4730 statusText = statusText.Replace("\r\n", "\n");
4732 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4735 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4738 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4740 // 文中の全角スペースを半角スペース1個にする
4741 statusText = statusText.Replace(" ", " ");
4744 // DM の場合はこれ以降の処理を行わない
4745 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4749 if (SettingManager.Common.PostShiftEnter)
4751 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4755 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4756 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4758 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4761 if (statusText.Contains("RT @"))
4762 disableFooter = true;
4767 var hashtag = this.HashMgr.UseHash;
4768 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4771 header = HashMgr.UseHash + " ";
4773 footer = " " + HashMgr.UseHash;
4778 if (SettingManager.Local.UseRecommendStatus)
4781 footer += this.recommendedStatusFooter;
4783 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4785 // テキストボックスに入力されている文字列を使用する
4786 footer += " " + SettingManager.Local.StatusText.Trim();
4790 statusText = header + statusText + footer;
4792 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4794 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4795 // 参照: https://support.twitter.com/articles/14020
4797 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4798 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4800 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4801 statusText = '\u200b' + statusText;
4809 /// 投稿欄に表示する入力可能な文字数を計算します
4811 private int GetRestStatusCount(string statusText)
4814 var remainCount = this.tw.GetTextLengthRemain(statusText);
4816 var uploadService = this.ImageSelector.SelectedService;
4817 if (this.ImageSelector.Visible && uploadService != null)
4819 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4820 remainCount -= uploadService.GetReservedTextLength(1);
4826 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4828 if (sender != this._curList)
4831 var listCache = this._listItemCache;
4832 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4834 // If the newly requested cache is a subset of the old cache,
4835 // no need to rebuild everything, so do nothing.
4839 // Now we need to rebuild the cache.
4840 this.CreateCache(e.StartIndex, e.EndIndex);
4843 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4845 var listCache = this._listItemCache;
4846 if (listCache?.TargetList == sender)
4848 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4855 // A cache miss, so create a new ListViewItem and pass it back.
4856 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4859 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4863 // 不正な要求に対する間に合わせの応答
4864 string[] sitem = {"", "", "", "", "", "", "", ""};
4865 e.Item = new ImageListViewItem(sitem);
4869 private void CreateCache(int startIndex, int endIndex)
4871 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4873 if (tabInfo.AllCount == 0)
4876 // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4877 int FilterRange(int index)
4878 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4880 // キャッシュ要求(要求範囲±30を作成)
4881 startIndex = FilterRange(startIndex - 30);
4882 endIndex = FilterRange(endIndex + 30);
4884 var cacheLength = endIndex - startIndex + 1;
4886 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4887 var listItems = Enumerable.Range(0, cacheLength)
4888 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4891 var listCache = new ListViewItemCache
4893 TargetList = this._curList,
4894 StartIndex = startIndex,
4895 EndIndex = endIndex,
4897 ListItem = listItems,
4900 Interlocked.Exchange(ref this._listItemCache, listCache);
4904 /// DetailsListView のための ListViewItem のキャッシュを消去する
4906 private void PurgeListViewItemCache()
4908 Interlocked.Exchange(ref this._listItemCache, null);
4911 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4913 StringBuilder mk = new StringBuilder();
4914 //if (Post.IsDeleted) mk.Append("×");
4915 //if (Post.IsMark) mk.Append("♪");
4916 //if (Post.IsProtect) mk.Append("Ю");
4917 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4918 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4919 ImageListViewItem itm;
4920 if (Post.RetweetedId == null)
4922 string[] sitem= {"",
4924 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4925 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4930 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4934 string[] sitem = {"",
4936 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4937 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4938 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4942 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4944 itm.StateIndex = Post.StateIndex;
4947 bool read = Post.IsRead;
4948 //未読管理していなかったら既読として扱う
4949 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4950 ChangeItemStyleRead(read, itm, Post, null);
4951 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4956 /// 全てのタブの振り分けルールを反映し直します
4958 private void ApplyPostFilters()
4960 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4962 this.PurgeListViewItemCache();
4963 this._curPost = null;
4964 this._curItemIndex = -1;
4965 this._statuses.FilterAll();
4967 foreach (TabPage tabPage in this.ListTab.TabPages)
4969 var tab = this._statuses.Tabs[tabPage.Text];
4971 var listview = (DetailsListView)tabPage.Tag;
4972 using (ControlTransaction.Update(listview))
4974 listview.VirtualListSize = tab.AllCount;
4977 if (SettingManager.Common.TabIconDisp)
4979 if (tab.UnreadCount > 0)
4980 tabPage.ImageIndex = 0;
4982 tabPage.ImageIndex = -1;
4986 if (!SettingManager.Common.TabIconDisp)
4987 this.ListTab.Refresh();
4989 SetMainWindowTitle();
4990 SetStatusLabelUrl();
4994 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4996 e.DrawDefault = true;
4999 private void MyList_HScrolled(object sender, EventArgs e)
5001 DetailsListView listView = (DetailsListView)sender;
5005 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5007 if (e.State == 0) return;
5008 e.DrawDefault = false;
5010 SolidBrush brs2 = null;
5011 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5013 if (e.Item.BackColor == _clSelf)
5014 brs2 = _brsBackColorMine;
5015 else if (e.Item.BackColor == _clAtSelf)
5016 brs2 = _brsBackColorAt;
5017 else if (e.Item.BackColor == _clTarget)
5018 brs2 = _brsBackColorYou;
5019 else if (e.Item.BackColor == _clAtTarget)
5020 brs2 = _brsBackColorAtYou;
5021 else if (e.Item.BackColor == _clAtFromTarget)
5022 brs2 = _brsBackColorAtFromTarget;
5023 else if (e.Item.BackColor == _clAtTo)
5024 brs2 = _brsBackColorAtTo;
5026 brs2 = _brsBackColorNone;
5031 if (((Control)sender).Focused)
5032 brs2 = _brsHighLight;
5034 brs2 = _brsDeactiveSelection;
5036 e.Graphics.FillRectangle(brs2, e.Bounds);
5037 e.DrawFocusRectangle();
5038 this.DrawListViewItemIcon(e);
5041 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5043 if (e.ItemState == 0) return;
5045 if (e.ColumnIndex > 0)
5048 var post = (PostClass)e.Item.Tag;
5050 RectangleF rct = e.Bounds;
5051 rct.Width = e.Header.Width;
5052 int fontHeight = e.Item.Font.Height;
5055 rct.Y += fontHeight;
5056 rct.Height -= fontHeight;
5059 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5061 //if (heightDiff > fontHeight * 0.7)
5063 // rct.Height += fontHeight;
5064 // drawLineCount += 1;
5067 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5068 if (!_iconCol && drawLineCount <= 1)
5070 //rct.Inflate(0, heightDiff / -2);
5071 //rct.Height += fontHeight / 2;
5073 else if (heightDiff < fontHeight * 0.7)
5075 //最終行が70%以上欠けていたら、最終行は表示しない
5076 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5077 rct.Height = (fontHeight * drawLineCount) - 1;
5084 //if (!_iconCol && drawLineCount > 1)
5086 // rct.Y += fontHeight * 0.2;
5087 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5092 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5093 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5098 Rectangle rctB = e.Bounds;
5099 rctB.Width = e.Header.Width;
5100 rctB.Height = fontHeight;
5102 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5104 TextRenderer.DrawText(e.Graphics,
5105 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5107 Rectangle.Round(rct),
5109 TextFormatFlags.WordBreak |
5110 TextFormatFlags.EndEllipsis |
5111 TextFormatFlags.GlyphOverhangPadding |
5112 TextFormatFlags.NoPrefix);
5113 TextRenderer.DrawText(e.Graphics,
5114 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 + "]",
5118 TextFormatFlags.SingleLine |
5119 TextFormatFlags.EndEllipsis |
5120 TextFormatFlags.GlyphOverhangPadding |
5121 TextFormatFlags.NoPrefix);
5127 if (e.ColumnIndex != 2)
5128 text = e.SubItem.Text;
5130 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5132 if (drawLineCount == 1)
5134 TextRenderer.DrawText(e.Graphics,
5137 Rectangle.Round(rct),
5139 TextFormatFlags.SingleLine |
5140 TextFormatFlags.EndEllipsis |
5141 TextFormatFlags.GlyphOverhangPadding |
5142 TextFormatFlags.NoPrefix |
5143 TextFormatFlags.VerticalCenter);
5147 TextRenderer.DrawText(e.Graphics,
5150 Rectangle.Round(rct),
5152 TextFormatFlags.WordBreak |
5153 TextFormatFlags.EndEllipsis |
5154 TextFormatFlags.GlyphOverhangPadding |
5155 TextFormatFlags.NoPrefix);
5158 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5163 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5165 if (_iconSz == 0) return;
5167 ImageListViewItem item = (ImageListViewItem)e.Item;
5169 //e.Bounds.Leftが常に0を指すから自前で計算
5170 Rectangle itemRect = item.Bounds;
5171 var col0 = e.Item.ListView.Columns[0];
5172 itemRect.Width = col0.Width;
5174 if (col0.DisplayIndex > 0)
5176 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5178 if (clm.DisplayIndex < col0.DisplayIndex)
5179 itemRect.X += clm.Width;
5183 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5184 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5185 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5188 var img = item.Image;
5191 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5192 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5194 if (iconRect.Width > 0)
5196 e.Graphics.FillRectangle(Brushes.White, iconRect);
5197 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5200 e.Graphics.DrawImage(img.Image, iconRect);
5202 catch (ArgumentException)
5204 item.RefreshImageAsync();
5210 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5211 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5213 item.GetImageAsync();
5216 if (item.StateIndex > -1)
5218 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5219 if (stateRect.Width > 0)
5221 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5222 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5223 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5228 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5230 base.ScaleControl(factor, specified);
5232 ScaleChildControl(this.TabImage, factor);
5234 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5235 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5237 foreach (var listview in listviews)
5239 ScaleChildControl(listview, factor);
5243 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5245 // ImageListViewItem item = (ImageListViewItem)e.Item;
5246 // if (item.StateImageIndex > -1)
5248 // ////e.Bounds.Leftが常に0を指すから自前で計算
5249 // //Rectangle itemRect = item.Bounds;
5250 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5252 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5254 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5256 // // itemRect.X += clm.Width;
5260 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5261 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5263 // if (rct.Width > 0)
5265 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5266 // //e.Graphics.FillRectangle(Brushes.White, rct);
5267 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5268 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5273 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5275 var tab = this._statuses.Tabs[this._curTab.Text];
5277 if (tab.AllCount == 0)
5279 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5283 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5288 case SEARCHTYPE.NextSearch: // 次を検索
5289 if (selectedIndex != -1)
5290 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5294 case SEARCHTYPE.PrevSearch: // 前を検索
5295 if (selectedIndex != -1)
5296 startIndex = Math.Max(selectedIndex - 1, 0);
5298 startIndex = tab.AllCount - 1;
5300 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5302 if (selectedIndex != -1)
5303 startIndex = selectedIndex;
5309 Func<string, bool> stringComparer;
5312 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5314 catch (ArgumentException)
5316 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5320 var reverse = searchType == SEARCHTYPE.PrevSearch;
5321 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5322 .DefaultIfEmpty(-1).First();
5324 if (foundIndex == -1)
5326 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5330 this.SelectListItem(this._curList, foundIndex);
5331 this._curList.EnsureVisible(foundIndex);
5334 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5337 this.ShowSearchDialog();
5340 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5342 var previousSearch = this.SearchDialog.ResultOptions;
5343 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5345 this.SearchDialog.Reset();
5346 this.ShowSearchDialog();
5352 previousSearch.Query,
5353 previousSearch.CaseSensitive,
5354 previousSearch.UseRegex,
5355 SEARCHTYPE.NextSearch);
5358 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5360 var previousSearch = this.SearchDialog.ResultOptions;
5361 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5363 this.SearchDialog.Reset();
5364 this.ShowSearchDialog();
5370 previousSearch.Query,
5371 previousSearch.CaseSensitive,
5372 previousSearch.UseRegex,
5373 SEARCHTYPE.PrevSearch);
5377 /// 検索ダイアログを表示し、検索を実行します
5379 private void ShowSearchDialog()
5381 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5383 this.TopMost = SettingManager.Common.AlwaysTop;
5386 this.TopMost = SettingManager.Common.AlwaysTop;
5388 var searchOptions = this.SearchDialog.ResultOptions;
5389 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5391 if (searchOptions.NewTab)
5393 var tabName = Properties.Resources.SearchResults_TabName;
5397 tabName = this._statuses.MakeTabName(tabName);
5399 catch (TabException ex)
5401 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5404 var resultTab = new LocalSearchTabModel(tabName);
5405 this.AddNewTab(resultTab, startup: false);
5406 this._statuses.AddTab(resultTab);
5408 var targetTab = this._statuses.Tabs[this._curTab.Text];
5410 Func<string, bool> stringComparer;
5413 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5415 catch (ArgumentException)
5417 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5421 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5422 if (foundIndices.Length == 0)
5424 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5428 var foundPosts = foundIndices.Select(x => targetTab[x]);
5429 foreach (var post in foundPosts)
5431 resultTab.AddPostQueue(post);
5434 this._statuses.DistributePosts();
5435 this.RefreshTimeline();
5437 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5438 .First(x => x.Text == tabName);
5440 this.ListTab.SelectedTab = tabPage;
5445 searchOptions.Query,
5446 searchOptions.CaseSensitive,
5447 searchOptions.UseRegex,
5448 SEARCHTYPE.DialogSearch);
5451 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5453 this.AddNewTabForSearch(searchOptions.Query);
5457 /// <summary>発言検索に使用するメソッドを生成します</summary>
5458 /// <exception cref="ArgumentException">
5459 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5461 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5465 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5466 var regex = new Regex(query, regexOption);
5468 return x => regex.IsMatch(x);
5472 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5474 return x => x.IndexOf(query, comparisonType) != -1;
5478 private void AboutMenuItem_Click(object sender, EventArgs e)
5480 using (TweenAboutBox about = new TweenAboutBox())
5482 about.ShowDialog(this);
5484 this.TopMost = SettingManager.Common.AlwaysTop;
5487 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5489 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5491 if (ImageSelector.Enabled)
5494 TabModel foundTab = null;
5497 DetailsListView lst = null;
5500 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5502 var tabPage = this.ListTab.TabPages[i];
5503 var tab = this._statuses.Tabs[tabPage.Text];
5504 var unreadIndex = tab.NextUnreadIndex;
5506 if (unreadIndex != -1)
5508 ListTab.SelectedIndex = i;
5510 foundIndex = unreadIndex;
5511 lst = (DetailsListView)tabPage.Tag;
5516 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5517 if (foundTab == null && bgnIdx > 0)
5519 for (int i = 0; i < bgnIdx; i++)
5521 var tabPage = this.ListTab.TabPages[i];
5522 var tab = this._statuses.Tabs[tabPage.Text];
5523 var unreadIndex = tab.NextUnreadIndex;
5525 if (unreadIndex != -1)
5527 ListTab.SelectedIndex = i;
5529 foundIndex = unreadIndex;
5530 lst = (DetailsListView)tabPage.Tag;
5536 if (foundTab == null)
5538 //全部調べたが未読見つからず→先頭タブの最新発言へ
5539 ListTab.SelectedIndex = 0;
5540 var tabPage = this.ListTab.TabPages[0];
5541 var tab = this._statuses.Tabs[tabPage.Text];
5543 if (tab.AllCount == 0)
5546 if (_statuses.SortOrder == SortOrder.Ascending)
5547 foundIndex = tab.AllCount - 1;
5551 lst = (DetailsListView)tabPage.Tag;
5554 SelectListItem(lst, foundIndex);
5556 if (_statuses.SortMode == ComparerMode.Id)
5558 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5559 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5565 lst.EnsureVisible(foundIndex);
5570 lst.EnsureVisible(foundIndex);
5576 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5578 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5580 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5581 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5585 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5587 if (_curList.SelectedIndices.Count > 0)
5589 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5590 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5594 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5596 await this.CheckNewVersion(false);
5599 private void RunTweenUp()
5601 ProcessStartInfo pinfo = new ProcessStartInfo();
5602 pinfo.UseShellExecute = true;
5603 pinfo.WorkingDirectory = MyCommon.settingPath;
5604 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5605 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5608 Process.Start(pinfo);
5612 MessageBox.Show("Failed to execute TweenUp3.exe.");
5616 public class VersionInfo
5618 public Version Version { get; set; }
5619 public Uri DownloadUri { get; set; }
5620 public string ReleaseNote { get; set; }
5624 /// OpenTween の最新バージョンの情報を取得します
5626 public async Task<VersionInfo> GetVersionInfoAsync()
5628 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5629 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5631 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5632 .ConfigureAwait(false);
5634 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5635 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5637 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5638 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5640 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5642 return new VersionInfo
5644 Version = Version.Parse(msgHeader[0]),
5645 DownloadUri = new Uri(msgHeader[1]),
5646 ReleaseNote = msgBody,
5650 private async Task CheckNewVersion(bool startup = false)
5652 if (ApplicationSettings.VersionInfoUrl == null)
5653 return; // 更新チェック無効化
5657 var versionInfo = await this.GetVersionInfoAsync();
5659 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5664 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5665 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5666 msgtext = MyCommon.ReplaceAppName(msgtext);
5668 MessageBox.Show(msgtext,
5669 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5670 MessageBoxButtons.OK, MessageBoxIcon.Information);
5675 using (var dialog = new UpdateDialog())
5677 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5678 MyCommon.GetReadableVersion(versionInfo.Version));
5679 dialog.DetailsText = versionInfo.ReleaseNote;
5681 if (dialog.ShowDialog(this) == DialogResult.Yes)
5683 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5689 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5692 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5693 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5694 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5699 private async Task Colorize()
5702 await this.DispSelectedPost();
5703 //件数関連の場合、タイトル即時書き換え
5704 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5705 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5706 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5707 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5709 SetMainWindowTitle();
5711 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5712 SetStatusLabelUrl();
5713 foreach (TabPage tb in ListTab.TabPages)
5715 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5717 if (SettingManager.Common.TabIconDisp)
5719 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5723 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5726 public string createDetailHtml(string orgdata)
5728 if (SettingManager.Local.UseTwemoji)
5729 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5731 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5734 private Task DispSelectedPost()
5736 return this.DispSelectedPost(false);
5739 private PostClass displayPost = new PostClass();
5742 /// サムネイル表示に使用する CancellationToken の生成元
5744 private CancellationTokenSource thumbnailTokenSource = null;
5746 private async Task DispSelectedPost(bool forceupdate)
5748 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5751 var oldDisplayPost = this.displayPost;
5752 this.displayPost = this._curPost;
5754 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5757 var loadTasks = new List<Task>
5759 this.tweetDetailsView.ShowPostDetails(this._curPost),
5762 this.SplitContainer3.Panel2Collapsed = true;
5764 if (SettingManager.Common.PreviewEnable)
5766 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5767 oldTokenSource?.Cancel();
5769 var token = this.thumbnailTokenSource.Token;
5770 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5775 await Task.WhenAll(loadTasks);
5777 catch (OperationCanceledException) { }
5780 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5782 await this.OpenApplicationWebsite();
5785 private async Task OpenApplicationWebsite()
5787 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5790 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5792 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5795 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5797 if (ListTab.SelectedTab != null)
5799 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5801 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5802 if (pnl.Controls["comboSearch"].Focused ||
5803 pnl.Controls["comboLang"].Focused ||
5804 pnl.Controls["buttonSearch"].Focused) return;
5807 if (e.Control || e.Shift || e.Alt)
5808 this._anchorFlag = false;
5810 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5813 e.SuppressKeyPress = true;
5816 if (asyncTask != null)
5821 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5823 private void InitializeShortcuts()
5825 this.shortcutCommands = new[]
5827 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5828 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5829 .FocusedOn(FocusedControl.ListTab)
5830 .Do(() => SendKeys.Send("{DOWN}")),
5832 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5833 .FocusedOn(FocusedControl.ListTab)
5834 .Do(() => SendKeys.Send("{UP}")),
5836 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5837 .FocusedOn(FocusedControl.ListTab)
5838 .Do(() => SendKeys.Send("{PGDN}")),
5840 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5841 .FocusedOn(FocusedControl.ListTab)
5842 .Do(() => SendKeys.Send("{PGUP}")),
5844 ShortcutCommand.Create(Keys.F1)
5845 .Do(() => this.OpenApplicationWebsite()),
5847 ShortcutCommand.Create(Keys.F3)
5848 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5850 ShortcutCommand.Create(Keys.F5)
5851 .Do(() => this.DoRefresh()),
5853 ShortcutCommand.Create(Keys.F6)
5854 .Do(() => this.GetReplyAsync()),
5856 ShortcutCommand.Create(Keys.F7)
5857 .Do(() => this.GetDirectMessagesAsync()),
5859 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5860 .NotFocusedOn(FocusedControl.StatusText)
5861 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5863 ShortcutCommand.Create(Keys.G)
5864 .NotFocusedOn(FocusedControl.StatusText)
5865 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5867 ShortcutCommand.Create(Keys.Right, Keys.N)
5868 .FocusedOn(FocusedControl.ListTab)
5869 .Do(() => this.GoRelPost(forward: true)),
5871 ShortcutCommand.Create(Keys.Left, Keys.P)
5872 .FocusedOn(FocusedControl.ListTab)
5873 .Do(() => this.GoRelPost(forward: false)),
5875 ShortcutCommand.Create(Keys.OemPeriod)
5876 .FocusedOn(FocusedControl.ListTab)
5877 .Do(() => this.GoAnchor()),
5879 ShortcutCommand.Create(Keys.I)
5880 .FocusedOn(FocusedControl.ListTab)
5881 .OnlyWhen(() => this.StatusText.Enabled)
5882 .Do(() => this.StatusText.Focus()),
5884 ShortcutCommand.Create(Keys.Enter)
5885 .FocusedOn(FocusedControl.ListTab)
5886 .Do(() => this.MakeReplyOrDirectStatus()),
5888 ShortcutCommand.Create(Keys.R)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .Do(() => this.DoRefresh()),
5892 ShortcutCommand.Create(Keys.L)
5893 .FocusedOn(FocusedControl.ListTab)
5894 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5896 ShortcutCommand.Create(Keys.H)
5897 .FocusedOn(FocusedControl.ListTab)
5898 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5900 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5901 .FocusedOn(FocusedControl.ListTab)
5902 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5904 ShortcutCommand.Create(Keys.S)
5905 .FocusedOn(FocusedControl.ListTab)
5906 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5908 ShortcutCommand.Create(Keys.A)
5909 .FocusedOn(FocusedControl.ListTab)
5910 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5912 // ] in_reply_to参照元へ戻る
5913 ShortcutCommand.Create(Keys.Oem4)
5914 .FocusedOn(FocusedControl.ListTab)
5915 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5917 // [ in_reply_toへジャンプ
5918 ShortcutCommand.Create(Keys.Oem6)
5919 .FocusedOn(FocusedControl.ListTab)
5920 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5922 ShortcutCommand.Create(Keys.Escape)
5923 .FocusedOn(FocusedControl.ListTab)
5925 this._anchorFlag = false;
5926 if (ListTab.SelectedTab != null)
5928 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5929 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5931 var relTp = ListTab.SelectedTab;
5932 RemoveSpecifiedTab(relTp.Text, false);
5938 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5939 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5940 .FocusedOn(FocusedControl.ListTab)
5941 .Do(() => this._anchorFlag = false, preventDefault: false),
5943 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5944 ShortcutCommand.Create(Keys.Up, Keys.Down)
5945 .FocusedOn(FocusedControl.PostBrowser)
5948 ShortcutCommand.Create(Keys.Control | Keys.R)
5949 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5951 ShortcutCommand.Create(Keys.Control | Keys.D)
5952 .Do(() => this.doStatusDelete()),
5954 ShortcutCommand.Create(Keys.Control | Keys.M)
5955 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5957 ShortcutCommand.Create(Keys.Control | Keys.S)
5958 .Do(() => this.FavoriteChange(FavAdd: true)),
5960 ShortcutCommand.Create(Keys.Control | Keys.I)
5961 .Do(() => this.doRepliedStatusOpen()),
5963 ShortcutCommand.Create(Keys.Control | Keys.Q)
5964 .Do(() => this.doQuoteOfficial()),
5966 ShortcutCommand.Create(Keys.Control | Keys.B)
5967 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5969 ShortcutCommand.Create(Keys.Control | Keys.T)
5970 .Do(() => this.HashManageMenuItem_Click(null, null)),
5972 ShortcutCommand.Create(Keys.Control | Keys.L)
5973 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5975 ShortcutCommand.Create(Keys.Control | Keys.Y)
5976 .NotFocusedOn(FocusedControl.PostBrowser)
5977 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5979 ShortcutCommand.Create(Keys.Control | Keys.F)
5980 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5982 ShortcutCommand.Create(Keys.Control | Keys.U)
5983 .Do(() => this.ShowUserTimeline()),
5985 ShortcutCommand.Create(Keys.Control | Keys.H)
5986 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5988 ShortcutCommand.Create(Keys.Control | Keys.G)
5989 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5991 ShortcutCommand.Create(Keys.Control | Keys.O)
5992 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5994 ShortcutCommand.Create(Keys.Control | Keys.E)
5995 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5997 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5998 .FocusedOn(FocusedControl.ListTab)
5999 .Do(() => this._colorize = true, preventDefault: false),
6001 ShortcutCommand.Create(Keys.Control | Keys.N)
6002 .FocusedOn(FocusedControl.ListTab)
6003 .Do(() => this.GoNextTab(forward: true)),
6005 ShortcutCommand.Create(Keys.Control | Keys.P)
6006 .FocusedOn(FocusedControl.ListTab)
6007 .Do(() => this.GoNextTab(forward: false)),
6009 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6010 .FocusedOn(FocusedControl.ListTab)
6011 .Do(() => this.CopyStot()),
6013 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6014 ShortcutCommand.Create(Keys.Control | Keys.D1)
6015 .FocusedOn(FocusedControl.ListTab)
6016 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6017 .Do(() => this.ListTab.SelectedIndex = 0),
6019 ShortcutCommand.Create(Keys.Control | Keys.D2)
6020 .FocusedOn(FocusedControl.ListTab)
6021 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6022 .Do(() => this.ListTab.SelectedIndex = 1),
6024 ShortcutCommand.Create(Keys.Control | Keys.D3)
6025 .FocusedOn(FocusedControl.ListTab)
6026 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6027 .Do(() => this.ListTab.SelectedIndex = 2),
6029 ShortcutCommand.Create(Keys.Control | Keys.D4)
6030 .FocusedOn(FocusedControl.ListTab)
6031 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6032 .Do(() => this.ListTab.SelectedIndex = 3),
6034 ShortcutCommand.Create(Keys.Control | Keys.D5)
6035 .FocusedOn(FocusedControl.ListTab)
6036 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6037 .Do(() => this.ListTab.SelectedIndex = 4),
6039 ShortcutCommand.Create(Keys.Control | Keys.D6)
6040 .FocusedOn(FocusedControl.ListTab)
6041 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6042 .Do(() => this.ListTab.SelectedIndex = 5),
6044 ShortcutCommand.Create(Keys.Control | Keys.D7)
6045 .FocusedOn(FocusedControl.ListTab)
6046 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6047 .Do(() => this.ListTab.SelectedIndex = 6),
6049 ShortcutCommand.Create(Keys.Control | Keys.D8)
6050 .FocusedOn(FocusedControl.ListTab)
6051 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6052 .Do(() => this.ListTab.SelectedIndex = 7),
6054 ShortcutCommand.Create(Keys.Control | Keys.D9)
6055 .FocusedOn(FocusedControl.ListTab)
6056 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6058 ShortcutCommand.Create(Keys.Control | Keys.A)
6059 .FocusedOn(FocusedControl.StatusText)
6060 .Do(() => this.StatusText.SelectAll()),
6062 ShortcutCommand.Create(Keys.Control | Keys.V)
6063 .FocusedOn(FocusedControl.StatusText)
6064 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6066 ShortcutCommand.Create(Keys.Control | Keys.Up)
6067 .FocusedOn(FocusedControl.StatusText)
6069 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6071 var inReplyToStatusId = this.inReplyTo?.Item1;
6072 var inReplyToScreenName = this.inReplyTo?.Item2;
6073 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6076 if (_hisIdx < 0) _hisIdx = 0;
6078 var historyItem = this._history[this._hisIdx];
6079 StatusText.Text = historyItem.status;
6080 StatusText.SelectionStart = StatusText.Text.Length;
6081 if (historyItem.inReplyToId != null)
6082 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6084 this.inReplyTo = null;
6087 ShortcutCommand.Create(Keys.Control | Keys.Down)
6088 .FocusedOn(FocusedControl.StatusText)
6090 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6092 var inReplyToStatusId = this.inReplyTo?.Item1;
6093 var inReplyToScreenName = this.inReplyTo?.Item2;
6094 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6097 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6099 var historyItem = this._history[this._hisIdx];
6100 StatusText.Text = historyItem.status;
6101 StatusText.SelectionStart = StatusText.Text.Length;
6102 if (historyItem.inReplyToId != null)
6103 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6105 this.inReplyTo = null;
6108 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6109 .FocusedOn(FocusedControl.StatusText)
6111 if (ListTab.SelectedIndex == 0)
6113 ListTab.SelectedIndex = ListTab.TabCount - 1;
6117 ListTab.SelectedIndex -= 1;
6122 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6123 .FocusedOn(FocusedControl.StatusText)
6125 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6127 ListTab.SelectedIndex = 0;
6131 ListTab.SelectedIndex += 1;
6136 ShortcutCommand.Create(Keys.Control | Keys.Y)
6137 .FocusedOn(FocusedControl.PostBrowser)
6139 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6140 MultiLineMenuItem_Click(null, null);
6143 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6144 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6146 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6147 .Do(() => this.DoRefreshMore()),
6149 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6150 .Do(() => this.GetReplyAsync(loadMore: true)),
6152 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6153 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6155 ShortcutCommand.Create(Keys.Shift | Keys.R)
6156 .NotFocusedOn(FocusedControl.StatusText)
6157 .Do(() => this.DoRefreshMore()),
6159 ShortcutCommand.Create(Keys.Shift | Keys.H)
6160 .FocusedOn(FocusedControl.ListTab)
6161 .Do(() => this.GoTopEnd(GoTop: true)),
6163 ShortcutCommand.Create(Keys.Shift | Keys.L)
6164 .FocusedOn(FocusedControl.ListTab)
6165 .Do(() => this.GoTopEnd(GoTop: false)),
6167 ShortcutCommand.Create(Keys.Shift | Keys.M)
6168 .FocusedOn(FocusedControl.ListTab)
6169 .Do(() => this.GoMiddle()),
6171 ShortcutCommand.Create(Keys.Shift | Keys.G)
6172 .FocusedOn(FocusedControl.ListTab)
6173 .Do(() => this.GoLast()),
6175 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6176 .FocusedOn(FocusedControl.ListTab)
6177 .Do(() => this.MoveMiddle()),
6179 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6180 .FocusedOn(FocusedControl.ListTab)
6181 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6183 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6184 .FocusedOn(FocusedControl.ListTab)
6185 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6187 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6188 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6189 .FocusedOn(FocusedControl.ListTab)
6190 .Do(() => this.GoFav(forward: true)),
6192 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6193 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6194 .FocusedOn(FocusedControl.ListTab)
6195 .Do(() => this.GoFav(forward: false)),
6197 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6198 .FocusedOn(FocusedControl.ListTab)
6199 .Do(() => this.GoBackSelectPostChain()),
6201 ShortcutCommand.Create(Keys.Alt | Keys.R)
6202 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6204 ShortcutCommand.Create(Keys.Alt | Keys.P)
6205 .OnlyWhen(() => this._curPost != null)
6206 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6208 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6209 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6211 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6212 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6214 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6215 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6217 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6218 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6220 // 別タブの同じ書き込みへ(ALT+←/→)
6221 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6222 .FocusedOn(FocusedControl.ListTab)
6223 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6225 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6226 .FocusedOn(FocusedControl.ListTab)
6227 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6229 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6230 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6232 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6233 .Do(() => this.CopyIdUri()),
6235 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6236 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6237 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6238 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6240 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6241 .Do(() => this.FavoriteChange(FavAdd: false)),
6243 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6244 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6246 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6247 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6249 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6250 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6252 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6253 .Do(() => this.doMoveToRTHome()),
6255 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6256 .Do(() => this.FavorareMenuItem_Click(null, null)),
6258 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6259 .FocusedOn(FocusedControl.StatusText)
6261 if (_curList != null && _curList.VirtualListSize != 0 &&
6262 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6264 var idx = _curList.SelectedIndices[0] - 1;
6265 SelectListItem(_curList, idx);
6266 _curList.EnsureVisible(idx);
6270 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6271 .FocusedOn(FocusedControl.StatusText)
6273 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6274 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6276 var idx = _curList.SelectedIndices[0] + 1;
6277 SelectListItem(_curList, idx);
6278 _curList.EnsureVisible(idx);
6282 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6283 .FocusedOn(FocusedControl.StatusText)
6285 if (StatusText.SelectionStart > 0)
6287 int endidx = StatusText.SelectionStart - 1;
6288 string startstr = "";
6289 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6291 char c = StatusText.Text[i];
6292 if (Char.IsLetterOrDigit(c) || c == '_')
6298 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6299 int cnt = AtIdSupl.ItemCount;
6300 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6301 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6305 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6306 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6316 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6317 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6318 .FocusedOn(FocusedControl.ListTab)
6319 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6321 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6322 .FocusedOn(FocusedControl.ListTab)
6323 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6325 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6326 .FocusedOn(FocusedControl.ListTab)
6327 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6329 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6330 .FocusedOn(FocusedControl.ListTab)
6331 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6333 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6334 .FocusedOn(FocusedControl.ListTab)
6335 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6337 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6338 .FocusedOn(FocusedControl.ListTab)
6339 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6341 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6342 .FocusedOn(FocusedControl.ListTab)
6343 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6345 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6346 .FocusedOn(FocusedControl.ListTab)
6347 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6349 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6350 .FocusedOn(FocusedControl.ListTab)
6351 .Do(() => this.SetSortLastColumn()),
6353 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6354 .Do(() => this.FavoritesRetweetOfficial()),
6356 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6357 .Do(() => this.FavoritesRetweetUnofficial()),
6359 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6360 .Do(() => this.OpenUserAppointUrl()),
6362 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6363 .FocusedOn(FocusedControl.PostBrowser)
6364 .Do(() => this.doReTweetUnofficial()),
6366 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6367 .OnlyWhen(() => this.ExistCurrentPost)
6368 .Do(() => this.tweetDetailsView.DoTranslation()),
6370 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6371 .Do(() => this.doReTweetUnofficial()),
6373 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6374 .Do(() => this.CopyUserId()),
6376 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6377 .Do(() => this.tweetThumbnail1.ScrollUp()),
6379 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6380 .Do(() => this.tweetThumbnail1.ScrollDown()),
6382 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6383 .FocusedOn(FocusedControl.ListTab)
6384 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6385 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6389 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6391 // Task を返す非同期処理があれば asyncTask に代入する
6394 // ShortcutCommand に対応しているコマンドはここで処理される
6395 foreach (var command in this.shortcutCommands)
6397 if (command.IsMatch(keyData, focusedOn))
6399 asyncTask = command.RunCommand();
6400 return command.PreventDefault;
6407 private void GoNextTab(bool forward)
6409 int idx = ListTab.SelectedIndex;
6413 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6418 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6420 ListTab.SelectedIndex = idx;
6423 private void CopyStot()
6426 StringBuilder sb = new StringBuilder();
6427 bool IsProtected = false;
6429 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6430 foreach (int idx in _curList.SelectedIndices)
6432 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6433 if (post.IsDeleted) continue;
6436 if (post.RetweetedId != null)
6437 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6439 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6443 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6448 MessageBox.Show(Properties.Resources.CopyStotText1);
6452 clstr = sb.ToString();
6455 Clipboard.SetDataObject(clstr, false, 5, 100);
6457 catch (Exception ex)
6459 MessageBox.Show(ex.Message);
6464 private void CopyIdUri()
6466 if (this._curTab == null)
6469 var tab = this._statuses.GetTabByName(this._curTab.Text);
6470 if (tab == null || tab is DirectMessagesTabModel)
6473 var copyUrls = new List<string>();
6474 foreach (int idx in _curList.SelectedIndices)
6476 var post = tab[idx];
6477 copyUrls.Add(MyCommon.GetStatusUrl(post));
6480 if (copyUrls.Count == 0)
6485 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6487 catch (ExternalException ex)
6489 MessageBox.Show(ex.Message);
6493 private void GoFav(bool forward)
6495 if (_curList.VirtualListSize == 0) return;
6502 if (_curList.SelectedIndices.Count == 0)
6508 fIdx = _curList.SelectedIndices[0] + 1;
6509 if (fIdx > _curList.VirtualListSize - 1) return;
6511 toIdx = _curList.VirtualListSize;
6516 if (_curList.SelectedIndices.Count == 0)
6518 fIdx = _curList.VirtualListSize - 1;
6522 fIdx = _curList.SelectedIndices[0] - 1;
6523 if (fIdx < 0) return;
6529 for (int idx = fIdx; idx != toIdx; idx += stp)
6531 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6533 SelectListItem(_curList, idx);
6534 _curList.EnsureVisible(idx);
6540 private void GoSamePostToAnotherTab(bool left)
6542 if (this._curList.SelectedIndices.Count == 0)
6545 var tab = this._statuses.Tabs[this._curTab.Text];
6547 // Directタブは対象外(見つかるはずがない)
6548 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6551 var selectedIndex = this._curList.SelectedIndices[0];
6552 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6554 int fIdx, toIdx, stp;
6559 if (ListTab.SelectedIndex == 0)
6565 fIdx = ListTab.SelectedIndex - 1;
6573 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6579 fIdx = ListTab.SelectedIndex + 1;
6581 toIdx = ListTab.TabCount;
6585 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6587 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6590 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6593 var foundIndex = targetTab.IndexOf(selectedStatusId);
6594 if (foundIndex != -1)
6596 ListTab.SelectedIndex = tabidx;
6597 SelectListItem(_curList, foundIndex);
6598 _curList.EnsureVisible(foundIndex);
6604 private void GoPost(bool forward)
6606 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6609 var tab = this._statuses.Tabs[this._curTab.Text];
6610 var selectedIndex = this._curList.SelectedIndices[0];
6612 int fIdx, toIdx, stp;
6616 fIdx = selectedIndex + 1;
6617 if (fIdx > tab.AllCount - 1) return;
6618 toIdx = tab.AllCount;
6623 fIdx = selectedIndex - 1;
6624 if (fIdx < 0) return;
6630 if (_curPost.RetweetedId == null)
6632 name = _curPost.ScreenName;
6636 name = _curPost.RetweetedBy;
6638 for (int idx = fIdx; idx != toIdx; idx += stp)
6640 var post = tab[idx];
6641 if (post.RetweetedId == null)
6643 if (post.ScreenName == name)
6645 SelectListItem(_curList, idx);
6646 _curList.EnsureVisible(idx);
6652 if (post.RetweetedBy == name)
6654 SelectListItem(_curList, idx);
6655 _curList.EnsureVisible(idx);
6662 private void GoRelPost(bool forward)
6664 if (this._curList.SelectedIndices.Count == 0)
6667 var tab = this._statuses.Tabs[this._curTab.Text];
6668 var selectedIndex = this._curList.SelectedIndices[0];
6670 int fIdx, toIdx, stp;
6674 fIdx = selectedIndex + 1;
6675 if (fIdx > tab.AllCount - 1) return;
6676 toIdx = tab.AllCount;
6681 fIdx = selectedIndex - 1;
6682 if (fIdx < 0) return;
6689 if (_curPost == null) return;
6690 _anchorPost = _curPost;
6695 if (_anchorPost == null) return;
6698 for (int idx = fIdx; idx != toIdx; idx += stp)
6700 var post = tab[idx];
6701 if (post.ScreenName == _anchorPost.ScreenName ||
6702 post.RetweetedBy == _anchorPost.ScreenName ||
6703 post.ScreenName == _anchorPost.RetweetedBy ||
6704 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6705 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6706 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6707 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6708 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6710 SelectListItem(_curList, idx);
6711 _curList.EnsureVisible(idx);
6717 private void GoAnchor()
6719 if (_anchorPost == null) return;
6720 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6721 if (idx == -1) return;
6723 SelectListItem(_curList, idx);
6724 _curList.EnsureVisible(idx);
6727 private void GoTopEnd(bool GoTop)
6729 if (_curList.VirtualListSize == 0)
6737 _item = _curList.GetItemAt(0, 25);
6745 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6747 idx = _curList.VirtualListSize - 1;
6751 SelectListItem(_curList, idx);
6754 private void GoMiddle()
6756 if (_curList.VirtualListSize == 0)
6764 _item = _curList.GetItemAt(0, 0);
6774 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6777 idx2 = _curList.VirtualListSize - 1;
6783 idx3 = (idx1 + idx2) / 2;
6785 SelectListItem(_curList, idx3);
6788 private void GoLast()
6790 if (_curList.VirtualListSize == 0) return;
6792 if (_statuses.SortOrder == SortOrder.Ascending)
6794 SelectListItem(_curList, _curList.VirtualListSize - 1);
6795 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6799 SelectListItem(_curList, 0);
6800 _curList.EnsureVisible(0);
6804 private void MoveTop()
6806 if (_curList.SelectedIndices.Count == 0) return;
6807 int idx = _curList.SelectedIndices[0];
6808 if (_statuses.SortOrder == SortOrder.Ascending)
6810 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6814 _curList.EnsureVisible(0);
6816 _curList.EnsureVisible(idx);
6819 private async Task GoInReplyToPostTree()
6821 if (_curPost == null) return;
6823 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6825 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6829 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6831 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6832 _curPost.InReplyToUser = post.InReplyToUser;
6833 _curPost.IsReply = post.IsReply;
6834 this.PurgeListViewItemCache();
6835 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6837 catch (WebApiException ex)
6839 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6843 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6845 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6847 replyChains = new Stack<ReplyChain>();
6849 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6852 string inReplyToTabName;
6853 long inReplyToId = _curPost.InReplyToStatusId.Value;
6854 string inReplyToUser = _curPost.InReplyToUser;
6855 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6857 var inReplyToPosts = from tab in _statuses.Tabs.Values
6858 orderby tab != curTabClass
6859 from post in tab.Posts.Values
6860 where post.StatusId == inReplyToId
6861 let index = tab.IndexOf(post.StatusId)
6863 select new {Tab = tab, Index = index};
6865 var inReplyPost = inReplyToPosts.FirstOrDefault();
6866 if (inReplyPost == null)
6870 await Task.Run(async () =>
6872 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6873 .ConfigureAwait(false);
6876 _statuses.AddPost(post);
6877 _statuses.DistributePosts();
6880 catch (WebApiException ex)
6882 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6883 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6887 this.RefreshTimeline();
6889 inReplyPost = inReplyToPosts.FirstOrDefault();
6890 if (inReplyPost == null)
6892 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6896 inReplyToTabName = inReplyPost.Tab.TabName;
6897 inReplyToIndex = inReplyPost.Index;
6899 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6900 DetailsListView listView = (DetailsListView)tabPage.Tag;
6902 if (_curTab != tabPage)
6904 this.ListTab.SelectTab(tabPage);
6907 this.SelectListItem(listView, inReplyToIndex);
6908 listView.EnsureVisible(inReplyToIndex);
6911 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6913 if (_curPost == null) return;
6915 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6916 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6920 if (_curPost.InReplyToStatusId != null)
6922 var posts = from t in _statuses.Tabs
6923 from p in t.Value.Posts
6924 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6925 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6927 orderby isForward ? indexOf : indexOf * -1
6928 orderby t.Value != curTabClass
6929 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6932 var postList = posts.ToList();
6933 for (int i = postList.Count - 1; i >= 0; i--)
6936 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6938 postList.RemoveAt(index);
6941 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6942 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6943 if (post == null) post = postList.First();
6944 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6945 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6946 SelectListItem(listView, post.Index);
6947 listView.EnsureVisible(post.Index);
6949 catch (InvalidOperationException)
6957 if (replyChains == null || replyChains.Count < 1)
6959 var posts = from t in _statuses.Tabs
6960 from p in t.Value.Posts
6961 where p.Value.InReplyToStatusId == _curPost.StatusId
6962 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6965 orderby t.Value != curTabClass
6966 select new {Tab = t.Value, Index = indexOf};
6969 var post = posts.First();
6970 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6971 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6972 SelectListItem(listView, post.Index);
6973 listView.EnsureVisible(post.Index);
6975 catch (InvalidOperationException)
6982 ReplyChain chainHead = replyChains.Pop();
6983 if (chainHead.InReplyToId == _curPost.StatusId)
6985 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6994 ListTab.SelectTab(chainHead.OriginalTab);
7000 SelectListItem(_curList, idx);
7001 _curList.EnsureVisible(idx);
7007 this.GoBackInReplyToPostTree(parallel);
7013 private void GoBackSelectPostChain()
7015 if (this.selectPostChains.Count > 1)
7024 this.selectPostChains.Pop();
7025 var (tabPage, post) = this.selectPostChains.Peek();
7027 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7031 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7032 if (idx == -1) continue; //該当ポストが存在しないので無視
7037 this.selectPostChains.Pop();
7039 catch (InvalidOperationException)
7045 while (this.selectPostChains.Count > 1);
7050 //履歴が残り1つであればクリアしておく
7051 if (this.selectPostChains.Count == 1)
7052 this.selectPostChains.Clear();
7056 DetailsListView lst = (DetailsListView)tp.Tag;
7057 this.ListTab.SelectedTab = tp;
7060 SelectListItem(lst, idx);
7061 lst.EnsureVisible(idx);
7067 private void PushSelectPostChain()
7069 int count = this.selectPostChains.Count;
7072 var (tabPage, post) = this.selectPostChains.Peek();
7073 if (tabPage == this._curTab)
7075 if (post == this._curPost) return; //最新の履歴と同一
7076 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7079 if (count >= 2500) TrimPostChain();
7080 this.selectPostChains.Push((this._curTab, this._curPost));
7083 private void TrimPostChain()
7085 if (this.selectPostChains.Count <= 2000) return;
7086 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7087 for (int i = 0; i < 2000; i++)
7089 p.Push(this.selectPostChains.Pop());
7091 this.selectPostChains.Clear();
7092 for (int i = 0; i < 2000; i++)
7094 this.selectPostChains.Push(p.Pop());
7098 private bool GoStatus(long statusId)
7100 if (statusId == 0) return false;
7101 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7103 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7105 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7106 ListTab.SelectedIndex = tabidx;
7107 SelectListItem(_curList, idx);
7108 _curList.EnsureVisible(idx);
7115 private bool GoDirectMessage(long statusId)
7117 if (statusId == 0) return false;
7118 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7120 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7122 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7123 ListTab.SelectedIndex = tabidx;
7124 SelectListItem(_curList, idx);
7125 _curList.EnsureVisible(idx);
7132 private void MyList_MouseClick(object sender, MouseEventArgs e)
7134 _anchorFlag = false;
7137 private void StatusText_Enter(object sender, EventArgs e)
7139 // フォーカスの戻り先を StatusText に設定
7140 this.Tag = StatusText;
7141 StatusText.BackColor = _clInputBackcolor;
7144 public Color InputBackColor
7146 get => _clInputBackcolor;
7147 set => _clInputBackcolor = value;
7150 private void StatusText_Leave(object sender, EventArgs e)
7152 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7153 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7154 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7157 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7159 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7162 e.SuppressKeyPress = true;
7165 this.StatusText_TextChanged(null, null);
7167 if (asyncTask != null)
7171 private void SaveConfigsAll(bool ifModified)
7175 SaveConfigsCommon();
7182 if (ModifySettingCommon) SaveConfigsCommon();
7183 if (ModifySettingLocal) SaveConfigsLocal();
7184 if (ModifySettingAtId) SaveConfigsAtId();
7188 private void SaveConfigsAtId()
7190 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7192 ModifySettingAtId = false;
7193 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7194 SettingManager.SaveAtIdList();
7197 private void SaveConfigsCommon()
7199 if (_ignoreConfigSave) return;
7201 ModifySettingCommon = false;
7204 SettingManager.Common.UserName = tw.Username;
7205 SettingManager.Common.UserId = tw.UserId;
7206 SettingManager.Common.Token = tw.AccessToken;
7207 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7209 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7210 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7212 SettingManager.Common.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7215 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7216 switch (_statuses.SortMode)
7218 case ComparerMode.Nickname: //ニックネーム
7219 SettingManager.Common.SortColumn = 1;
7221 case ComparerMode.Data: //本文
7222 SettingManager.Common.SortColumn = 2;
7224 case ComparerMode.Id: //時刻=発言Id
7225 SettingManager.Common.SortColumn = 3;
7227 case ComparerMode.Name: //名前
7228 SettingManager.Common.SortColumn = 4;
7230 case ComparerMode.Source: //Source
7231 SettingManager.Common.SortColumn = 7;
7235 SettingManager.Common.HashTags = HashMgr.HashHistories;
7236 if (HashMgr.IsPermanent)
7238 SettingManager.Common.HashSelected = HashMgr.UseHash;
7242 SettingManager.Common.HashSelected = "";
7244 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7245 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7246 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7247 if (ToolStripFocusLockMenuItem != null &&
7248 ToolStripFocusLockMenuItem.IsDisposed == false)
7250 SettingManager.Common.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7252 SettingManager.Common.TrackWord = tw.TrackWord;
7253 SettingManager.Common.AllAtReply = tw.AllAtReply;
7254 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7255 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7257 SettingManager.SaveCommon();
7261 private void SaveConfigsLocal()
7263 if (_ignoreConfigSave) return;
7266 ModifySettingLocal = false;
7267 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7268 SettingManager.Local.FormSize = _mySize;
7269 SettingManager.Local.FormLocation = _myLoc;
7270 SettingManager.Local.SplitterDistance = _mySpDis;
7271 SettingManager.Local.PreviewDistance = _mySpDis3;
7272 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7273 SettingManager.Local.StatusTextHeight = _mySpDis2;
7275 SettingManager.Local.FontUnread = _fntUnread;
7276 SettingManager.Local.ColorUnread = _clUnread;
7277 SettingManager.Local.FontRead = _fntReaded;
7278 SettingManager.Local.ColorRead = _clReaded;
7279 SettingManager.Local.FontDetail = _fntDetail;
7280 SettingManager.Local.ColorDetail = _clDetail;
7281 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7282 SettingManager.Local.ColorDetailLink = _clDetailLink;
7283 SettingManager.Local.ColorFav = _clFav;
7284 SettingManager.Local.ColorOWL = _clOWL;
7285 SettingManager.Local.ColorRetweet = _clRetweet;
7286 SettingManager.Local.ColorSelf = _clSelf;
7287 SettingManager.Local.ColorAtSelf = _clAtSelf;
7288 SettingManager.Local.ColorTarget = _clTarget;
7289 SettingManager.Local.ColorAtTarget = _clAtTarget;
7290 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7291 SettingManager.Local.ColorAtTo = _clAtTo;
7292 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7293 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7294 SettingManager.Local.ColorInputFont = _clInputFont;
7295 SettingManager.Local.FontInputFont = _fntInputFont;
7297 if (_ignoreConfigSave) return;
7298 SettingManager.SaveLocal();
7302 private void SaveConfigsTabs()
7304 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7306 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7307 .Select(x => this._statuses.Tabs[x.Text])
7308 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7310 foreach (var tab in tabs)
7312 if (!tab.IsPermanentTabType)
7315 var tabSetting = new SettingTabs.SettingTabItem
7317 TabName = tab.TabName,
7318 TabType = tab.TabType,
7319 UnreadManage = tab.UnreadManage,
7320 Protected = tab.Protected,
7321 Notify = tab.Notify,
7322 SoundFile = tab.SoundFile,
7327 case FilterTabModel filterTab:
7328 tabSetting.FilterArray = filterTab.FilterArray;
7330 case UserTimelineTabModel userTab:
7331 tabSetting.User = userTab.ScreenName;
7333 case PublicSearchTabModel searchTab:
7334 tabSetting.SearchWords = searchTab.SearchWords;
7335 tabSetting.SearchLang = searchTab.SearchLang;
7337 case ListTimelineTabModel listTab:
7338 tabSetting.ListInfo = listTab.ListInfo;
7342 tabSettingList.Add(tabSetting);
7345 SettingManager.Tabs.Tabs = tabSettingList;
7346 SettingManager.SaveTabs();
7349 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7351 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7352 if (ret != DialogResult.OK)
7355 var match = Twitter.StatusUrlRegex.Match(inputText);
7358 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7359 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7365 var statusId = long.Parse(match.Groups["StatusId"].Value);
7366 await this.OpenRelatedTab(statusId);
7368 catch (TabException ex)
7370 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7374 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7376 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7377 Properties.Resources.SaveLogMenuItem_ClickText2,
7378 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7379 if (rslt == DialogResult.Cancel) return;
7381 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7382 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7383 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7384 SaveFileDialog1.FilterIndex = 0;
7385 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7386 SaveFileDialog1.RestoreDirectory = true;
7388 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7390 if (!SaveFileDialog1.ValidateNames) return;
7391 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7393 if (rslt == DialogResult.Yes)
7396 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7398 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7399 string protect = "";
7400 if (post.IsProtect) protect = "Protect";
7401 sw.WriteLine(post.Nickname + "\t" +
7402 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7403 post.CreatedAt + "\t" +
7404 post.ScreenName + "\t" +
7405 post.StatusId + "\t" +
7406 post.ImageUrl + "\t" +
7407 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7413 foreach (int idx in _curList.SelectedIndices)
7415 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7416 string protect = "";
7417 if (post.IsProtect) protect = "Protect";
7418 sw.WriteLine(post.Nickname + "\t" +
7419 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7420 post.CreatedAt + "\t" +
7421 post.ScreenName + "\t" +
7422 post.StatusId + "\t" +
7423 post.ImageUrl + "\t" +
7424 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7430 this.TopMost = SettingManager.Common.AlwaysTop;
7433 public bool TabRename(string origTabName, out string newTabName)
7437 using (InputTabName inputName = new InputTabName())
7439 inputName.TabName = origTabName;
7440 inputName.ShowDialog();
7441 if (inputName.DialogResult == DialogResult.Cancel) return false;
7442 newTabName = inputName.TabName;
7444 this.TopMost = SettingManager.Common.AlwaysTop;
7445 if (!string.IsNullOrEmpty(newTabName))
7448 for (int i = 0; i < ListTab.TabCount; i++)
7450 if (ListTab.TabPages[i].Text == newTabName)
7452 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7453 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7458 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7459 .FirstOrDefault(x => x.Text == origTabName);
7462 if (tabPage != null)
7463 tabPage.Text = newTabName;
7465 _statuses.RenameTab(origTabName, newTabName);
7467 SaveConfigsCommon();
7469 _rclickTabName = newTabName;
7478 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7480 if (e.Button == MouseButtons.Middle)
7482 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7484 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7486 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7487 this.SaveConfigsTabs();
7494 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7496 TabRename(this.ListTab.SelectedTab.Text, out var _);
7499 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7501 if (SettingManager.Common.TabMouseLock) return;
7502 if (e.Button == MouseButtons.Left)
7504 for (int i = 0; i < ListTab.TabPages.Count; i++)
7506 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7509 _tabMouseDownPoint = e.Location;
7520 private void ListTab_DragEnter(object sender, DragEventArgs e)
7522 if (e.Data.GetDataPresent(typeof(TabPage)))
7523 e.Effect = DragDropEffects.Move;
7525 e.Effect = DragDropEffects.None;
7528 private void ListTab_DragDrop(object sender, DragEventArgs e)
7530 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7535 Point cpos = new Point(e.X, e.Y);
7536 Point spos = ListTab.PointToClient(cpos);
7538 for (i = 0; i < ListTab.TabPages.Count; i++)
7540 Rectangle rect = ListTab.GetTabRect(i);
7541 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7542 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7544 tn = ListTab.TabPages[i].Text;
7545 if (spos.X <= (rect.Left + rect.Right) / 2)
7554 //タブのないところにドロップ->最後尾へ移動
7555 if (string.IsNullOrEmpty(tn))
7557 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7559 i = ListTab.TabPages.Count - 1;
7562 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7563 if (tp.Text == tn) return;
7565 ReOrderTab(tp.Text, tn, bef);
7568 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7570 var baseIndex = this.GetTabPageIndex(baseTabText);
7571 if (baseIndex == -1)
7574 var targetIndex = this.GetTabPageIndex(targetTabText);
7575 if (targetIndex == -1)
7578 using (ControlTransaction.Layout(this.ListTab))
7580 var mTp = this.ListTab.TabPages[targetIndex];
7581 this.ListTab.TabPages.Remove(mTp);
7583 if (targetIndex < baseIndex)
7586 if (isBeforeBaseTab)
7587 ListTab.TabPages.Insert(baseIndex, mTp);
7589 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7595 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7597 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7598 //isReply:true=@,false=DM
7599 if (!StatusText.Enabled) return;
7600 if (_curList == null) return;
7601 if (_curTab == null) return;
7602 if (!this.ExistCurrentPost) return;
7604 // 複数あてリプライはReplyではなく通常ポスト
7605 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7606 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7607 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7609 if (_curList.SelectedIndices.Count > 0)
7612 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7615 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7618 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7619 StatusText.SelectionStart = StatusText.Text.Length;
7621 this.inReplyTo = null;
7624 if (string.IsNullOrEmpty(StatusText.Text))
7628 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7629 StatusText.Text = "@" + _curPost.ScreenName + " ";
7631 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7632 var inReplyToScreenName = this._curPost.ScreenName;
7633 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7641 //1件選んでEnter or DoubleClick
7642 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7644 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7647 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7648 var inReplyToScreenName = this._curPost.ScreenName;
7649 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7653 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7656 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7659 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7660 this.inReplyTo = null;
7665 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7666 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7667 var inReplyToScreenName = this._curPost.ScreenName;
7668 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7675 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7676 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7677 this.inReplyTo = null;
7682 //1件選んでCtrl-Rの場合(返信先操作せず)
7683 int sidx = StatusText.SelectionStart;
7684 string id = "@" + _curPost.ScreenName + " ";
7687 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7692 StatusText.Text = StatusText.Text.Insert(sidx, id);
7694 //if (StatusText.Text.StartsWith("@"))
7697 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7698 // sidx += 5 + _curPost.ScreenName.Length;
7703 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7704 // sidx += 3 + _curPost.ScreenName.Length;
7706 StatusText.SelectionStart = sidx;
7709 //_reply_to_name = null;
7717 if (!isAuto && !isReply) return;
7719 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7723 //Enter or DoubleClick
7725 string sTxt = StatusText.Text;
7726 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7729 this.inReplyTo = null;
7731 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7733 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7734 if (!sTxt.Contains("@" + post.ScreenName + " "))
7736 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7737 //sTxt = "@" + post.ScreenName + " " + sTxt;
7740 StatusText.Text = sTxt;
7745 if (_curList.SelectedIndices.Count > 1)
7750 int sidx = StatusText.SelectionStart;
7751 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7753 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7754 if (!ids.Contains("@" + post.ScreenName + " ") &&
7755 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7757 ids += "@" + post.ScreenName + " ";
7761 foreach (string nm in post.ReplyToList)
7763 if (!ids.Contains("@" + nm + " ") &&
7764 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7766 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7768 ids += "@" + m.Result("${id}") + " ";
7770 ids += "@" + nm + " ";
7775 if (ids.Length == 0) return;
7776 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7778 StatusText.Text = ". " + StatusText.Text;
7780 this.inReplyTo = null;
7784 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7789 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7791 //if (StatusText.Text.StartsWith("@"))
7793 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7794 // sidx += 2 + ids.Length;
7798 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7799 // sidx += 1 + ids.Length;
7801 StatusText.SelectionStart = sidx;
7807 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7810 int sidx = StatusText.SelectionStart;
7811 PostClass post = _curPost;
7812 if (!ids.Contains("@" + post.ScreenName + " ") &&
7813 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7815 ids += "@" + post.ScreenName + " ";
7817 foreach (string nm in post.ReplyToList)
7819 if (!ids.Contains("@" + nm + " ") &&
7820 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7822 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7824 ids += "@" + m.Result("${id}") + " ";
7826 ids += "@" + nm + " ";
7829 if (!string.IsNullOrEmpty(post.RetweetedBy))
7831 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7832 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7834 ids += "@" + post.RetweetedBy + " ";
7837 if (ids.Length == 0) return;
7838 if (string.IsNullOrEmpty(StatusText.Text))
7841 StatusText.Text = ids;
7842 StatusText.SelectionStart = ids.Length;
7845 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7846 var inReplyToScreenName = this._curPost.ScreenName;
7847 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7853 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7858 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7860 StatusText.SelectionStart = sidx;
7866 StatusText.SelectionStart = StatusText.Text.Length;
7871 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7876 private static int iconCnt = 0;
7877 private static int blinkCnt = 0;
7878 private static bool blink = false;
7879 private static bool idle = false;
7881 private async Task RefreshTasktrayIcon()
7884 await this.Colorize();
7886 if (!TimerRefreshIcon.Enabled) return;
7887 //Static usCheckCnt As int = 0
7889 //Static iconDlListTopItem As ListViewItem = null
7891 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7892 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7894 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7896 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7902 //if (usCheckCnt > 300) //1min
7905 // if (!this.IsReceivedUserStream)
7907 // TraceOut("ReconnectUserStream");
7908 // tw.ReconnectUserStream();
7912 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7914 if (iconCnt >= this.NIconRefresh.Length)
7922 SaveConfigsAll(true);
7927 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7929 _myStatusError = false;
7933 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7934 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7936 if (blinkCnt > 0) return;
7938 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7940 NotifyIcon1.Icon = ReplyIcon;
7944 NotifyIcon1.Icon = ReplyIconBlink;
7952 //優先度:エラー→オフライン→アイドル
7956 NotifyIcon1.Icon = NIconAtRed;
7959 if (_myStatusOnline)
7961 NotifyIcon1.Icon = NIconAt;
7965 NotifyIcon1.Icon = NIconAtSmoke;
7969 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7972 await this.RefreshTasktrayIcon();
7975 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7977 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7978 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7980 if (ListTab != null && ListTab.SelectedTab != null)
7981 _rclickTabName = ListTab.SelectedTab.Text;
7986 if (_statuses == null) return;
7987 if (_statuses.Tabs == null) return;
7989 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7992 NotifyDispMenuItem.Checked = tb.Notify;
7993 this.NotifyTbMenuItem.Checked = tb.Notify;
7995 soundfileListup = true;
7996 SoundFileComboBox.Items.Clear();
7997 this.SoundFileTbComboBox.Items.Clear();
7998 SoundFileComboBox.Items.Add("");
7999 this.SoundFileTbComboBox.Items.Add("");
8000 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8001 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8003 oDir = oDir.GetDirectories("Sounds")[0];
8005 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8007 SoundFileComboBox.Items.Add(oFile.Name);
8008 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8010 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8011 if (idx == -1) idx = 0;
8012 SoundFileComboBox.SelectedIndex = idx;
8013 this.SoundFileTbComboBox.SelectedIndex = idx;
8014 soundfileListup = false;
8015 UreadManageMenuItem.Checked = tb.UnreadManage;
8016 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8018 TabMenuControl(_rclickTabName);
8021 private void TabMenuControl(string tabName)
8023 var tabInfo = _statuses.GetTabByName(tabName);
8025 this.FilterEditMenuItem.Enabled = true;
8026 this.EditRuleTbMenuItem.Enabled = true;
8028 if (tabInfo.IsDefaultTabType)
8030 this.ProtectTabMenuItem.Enabled = false;
8031 this.ProtectTbMenuItem.Enabled = false;
8035 this.ProtectTabMenuItem.Enabled = true;
8036 this.ProtectTbMenuItem.Enabled = true;
8039 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8041 this.ProtectTabMenuItem.Checked = true;
8042 this.ProtectTbMenuItem.Checked = true;
8043 this.DeleteTabMenuItem.Enabled = false;
8044 this.DeleteTbMenuItem.Enabled = false;
8048 this.ProtectTabMenuItem.Checked = false;
8049 this.ProtectTbMenuItem.Checked = false;
8050 this.DeleteTabMenuItem.Enabled = true;
8051 this.DeleteTbMenuItem.Enabled = true;
8055 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8057 var checkState = ((ToolStripMenuItem)sender).Checked;
8060 this.ProtectTbMenuItem.Checked = checkState;
8061 this.ProtectTabMenuItem.Checked = checkState;
8064 this.DeleteTabMenuItem.Enabled = !checkState;
8065 this.DeleteTbMenuItem.Enabled = !checkState;
8067 if (string.IsNullOrEmpty(_rclickTabName)) return;
8068 _statuses.Tabs[_rclickTabName].Protected = checkState;
8073 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8075 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8076 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8078 if (string.IsNullOrEmpty(_rclickTabName)) return;
8079 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8084 public void ChangeTabUnreadManage(string tabName, bool isManage)
8086 var idx = this.GetTabPageIndex(tabName);
8090 _statuses.Tabs[tabName].UnreadManage = isManage;
8091 if (SettingManager.Common.TabIconDisp)
8093 if (_statuses.Tabs[tabName].UnreadCount > 0)
8094 ListTab.TabPages[idx].ImageIndex = 0;
8096 ListTab.TabPages[idx].ImageIndex = -1;
8099 if (_curTab.Text == tabName)
8101 this.PurgeListViewItemCache();
8105 SetMainWindowTitle();
8106 SetStatusLabelUrl();
8107 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8110 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8112 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8113 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8115 if (string.IsNullOrEmpty(_rclickTabName)) return;
8117 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8122 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8124 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8126 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8131 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8133 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8135 RemoveSpecifiedTab(_rclickTabName, true);
8139 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8141 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8143 using (var fltDialog = new FilterDialog())
8145 fltDialog.Owner = this;
8146 fltDialog.SetCurrent(_rclickTabName);
8147 fltDialog.ShowDialog(this);
8149 this.TopMost = SettingManager.Common.AlwaysTop;
8151 this.ApplyPostFilters();
8155 private void AddTabMenuItem_Click(object sender, EventArgs e)
8157 string tabName = null;
8158 MyCommon.TabUsageType tabUsage;
8159 using (InputTabName inputName = new InputTabName())
8161 inputName.TabName = _statuses.MakeTabName("MyTab");
8162 inputName.IsShowUsage = true;
8163 inputName.ShowDialog();
8164 if (inputName.DialogResult == DialogResult.Cancel) return;
8165 tabName = inputName.TabName;
8166 tabUsage = inputName.Usage;
8168 this.TopMost = SettingManager.Common.AlwaysTop;
8169 if (!string.IsNullOrEmpty(tabName))
8172 ListElement list = null;
8173 if (tabUsage == MyCommon.TabUsageType.Lists)
8175 using (ListAvailable listAvail = new ListAvailable())
8177 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8178 if (listAvail.SelectedList == null) return;
8179 list = listAvail.SelectedList;
8186 case MyCommon.TabUsageType.UserDefined:
8187 tab = new FilterTabModel(tabName);
8189 case MyCommon.TabUsageType.PublicSearch:
8190 tab = new PublicSearchTabModel(tabName);
8192 case MyCommon.TabUsageType.Lists:
8193 tab = new ListTimelineTabModel(tabName, list);
8199 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8201 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8202 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8208 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8210 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8211 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8213 if (tabUsage == MyCommon.TabUsageType.Lists)
8215 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8216 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8217 this.GetListTimelineAsync(listTab);
8223 private void TabMenuItem_Click(object sender, EventArgs e)
8225 using (var fltDialog = new FilterDialog())
8227 fltDialog.Owner = this;
8230 foreach (int idx in _curList.SelectedIndices)
8233 if (!SelectTab(out var tabName)) return;
8235 fltDialog.SetCurrent(tabName);
8236 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8238 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8242 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8244 fltDialog.ShowDialog(this);
8245 this.TopMost = SettingManager.Common.AlwaysTop;
8249 this.ApplyPostFilters();
8251 if (this.ListTab.SelectedTab != null &&
8252 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8254 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8258 protected override bool ProcessDialogKey(Keys keyData)
8260 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8261 if ((keyData & Keys.KeyCode) == Keys.Enter)
8263 if (StatusText.Focused)
8265 bool _NewLine = false;
8268 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8270 if (StatusText.Multiline)
8272 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8274 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8278 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8282 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8284 if (StatusText.Multiline)
8286 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8288 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8292 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8298 if (StatusText.Multiline)
8300 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8302 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8303 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8307 if (((keyData & Keys.Shift) == Keys.Shift) ||
8308 (((keyData & Keys.Control) != Keys.Control) &&
8309 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8315 int pos1 = StatusText.SelectionStart;
8316 if (StatusText.SelectionLength > 0)
8318 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8320 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8321 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8326 PostButton_Click(null, null);
8330 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8331 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8332 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8334 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8339 return base.ProcessDialogKey(keyData);
8342 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8344 MakeReplyOrDirectStatus(false, true, true);
8347 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8350 if (_curList.SelectedIndices.Count == 0) return;
8352 var tab = this._statuses.Tabs[this._curTab.Text];
8353 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8354 .Select(x => tab[x])
8355 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8358 this.AddFilterRuleByScreenName(screenNameArray);
8360 if (screenNameArray.Length != 0)
8362 List<string> atids = new List<string>();
8363 foreach (var screenName in screenNameArray)
8365 atids.Add("@" + screenName);
8367 int cnt = AtIdSupl.ItemCount;
8368 AtIdSupl.AddRangeItem(atids.ToArray());
8369 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8373 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8375 if (this._curList.SelectedIndices.Count == 0)
8378 var tab = this._statuses.Tabs[this._curTab.Text];
8379 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8380 .Select(x => tab[x].Source).ToArray();
8382 this.AddFilterRuleBySource(sourceArray);
8385 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8388 if (!SelectTab(out var tabName)) return;
8390 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8394 if (tab.TabType != MyCommon.TabUsageType.Mute)
8396 this.MoveOrCopy(out mv, out mk);
8400 // ミュートタブでは常に MoveMatches を true にする
8405 foreach (var screenName in screenNameArray)
8407 tab.AddFilter(new PostFilterRule
8409 FilterName = screenName,
8410 UseNameField = true,
8414 FilterByUrl = false,
8418 this.ApplyPostFilters();
8422 public void AddFilterRuleBySource(params string[] sourceArray)
8424 // タブ選択ダイアログを表示(or追加)
8425 if (!this.SelectTab(out var tabName))
8428 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8432 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8434 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8435 this.MoveOrCopy(out mv, out mk);
8439 // ミュートタブでは常に MoveMatches を true にする
8444 // 振り分けルールに追加するSource
8445 foreach (var source in sourceArray)
8447 filterTab.AddFilter(new PostFilterRule
8449 FilterSource = source,
8453 FilterByUrl = false,
8457 this.ApplyPostFilters();
8458 this.SaveConfigsTabs();
8461 private bool SelectTab(out string tabName)
8468 using (var dialog = new TabsDialog(_statuses))
8470 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8472 var selectedTab = dialog.SelectedTab;
8473 tabName = selectedTab == null ? null : selectedTab.TabName;
8476 ListTab.SelectedTab.Focus();
8478 if (tabName == null)
8480 using (InputTabName inputName = new InputTabName())
8482 inputName.TabName = _statuses.MakeTabName("MyTab");
8483 inputName.ShowDialog();
8484 if (inputName.DialogResult == DialogResult.Cancel) return false;
8485 tabName = inputName.TabName;
8487 this.TopMost = SettingManager.Common.AlwaysTop;
8488 if (!string.IsNullOrEmpty(tabName))
8490 var tab = new FilterTabModel(tabName);
8491 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8493 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8494 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8512 private void MoveOrCopy(out bool move, out bool mark)
8516 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8517 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8525 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8526 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8536 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8541 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8546 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8548 if (StatusText.Focused)
8551 StatusText.SelectAll();
8555 // ListView上でのCtrl+A
8556 NativeMethods.SelectAllItems(this._curList);
8560 private void MoveMiddle()
8566 if (_curList.SelectedIndices.Count == 0) return;
8568 int idx = _curList.SelectedIndices[0];
8570 _item = _curList.GetItemAt(0, 25);
8576 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8578 idx2 = _curList.VirtualListSize - 1;
8582 idx -= Math.Abs(idx1 - idx2) / 2;
8583 if (idx < 0) idx = 0;
8585 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8586 _curList.EnsureVisible(idx);
8589 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8591 var linkElements = this.tweetDetailsView.GetLinkElements();
8593 if (linkElements.Length > 0)
8595 UrlDialog.ClearUrl();
8597 string openUrlStr = "";
8599 if (linkElements.Length == 1)
8601 // ツイートに含まれる URL が 1 つのみの場合
8602 // => OpenURL ダイアログを表示せずにリンクを開く
8607 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8609 catch (ArgumentException)
8618 if (string.IsNullOrEmpty(urlStr)) return;
8619 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8621 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8622 await this.OpenUriAsync(new Uri(openUrlStr));
8626 // ツイートに含まれる URL が複数ある場合
8627 // => OpenURL を表示しユーザーが選択したリンクを開く
8629 foreach (var linkElm in linkElements)
8632 string linkText = "";
8636 urlStr = linkElm.GetAttribute("title");
8637 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8638 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8639 linkText = linkElm.InnerText;
8641 catch (ArgumentException)
8650 if (string.IsNullOrEmpty(urlStr)) continue;
8651 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8655 if (UrlDialog.ShowDialog() == DialogResult.OK)
8657 openUrlStr = UrlDialog.SelectedUrl;
8659 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8660 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8667 this.TopMost = SettingManager.Common.AlwaysTop;
8672 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8674 if (string.IsNullOrEmpty(_rclickTabName)) return;
8675 ClearTab(_rclickTabName, true);
8678 private void ClearTab(string tabName, bool showWarning)
8682 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8683 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8689 _statuses.ClearTabIds(tabName);
8690 if (ListTab.SelectedTab.Text == tabName)
8693 _anchorFlag = false;
8694 this.PurgeListViewItemCache();
8698 foreach (TabPage tb in ListTab.TabPages)
8700 if (tb.Text == tabName)
8702 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8707 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8709 SetMainWindowTitle();
8710 SetStatusLabelUrl();
8713 private static long followers = 0;
8715 private void SetMainWindowTitle()
8718 StringBuilder ttl = new StringBuilder(256);
8721 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8722 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8723 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8724 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8726 foreach (var tab in _statuses.Tabs.Values)
8728 ur += tab.UnreadCount;
8733 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8734 ttl.Append(Application.ProductName);
8736 switch (SettingManager.Common.DispLatestPost)
8738 case MyCommon.DispTitleEnum.Ver:
8739 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8741 case MyCommon.DispTitleEnum.Post:
8742 if (_history != null && _history.Count > 1)
8743 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8745 case MyCommon.DispTitleEnum.UnreadRepCount:
8746 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8748 case MyCommon.DispTitleEnum.UnreadAllCount:
8749 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8751 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8752 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8754 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8755 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8757 case MyCommon.DispTitleEnum.OwnStatus:
8758 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8759 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8765 this.Text = ttl.ToString();
8767 catch (AccessViolationException)
8769 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8773 private string GetStatusLabelText()
8776 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8777 if (_statuses == null) return "";
8778 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8779 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8780 if (tbRep == null || tbDm == null) return "";
8781 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8786 StringBuilder slbl = new StringBuilder(256);
8789 foreach (var tab in _statuses.Tabs.Values)
8791 ur += tab.UnreadCount;
8793 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8795 tur = tab.UnreadCount;
8806 UnreadAtCounter = urat;
8808 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8810 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8811 if (SettingManager.Common.TimelinePeriod == 0)
8813 slbl.Append(Properties.Resources.SetStatusLabelText2);
8817 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8819 return slbl.ToString();
8822 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8826 if (this.InvokeRequired && !this.IsDisposed)
8828 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8832 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8833 SetApiStatusLabel(endpointName);
8836 catch (ObjectDisposedException)
8840 catch (InvalidOperationException)
8846 private void SetApiStatusLabel(string endpointName = null)
8848 if (_curTab == null)
8850 this.toolStripApiGauge.ApiEndpoint = null;
8854 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8856 if (endpointName == null)
8861 case MyCommon.TabUsageType.Home:
8862 case MyCommon.TabUsageType.UserDefined:
8863 endpointName = "/statuses/home_timeline";
8866 case MyCommon.TabUsageType.Mentions:
8867 endpointName = "/statuses/mentions_timeline";
8870 case MyCommon.TabUsageType.Favorites:
8871 endpointName = "/favorites/list";
8874 case MyCommon.TabUsageType.DirectMessage:
8875 endpointName = "/direct_messages";
8878 case MyCommon.TabUsageType.UserTimeline:
8879 endpointName = "/statuses/user_timeline";
8882 case MyCommon.TabUsageType.Lists:
8883 endpointName = "/lists/statuses";
8886 case MyCommon.TabUsageType.PublicSearch:
8887 endpointName = "/search/tweets";
8890 case MyCommon.TabUsageType.Related:
8891 endpointName = "/statuses/show/:id";
8898 this.toolStripApiGauge.ApiEndpoint = endpointName;
8902 // 表示中のタブに関連する endpoint であれば更新
8905 switch (endpointName)
8907 case "/statuses/home_timeline":
8908 update = tabType == MyCommon.TabUsageType.Home ||
8909 tabType == MyCommon.TabUsageType.UserDefined;
8912 case "/statuses/mentions_timeline":
8913 update = tabType == MyCommon.TabUsageType.Mentions;
8916 case "/favorites/list":
8917 update = tabType == MyCommon.TabUsageType.Favorites;
8920 case "/direct_messages:":
8921 update = tabType == MyCommon.TabUsageType.DirectMessage;
8924 case "/statuses/user_timeline":
8925 update = tabType == MyCommon.TabUsageType.UserTimeline;
8928 case "/lists/statuses":
8929 update = tabType == MyCommon.TabUsageType.Lists;
8932 case "/search/tweets":
8933 update = tabType == MyCommon.TabUsageType.PublicSearch;
8936 case "/statuses/show/:id":
8937 update = tabType == MyCommon.TabUsageType.Related;
8946 this.toolStripApiGauge.ApiEndpoint = endpointName;
8952 private void SetStatusLabelUrl()
8954 StatusLabelUrl.Text = GetStatusLabelText();
8957 public void SetStatusLabel(string text)
8959 StatusLabel.Text = text;
8962 private void SetNotifyIconText()
8964 var ur = new StringBuilder(64);
8966 // タスクトレイアイコンのツールチップテキスト書き換え
8968 ur.Remove(0, ur.Length);
8969 if (SettingManager.Common.DispUsername)
8971 ur.Append(tw.Username);
8974 ur.Append(Application.ProductName);
8976 ur.Append("(Debug Build)");
8978 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8981 ur.Append(UnreadCounter);
8983 ur.Append(UnreadAtCounter);
8986 NotifyIcon1.Text = ur.ToString();
8989 internal void CheckReplyTo(string StatusText)
8993 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8995 foreach (Match hm in m)
8997 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8999 hstr += "#" + hm.Result("$3") + " ";
9000 HashSupl.AddItem("#" + hm.Result("$3"));
9003 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9005 hstr += HashMgr.UseHash;
9007 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9009 // 本当にリプライ先指定すべきかどうかの判定
9010 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9012 if (SettingManager.Common.UseAtIdSupplement)
9014 int bCnt = AtIdSupl.ItemCount;
9015 foreach (Match mid in m)
9017 AtIdSupl.AddItem(mid.Result("${id}"));
9019 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9022 // リプライ先ステータスIDの指定がない場合は指定しない
9023 if (this.inReplyTo == null)
9027 // 次の条件を満たす場合に in_reply_to_status_id 指定
9028 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9029 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9030 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9034 var inReplyToScreenName = this.inReplyTo.Item2;
9035 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9037 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9041 foreach (Match mid in m)
9043 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9048 this.inReplyTo = null;
9051 private void TweenMain_Resize(object sender, EventArgs e)
9053 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9055 this.Visible = false;
9057 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9059 // 現在の DPI と設定保存時の DPI との比を取得する
9060 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9062 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9063 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9064 this.DesktopLocation = SettingManager.Local.FormLocation;
9065 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9068 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9069 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9070 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9072 this.SplitContainer1.SplitterDistance = splitterDistance;
9076 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9077 if (StatusText.Multiline)
9079 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9080 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9081 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9083 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9085 StatusText.Height = statusTextHeight;
9089 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9091 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9095 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9096 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9098 this.SplitContainer3.SplitterDistance = previewDistance;
9101 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9102 this.SplitContainer3.Panel2Collapsed = true;
9104 _initialLayout = false;
9106 if (this.WindowState != FormWindowState.Minimized)
9108 _formWindowState = this.WindowState;
9112 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9114 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9115 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9116 if (PlaySoundMenuItem.Checked)
9118 SettingManager.Common.PlaySound = true;
9122 SettingManager.Common.PlaySound = false;
9124 ModifySettingCommon = true;
9127 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9129 if (this._initialLayout)
9132 int splitterDistance;
9133 switch (this.WindowState)
9135 case FormWindowState.Normal:
9136 splitterDistance = this.SplitContainer1.SplitterDistance;
9138 case FormWindowState.Maximized:
9139 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9140 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9141 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9142 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9148 this._mySpDis = splitterDistance;
9149 this.ModifySettingLocal = true;
9152 private async Task doRepliedStatusOpen()
9154 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9156 if (MyCommon.IsKeyDown(Keys.Shift))
9158 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9161 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9163 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9164 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9168 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9170 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9171 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9172 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9175 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9180 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9182 await this.doRepliedStatusOpen();
9185 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9187 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9188 if (multiline != this.StatusText.Multiline)
9190 this.StatusText.Multiline = multiline;
9191 MultiLineMenuItem.Checked = multiline;
9192 ModifySettingLocal = true;
9196 private void StatusText_MultilineChanged(object sender, EventArgs e)
9198 if (this.StatusText.Multiline)
9199 this.StatusText.ScrollBars = ScrollBars.Vertical;
9201 this.StatusText.ScrollBars = ScrollBars.None;
9203 ModifySettingLocal = true;
9206 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9209 StatusText.Multiline = MultiLineMenuItem.Checked;
9210 SettingManager.Local.StatusMultiline = MultiLineMenuItem.Checked;
9211 if (MultiLineMenuItem.Checked)
9213 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9214 SplitContainer2.SplitterDistance = 0;
9216 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9220 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9222 ModifySettingLocal = true;
9225 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9227 if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9229 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9230 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9231 (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9233 MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9238 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9239 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9241 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9242 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9243 //Appendix A. Collected ABNF for URI
9244 //http://www.ietf.org/rfc/rfc3986.txt
9248 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9250 if (StatusText.SelectionLength > 0)
9252 string tmp = StatusText.SelectedText;
9253 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9254 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9256 // 文字列が選択されている場合はその文字列について処理
9258 //nico.ms使用、nicovideoにマッチしたら変換
9259 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9261 result = nicoms.Shorten(tmp);
9263 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9265 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9268 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9269 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9270 result = resultUri.AbsoluteUri;
9272 catch (WebApiException e)
9274 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9277 catch (UriFormatException e)
9279 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9288 if (!string.IsNullOrEmpty(result))
9290 urlUndo undotmp = new urlUndo();
9292 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9293 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9294 if (origUrlIndex == -1)
9297 StatusText.Select(origUrlIndex, tmp.Length);
9298 StatusText.SelectedText = result;
9301 undotmp.Before = tmp;
9302 undotmp.After = result;
9304 if (urlUndoBuffer == null)
9306 urlUndoBuffer = new List<urlUndo>();
9307 UrlUndoToolStripMenuItem.Enabled = true;
9310 urlUndoBuffer.Add(undotmp);
9316 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9317 @"(?<url>(?<protocol>https?://)" +
9318 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9319 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9320 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9321 // 正規表現にマッチしたURL文字列をtinyurl化
9322 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9324 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9325 string tmp = mt.Result("${url}");
9326 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9327 urlUndo undotmp = new urlUndo();
9330 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9332 //nico.ms使用、nicovideoにマッチしたら変換
9333 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9335 result = nicoms.Shorten(tmp);
9337 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9339 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9342 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9343 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9344 result = resultUri.AbsoluteUri;
9346 catch (HttpRequestException e)
9348 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9349 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9350 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9352 this.StatusLabel.Text = Converter_Type + ":" + message;
9355 catch (WebApiException e)
9357 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9360 catch (UriFormatException e)
9362 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9371 if (!string.IsNullOrEmpty(result))
9373 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9374 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9375 if (origUrlIndex == -1)
9378 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9379 StatusText.SelectedText = result;
9381 undotmp.Before = mt.Result("${url}");
9382 undotmp.After = result;
9384 if (urlUndoBuffer == null)
9386 urlUndoBuffer = new List<urlUndo>();
9387 UrlUndoToolStripMenuItem.Enabled = true;
9390 urlUndoBuffer.Add(undotmp);
9398 private void doUrlUndo()
9400 if (urlUndoBuffer != null)
9402 string tmp = StatusText.Text;
9403 foreach (urlUndo data in urlUndoBuffer)
9405 tmp = tmp.Replace(data.After, data.Before);
9407 StatusText.Text = tmp;
9408 urlUndoBuffer = null;
9409 UrlUndoToolStripMenuItem.Enabled = false;
9410 StatusText.SelectionStart = 0;
9411 StatusText.SelectionLength = 0;
9415 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9417 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9420 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9422 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9425 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9427 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9430 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9432 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9435 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9437 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9439 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9440 Random rnd = new Random();
9441 // 前回使用した短縮URLサービス以外を選択する
9444 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9446 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9447 await UrlConvertAsync(svc);
9451 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9456 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9458 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9459 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9460 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9461 ModifySettingCommon = true;
9464 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9466 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9467 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9468 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9469 ModifySettingCommon = true;
9472 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9474 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9475 MenuStrip1.Tag = new Object();
9476 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9479 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9481 if (this.Tag != null) // 設定された戻り先へ遷移
9483 if (this.Tag == this.ListTab.SelectedTab)
9484 ((Control)this.ListTab.SelectedTab.Tag).Select();
9486 ((Control)this.Tag).Select();
9488 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9490 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9492 this.Tag = ListTab.SelectedTab.Tag;
9493 ((Control)this.Tag).Select();
9496 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9497 MenuStrip1.Tag = null;
9500 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9502 DetailsListView lst = (DetailsListView)sender;
9503 if (SettingManager.Local == null) return;
9507 SettingManager.Local.Width1 = lst.Columns[0].Width;
9508 SettingManager.Local.Width3 = lst.Columns[1].Width;
9512 int[] darr = new int[lst.Columns.Count];
9513 for (int i = 0; i < lst.Columns.Count; i++)
9515 darr[lst.Columns[i].DisplayIndex] = i;
9517 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9519 for (int i = 0; i < lst.Columns.Count; i++)
9524 SettingManager.Local.DisplayIndex1 = i;
9527 SettingManager.Local.DisplayIndex2 = i;
9530 SettingManager.Local.DisplayIndex3 = i;
9533 SettingManager.Local.DisplayIndex4 = i;
9536 SettingManager.Local.DisplayIndex5 = i;
9539 SettingManager.Local.DisplayIndex6 = i;
9542 SettingManager.Local.DisplayIndex7 = i;
9545 SettingManager.Local.DisplayIndex8 = i;
9549 SettingManager.Local.Width1 = lst.Columns[0].Width;
9550 SettingManager.Local.Width2 = lst.Columns[1].Width;
9551 SettingManager.Local.Width3 = lst.Columns[2].Width;
9552 SettingManager.Local.Width4 = lst.Columns[3].Width;
9553 SettingManager.Local.Width5 = lst.Columns[4].Width;
9554 SettingManager.Local.Width6 = lst.Columns[5].Width;
9555 SettingManager.Local.Width7 = lst.Columns[6].Width;
9556 SettingManager.Local.Width8 = lst.Columns[7].Width;
9558 ModifySettingLocal = true;
9559 _isColumnChanged = true;
9562 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9564 DetailsListView lst = (DetailsListView)sender;
9565 if (SettingManager.Local == null) return;
9568 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9570 SettingManager.Local.Width1 = lst.Columns[0].Width;
9571 ModifySettingLocal = true;
9572 _isColumnChanged = true;
9574 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9576 SettingManager.Local.Width3 = lst.Columns[1].Width;
9577 ModifySettingLocal = true;
9578 _isColumnChanged = true;
9583 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9585 SettingManager.Local.Width1 = lst.Columns[0].Width;
9586 ModifySettingLocal = true;
9587 _isColumnChanged = true;
9589 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9591 SettingManager.Local.Width2 = lst.Columns[1].Width;
9592 ModifySettingLocal = true;
9593 _isColumnChanged = true;
9595 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9597 SettingManager.Local.Width3 = lst.Columns[2].Width;
9598 ModifySettingLocal = true;
9599 _isColumnChanged = true;
9601 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9603 SettingManager.Local.Width4 = lst.Columns[3].Width;
9604 ModifySettingLocal = true;
9605 _isColumnChanged = true;
9607 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9609 SettingManager.Local.Width5 = lst.Columns[4].Width;
9610 ModifySettingLocal = true;
9611 _isColumnChanged = true;
9613 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9615 SettingManager.Local.Width6 = lst.Columns[5].Width;
9616 ModifySettingLocal = true;
9617 _isColumnChanged = true;
9619 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9621 SettingManager.Local.Width7 = lst.Columns[6].Width;
9622 ModifySettingLocal = true;
9623 _isColumnChanged = true;
9625 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9627 SettingManager.Local.Width8 = lst.Columns[7].Width;
9628 ModifySettingLocal = true;
9629 _isColumnChanged = true;
9632 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9635 // SaveConfigsLocal();
9639 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9641 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9642 ModifySettingLocal = true;
9645 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9647 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9649 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9651 SelectMedia_DragDrop(e);
9654 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9656 var (url, title) = GetUrlFromDataObject(e.Data);
9662 appendText = title + " " + url;
9664 if (this.StatusText.TextLength == 0)
9665 this.StatusText.Text = appendText;
9667 this.StatusText.Text += " " + appendText;
9669 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9671 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9673 this.StatusText.Text += text;
9675 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9677 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9678 if (data != null) StatusText.Text += data;
9683 /// IDataObject から URL とタイトルの対を取得します
9686 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9688 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9689 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9690 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9692 if (data.GetDataPresent("text/x-moz-url"))
9694 // Firefox, Google Chrome で利用可能
9695 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9697 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9699 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9700 if (lines.Length < 2)
9701 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9703 return (lines[0], lines[1]);
9706 else if (data.GetDataPresent("IESiteModeToUrl"))
9708 // Internet Exproler 用
9709 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9711 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9713 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9714 if (lines.Length < 2)
9715 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9717 return (lines[0], lines[1]);
9720 else if (data.GetDataPresent("UniformResourceLocatorW"))
9724 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9726 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9731 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9734 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9736 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9738 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9740 SelectMedia_DragEnter(e);
9744 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9746 e.Effect = DragDropEffects.Copy;
9749 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9751 e.Effect = DragDropEffects.Copy;
9754 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9756 e.Effect = DragDropEffects.Copy;
9760 e.Effect = DragDropEffects.None;
9763 private void TweenMain_DragOver(object sender, DragEventArgs e)
9767 public bool IsNetworkAvailable()
9770 nw = MyCommon.IsNetworkAvailable();
9771 _myStatusOnline = nw;
9775 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9777 var uriStr = uri.AbsoluteUri;
9779 // OpenTween 内部で使用する URL
9780 if (uri.Authority == "opentween")
9782 await this.OpenInternalUriAsync(uri);
9786 // ハッシュタグを含む Twitter 検索
9787 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9790 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9791 var pos = unescapedQuery.IndexOf('#');
9792 if (pos == -1) return;
9794 var hash = unescapedQuery.Substring(pos);
9795 this.HashSupl.AddItem(hash);
9796 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9797 this.AddNewTabForSearch(hash);
9802 // フラグが立っている場合は設定と逆の動作をする
9803 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9804 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9806 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9807 if (userUriMatch.Success)
9809 var screenName = userUriMatch.Groups["ScreenName"].Value;
9810 if (this.IsTwitterId(screenName))
9812 this.AddNewTabForUserTimeline(screenName);
9819 await this.OpenUriInBrowserAsync(uriStr);
9823 /// OpenTween 内部の機能を呼び出すための URL を開きます
9825 private async Task OpenInternalUriAsync(Uri uri)
9827 // ツイートを開く (//opentween/status/:status_id)
9828 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9831 var statusId = long.Parse(match.Groups[1].Value);
9832 await this.OpenRelatedTab(statusId);
9837 public Task OpenUriInBrowserAsync(string UriString)
9839 return Task.Run(() =>
9841 string myPath = UriString;
9845 var configBrowserPath = SettingManager.Local.BrowserPath;
9846 if (!string.IsNullOrEmpty(configBrowserPath))
9848 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9850 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9851 string browserPath = configBrowserPath.Substring(1, sep - 1);
9853 if (sep < configBrowserPath.Length - 1)
9855 arg = configBrowserPath.Substring(sep + 1);
9857 myPath = arg + " " + myPath;
9858 System.Diagnostics.Process.Start(browserPath, myPath);
9862 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9867 System.Diagnostics.Process.Start(myPath);
9872 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9877 private void ListTabSelect(TabPage _tab)
9881 this.PurgeListViewItemCache();
9884 _curList = (DetailsListView)_tab.Tag;
9886 if (_curList.SelectedIndices.Count > 0)
9888 _curItemIndex = _curList.SelectedIndices[0];
9889 _curPost = GetCurTabPost(_curItemIndex);
9898 _anchorFlag = false;
9902 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9906 for (int i = 0; i < _curList.Columns.Count; i++)
9908 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9913 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9915 ListTabSelect(e.TabPage);
9918 private void SelectListItem(DetailsListView LView, int Index)
9921 Rectangle bnd = new Rectangle();
9923 var item = LView.FocusedItem;
9932 LView.SelectedIndices.Clear();
9934 while (LView.SelectedIndices.Count > 0);
9935 item = LView.Items[Index];
9936 item.Selected = true;
9937 item.Focused = true;
9939 if (flg) LView.Invalidate(bnd);
9942 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9945 Rectangle bnd = new Rectangle();
9947 var item = LView.FocusedItem;
9958 LView.SelectedIndices.Clear();
9960 while (LView.SelectedIndices.Count > 0);
9961 LView.SelectItems(Index);
9963 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9965 LView.SelectionMark = selectionMarkIndex;
9967 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9969 LView.Items[focusedIndex].Focused = true;
9971 else if (Index != null && Index.Length != 0)
9973 LView.Items[Index.Last()].Focused = true;
9976 if (flg) LView.Invalidate(bnd);
9979 private void StartUserStream()
9981 tw.NewPostFromStream += tw_NewPostFromStream;
9982 tw.UserStreamStarted += tw_UserStreamStarted;
9983 tw.UserStreamStopped += tw_UserStreamStopped;
9984 tw.PostDeleted += tw_PostDeleted;
9985 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9987 this.RefreshUserStreamsMenu();
9989 if (SettingManager.Common.UserstreamStartup)
9990 tw.StartUserStream();
9993 private async void TweenMain_Shown(object sender, EventArgs e)
9995 NotifyIcon1.Visible = true;
9997 if (this.IsNetworkAvailable())
10001 var loadTasks = new List<Task>
10003 this.RefreshMuteUserIdsAsync(),
10004 this.RefreshBlockIdsAsync(),
10005 this.RefreshNoRetweetIdsAsync(),
10006 this.RefreshTwitterConfigurationAsync(),
10007 this.GetHomeTimelineAsync(),
10008 this.GetReplyAsync(),
10009 this.GetDirectMessagesAsync(),
10010 this.GetPublicSearchAllAsync(),
10011 this.GetUserTimelineAllAsync(),
10012 this.GetListTimelineAllAsync(),
10015 if (SettingManager.Common.StartupFollowers)
10016 loadTasks.Add(this.RefreshFollowerIdsAsync());
10018 if (SettingManager.Common.GetFav)
10019 loadTasks.Add(this.GetFavoritesAsync());
10021 var allTasks = Task.WhenAll(loadTasks);
10026 var timeout = Task.Delay(5000);
10027 if (await Task.WhenAny(allTasks, timeout) != timeout)
10031 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10033 if (MyCommon._endingFlag)
10037 if (MyCommon._endingFlag) return;
10039 if (ApplicationSettings.VersionInfoUrl != null)
10041 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10042 if (SettingManager.Common.StartupVersion)
10043 await this.CheckNewVersion(true);
10047 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10048 this.VerUpMenuItem.Enabled = false;
10049 this.VerUpMenuItem.Available = false;
10050 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10053 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10054 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10056 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10057 SettingStripMenuItem_Click(null, null);
10061 var reloadTasks = new List<Task>();
10063 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10064 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10066 if (!tw.GetNoRetweetSuccess)
10067 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10069 if (this.tw.Configuration.PhotoSizeLimit == 0)
10070 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10072 await Task.WhenAll(reloadTasks);
10077 TimerTimeline.Enabled = true;
10080 private async Task doGetFollowersMenu()
10082 await this.RefreshFollowerIdsAsync();
10083 await this.DispSelectedPost(true);
10086 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10088 await this.doGetFollowersMenu();
10091 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10093 doReTweetUnofficial();
10096 private async Task doReTweetOfficial(bool isConfirm)
10099 if (this.ExistCurrentPost)
10101 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10103 if (this._curPost.IsProtect)
10104 MessageBox.Show("Protected.");
10106 _DoFavRetweetFlags = false;
10109 if (_curList.SelectedIndices.Count > 15)
10111 MessageBox.Show(Properties.Resources.RetweetLimitText);
10112 _DoFavRetweetFlags = false;
10115 else if (_curList.SelectedIndices.Count > 1)
10117 string QuestionText = Properties.Resources.RetweetQuestion2;
10118 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10119 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10121 case DialogResult.Cancel:
10122 case DialogResult.No:
10123 _DoFavRetweetFlags = false;
10129 if (!SettingManager.Common.RetweetNoConfirm)
10131 string Questiontext = Properties.Resources.RetweetQuestion1;
10132 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10133 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10135 _DoFavRetweetFlags = false;
10141 var statusIds = new List<long>();
10142 foreach (int idx in _curList.SelectedIndices)
10144 PostClass post = GetCurTabPost(idx);
10145 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10146 statusIds.Add(post.StatusId);
10149 await this.RetweetAsync(statusIds);
10153 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10155 await this.doReTweetOfficial(true);
10158 private async Task FavoritesRetweetOfficial()
10160 if (!this.ExistCurrentPost) return;
10161 _DoFavRetweetFlags = true;
10162 var retweetTask = this.doReTweetOfficial(true);
10163 if (_DoFavRetweetFlags)
10165 _DoFavRetweetFlags = false;
10166 var favoriteTask = this.FavoriteChange(true, false);
10168 await Task.WhenAll(retweetTask, favoriteTask);
10176 private async Task FavoritesRetweetUnofficial()
10178 if (this.ExistCurrentPost && !_curPost.IsDm)
10180 _DoFavRetweetFlags = true;
10181 var favoriteTask = this.FavoriteChange(true);
10182 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10184 _DoFavRetweetFlags = false;
10185 doReTweetUnofficial();
10188 await favoriteTask;
10193 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10195 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10196 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10197 /// <returns>復元されたツイート本文</returns>
10198 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10200 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10203 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10205 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10207 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10211 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10213 statusHtml = statusHtml.Replace("<br>", " ");
10215 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10216 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10217 statusHtml = statusHtml.Replace(" ", " ");
10219 return WebUtility.HtmlDecode(statusHtml);
10222 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10224 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10226 if (_curPost != null)
10227 await this.DispSelectedPost(true);
10230 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10232 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10233 DebugModeToolStripMenuItem.Visible = true;
10235 DebugModeToolStripMenuItem.Visible = false;
10238 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10240 SettingManager.Common.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10243 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10245 ToolStripMenuItemUrlAutoShorten.Checked = SettingManager.Common.UrlConvertAuto;
10248 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10250 if (TraceOutToolStripMenuItem.Checked)
10251 MyCommon.TraceFlag = true;
10253 MyCommon.TraceFlag = false;
10256 private void TweenMain_Deactivate(object sender, EventArgs e)
10258 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10259 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10262 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10264 if (string.IsNullOrEmpty(_rclickTabName)) return;
10266 TabRename(_rclickTabName, out var _);
10269 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10271 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10274 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10276 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10279 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10281 TwitterApiStatus apiStatus;
10283 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10285 var cancellationToken = dialog.EnableCancellation();
10289 var task = this.tw.GetInfoApi();
10290 apiStatus = await dialog.WaitForAsync(this, task);
10292 catch (WebApiException)
10297 if (cancellationToken.IsCancellationRequested)
10300 if (apiStatus == null)
10302 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10307 using (var apiDlg = new ApiInfoDialog())
10309 apiDlg.ShowDialog(this);
10313 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10315 var id = _curPost?.ScreenName ?? "";
10317 await this.FollowCommand(id);
10320 internal async Task FollowCommand(string id)
10322 using (var inputName = new InputTabName())
10324 inputName.FormTitle = "Follow";
10325 inputName.FormDescription = Properties.Resources.FRMessage1;
10326 inputName.TabName = id;
10328 if (inputName.ShowDialog(this) != DialogResult.OK)
10330 if (string.IsNullOrWhiteSpace(inputName.TabName))
10333 id = inputName.TabName.Trim();
10336 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10340 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10341 await dialog.WaitForAsync(this, task);
10343 catch (WebApiException ex)
10345 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10350 MessageBox.Show(Properties.Resources.FRMessage3);
10353 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10355 var id = _curPost?.ScreenName ?? "";
10357 await this.RemoveCommand(id, false);
10360 internal async Task RemoveCommand(string id, bool skipInput)
10364 using (var inputName = new InputTabName())
10366 inputName.FormTitle = "Unfollow";
10367 inputName.FormDescription = Properties.Resources.FRMessage1;
10368 inputName.TabName = id;
10370 if (inputName.ShowDialog(this) != DialogResult.OK)
10372 if (string.IsNullOrWhiteSpace(inputName.TabName))
10375 id = inputName.TabName.Trim();
10379 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10383 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10384 await dialog.WaitForAsync(this, task);
10386 catch (WebApiException ex)
10388 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10393 MessageBox.Show(Properties.Resources.FRMessage3);
10396 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10398 var id = _curPost?.ScreenName ?? "";
10400 await this.ShowFriendship(id);
10403 internal async Task ShowFriendship(string id)
10405 using (var inputName = new InputTabName())
10407 inputName.FormTitle = "Show Friendships";
10408 inputName.FormDescription = Properties.Resources.FRMessage1;
10409 inputName.TabName = id;
10411 if (inputName.ShowDialog(this) != DialogResult.OK)
10413 if (string.IsNullOrWhiteSpace(inputName.TabName))
10416 id = inputName.TabName.Trim();
10419 bool isFollowing, isFollowed;
10421 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10423 var cancellationToken = dialog.EnableCancellation();
10427 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10428 var friendship = await dialog.WaitForAsync(this, task);
10430 isFollowing = friendship.Relationship.Source.Following;
10431 isFollowed = friendship.Relationship.Source.FollowedBy;
10433 catch (WebApiException ex)
10435 if (!cancellationToken.IsCancellationRequested)
10436 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10440 if (cancellationToken.IsCancellationRequested)
10444 string result = "";
10447 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10451 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10455 result += Properties.Resources.GetFriendshipInfo3;
10459 result += Properties.Resources.GetFriendshipInfo4;
10461 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10462 MessageBox.Show(result);
10465 internal async Task ShowFriendship(string[] ids)
10467 foreach (string id in ids)
10469 bool isFollowing, isFollowed;
10471 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10473 var cancellationToken = dialog.EnableCancellation();
10477 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10478 var friendship = await dialog.WaitForAsync(this, task);
10480 isFollowing = friendship.Relationship.Source.Following;
10481 isFollowed = friendship.Relationship.Source.FollowedBy;
10483 catch (WebApiException ex)
10485 if (!cancellationToken.IsCancellationRequested)
10486 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10490 if (cancellationToken.IsCancellationRequested)
10494 string result = "";
10500 ff += Properties.Resources.GetFriendshipInfo1;
10504 ff += Properties.Resources.GetFriendshipInfo2;
10507 ff += System.Environment.NewLine + " ";
10510 ff += Properties.Resources.GetFriendshipInfo3;
10514 ff += Properties.Resources.GetFriendshipInfo4;
10516 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10519 if (MessageBox.Show(
10520 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10521 MessageBoxButtons.YesNo,
10522 MessageBoxIcon.Question,
10523 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10525 await this.RemoveCommand(id, true);
10530 MessageBox.Show(result);
10535 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10537 await this.doShowUserStatus(tw.Username, false);
10538 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10540 // doShowUserStatus(tw.Username, false);
10544 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10549 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10550 // URLから切り出した文字列を渡す
10552 public bool IsTwitterId(string name)
10554 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10555 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10557 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10560 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10562 ModifySettingCommon = true;
10565 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10567 ModifySettingCommon = true;
10570 private void doQuoteOfficial()
10572 if (this.ExistCurrentPost)
10574 if (_curPost.IsDm ||
10575 !StatusText.Enabled) return;
10577 if (_curPost.IsProtect)
10579 MessageBox.Show("Protected.");
10583 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10585 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10587 this.inReplyTo = null;
10589 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10590 StatusText.Focus();
10594 private void doReTweetUnofficial()
10597 if (this.ExistCurrentPost)
10599 if (_curPost.IsDm || !StatusText.Enabled)
10602 if (_curPost.IsProtect)
10604 MessageBox.Show("Protected.");
10607 string rtdata = _curPost.Text;
10608 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10610 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10612 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10614 // 投稿時に in_reply_to_status_id を付加する
10615 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10616 var inReplyToScreenName = this._curPost.ScreenName;
10617 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10619 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10620 StatusText.Focus();
10624 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10629 private void SearchButton_Click(object sender, EventArgs e)
10632 Control pnl = ((Control)sender).Parent;
10633 if (pnl == null) return;
10634 string tbName = pnl.Parent.Text;
10635 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10636 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10637 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10638 cmb.Text = cmb.Text.Trim();
10639 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10640 bool Quote = false;
10641 StringBuilder buf = new StringBuilder();
10642 char[] c = cmb.Text.ToCharArray();
10643 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10645 if (cnt > cmb.Text.Length - 4)
10647 buf.Append(cmb.Text.Substring(cnt));
10656 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10658 buf.Append(" OR ");
10663 buf.Append(c[cnt]);
10665 cmb.Text = buf.ToString();
10667 var listView = (DetailsListView)pnl.Parent.Tag;
10669 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10671 tb.SearchWords = cmb.Text;
10672 tb.SearchLang = cmbLang.Text;
10673 if (string.IsNullOrEmpty(cmb.Text))
10681 int idx = cmb.Items.IndexOf(tb.SearchWords);
10682 if (idx > -1) cmb.Items.RemoveAt(idx);
10683 cmb.Items.Insert(0, tb.SearchWords);
10684 cmb.Text = tb.SearchWords;
10686 this.PurgeListViewItemCache();
10687 listView.VirtualListSize = 0;
10688 _statuses.ClearTabIds(tbName);
10689 SaveConfigsTabs(); //検索条件の保存
10692 this.GetPublicSearchAsync(tb);
10696 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10699 await this.DoRefreshMore();
10703 /// 指定されたタブのListTabにおける位置を返します
10706 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10708 public int GetTabPageIndex(string tabName)
10711 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10713 if (tabPage.Text == tabName)
10722 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10724 if (_statuses.RemovedTab.Count == 0)
10726 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10731 DetailsListView listView = null;
10733 TabModel tb = _statuses.RemovedTab.Pop();
10734 if (tb.TabType == MyCommon.TabUsageType.Related)
10736 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10737 if (relatedTab != null)
10739 // 関連発言なら既存のタブを置き換える
10740 tb.TabName = relatedTab.TabName;
10741 this.ClearTab(tb.TabName, false);
10742 _statuses.Tabs[tb.TabName] = tb;
10744 for (int i = 0; i < ListTab.TabPages.Count; i++)
10746 var tabPage = ListTab.TabPages[i];
10747 if (tb.TabName == tabPage.Text)
10749 listView = (DetailsListView)tabPage.Tag;
10750 ListTab.SelectedIndex = i;
10757 const string TabName = "Related Tweets";
10758 string renamed = TabName;
10759 for (int i = 2; i <= 100; i++)
10761 if (!_statuses.ContainsTab(renamed)) break;
10762 renamed = TabName + i;
10764 tb.TabName = renamed;
10766 _statuses.AddTab(tb);
10767 AddNewTab(tb, startup: false);
10769 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10770 listView = (DetailsListView)tabPage.Tag;
10771 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10776 string renamed = tb.TabName;
10777 for (int i = 1; i < int.MaxValue; i++)
10779 if (!_statuses.ContainsTab(renamed)) break;
10780 renamed = tb.TabName + "(" + i + ")";
10782 tb.TabName = renamed;
10784 _statuses.AddTab(tb);
10785 AddNewTab(tb, startup: false);
10787 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10788 listView = (DetailsListView)tabPage.Tag;
10789 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10793 if (listView != null)
10795 using (ControlTransaction.Update(listView))
10797 listView.VirtualListSize = tb.AllCount;
10803 private async Task doMoveToRTHome()
10805 if (_curList.SelectedIndices.Count > 0)
10807 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10808 if (post.RetweetedId != null)
10810 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10815 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10817 await this.doMoveToRTHome();
10820 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10822 var screenName = this._curPost?.ScreenName;
10823 if (screenName != null)
10824 this.ListManageUserContext(screenName);
10827 public void ListManageUserContext(string screenName)
10829 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10831 listSelectForm.ShowDialog(this);
10835 private void SearchControls_Enter(object sender, EventArgs e)
10837 Control pnl = (Control)sender;
10838 foreach (Control ctl in pnl.Controls)
10840 ctl.TabStop = true;
10844 private void SearchControls_Leave(object sender, EventArgs e)
10846 Control pnl = (Control)sender;
10847 foreach (Control ctl in pnl.Controls)
10849 ctl.TabStop = false;
10853 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10855 if (ListTab.SelectedTab != null)
10857 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10858 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10862 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10864 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10867 private void HashManageMenuItem_Click(object sender, EventArgs e)
10869 DialogResult rslt = DialogResult.Cancel;
10872 rslt = HashMgr.ShowDialog();
10878 this.TopMost = SettingManager.Common.AlwaysTop;
10879 if (rslt == DialogResult.Cancel) return;
10880 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10882 HashStripSplitButton.Text = HashMgr.UseHash;
10883 HashToggleMenuItem.Checked = true;
10884 HashToggleToolStripMenuItem.Checked = true;
10888 HashStripSplitButton.Text = "#[-]";
10889 HashToggleMenuItem.Checked = false;
10890 HashToggleToolStripMenuItem.Checked = false;
10892 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10894 // int sidx = StatusText.SelectionStart;
10895 // string hash = HashMgr.UseHash + " ";
10898 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10899 // hash = " " + hash;
10901 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10902 // sidx += hash.Length;
10903 // StatusText.SelectionStart = sidx;
10904 // StatusText.Focus();
10906 ModifySettingCommon = true;
10907 this.StatusText_TextChanged(null, null);
10910 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10912 HashMgr.ToggleHash();
10913 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10915 HashStripSplitButton.Text = HashMgr.UseHash;
10916 HashToggleMenuItem.Checked = true;
10917 HashToggleToolStripMenuItem.Checked = true;
10921 HashStripSplitButton.Text = "#[-]";
10922 HashToggleMenuItem.Checked = false;
10923 HashToggleToolStripMenuItem.Checked = false;
10925 ModifySettingCommon = true;
10926 this.StatusText_TextChanged(null, null);
10929 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10931 HashToggleMenuItem_Click(null, null);
10934 public void SetPermanentHashtag(string hashtag)
10936 HashMgr.SetPermanentHash("#" + hashtag);
10937 HashStripSplitButton.Text = HashMgr.UseHash;
10938 HashToggleMenuItem.Checked = true;
10939 HashToggleToolStripMenuItem.Checked = true;
10941 ModifySettingCommon = true;
10944 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10946 if (ListTab.SelectedTab == null) return;
10947 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10948 if (!this.ExistCurrentPost)
10950 this.ReplyOpMenuItem.Enabled = false;
10951 this.ReplyAllOpMenuItem.Enabled = false;
10952 this.DmOpMenuItem.Enabled = false;
10953 this.ShowProfMenuItem.Enabled = false;
10954 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10955 this.ListManageMenuItem.Enabled = false;
10956 this.OpenFavOpMenuItem.Enabled = false;
10957 this.CreateTabRuleOpMenuItem.Enabled = false;
10958 this.CreateIdRuleOpMenuItem.Enabled = false;
10959 this.CreateSourceRuleOpMenuItem.Enabled = false;
10960 this.ReadOpMenuItem.Enabled = false;
10961 this.UnreadOpMenuItem.Enabled = false;
10965 this.ReplyOpMenuItem.Enabled = true;
10966 this.ReplyAllOpMenuItem.Enabled = true;
10967 this.DmOpMenuItem.Enabled = true;
10968 this.ShowProfMenuItem.Enabled = true;
10969 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10970 this.ListManageMenuItem.Enabled = true;
10971 this.OpenFavOpMenuItem.Enabled = true;
10972 this.CreateTabRuleOpMenuItem.Enabled = true;
10973 this.CreateIdRuleOpMenuItem.Enabled = true;
10974 this.CreateSourceRuleOpMenuItem.Enabled = true;
10975 this.ReadOpMenuItem.Enabled = true;
10976 this.UnreadOpMenuItem.Enabled = true;
10979 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10981 this.FavOpMenuItem.Enabled = false;
10982 this.UnFavOpMenuItem.Enabled = false;
10983 this.OpenStatusOpMenuItem.Enabled = false;
10984 this.OpenFavotterOpMenuItem.Enabled = false;
10985 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10986 this.RtOpMenuItem.Enabled = false;
10987 this.RtUnOpMenuItem.Enabled = false;
10988 this.QtOpMenuItem.Enabled = false;
10989 this.FavoriteRetweetMenuItem.Enabled = false;
10990 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10994 this.FavOpMenuItem.Enabled = true;
10995 this.UnFavOpMenuItem.Enabled = true;
10996 this.OpenStatusOpMenuItem.Enabled = true;
10997 this.OpenFavotterOpMenuItem.Enabled = true;
10998 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11000 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11002 this.RtOpMenuItem.Enabled = false;
11003 this.RtUnOpMenuItem.Enabled = false;
11004 this.QtOpMenuItem.Enabled = false;
11005 this.FavoriteRetweetMenuItem.Enabled = false;
11006 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11010 this.RtOpMenuItem.Enabled = true;
11011 this.RtUnOpMenuItem.Enabled = true;
11012 this.QtOpMenuItem.Enabled = true;
11013 this.FavoriteRetweetMenuItem.Enabled = true;
11014 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11018 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11020 this.RefreshPrevOpMenuItem.Enabled = true;
11024 this.RefreshPrevOpMenuItem.Enabled = false;
11026 if (!this.ExistCurrentPost
11027 || _curPost.InReplyToStatusId == null)
11029 OpenRepSourceOpMenuItem.Enabled = false;
11033 OpenRepSourceOpMenuItem.Enabled = true;
11035 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11037 OpenRterHomeMenuItem.Enabled = false;
11041 OpenRterHomeMenuItem.Enabled = true;
11044 if (this.ExistCurrentPost)
11046 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11050 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11052 ContextMenuTabProperty_Opening(sender, null);
11055 public Twitter TwitterInstance
11060 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11062 if (this._initialLayout)
11065 int splitterDistance;
11066 switch (this.WindowState)
11068 case FormWindowState.Normal:
11069 splitterDistance = this.SplitContainer3.SplitterDistance;
11071 case FormWindowState.Maximized:
11072 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11073 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11074 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11075 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11081 this._mySpDis3 = splitterDistance;
11082 this.ModifySettingLocal = true;
11085 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11087 if (_statuses.RemovedTab.Count == 0)
11089 UndoRemoveTabMenuItem.Enabled = false;
11093 UndoRemoveTabMenuItem.Enabled = true;
11095 if (ListTab.SelectedTab != null)
11097 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11098 PublicSearchQueryMenuItem.Enabled = true;
11100 PublicSearchQueryMenuItem.Enabled = false;
11104 PublicSearchQueryMenuItem.Enabled = false;
11106 if (!this.ExistCurrentPost)
11108 this.CopySTOTMenuItem.Enabled = false;
11109 this.CopyURLMenuItem.Enabled = false;
11110 this.CopyUserIdStripMenuItem.Enabled = false;
11114 this.CopySTOTMenuItem.Enabled = true;
11115 this.CopyURLMenuItem.Enabled = true;
11116 this.CopyUserIdStripMenuItem.Enabled = true;
11117 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11118 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11122 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11124 SetNotifyIconText();
11127 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11129 var id = _curPost?.ScreenName ?? "";
11131 await this.ShowUserStatus(id);
11134 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11136 TwitterUser user = null;
11138 if (ShowInputDialog)
11140 using (var inputName = new InputTabName())
11142 inputName.FormTitle = "Show UserStatus";
11143 inputName.FormDescription = Properties.Resources.FRMessage1;
11144 inputName.TabName = id;
11146 if (inputName.ShowDialog(this) != DialogResult.OK)
11148 if (string.IsNullOrWhiteSpace(inputName.TabName))
11151 id = inputName.TabName.Trim();
11155 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11157 var cancellationToken = dialog.EnableCancellation();
11161 var task = this.twitterApi.UsersShow(id);
11162 user = await dialog.WaitForAsync(this, task);
11164 catch (WebApiException ex)
11166 if (!cancellationToken.IsCancellationRequested)
11167 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11171 if (cancellationToken.IsCancellationRequested)
11175 await this.doShowUserStatus(user);
11178 private async Task doShowUserStatus(TwitterUser user)
11180 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11182 var showUserTask = userDialog.ShowUserAsync(user);
11183 userDialog.ShowDialog(this);
11186 this.BringToFront();
11188 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11189 await showUserTask;
11193 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11195 return this.doShowUserStatus(id, ShowInputDialog);
11198 internal Task ShowUserStatus(string id)
11200 return this.doShowUserStatus(id, true);
11203 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11205 if (_curPost != null)
11207 await this.ShowUserStatus(_curPost.ScreenName, false);
11211 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11213 if (!this.ExistCurrentPost)
11216 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11217 TwitterStatus status;
11219 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11221 var cancellationToken = dialog.EnableCancellation();
11225 var task = this.twitterApi.StatusesShow(statusId);
11226 status = await dialog.WaitForAsync(this, task);
11228 catch (WebApiException ex)
11230 if (!cancellationToken.IsCancellationRequested)
11231 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11235 if (cancellationToken.IsCancellationRequested)
11239 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11242 private HookGlobalHotkey _hookGlobalHotkey;
11245 _hookGlobalHotkey = new HookGlobalHotkey(this);
11247 // この呼び出しは、Windows フォーム デザイナで必要です。
11248 InitializeComponent();
11250 // InitializeComponent() 呼び出しの後で初期化を追加します。
11252 if (!this.DesignMode)
11254 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11255 this.StatusText.Dock = DockStyle.Fill;
11258 this.tweetDetailsView.Owner = this;
11260 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11261 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11262 this.gh.NotifyClicked += GrowlHelper_Callback;
11264 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11265 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11267 this.ImageSelector.Visible = false;
11268 this.ImageSelector.Enabled = false;
11269 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11271 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11273 this.ReplaceAppName();
11274 this.InitializeShortcuts();
11277 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11279 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11282 this.Visible = false;
11284 else if (Form.ActiveForm == null)
11286 this.Visible = true;
11287 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11289 this.BringToFront();
11290 this.StatusText.Focus();
11294 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11296 this.MultiLineMenuItem.PerformClick();
11299 public PostClass CurPost
11301 get { return _curPost; }
11305 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11307 if (ImageSelector.Visible)
11308 ImageSelector.EndSelection();
11310 ImageSelector.BeginSelection();
11313 private void SelectMedia_DragEnter(DragEventArgs e)
11315 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11317 e.Effect = DragDropEffects.Copy;
11320 e.Effect = DragDropEffects.None;
11323 private void SelectMedia_DragDrop(DragEventArgs e)
11326 this.BringToFront();
11327 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11328 StatusText.Focus();
11331 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11333 TimelinePanel.Visible = false;
11334 TimelinePanel.Enabled = false;
11337 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11339 TimelinePanel.Visible = true;
11340 TimelinePanel.Enabled = true;
11341 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11344 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11346 this.AllowDrop = false;
11349 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11351 this.AllowDrop = true;
11354 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11356 if (ImageSelector.Visible)
11358 ModifySettingCommon = true;
11359 SaveConfigsAll(true);
11361 this.StatusText_TextChanged(null, null);
11365 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11367 this.StatusText_TextChanged(null, null);
11371 /// StatusTextでCtrl+Vが押下された時の処理
11373 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11377 if (Clipboard.ContainsText())
11379 // clipboardにテキストがある場合は貼り付け処理
11380 this.StatusText.Paste(Clipboard.GetText());
11382 else if (Clipboard.ContainsImage())
11385 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11386 Properties.Resources.PostPictureWarn4,
11387 MessageBoxButtons.OKCancel,
11388 MessageBoxIcon.Question,
11389 MessageBoxDefaultButton.Button2)
11390 == DialogResult.OK)
11392 // clipboardから画像を取得
11393 using (var image = Clipboard.GetImage())
11395 this.ImageSelector.BeginSelection(image);
11400 catch (ExternalException ex)
11402 MessageBox.Show(ex.Message);
11407 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11409 using (ListManage form = new ListManage(tw))
11411 form.ShowDialog(this);
11415 public bool ModifySettingCommon { get; set; }
11416 public bool ModifySettingLocal { get; set; }
11417 public bool ModifySettingAtId { get; set; }
11419 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11421 if (this.ExistCurrentPost && !_curPost.IsDm)
11422 RtCountMenuItem.Enabled = true;
11424 RtCountMenuItem.Enabled = false;
11426 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11427 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11429 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11432 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11437 private void CopyUserId()
11439 if (_curPost == null) return;
11440 string clstr = _curPost.ScreenName;
11443 Clipboard.SetDataObject(clstr, false, 5, 100);
11445 catch (Exception ex)
11447 MessageBox.Show(ex.Message);
11451 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11453 if (this.ExistCurrentPost && !_curPost.IsDm)
11457 await this.OpenRelatedTab(this._curPost);
11459 catch (TabException ex)
11461 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11467 /// 指定されたツイートに対する関連発言タブを開きます
11469 /// <param name="statusId">表示するツイートのID</param>
11470 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11471 public async Task OpenRelatedTab(long statusId)
11473 var post = this._statuses[statusId];
11478 post = await this.tw.GetStatusApi(false, statusId);
11480 catch (WebApiException ex)
11482 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11487 await this.OpenRelatedTab(post);
11491 /// 指定されたツイートに対する関連発言タブを開きます
11493 /// <param name="post">表示する対象となるツイート</param>
11494 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11495 private async Task OpenRelatedTab(PostClass post)
11497 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11498 if (tabRelated != null)
11500 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11503 var tabName = this._statuses.MakeTabName("Related Tweets");
11505 tabRelated = new RelatedPostsTabModel(tabName, post);
11506 tabRelated.UnreadManage = false;
11507 tabRelated.Notify = false;
11509 this._statuses.AddTab(tabRelated);
11510 this.AddNewTab(tabRelated, startup: false);
11513 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11515 tabPage = this.ListTab.TabPages[i];
11516 if (tabName == tabPage.Text)
11518 this.ListTab.SelectedIndex = i;
11523 await this.GetRelatedTweetsAsync(tabRelated);
11525 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11526 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11528 if (tabPage != null)
11530 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11532 var listView = (DetailsListView)tabPage.Tag;
11533 var targetPost = tabRelated.TargetPost;
11534 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11536 if (index != -1 && index < listView.Items.Count)
11538 listView.SelectedIndices.Add(index);
11539 listView.Items[index].Focused = true;
11544 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11546 StringBuilder buf = new StringBuilder();
11547 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11548 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11549 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11550 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11551 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11554 private void tw_UserIdChanged()
11556 this.ModifySettingCommon = true;
11559 #region "Userstream"
11560 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11564 if (InvokeRequired && !IsDisposed)
11566 await this.InvokeAsync(async () =>
11568 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11569 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11571 this.PurgeListViewItemCache();
11572 ((DetailsListView)_curTab.Tag).Update();
11573 if (_curPost != null && _curPost.StatusId == e.StatusId)
11574 await this.DispSelectedPost(true);
11580 catch (ObjectDisposedException)
11584 catch (InvalidOperationException)
11590 private int userStreamsRefreshing = 0;
11592 private async void tw_NewPostFromStream(object sender, EventArgs e)
11594 if (SettingManager.Common.ReadOldPosts)
11596 _statuses.SetReadHomeTab(); //新着時未読クリア
11599 this._statuses.DistributePosts();
11601 if (SettingManager.Common.UserstreamPeriod > 0) return;
11603 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11604 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11608 await this.InvokeAsync(() => this.RefreshTimeline())
11609 .ConfigureAwait(false);
11613 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11618 private async void tw_UserStreamStarted(object sender, EventArgs e)
11622 if (InvokeRequired && !IsDisposed)
11624 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11628 catch (ObjectDisposedException)
11632 catch (InvalidOperationException)
11637 this.RefreshUserStreamsMenu();
11638 this.MenuItemUserStream.Enabled = true;
11640 StatusLabel.Text = "UserStream Started.";
11643 private async void tw_UserStreamStopped(object sender, EventArgs e)
11647 if (InvokeRequired && !IsDisposed)
11649 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11653 catch (ObjectDisposedException)
11657 catch (InvalidOperationException)
11662 this.RefreshUserStreamsMenu();
11663 this.MenuItemUserStream.Enabled = true;
11665 StatusLabel.Text = "UserStream Stopped.";
11668 private void RefreshUserStreamsMenu()
11670 if (this.tw.UserStreamActive)
11672 this.MenuItemUserStream.Text = "&UserStream ▶";
11673 this.StopToolStripMenuItem.Text = "&Stop";
11677 this.MenuItemUserStream.Text = "&UserStream ■";
11678 this.StopToolStripMenuItem.Text = "&Start";
11682 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11686 if (InvokeRequired && !IsDisposed)
11688 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11692 catch (ObjectDisposedException)
11696 catch (InvalidOperationException)
11700 var ev = e.EventData;
11701 StatusLabel.Text = "Event: " + ev.Event;
11702 //if (ev.Event == "favorite")
11704 // NotifyFavorite(ev);
11707 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11709 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11711 this.PurgeListViewItemCache();
11712 ((DetailsListView)_curTab.Tag).Update();
11714 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11716 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11717 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11722 private void NotifyEvent(Twitter.FormattedEvent ev)
11725 if (BalloonRequired(ev))
11727 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11728 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11729 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11730 StringBuilder title = new StringBuilder();
11731 if (SettingManager.Common.DispUsername)
11733 title.Append(tw.Username);
11734 title.Append(" - ");
11740 title.Append(Application.ProductName);
11741 title.Append(" [");
11742 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11743 title.Append("] by ");
11744 if (!string.IsNullOrEmpty(ev.Username))
11746 title.Append(ev.Username);
11750 //title.Append("");
11753 if (!string.IsNullOrEmpty(ev.Target))
11755 //NotifyIcon1.BalloonTipText = ev.Target;
11760 //NotifyIcon1.BalloonTipText = " ";
11763 //NotifyIcon1.ShowBalloonTip(500);
11764 if (SettingManager.Common.IsUseNotifyGrowl)
11766 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11767 ev.Id.ToString(), title.ToString(), text);
11771 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11772 NotifyIcon1.BalloonTipTitle = title.ToString();
11773 NotifyIcon1.BalloonTipText = text;
11774 NotifyIcon1.ShowBalloonTip(500);
11779 string snd = SettingManager.Common.EventSoundFile;
11780 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11782 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11786 string dir = Application.StartupPath;
11787 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11789 dir = Path.Combine(dir, "Sounds");
11791 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11803 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11805 MenuItemUserStream.Enabled = false;
11806 if (StopRefreshAllMenuItem.Checked)
11808 StopRefreshAllMenuItem.Checked = false;
11811 if (this.tw.UserStreamActive)
11813 tw.StopUserStream();
11817 tw.StartUserStream();
11821 private static string inputTrack = "";
11823 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11825 if (TrackToolStripMenuItem.Checked)
11827 using (InputTabName inputForm = new InputTabName())
11829 inputForm.TabName = inputTrack;
11830 inputForm.FormTitle = "Input track word";
11831 inputForm.FormDescription = "Track word";
11832 if (inputForm.ShowDialog() != DialogResult.OK)
11834 TrackToolStripMenuItem.Checked = false;
11837 inputTrack = inputForm.TabName.Trim();
11839 if (!inputTrack.Equals(tw.TrackWord))
11841 tw.TrackWord = inputTrack;
11842 this.ModifySettingCommon = true;
11843 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11844 tw.ReconnectUserStream();
11850 tw.ReconnectUserStream();
11852 this.ModifySettingCommon = true;
11855 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11857 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11858 this.ModifySettingCommon = true;
11859 tw.ReconnectUserStream();
11862 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11864 if (evtDialog == null || evtDialog.IsDisposed)
11867 evtDialog = new EventViewerDialog();
11868 evtDialog.Owner = this;
11870 Point pos = evtDialog.Location;
11871 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11872 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11873 evtDialog.Location = pos;
11875 evtDialog.EventSource = tw.StoredEvent;
11876 if (!evtDialog.Visible)
11878 evtDialog.Show(this);
11882 evtDialog.Activate();
11884 this.TopMost = SettingManager.Common.AlwaysTop;
11888 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11890 MyCommon._endingFlag = true;
11894 Application.Restart();
11898 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11902 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11904 if (!string.IsNullOrEmpty(tw.Username))
11905 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11908 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11910 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11913 private bool ExistCurrentPost
11917 if (_curPost == null) return false;
11918 if (_curPost.IsDeleted) return false;
11923 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11925 ShowUserTimeline();
11928 private string GetUserIdFromCurPostOrInput(string caption)
11930 var id = _curPost?.ScreenName ?? "";
11932 using (InputTabName inputName = new InputTabName())
11934 inputName.FormTitle = caption;
11935 inputName.FormDescription = Properties.Resources.FRMessage1;
11936 inputName.TabName = id;
11937 if (inputName.ShowDialog() == DialogResult.OK &&
11938 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11940 id = inputName.TabName.Trim();
11950 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11952 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11953 if (!string.IsNullOrEmpty(id))
11955 AddNewTabForUserTimeline(id);
11959 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11961 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11962 if (!string.IsNullOrEmpty(id))
11964 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11968 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11970 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11973 private void TimelineRefreshEnableChange(bool isEnable)
11977 tw.StartUserStream();
11981 tw.StopUserStream();
11983 TimerTimeline.Enabled = isEnable;
11986 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11988 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11991 private async Task OpenUserAppointUrl()
11993 if (SettingManager.Common.UserAppointUrl != null)
11995 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11997 if (_curPost != null)
11999 string xUrl = SettingManager.Common.UserAppointUrl;
12000 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12002 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12003 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12005 await this.OpenUriInBrowserAsync(xUrl);
12010 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12015 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12017 await this.OpenUserAppointUrl();
12020 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12022 if (Form.ActiveForm == null)
12024 await this.InvokeAsync(() =>
12026 this.Visible = true;
12027 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12029 this.BringToFront();
12030 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12032 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12036 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12042 private void ReplaceAppName()
12044 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12045 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12048 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12050 this.SplitContainer3.Panel2Collapsed = false;
12053 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12055 await this.OpenThumbnailPicture(e.Thumbnail);
12058 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12060 await this.OpenUriInBrowserAsync(e.ImageUrl);
12063 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12065 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12067 await this.OpenUriInBrowserAsync(url);
12070 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12072 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12075 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12077 if (e.KeyCode == Keys.Space)
12079 this.JumpUnreadMenuItem_Click(null, null);
12081 e.SuppressKeyPress = true;
12085 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12087 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12088 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12089 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12090 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12091 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12093 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12096 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12098 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12101 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12103 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12106 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12108 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12111 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12113 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12116 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12118 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12121 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12123 if (SettingManager.Common.IconSize == iconSize) return;
12125 var oldIconCol = _iconCol;
12127 SettingManager.Common.IconSize = iconSize;
12128 ApplyListViewIconSize(iconSize);
12130 if (_iconCol != oldIconCol)
12132 foreach (TabPage tp in ListTab.TabPages)
12134 ResetColumns((DetailsListView)tp.Tag);
12138 _curList?.Refresh();
12140 ModifySettingCommon = true;
12143 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12145 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12146 if (SettingManager.Common.SortOrderLock == state) return;
12148 SettingManager.Common.SortOrderLock = state;
12150 ModifySettingCommon = true;
12153 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12155 if (!string.IsNullOrEmpty(e.StatusText))
12157 this.StatusLabelUrl.Text = e.StatusText;
12161 this.SetStatusLabelUrl();