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.BitlyId = SettingManager.Common.BilyUser;
815 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
817 // アクセストークンが有効であるか確認する
818 // ここが Twitter API への最初のアクセスになるようにすること
821 this.tw.VerifyCredentials();
823 catch (WebApiException ex)
825 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
826 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
830 //プロキシ設定等の通信まわりの初期化が済んでから処理する
831 ThumbnailGenerator.InitializeGenerator();
833 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
834 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
835 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
837 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
840 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
843 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
844 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
845 HashMgr = new HashtagManage(HashSupl,
846 SettingManager.Common.HashTags.ToArray(),
847 SettingManager.Common.HashSelected,
848 SettingManager.Common.HashIsPermanent,
849 SettingManager.Common.HashIsHead,
850 SettingManager.Common.HashIsNotAddToAtReply);
851 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
854 this.IconCache = new ImageCache();
855 this.tweetDetailsView.IconCache = this.IconCache;
858 _fntUnread = SettingManager.Local.FontUnread;
859 _clUnread = SettingManager.Local.ColorUnread;
860 _fntReaded = SettingManager.Local.FontRead;
861 _clReaded = SettingManager.Local.ColorRead;
862 _clFav = SettingManager.Local.ColorFav;
863 _clOWL = SettingManager.Local.ColorOWL;
864 _clRetweet = SettingManager.Local.ColorRetweet;
865 _fntDetail = SettingManager.Local.FontDetail;
866 _clDetail = SettingManager.Local.ColorDetail;
867 _clDetailLink = SettingManager.Local.ColorDetailLink;
868 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
869 _clSelf = SettingManager.Local.ColorSelf;
870 _clAtSelf = SettingManager.Local.ColorAtSelf;
871 _clTarget = SettingManager.Local.ColorTarget;
872 _clAtTarget = SettingManager.Local.ColorAtTarget;
873 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
874 _clAtTo = SettingManager.Local.ColorAtTo;
875 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
876 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
877 _clInputFont = SettingManager.Local.ColorInputFont;
878 _fntInputFont = SettingManager.Local.FontInputFont;
880 _brsBackColorMine = new SolidBrush(_clSelf);
881 _brsBackColorAt = new SolidBrush(_clAtSelf);
882 _brsBackColorYou = new SolidBrush(_clTarget);
883 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
884 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
885 _brsBackColorAtTo = new SolidBrush(_clAtTo);
886 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
887 _brsBackColorNone = new SolidBrush(_clListBackcolor);
889 // StringFormatオブジェクトへの事前設定
890 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
891 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
892 //sf.FormatFlags = StringFormatFlags.LineLimit; //
893 sfTab.Alignment = StringAlignment.Center;
894 sfTab.LineAlignment = StringAlignment.Center;
896 InitDetailHtmlFormat();
898 //Regex statregex = new Regex("^0*");
899 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
901 _history.Add(new PostingStatus());
903 this.inReplyTo = null;
906 SearchDialog.Owner = this;
907 UrlDialog.Owner = this;
910 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
911 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
913 //新着取得時のリストスクロールをするか。trueならスクロールしない
914 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
915 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
917 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
918 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
920 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
921 this.ToolStripFocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
924 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
925 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
926 _myLoc = SettingManager.Local.FormLocation;
928 if (this.WindowState != FormWindowState.Minimized)
930 this.DesktopLocation = SettingManager.Local.FormLocation;
931 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
932 bool outOfScreen = true;
933 if (Screen.AllScreens.Length == 1) //ハングするとの報告
935 foreach (Screen scr in Screen.AllScreens)
937 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
945 this.DesktopLocation = new Point(0, 0);
946 _myLoc = this.DesktopLocation;
950 this.TopMost = SettingManager.Common.AlwaysTop;
951 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
952 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
953 if (SettingManager.Local.PreviewDistance == -1)
955 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
956 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
957 SettingManager.Local.PreviewDistance = _mySpDis3;
961 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
963 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
964 //this.Tween_ClientSizeChanged(this, null);
965 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
966 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
968 StatusText.Font = _fntInputFont;
969 StatusText.ForeColor = _clInputFont;
971 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
972 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
973 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
975 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
976 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
978 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
979 if (SettingManager.Common.UnreadManage == false)
981 ReadedStripMenuItem.Enabled = false;
982 UnreadStripMenuItem.Enabled = false;
985 //リンク先URL表示部の初期化(画面左下)
986 StatusLabelUrl.Text = "";
988 StatusLabel.Text = "";
989 StatusLabel.AutoToolTip = false;
990 StatusLabel.ToolTipText = "";
992 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
994 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
995 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
996 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
997 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
999 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1000 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1001 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1002 this.SplitContainer2.Panel2.AccessibleName = "";
1004 ////////////////////////////////////////////////////////////////////////////////
1005 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1006 var mode = ComparerMode.Id;
1007 switch (SettingManager.Common.SortColumn)
1009 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1013 mode = ComparerMode.Id; //Idソートに読み替え
1016 mode = ComparerMode.Nickname;
1019 mode = ComparerMode.Data;
1022 mode = ComparerMode.Id;
1025 mode = ComparerMode.Name;
1028 mode = ComparerMode.Source;
1031 _statuses.SetSortMode(mode, sortOrder);
1032 ////////////////////////////////////////////////////////////////////////////////
1034 ApplyListViewIconSize(SettingManager.Common.IconSize);
1036 //<<<<<<<<タブ関連>>>>>>>
1040 //デフォルトタブの存在チェック、ない場合には追加
1041 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1042 this._statuses.AddTab(new HomeTabModel());
1044 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1045 this._statuses.AddTab(new MentionsTabModel());
1047 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1048 this._statuses.AddTab(new DirectMessagesTabModel());
1050 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1051 this._statuses.AddTab(new FavoritesTabModel());
1053 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1054 this._statuses.AddTab(new MuteTabModel());
1056 foreach (var tab in _statuses.Tabs.Values)
1059 if (tab.TabType == MyCommon.TabUsageType.Mute)
1062 if (!AddNewTab(tab, startup: true))
1063 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1066 _curTab = ListTab.SelectedTab;
1068 _curList = (DetailsListView)_curTab.Tag;
1070 if (SettingManager.Common.TabIconDisp)
1072 ListTab.DrawMode = TabDrawMode.Normal;
1076 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1077 ListTab.DrawItem += ListTab_DrawItem;
1078 ListTab.ImageList = null;
1081 if (SettingManager.Common.HotkeyEnabled)
1084 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1085 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1086 modKey |= HookGlobalHotkey.ModKeys.Alt;
1087 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1088 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1089 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1090 modKey |= HookGlobalHotkey.ModKeys.Shift;
1091 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1092 modKey |= HookGlobalHotkey.ModKeys.Win;
1094 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1097 if (SettingManager.Common.IsUseNotifyGrowl)
1100 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1102 SetMainWindowTitle();
1103 SetNotifyIconText();
1105 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1107 this.Visible = true;
1111 TimerTimeline.AutoReset = true;
1112 TimerTimeline.SynchronizingObject = this;
1114 TimerTimeline.Interval = 1000;
1115 TimerTimeline.Enabled = true;
1117 TimerRefreshIcon.Interval = 200;
1118 TimerRefreshIcon.Enabled = true;
1120 _ignoreConfigSave = false;
1121 this.TweenMain_Resize(null, null);
1122 if (saveRequired) SaveConfigsAll(false);
1124 foreach (var ua in SettingManager.Common.UserAccounts)
1126 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1128 ua.UserId = tw.UserId;
1135 // 初回起動時だけ右下のメニューを目立たせる
1136 HashStripSplitButton.ShowDropDown();
1140 private void InitDetailHtmlFormat()
1142 if (SettingManager.Common.IsMonospace)
1144 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1145 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1149 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1150 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1153 detailHtmlFormatHeader = detailHtmlFormatHeader
1154 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1155 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1156 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1157 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1158 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1159 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1162 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1167 txt = ListTab.TabPages[e.Index].Text;
1174 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1175 if (e.State == DrawItemState.Selected)
1177 e.DrawFocusRectangle();
1182 if (_statuses.Tabs[txt].UnreadCount > 0)
1185 fore = System.Drawing.SystemBrushes.ControlText;
1189 fore = System.Drawing.SystemBrushes.ControlText;
1191 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1194 private void LoadConfig()
1196 SettingManager.Local = SettingManager.Local;
1198 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1199 if (SettingManager.Local.ScaleDimension.IsEmpty)
1200 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1202 var tabSettings = SettingManager.Tabs;
1203 foreach (var tabSetting in tabSettings.Tabs)
1206 switch (tabSetting.TabType)
1208 case MyCommon.TabUsageType.Home:
1209 tab = new HomeTabModel(tabSetting.TabName);
1211 case MyCommon.TabUsageType.Mentions:
1212 tab = new MentionsTabModel(tabSetting.TabName);
1214 case MyCommon.TabUsageType.DirectMessage:
1215 tab = new DirectMessagesTabModel(tabSetting.TabName);
1217 case MyCommon.TabUsageType.Favorites:
1218 tab = new FavoritesTabModel(tabSetting.TabName);
1220 case MyCommon.TabUsageType.UserDefined:
1221 tab = new FilterTabModel(tabSetting.TabName);
1223 case MyCommon.TabUsageType.UserTimeline:
1224 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1226 case MyCommon.TabUsageType.PublicSearch:
1227 tab = new PublicSearchTabModel(tabSetting.TabName)
1229 SearchWords = tabSetting.SearchWords,
1230 SearchLang = tabSetting.SearchLang,
1233 case MyCommon.TabUsageType.Lists:
1234 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1236 case MyCommon.TabUsageType.Mute:
1237 tab = new MuteTabModel(tabSetting.TabName);
1243 tab.UnreadManage = tabSetting.UnreadManage;
1244 tab.Protected = tabSetting.Protected;
1245 tab.Notify = tabSetting.Notify;
1246 tab.SoundFile = tabSetting.SoundFile;
1248 if (tab.IsDistributableTabType)
1250 var filterTab = (FilterTabModel)tab;
1251 filterTab.FilterArray = tabSetting.FilterArray;
1252 filterTab.FilterModified = false;
1255 if (this._statuses.ContainsTab(tab.TabName))
1256 tab.TabName = this._statuses.MakeTabName("MyTab");
1258 this._statuses.AddTab(tab);
1260 if (_statuses.Tabs.Count == 0)
1262 _statuses.AddTab(new HomeTabModel());
1263 _statuses.AddTab(new MentionsTabModel());
1264 _statuses.AddTab(new DirectMessagesTabModel());
1265 _statuses.AddTab(new FavoritesTabModel());
1269 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1271 if (!TimerTimeline.Enabled) return;
1275 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1277 private static int homeCounter = 0;
1278 private static int mentionCounter = 0;
1279 private static int dmCounter = 0;
1280 private static int pubSearchCounter = 0;
1281 private static int userTimelineCounter = 0;
1282 private static int listsCounter = 0;
1283 private static int usCounter = 0;
1284 private static int ResumeWait = 0;
1285 private static int refreshFollowers = 0;
1287 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1289 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1290 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1291 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1292 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1293 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1294 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1295 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1296 Interlocked.Increment(ref refreshFollowers);
1298 var refreshTasks = new List<Task>();
1301 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1303 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1304 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1305 refreshTasks.Add(this.GetHomeTimelineAsync());
1306 ResetTimers.Timeline = false;
1308 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1310 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1311 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1312 refreshTasks.Add(this.GetReplyAsync());
1313 ResetTimers.Reply = false;
1315 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1317 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1318 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1319 refreshTasks.Add(this.GetDirectMessagesAsync());
1320 ResetTimers.DirectMessage = false;
1322 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1324 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1325 if (!ResetTimers.PublicSearch)
1326 refreshTasks.Add(this.GetPublicSearchAllAsync());
1327 ResetTimers.PublicSearch = false;
1329 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1331 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1332 if (!ResetTimers.UserTimeline)
1333 refreshTasks.Add(this.GetUserTimelineAllAsync());
1334 ResetTimers.UserTimeline = false;
1336 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1338 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1339 if (!ResetTimers.Lists)
1340 refreshTasks.Add(this.GetListTimelineAllAsync());
1341 ResetTimers.Lists = false;
1343 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1345 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1346 if (this.tw.UserStreamActive)
1347 this.RefreshTimeline();
1348 ResetTimers.UserStream = false;
1350 if (refreshFollowers > 6 * 3600)
1352 Interlocked.Exchange(ref refreshFollowers, 0);
1353 refreshTasks.AddRange(new[]
1355 this.doGetFollowersMenu(),
1356 this.RefreshNoRetweetIdsAsync(),
1357 this.RefreshTwitterConfigurationAsync(),
1362 Interlocked.Increment(ref ResumeWait);
1363 if (ResumeWait > 30)
1366 Interlocked.Exchange(ref ResumeWait, 0);
1367 refreshTasks.AddRange(new[]
1369 this.GetHomeTimelineAsync(),
1370 this.GetReplyAsync(),
1371 this.GetDirectMessagesAsync(),
1372 this.GetPublicSearchAllAsync(),
1373 this.GetUserTimelineAllAsync(),
1374 this.GetListTimelineAllAsync(),
1375 this.doGetFollowersMenu(),
1376 this.RefreshTwitterConfigurationAsync(),
1381 await Task.WhenAll(refreshTasks);
1384 private void RefreshTimeline()
1386 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1388 // 現在表示中のタブのスクロール位置を退避
1389 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1391 // 各タブのリスト上の選択位置などを退避
1392 var listSelections = this.SaveListViewSelection();
1396 addCount = _statuses.SubmitUpdate(out var soundFile, out var notifyPosts,
1397 out var newMentionOrDm, out var isDelete);
1399 if (MyCommon._endingFlag) return;
1402 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1404 var listView = (DetailsListView)tabPage.Tag;
1405 var tabModel = this._statuses.Tabs[tabPage.Text];
1407 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1409 using (ControlTransaction.Update(listView))
1411 if (listView == this._curList)
1412 this.PurgeListViewItemCache();
1417 listView.VirtualListSize = tabModel.AllCount;
1419 catch (NullReferenceException ex)
1421 // WinForms 内部で ListView.set_TopItem が発生させている例外
1422 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1423 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1427 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1434 if (SettingManager.Common.TabIconDisp)
1436 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1438 var tabModel = this._statuses.Tabs[tabPage.Text];
1439 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1440 tabPage.ImageIndex = 0; // 未読アイコン
1445 this.ListTab.Refresh();
1450 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1453 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1455 SetMainWindowTitle();
1456 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1458 HashSupl.AddRangeItem(tw.GetHashList());
1462 internal struct ListViewScroll
1464 public ScrollLockMode ScrollLockMode { get; set; }
1465 public long? TopItemStatusId { get; set; }
1468 internal enum ScrollLockMode
1470 /// <summary>固定しない</summary>
1473 /// <summary>最上部に固定する</summary>
1476 /// <summary>最下部に固定する</summary>
1479 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1484 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1486 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1488 var listScroll = new ListViewScroll
1490 ScrollLockMode = this.GetScrollLockMode(listView),
1493 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1495 var topItemIndex = listView.TopItem?.Index ?? -1;
1496 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1497 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1503 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1505 if (this._statuses.SortMode == ComparerMode.Id)
1507 if (this._statuses.SortOrder == SortOrder.Ascending)
1510 if (this.ListLockMenuItem.Checked)
1511 return ScrollLockMode.None;
1513 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1516 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1517 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1518 return ScrollLockMode.FixedToBottom;
1520 return ScrollLockMode.None;
1525 if (this.ListLockMenuItem.Checked)
1526 return ScrollLockMode.FixedToItem;
1528 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1529 var topItem = listView.TopItem;
1530 if (topItem == null || topItem.Index == 0)
1531 return ScrollLockMode.FixedToTop;
1533 return ScrollLockMode.FixedToItem;
1538 return ScrollLockMode.FixedToItem;
1542 internal struct ListViewSelection
1544 public long[] SelectedStatusIds { get; set; }
1545 public long? SelectionMarkStatusId { get; set; }
1546 public long? FocusedStatusId { get; set; }
1550 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1552 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1554 var listsDict = new Dictionary<string, ListViewSelection>();
1556 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1558 var listView = (DetailsListView)tabPage.Tag;
1559 var tab = _statuses.Tabs[tabPage.Text];
1561 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1568 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1570 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1572 if (listView.VirtualListSize == 0)
1574 return new ListViewSelection
1576 SelectedStatusIds = new long[0],
1577 SelectionMarkStatusId = null,
1578 FocusedStatusId = null,
1582 return new ListViewSelection
1584 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1585 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1586 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1590 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1592 var selectedIndices = listView.SelectedIndices;
1593 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1594 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1599 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1601 var index = listView.FocusedItem?.Index ?? -1;
1603 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1606 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1608 var index = listView.SelectionMark;
1610 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1614 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1616 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1618 if (listView.VirtualListSize == 0)
1621 switch (listScroll.ScrollLockMode)
1623 case ScrollLockMode.FixedToTop:
1624 listView.EnsureVisible(0);
1626 case ScrollLockMode.FixedToBottom:
1627 listView.EnsureVisible(listView.VirtualListSize - 1);
1629 case ScrollLockMode.FixedToItem:
1630 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1632 listView.TopItem = listView.Items[topIndex];
1634 case ScrollLockMode.None:
1641 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1643 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1645 // status_id から ListView 上のインデックスに変換
1646 int[] selectedIndices = null;
1647 if (listSelection.SelectedStatusIds != null)
1648 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1650 var focusedIndex = -1;
1651 if (listSelection.FocusedStatusId != null)
1652 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1654 var selectionMarkIndex = -1;
1655 if (listSelection.SelectionMarkStatusId != null)
1656 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1658 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1661 private bool BalloonRequired()
1663 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1664 ev.Eventtype = MyCommon.EVENTTYPE.None;
1666 return BalloonRequired(ev);
1669 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1671 if (type == MyCommon.EVENTTYPE.None)
1674 if (!SettingManager.Common.EventNotifyEnabled)
1677 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1680 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1685 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1688 private bool BalloonRequired(Twitter.FormattedEvent ev)
1693 if (NativeMethods.IsScreenSaverRunning())
1697 if (!this.NewPostPopMenuItem.Checked)
1699 // 「新着通知が無効でもイベントを通知する」にも該当しない
1700 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1704 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1705 if (SettingManager.Common.LimitBalloon)
1707 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1711 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1714 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1716 if (SettingManager.Common.ReadOwnPost)
1718 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1723 if (BalloonRequired())
1725 if (notifyPosts != null && notifyPosts.Length > 0)
1727 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1728 if (SettingManager.Common.IsUseNotifyGrowl)
1730 StringBuilder sb = new StringBuilder();
1734 foreach (PostClass post in notifyPosts)
1736 if (!(notifyPosts.Length > 3))
1742 if (post.IsReply && !post.IsExcludeReply) reply = true;
1743 if (post.IsDm) dm = true;
1744 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1745 switch (SettingManager.Common.NameBalloon)
1747 case MyCommon.NameBalloonEnum.UserID:
1748 sb.Append(post.ScreenName).Append(" : ");
1750 case MyCommon.NameBalloonEnum.NickName:
1751 sb.Append(post.Nickname).Append(" : ");
1754 sb.Append(post.TextFromApi);
1755 if (notifyPosts.Length > 3)
1757 if (notifyPosts.Last() != post) continue;
1760 StringBuilder title = new StringBuilder();
1761 GrowlHelper.NotifyType nt;
1762 if (SettingManager.Common.DispUsername)
1764 title.Append(tw.Username);
1765 title.Append(" - ");
1773 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1774 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1775 title.Append(Application.ProductName);
1776 title.Append(" [DM] ");
1777 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1778 nt = GrowlHelper.NotifyType.DirectMessage;
1782 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1783 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1784 title.Append(Application.ProductName);
1785 title.Append(" [Reply!] ");
1786 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1787 nt = GrowlHelper.NotifyType.Reply;
1791 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1792 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1793 title.Append(Application.ProductName);
1795 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1796 nt = GrowlHelper.NotifyType.Notify;
1798 string bText = sb.ToString();
1799 if (string.IsNullOrEmpty(bText)) return;
1801 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1802 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1807 StringBuilder sb = new StringBuilder();
1810 foreach (PostClass post in notifyPosts)
1812 if (post.IsReply && !post.IsExcludeReply) reply = true;
1813 if (post.IsDm) dm = true;
1814 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1815 switch (SettingManager.Common.NameBalloon)
1817 case MyCommon.NameBalloonEnum.UserID:
1818 sb.Append(post.ScreenName).Append(" : ");
1820 case MyCommon.NameBalloonEnum.NickName:
1821 sb.Append(post.Nickname).Append(" : ");
1824 sb.Append(post.TextFromApi);
1827 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1828 StringBuilder title = new StringBuilder();
1830 if (SettingManager.Common.DispUsername)
1832 title.Append(tw.Username);
1833 title.Append(" - ");
1841 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1842 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1843 ntIcon = ToolTipIcon.Warning;
1844 title.Append(Application.ProductName);
1845 title.Append(" [DM] ");
1846 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1850 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1851 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1852 ntIcon = ToolTipIcon.Warning;
1853 title.Append(Application.ProductName);
1854 title.Append(" [Reply!] ");
1855 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1859 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1860 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1861 ntIcon = ToolTipIcon.Info;
1862 title.Append(Application.ProductName);
1864 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1866 string bText = sb.ToString();
1867 if (string.IsNullOrEmpty(bText)) return;
1868 //NotifyIcon1.BalloonTipText = sb.ToString();
1869 //NotifyIcon1.ShowBalloonTip(500);
1870 NotifyIcon1.BalloonTipTitle = title.ToString();
1871 NotifyIcon1.BalloonTipText = bText;
1872 NotifyIcon1.BalloonTipIcon = ntIcon;
1873 NotifyIcon1.ShowBalloonTip(500);
1879 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1883 string dir = Application.StartupPath;
1884 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1886 dir = Path.Combine(dir, "Sounds");
1888 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1898 //mentions新着時に画面ブリンク
1899 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1901 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1905 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1907 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1909 _curItemIndex = _curList.SelectedIndices[0];
1910 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1914 this._curPost = GetCurTabPost(_curItemIndex);
1916 catch (ArgumentException)
1921 this.PushSelectPostChain();
1923 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1925 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1931 private void ChangeCacheStyleRead(bool Read, int Index)
1933 var tabInfo = _statuses.Tabs[_curTab.Text];
1934 //Read:true=既読 false=未読
1935 //未読管理していなかったら既読として扱う
1936 if (!tabInfo.UnreadManage ||
1937 !SettingManager.Common.UnreadManage) Read = true;
1939 var listCache = this._listItemCache;
1940 if (listCache == null)
1943 // キャッシュに含まれていないアイテムは対象外
1944 if (!listCache.TryGetValue(Index, out var itm, out var post))
1947 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1950 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1957 Item.SubItems[5].Text = "";
1962 Item.SubItems[5].Text = "★";
1968 else if (Post.RetweetedId != null)
1970 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1972 else if (Read || !SettingManager.Common.UseUnreadStyle)
1977 if (DList == null || Item.Index == -1)
1979 Item.ForeColor = cl;
1980 if (SettingManager.Common.UseUnreadStyle)
1986 if (SettingManager.Common.UseUnreadStyle)
1987 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1989 DList.ChangeItemForeColor(Item.Index, cl);
1990 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1994 private void ColorizeList()
1996 //Index:更新対象のListviewItem.Index。Colorを返す。
1997 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2000 _post = _anchorPost;
2004 if (_post == null) return;
2006 var listCache = this._listItemCache;
2007 if (listCache == null)
2010 var index = listCache.StartIndex;
2011 foreach (var cachedPost in listCache.Post)
2013 var backColor = this.JudgeColor(_post, cachedPost);
2014 this._curList.ChangeItemBackColor(index++, backColor);
2018 private void ColorizeList(ListViewItem Item, int Index)
2020 //Index:更新対象のListviewItem.Index。Colorを返す。
2021 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2024 _post = _anchorPost;
2028 PostClass tPost = GetCurTabPost(Index);
2030 if (_post == null) return;
2032 if (Item.Index == -1)
2033 Item.BackColor = JudgeColor(_post, tPost);
2035 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2038 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2041 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2044 else if (TargetPost.IsMe)
2047 else if (TargetPost.IsReply)
2050 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2052 cl = _clAtFromTarget;
2053 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2056 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2061 cl = _clListBackcolor;
2066 private async void PostButton_Click(object sender, EventArgs e)
2068 if (StatusText.Text.Trim().Length == 0)
2070 if (!ImageSelector.Enabled)
2072 await this.DoRefresh();
2077 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2079 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2081 MessageBoxButtons.YesNoCancel,
2082 MessageBoxIcon.Question);
2085 case DialogResult.Yes:
2086 StatusText.Text = "";
2087 await this.doReTweetOfficial(false);
2089 case DialogResult.Cancel:
2094 var inReplyToStatusId = this.inReplyTo?.Item1;
2095 var inReplyToScreenName = this.inReplyTo?.Item2;
2096 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2098 if (SettingManager.Common.Nicoms)
2100 StatusText.SelectionStart = StatusText.Text.Length;
2101 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2103 //if (SettingDialog.UrlConvertAuto)
2105 // StatusText.SelectionStart = StatusText.Text.Length;
2106 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2108 //else if (SettingDialog.Nicoms)
2110 // StatusText.SelectionStart = StatusText.Text.Length;
2111 // UrlConvert(UrlConverter.Nicoms);
2113 StatusText.SelectionStart = StatusText.Text.Length;
2114 CheckReplyTo(StatusText.Text);
2116 var statusText = this.FormatStatusText(this.StatusText.Text);
2118 if (this.GetRestStatusCount(statusText) < 0)
2120 // 文字数制限を超えているが強制的に投稿するか
2121 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2122 if (ret != DialogResult.OK)
2126 var status = new PostingStatus();
2127 status.status = statusText;
2129 status.inReplyToId = this.inReplyTo?.Item1;
2130 status.inReplyToName = this.inReplyTo?.Item2;
2131 if (ImageSelector.Visible)
2134 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2138 this.inReplyTo = null;
2139 StatusText.Text = "";
2140 _history.Add(new PostingStatus());
2141 _hisIdx = _history.Count - 1;
2142 if (!ToolStripFocusLockMenuItem.Checked)
2143 ((Control)ListTab.SelectedTab.Tag).Focus();
2144 urlUndoBuffer = null;
2145 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2148 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2150 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2151 await this.OpenUriInBrowserAsync(tmp);
2154 await this.PostMessageAsync(status);
2157 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2159 MyCommon._endingFlag = true;
2163 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2165 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2167 //_endingFlag=false:フォームの×ボタン
2169 this.Visible = false;
2173 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2174 _ignoreConfigSave = true;
2175 MyCommon._endingFlag = true;
2176 TimerTimeline.Enabled = false;
2177 TimerRefreshIcon.Enabled = false;
2181 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2183 this.Visible = true;
2184 if (this.WindowState == FormWindowState.Minimized)
2186 this.WindowState = FormWindowState.Normal;
2189 this.BringToFront();
2192 private static int errorCount = 0;
2194 private static bool CheckAccountValid()
2196 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2202 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2211 private Task GetHomeTimelineAsync()
2213 return this.GetHomeTimelineAsync(loadMore: false);
2216 private async Task GetHomeTimelineAsync(bool loadMore)
2218 await this.workerSemaphore.WaitAsync();
2222 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2223 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2225 this.RefreshTimeline();
2227 catch (WebApiException ex)
2229 this._myStatusError = true;
2230 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2234 this.workerSemaphore.Release();
2238 private Task GetReplyAsync()
2240 return this.GetReplyAsync(loadMore: false);
2243 private async Task GetReplyAsync(bool loadMore)
2245 await this.workerSemaphore.WaitAsync();
2249 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2250 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2252 this.RefreshTimeline();
2254 catch (WebApiException ex)
2256 this._myStatusError = true;
2257 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2261 this.workerSemaphore.Release();
2265 private Task GetDirectMessagesAsync()
2267 return this.GetDirectMessagesAsync(loadMore: false);
2270 private async Task GetDirectMessagesAsync(bool loadMore)
2272 await this.workerSemaphore.WaitAsync();
2276 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2277 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2279 this.RefreshTimeline();
2281 catch (WebApiException ex)
2283 this._myStatusError = true;
2284 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2288 this.workerSemaphore.Release();
2292 private Task GetFavoritesAsync()
2294 return this.GetFavoritesAsync(loadMore: false);
2297 private async Task GetFavoritesAsync(bool loadMore)
2299 await this.workerSemaphore.WaitAsync();
2303 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2304 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2306 this.RefreshTimeline();
2308 catch (WebApiException ex)
2310 this._myStatusError = true;
2311 this.StatusLabel.Text = ex.Message;
2315 this.workerSemaphore.Release();
2319 private Task GetPublicSearchAllAsync()
2321 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2323 return this.GetPublicSearchAsync(tabs, loadMore: false);
2326 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2328 return this.GetPublicSearchAsync(tab, loadMore: false);
2331 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2333 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2336 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2338 await this.workerSemaphore.WaitAsync();
2342 foreach (var tab in tabs)
2346 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2348 catch (WebApiException ex)
2350 this._myStatusError = true;
2351 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2355 this.RefreshTimeline();
2359 this.workerSemaphore.Release();
2363 private Task GetUserTimelineAllAsync()
2365 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2367 return this.GetUserTimelineAsync(tabs, loadMore: false);
2370 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2372 return this.GetUserTimelineAsync(tab, loadMore: false);
2375 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2377 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2380 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2382 await this.workerSemaphore.WaitAsync();
2386 foreach (var tab in tabs)
2390 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2392 catch (WebApiException ex)
2394 this._myStatusError = true;
2395 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2399 this.RefreshTimeline();
2403 this.workerSemaphore.Release();
2407 private Task GetListTimelineAllAsync()
2409 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2411 return this.GetListTimelineAsync(tabs, loadMore: false);
2414 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2416 return this.GetListTimelineAsync(tab, loadMore: false);
2419 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2421 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2424 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2426 await this.workerSemaphore.WaitAsync();
2430 foreach (var tab in tabs)
2434 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2436 catch (WebApiException ex)
2438 this._myStatusError = true;
2439 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2443 this.RefreshTimeline();
2447 this.workerSemaphore.Release();
2451 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2453 await this.workerSemaphore.WaitAsync();
2457 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2459 this.RefreshTimeline();
2461 catch (WebApiException ex)
2463 this._myStatusError = true;
2464 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2468 this.workerSemaphore.Release();
2472 private async Task FavAddAsync(long statusId, TabModel tab)
2474 await this.workerSemaphore.WaitAsync();
2478 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2480 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2482 catch (WebApiException ex)
2484 this._myStatusError = true;
2485 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2489 this.workerSemaphore.Release();
2493 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2495 if (ct.IsCancellationRequested)
2498 if (!CheckAccountValid())
2499 throw new WebApiException("Auth error. Check your account");
2501 if (!tab.Posts.TryGetValue(statusId, out var post))
2507 await Task.Run(async () =>
2509 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2513 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2515 .ConfigureAwait(false);
2517 if (SettingManager.Common.RestrictFavCheck)
2519 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2520 .ConfigureAwait(false);
2522 if (status.Favorited != true)
2523 throw new WebApiException("NG(Restricted?)");
2526 this._favTimestamps.Add(DateTime.Now);
2529 if (this._statuses.ContainsKey(statusId))
2531 var postTl = this._statuses[statusId];
2532 postTl.IsFav = true;
2534 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2535 favTab.AddPostQueue(postTl);
2538 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2539 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2541 if (tb.Contains(statusId))
2542 tb.Posts[statusId].IsFav = true;
2545 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2547 catch (WebApiException)
2549 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2554 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2555 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2557 if (this._favTimestamps[i] < oneHour)
2558 this._favTimestamps.RemoveAt(i);
2561 this._statuses.DistributePosts();
2564 if (ct.IsCancellationRequested)
2567 this.RefreshTimeline();
2569 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2571 using (ControlTransaction.Update(this._curList))
2573 var idx = tab.IndexOf(statusId);
2575 this.ChangeCacheStyleRead(post.IsRead, idx);
2578 if (statusId == this._curPost.StatusId)
2579 await this.DispSelectedPost(true); // 選択アイテム再表示
2583 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2585 await this.workerSemaphore.WaitAsync();
2589 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2591 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2593 catch (WebApiException ex)
2595 this._myStatusError = true;
2596 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2600 this.workerSemaphore.Release();
2604 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2606 if (ct.IsCancellationRequested)
2609 if (!CheckAccountValid())
2610 throw new WebApiException("Auth error. Check your account");
2612 var successIds = new List<long>();
2614 await Task.Run(async () =>
2618 var failedCount = 0;
2619 foreach (var statusId in statusIds)
2623 var post = tab.Posts[statusId];
2625 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2632 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2634 .ConfigureAwait(false);
2636 catch (WebApiException)
2642 successIds.Add(statusId);
2643 post.IsFav = false; // リスト再描画必要
2645 if (this._statuses.ContainsKey(statusId))
2647 this._statuses[statusId].IsFav = false;
2650 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2651 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2653 if (tb.Contains(statusId))
2654 tb.Posts[statusId].IsFav = false;
2659 if (ct.IsCancellationRequested)
2662 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2663 foreach (var statusId in successIds)
2665 // ツイートが削除された訳ではないので IsDeleted はセットしない
2666 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2669 this.RefreshTimeline();
2671 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2673 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2679 using (ControlTransaction.Update(this._curList))
2681 foreach (var statusId in successIds)
2683 var idx = tab.IndexOf(statusId);
2687 var post = tab.Posts[statusId];
2688 this.ChangeCacheStyleRead(post.IsRead, idx);
2692 if (successIds.Contains(this._curPost.StatusId))
2693 await this.DispSelectedPost(true); // 選択アイテム再表示
2698 private async Task PostMessageAsync(PostingStatus status)
2700 await this.workerSemaphore.WaitAsync();
2704 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2706 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2708 catch (WebApiException ex)
2710 this._myStatusError = true;
2711 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2715 this.workerSemaphore.Release();
2719 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2721 if (ct.IsCancellationRequested)
2724 if (!CheckAccountValid())
2725 throw new WebApiException("Auth error. Check your account");
2727 p.Report("Posting...");
2733 await Task.Run(async () =>
2735 if (status.mediaItems == null || status.mediaItems.Length == 0)
2737 await this.tw.PostStatus(status.status, status.inReplyToId)
2738 .ConfigureAwait(false);
2742 var service = ImageSelector.GetService(status.imageService);
2743 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2744 .ConfigureAwait(false);
2748 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2750 catch (WebApiException ex)
2752 // 処理は中断せずエラーの表示のみ行う
2753 errMsg = $"Err:{ex.Message}(PostMessage)";
2755 this._myStatusError = true;
2757 catch (UnauthorizedAccessException ex)
2759 // アップロード対象のファイルが開けなかった場合など
2760 errMsg = $"Err:{ex.Message}(PostMessage)";
2762 this._myStatusError = true;
2766 // 使い終わった MediaItem は破棄する
2767 if (status.mediaItems != null)
2769 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2771 disposableItem.Dispose();
2776 if (ct.IsCancellationRequested)
2779 if (!string.IsNullOrEmpty(errMsg) &&
2780 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2781 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2783 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2785 var ret = MessageBox.Show(
2787 "Failed to update status",
2788 MessageBoxButtons.RetryCancel,
2789 MessageBoxIcon.Question);
2791 if (ret == DialogResult.Retry)
2793 await this.PostMessageAsync(status);
2797 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2798 if (this.ToolStripFocusLockMenuItem.Checked)
2799 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2804 this._postTimestamps.Add(DateTime.Now);
2806 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2807 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2809 if (this._postTimestamps[i] < oneHour)
2810 this._postTimestamps.RemoveAt(i);
2813 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2815 this.HashMgr.ClearHashtag();
2816 this.HashStripSplitButton.Text = "#[-]";
2817 this.HashToggleMenuItem.Checked = false;
2818 this.HashToggleToolStripMenuItem.Checked = false;
2821 this.SetMainWindowTitle();
2823 if (SettingManager.Common.PostAndGet)
2825 if (this.tw.UserStreamActive)
2826 this.RefreshTimeline();
2828 await this.GetHomeTimelineAsync();
2832 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2834 await this.workerSemaphore.WaitAsync();
2838 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2840 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2842 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2843 await this.GetHomeTimelineAsync();
2845 catch (WebApiException ex)
2847 this._myStatusError = true;
2848 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2852 this.workerSemaphore.Release();
2856 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2858 if (ct.IsCancellationRequested)
2861 if (!CheckAccountValid())
2862 throw new WebApiException("Auth error. Check your account");
2865 if (!SettingManager.Common.UnreadManage)
2868 read = this._initial && SettingManager.Common.Read;
2870 p.Report("Posting...");
2872 foreach (var statusId in statusIds)
2874 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2877 if (ct.IsCancellationRequested)
2880 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2882 this._postTimestamps.Add(DateTime.Now);
2884 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2885 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2887 if (this._postTimestamps[i] < oneHour)
2888 this._postTimestamps.RemoveAt(i);
2892 private async Task RefreshFollowerIdsAsync()
2894 await this.workerSemaphore.WaitAsync();
2897 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2899 await this.tw.RefreshFollowerIds();
2901 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2903 this.RefreshTimeline();
2904 this.PurgeListViewItemCache();
2905 this._curList?.Refresh();
2907 catch (WebApiException ex)
2909 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2913 this.workerSemaphore.Release();
2917 private async Task RefreshNoRetweetIdsAsync()
2919 await this.workerSemaphore.WaitAsync();
2922 await this.tw.RefreshNoRetweetIds();
2924 this.StatusLabel.Text = "NoRetweetIds refreshed";
2926 catch (WebApiException ex)
2928 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2932 this.workerSemaphore.Release();
2936 private async Task RefreshBlockIdsAsync()
2938 await this.workerSemaphore.WaitAsync();
2941 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2943 await this.tw.RefreshBlockIds();
2945 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2947 catch (WebApiException ex)
2949 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2953 this.workerSemaphore.Release();
2957 private async Task RefreshTwitterConfigurationAsync()
2959 await this.workerSemaphore.WaitAsync();
2962 await this.tw.RefreshConfiguration();
2964 if (this.tw.Configuration.PhotoSizeLimit != 0)
2966 foreach (var service in this.ImageSelector.GetServices())
2968 service.UpdateTwitterConfiguration(this.tw.Configuration);
2972 this.PurgeListViewItemCache();
2974 this._curList?.Refresh();
2976 catch (WebApiException ex)
2978 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2982 this.workerSemaphore.Release();
2986 private async Task RefreshMuteUserIdsAsync()
2988 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2992 await tw.RefreshMuteUserIdsAsync();
2994 catch (WebApiException ex)
2996 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3000 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3003 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3005 if (e.Button == MouseButtons.Left)
3007 this.Visible = true;
3008 if (this.WindowState == FormWindowState.Minimized)
3010 this.WindowState = _formWindowState;
3013 this.BringToFront();
3017 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3019 switch (SettingManager.Common.ListDoubleClickAction)
3022 MakeReplyOrDirectStatus();
3025 await this.FavoriteChange(true);
3028 if (_curPost != null)
3029 await this.ShowUserStatus(_curPost.ScreenName, false);
3035 ShowRelatedStatusesMenuItem_Click(null, null);
3038 MoveToHomeToolStripMenuItem_Click(null, null);
3041 StatusOpenMenuItem_Click(null, null);
3049 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3051 await this.FavoriteChange(true);
3054 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3056 await this.FavoriteChange(false);
3060 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3062 await this.FavoritesRetweetOfficial();
3065 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3067 await this.FavoritesRetweetUnofficial();
3070 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3072 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3075 //trueでFavAdd,falseでFavRemove
3076 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3077 || !this.ExistCurrentPost) return;
3079 if (this._curList.SelectedIndices.Count > 1)
3084 // https://support.twitter.com/articles/76915#favoriting
3085 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3086 _DoFavRetweetFlags = false;
3091 if (multiFavoriteChangeDialogEnable)
3093 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3094 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3095 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3097 if (confirm == DialogResult.Cancel)
3105 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3106 if (selectedPost.IsFav)
3108 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3112 await this.FavAddAsync(selectedPost.StatusId, tab);
3116 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3117 .Select(x => this.GetCurTabPost(x))
3118 .Where(x => x.IsFav);
3120 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3121 if (statusIds.Length == 0)
3123 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3127 await this.FavRemoveAsync(statusIds, tab);
3131 private PostClass GetCurTabPost(int Index)
3133 var listCache = this._listItemCache;
3134 if (listCache != null)
3136 if (listCache.TryGetValue(Index, out var item, out var post))
3140 return _statuses.Tabs[_curTab.Text][Index];
3143 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3145 if (_curList.SelectedIndices.Count > 0)
3146 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3147 else if (_curList.SelectedIndices.Count == 0)
3148 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3151 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3153 if (_curList.SelectedIndices.Count > 0)
3154 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3157 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3159 if ((!_initialLayout) && this.Visible)
3161 if (this.WindowState == FormWindowState.Normal)
3163 _mySize = this.ClientSize;
3164 _mySpDis = this.SplitContainer1.SplitterDistance;
3165 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3166 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3167 ModifySettingLocal = true;
3172 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3174 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3175 if (comparerMode == null)
3178 this.SetSortColumn(comparerMode.Value);
3182 /// 列インデックスからソートを行う ComparerMode を求める
3184 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3185 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3186 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3189 return ComparerMode.Id;
3191 switch (columnIndex)
3194 return ComparerMode.Nickname;
3196 return ComparerMode.Data;
3198 return ComparerMode.Id;
3200 return ComparerMode.Name;
3202 return ComparerMode.Source;
3204 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3210 /// 発言一覧の指定した位置の列でソートする
3212 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3213 private void SetSortColumnByDisplayIndex(int columnIndex)
3215 // 表示上の列の位置から ColumnHeader を求める
3216 var col = this._curList.Columns.Cast<ColumnHeader>()
3217 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3222 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3223 if (comparerMode == null)
3226 this.SetSortColumn(comparerMode.Value);
3230 /// 発言一覧の最後列の項目でソートする
3232 private void SetSortLastColumn()
3234 // 表示上の最後列にある ColumnHeader を求める
3235 var col = this._curList.Columns.Cast<ColumnHeader>()
3236 .OrderByDescending(x => x.DisplayIndex)
3239 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3240 if (comparerMode == null)
3243 this.SetSortColumn(comparerMode.Value);
3247 /// 発言一覧を指定された ComparerMode に基づいてソートする
3249 private void SetSortColumn(ComparerMode sortColumn)
3251 if (SettingManager.Common.SortOrderLock)
3254 this._statuses.ToggleSortOrder(sortColumn);
3255 this.InitColumnText();
3257 var list = this._curList;
3260 list.Columns[0].Text = this.ColumnText[0];
3261 list.Columns[1].Text = this.ColumnText[2];
3265 for (var i = 0; i <= 7; i++)
3267 list.Columns[i].Text = this.ColumnText[i];
3271 this.PurgeListViewItemCache();
3273 var tab = this._statuses.Tabs[this._curTab.Text];
3274 if (tab.AllCount > 0 && this._curPost != null)
3276 var idx = tab.IndexOf(this._curPost.StatusId);
3279 this.SelectListItem(list, idx);
3280 list.EnsureVisible(idx);
3285 this.ModifySettingCommon = true;
3288 private void TweenMain_LocationChanged(object sender, EventArgs e)
3290 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3292 _myLoc = this.DesktopLocation;
3293 ModifySettingLocal = true;
3297 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3299 if (ListTab.SelectedTab == null) return;
3300 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3301 if (!this.ExistCurrentPost)
3303 ReplyStripMenuItem.Enabled = false;
3304 ReplyAllStripMenuItem.Enabled = false;
3305 DMStripMenuItem.Enabled = false;
3306 ShowProfileMenuItem.Enabled = false;
3307 ShowUserTimelineContextMenuItem.Enabled = false;
3308 ListManageUserContextToolStripMenuItem2.Enabled = false;
3309 MoveToFavToolStripMenuItem.Enabled = false;
3310 TabMenuItem.Enabled = false;
3311 IDRuleMenuItem.Enabled = false;
3312 SourceRuleMenuItem.Enabled = false;
3313 ReadedStripMenuItem.Enabled = false;
3314 UnreadStripMenuItem.Enabled = false;
3318 ShowProfileMenuItem.Enabled = true;
3319 ListManageUserContextToolStripMenuItem2.Enabled = true;
3320 ReplyStripMenuItem.Enabled = true;
3321 ReplyAllStripMenuItem.Enabled = true;
3322 DMStripMenuItem.Enabled = true;
3323 ShowUserTimelineContextMenuItem.Enabled = true;
3324 MoveToFavToolStripMenuItem.Enabled = true;
3325 TabMenuItem.Enabled = true;
3326 IDRuleMenuItem.Enabled = true;
3327 SourceRuleMenuItem.Enabled = true;
3328 ReadedStripMenuItem.Enabled = true;
3329 UnreadStripMenuItem.Enabled = true;
3331 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3333 FavAddToolStripMenuItem.Enabled = false;
3334 FavRemoveToolStripMenuItem.Enabled = false;
3335 StatusOpenMenuItem.Enabled = false;
3336 FavorareMenuItem.Enabled = false;
3337 ShowRelatedStatusesMenuItem.Enabled = false;
3339 ReTweetStripMenuItem.Enabled = false;
3340 ReTweetUnofficialStripMenuItem.Enabled = false;
3341 QuoteStripMenuItem.Enabled = false;
3342 FavoriteRetweetContextMenu.Enabled = false;
3343 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3347 FavAddToolStripMenuItem.Enabled = true;
3348 FavRemoveToolStripMenuItem.Enabled = true;
3349 StatusOpenMenuItem.Enabled = true;
3350 FavorareMenuItem.Enabled = true;
3351 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3353 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3355 ReTweetStripMenuItem.Enabled = false;
3356 ReTweetUnofficialStripMenuItem.Enabled = false;
3357 QuoteStripMenuItem.Enabled = false;
3358 FavoriteRetweetContextMenu.Enabled = false;
3359 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3363 ReTweetStripMenuItem.Enabled = true;
3364 ReTweetUnofficialStripMenuItem.Enabled = true;
3365 QuoteStripMenuItem.Enabled = true;
3366 FavoriteRetweetContextMenu.Enabled = true;
3367 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3370 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3372 // RefreshMoreStripMenuItem.Enabled = true;
3376 // RefreshMoreStripMenuItem.Enabled = false;
3378 if (!this.ExistCurrentPost
3379 || _curPost.InReplyToStatusId == null)
3381 RepliedStatusOpenMenuItem.Enabled = false;
3385 RepliedStatusOpenMenuItem.Enabled = true;
3387 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3389 MoveToRTHomeMenuItem.Enabled = false;
3393 MoveToRTHomeMenuItem.Enabled = true;
3396 if (this.ExistCurrentPost)
3398 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3399 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3400 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3402 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3406 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3408 MakeReplyOrDirectStatus(false, true);
3411 private void DMStripMenuItem_Click(object sender, EventArgs e)
3413 MakeReplyOrDirectStatus(false, false);
3416 private async Task doStatusDelete()
3418 if (this._curTab == null || this._curList == null)
3421 if (this._curList.SelectedIndices.Count == 0)
3424 var posts = this._curList.SelectedIndices.Cast<int>()
3425 .Select(x => this.GetCurTabPost(x))
3428 // 選択されたツイートの中に削除可能なものが一つでもあるか
3429 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3432 var ret = MessageBox.Show(this,
3433 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3434 Properties.Resources.DeleteStripMenuItem_ClickText2,
3435 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3437 if (ret != DialogResult.OK)
3440 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3442 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3444 Exception lastException = null;
3445 foreach (var post in posts)
3447 if (!post.CanDeleteBy(this.tw.UserId))
3454 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3459 if (post.RetweetedByUserId == this.tw.UserId)
3461 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3463 await this.twitterApi.StatusesDestroy(post.StatusId)
3468 if (post.UserId == this.tw.UserId)
3470 if (post.RetweetedId != null)
3471 // 他人に RT された自分のツイート
3472 // => RT 元の自分のツイートを削除
3473 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3478 await this.twitterApi.StatusesDestroy(post.StatusId)
3484 catch (WebApiException ex)
3490 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3493 if (lastException == null)
3494 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3496 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3498 this.PurgeListViewItemCache();
3499 this._curPost = null;
3500 this._curItemIndex = -1;
3502 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3504 var listView = (DetailsListView)tabPage.Tag;
3505 var tab = this._statuses.Tabs[tabPage.Text];
3507 using (ControlTransaction.Update(listView))
3509 listView.VirtualListSize = tab.AllCount;
3511 if (tabPage == this._curTab)
3513 listView.SelectedIndices.Clear();
3515 if (tab.AllCount != 0)
3518 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3519 selectedIndex = focusedIndex;
3521 selectedIndex = tab.AllCount - 1;
3523 listView.SelectedIndices.Add(selectedIndex);
3524 listView.EnsureVisible(selectedIndex);
3525 listView.FocusedItem = listView.Items[selectedIndex];
3530 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3532 if (tabPage.ImageIndex == 0)
3533 tabPage.ImageIndex = -1; // タブアイコン
3537 if (!SettingManager.Common.TabIconDisp)
3538 this.ListTab.Refresh();
3542 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3544 await this.doStatusDelete();
3547 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3549 using (ControlTransaction.Update(this._curList))
3551 foreach (int idx in _curList.SelectedIndices)
3553 var post = this._statuses.Tabs[this._curTab.Text][idx];
3554 this._statuses.SetReadAllTab(post.StatusId, read: true);
3555 ChangeCacheStyleRead(true, idx);
3559 foreach (TabPage tb in ListTab.TabPages)
3561 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3563 if (SettingManager.Common.TabIconDisp)
3565 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3569 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3572 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3574 using (ControlTransaction.Update(this._curList))
3576 foreach (int idx in _curList.SelectedIndices)
3578 var post = this._statuses.Tabs[this._curTab.Text][idx];
3579 this._statuses.SetReadAllTab(post.StatusId, read: false);
3580 ChangeCacheStyleRead(false, idx);
3584 foreach (TabPage tb in ListTab.TabPages)
3586 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3588 if (SettingManager.Common.TabIconDisp)
3590 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3594 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3597 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3599 await this.DoRefresh();
3602 private async Task DoRefresh()
3604 if (_curTab != null)
3606 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3611 case MentionsTabModel replyTab:
3612 await this.GetReplyAsync();
3614 case DirectMessagesTabModel dmTab:
3615 await this.GetDirectMessagesAsync();
3617 case FavoritesTabModel favTab:
3618 await this.GetFavoritesAsync();
3620 case PublicSearchTabModel searchTab:
3621 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3622 await this.GetPublicSearchAsync(searchTab);
3624 case UserTimelineTabModel userTab:
3625 await this.GetUserTimelineAsync(userTab);
3627 case ListTimelineTabModel listTab:
3628 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3629 await this.GetListTimelineAsync(listTab);
3632 await this.GetHomeTimelineAsync();
3638 await this.GetHomeTimelineAsync();
3642 private async Task DoRefreshMore()
3645 if (_curTab != null)
3647 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out var tab))
3652 case MentionsTabModel replyTab:
3653 await this.GetReplyAsync(loadMore: true);
3655 case DirectMessagesTabModel dmTab:
3656 await this.GetDirectMessagesAsync(loadMore: true);
3658 case FavoritesTabModel favTab:
3659 await this.GetFavoritesAsync(loadMore: true);
3661 case PublicSearchTabModel searchTab:
3662 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3663 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3665 case UserTimelineTabModel userTab:
3666 await this.GetUserTimelineAsync(userTab, loadMore: true);
3668 case ListTimelineTabModel listTab:
3669 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3670 await this.GetListTimelineAsync(listTab, loadMore: true);
3673 await this.GetHomeTimelineAsync(loadMore: true);
3679 await this.GetHomeTimelineAsync(loadMore: true);
3683 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3685 DialogResult result = DialogResult.Abort;
3687 using (var settingDialog = new AppendSettingDialog())
3689 settingDialog.Icon = this.MainIcon;
3690 settingDialog.Owner = this;
3691 settingDialog.ShowInTaskbar = showTaskbarIcon;
3692 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3694 settingDialog.tw = this.tw;
3695 settingDialog.twitterApi = this.twitterApi;
3697 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3701 result = settingDialog.ShowDialog(this);
3705 return DialogResult.Abort;
3708 if (result == DialogResult.OK)
3712 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3720 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3723 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3725 var oldIconSz = SettingManager.Common.IconSize;
3727 if (ShowSettingDialog() == DialogResult.OK)
3731 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3732 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3733 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3734 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3735 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3736 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3738 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3739 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3740 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3741 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3742 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3743 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3745 ImageSelector.Reset(tw, this.tw.Configuration);
3749 if (SettingManager.Common.TabIconDisp)
3751 ListTab.DrawItem -= ListTab_DrawItem;
3752 ListTab.DrawMode = TabDrawMode.Normal;
3753 ListTab.ImageList = this.TabImage;
3757 ListTab.DrawItem -= ListTab_DrawItem;
3758 ListTab.DrawItem += ListTab_DrawItem;
3759 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3760 ListTab.ImageList = null;
3763 catch (Exception ex)
3765 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3766 ex.Data["IsTerminatePermission"] = false;
3772 if (!SettingManager.Common.UnreadManage)
3774 ReadedStripMenuItem.Enabled = false;
3775 UnreadStripMenuItem.Enabled = false;
3776 if (SettingManager.Common.TabIconDisp)
3778 foreach (TabPage myTab in ListTab.TabPages)
3780 myTab.ImageIndex = -1;
3786 ReadedStripMenuItem.Enabled = true;
3787 UnreadStripMenuItem.Enabled = true;
3790 catch (Exception ex)
3792 ex.Data["Instance"] = "ListTab(UnreadManage)";
3793 ex.Data["IsTerminatePermission"] = false;
3800 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3802 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3803 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3804 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3806 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3807 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3808 _fntUnread = SettingManager.Local.FontUnread;
3809 _clUnread = SettingManager.Local.ColorUnread;
3810 _fntReaded = SettingManager.Local.FontRead;
3811 _clReaded = SettingManager.Local.ColorRead;
3812 _clFav = SettingManager.Local.ColorFav;
3813 _clOWL = SettingManager.Local.ColorOWL;
3814 _clRetweet = SettingManager.Local.ColorRetweet;
3815 _fntDetail = SettingManager.Local.FontDetail;
3816 _clDetail = SettingManager.Local.ColorDetail;
3817 _clDetailLink = SettingManager.Local.ColorDetailLink;
3818 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3819 _clSelf = SettingManager.Local.ColorSelf;
3820 _clAtSelf = SettingManager.Local.ColorAtSelf;
3821 _clTarget = SettingManager.Local.ColorTarget;
3822 _clAtTarget = SettingManager.Local.ColorAtTarget;
3823 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3824 _clAtTo = SettingManager.Local.ColorAtTo;
3825 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3826 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3827 _clInputFont = SettingManager.Local.ColorInputFont;
3828 _fntInputFont = SettingManager.Local.FontInputFont;
3829 _brsBackColorMine.Dispose();
3830 _brsBackColorAt.Dispose();
3831 _brsBackColorYou.Dispose();
3832 _brsBackColorAtYou.Dispose();
3833 _brsBackColorAtFromTarget.Dispose();
3834 _brsBackColorAtTo.Dispose();
3835 _brsBackColorNone.Dispose();
3836 _brsBackColorMine = new SolidBrush(_clSelf);
3837 _brsBackColorAt = new SolidBrush(_clAtSelf);
3838 _brsBackColorYou = new SolidBrush(_clTarget);
3839 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3840 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3841 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3842 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3846 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3847 StatusText.Font = _fntInputFont;
3848 StatusText.ForeColor = _clInputFont;
3850 catch (Exception ex)
3852 MessageBox.Show(ex.Message);
3857 InitDetailHtmlFormat();
3859 catch (Exception ex)
3861 ex.Data["Instance"] = "Font";
3862 ex.Data["IsTerminatePermission"] = false;
3868 foreach (TabPage tb in ListTab.TabPages)
3870 if (SettingManager.Common.TabIconDisp)
3872 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3879 catch (Exception ex)
3881 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3882 ex.Data["IsTerminatePermission"] = false;
3888 var oldIconCol = _iconCol;
3890 if (SettingManager.Common.IconSize != oldIconSz)
3891 ApplyListViewIconSize(SettingManager.Common.IconSize);
3893 foreach (TabPage tp in ListTab.TabPages)
3895 DetailsListView lst = (DetailsListView)tp.Tag;
3897 using (ControlTransaction.Update(lst))
3899 lst.GridLines = SettingManager.Common.ShowGrid;
3900 lst.Font = _fntReaded;
3901 lst.BackColor = _clListBackcolor;
3903 if (_iconCol != oldIconCol)
3908 catch (Exception ex)
3910 ex.Data["Instance"] = "ListView(IconSize)";
3911 ex.Data["IsTerminatePermission"] = false;
3915 SetMainWindowTitle();
3916 SetNotifyIconText();
3918 this.PurgeListViewItemCache();
3919 _curList?.Refresh();
3922 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3923 if (SettingManager.Common.HotkeyEnabled)
3925 ///グローバルホットキーの登録。設定で変更可能にするかも
3926 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3927 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3928 modKey |= HookGlobalHotkey.ModKeys.Alt;
3929 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3930 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3931 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3932 modKey |= HookGlobalHotkey.ModKeys.Shift;
3933 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3934 modKey |= HookGlobalHotkey.ModKeys.Win;
3936 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3939 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3942 StatusText_TextChanged(null, null);
3951 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3952 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3955 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3957 this.TopMost = SettingManager.Common.AlwaysTop;
3958 SaveConfigsAll(false);
3960 if (tw.Username != oldUser.Username)
3961 await this.doGetFollowersMenu();
3967 private void SetTabAlignment()
3969 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3970 if (ListTab.Alignment == newAlignment) return;
3972 // 各タブのリスト上の選択位置などを退避
3973 var listSelections = this.SaveListViewSelection();
3975 ListTab.Alignment = newAlignment;
3977 foreach (TabPage tab in ListTab.TabPages)
3979 DetailsListView lst = (DetailsListView)tab.Tag;
3980 TabModel tabInfo = _statuses.Tabs[tab.Text];
3981 using (ControlTransaction.Update(lst))
3984 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
3989 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
3995 case MyCommon.IconSizes.IconNone:
3998 case MyCommon.IconSizes.Icon16:
4001 case MyCommon.IconSizes.Icon24:
4004 case MyCommon.IconSizes.Icon48:
4007 case MyCommon.IconSizes.Icon48_2:
4015 // ディスプレイの DPI 設定を考慮したサイズを設定する
4016 _listViewImageList.ImageSize = new Size(
4018 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4022 _listViewImageList.ImageSize = new Size(1, 1);
4026 private void ResetColumns(DetailsListView list)
4028 using (ControlTransaction.Update(list))
4029 using (ControlTransaction.Layout(list, false))
4032 list.ColumnClick -= MyList_ColumnClick;
4033 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4034 list.ColumnReordered -= MyList_ColumnReordered;
4035 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4037 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4038 list.Columns.Clear();
4039 cols.ForEach(col => col.Dispose());
4042 InitColumns(list, true);
4044 list.ColumnClick += MyList_ColumnClick;
4045 list.DrawColumnHeader += MyList_DrawColumnHeader;
4046 list.ColumnReordered += MyList_ColumnReordered;
4047 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4051 public void AddNewTabForSearch(string searchWord)
4053 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4054 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4056 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4058 foreach (TabPage tp in ListTab.TabPages)
4060 if (tb.TabName == tp.Text)
4062 ListTab.SelectedTab = tp;
4069 string tabName = searchWord;
4070 for (int i = 0; i <= 100; i++)
4072 if (_statuses.ContainsTab(tabName))
4078 var tab = new PublicSearchTabModel(tabName);
4079 _statuses.AddTab(tab);
4080 AddNewTab(tab, startup: false);
4082 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4084 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4085 cmb.Items.Add(searchWord);
4086 cmb.Text = searchWord;
4089 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4092 private void ShowUserTimeline()
4094 if (!this.ExistCurrentPost) return;
4095 AddNewTabForUserTimeline(_curPost.ScreenName);
4098 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4100 if (e.KeyCode == Keys.Escape)
4102 TabPage relTp = ListTab.SelectedTab;
4103 RemoveSpecifiedTab(relTp.Text, false);
4105 e.SuppressKeyPress = true;
4109 public void AddNewTabForUserTimeline(string user)
4111 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4112 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4114 if (tb.ScreenName == user)
4116 foreach (TabPage tp in ListTab.TabPages)
4118 if (tb.TabName == tp.Text)
4120 ListTab.SelectedTab = tp;
4127 string tabName = "user:" + user;
4128 while (_statuses.ContainsTab(tabName))
4133 var tab = new UserTimelineTabModel(tabName, user);
4134 this._statuses.AddTab(tab);
4135 this.AddNewTab(tab, startup: false);
4137 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4140 this.GetUserTimelineAsync(tab);
4143 public bool AddNewTab(TabModel tab, bool startup)
4146 foreach (TabPage tb in ListTab.TabPages)
4148 if (tb.Text == tab.TabName) return false;
4152 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4154 var _tabPage = new TabPage();
4155 var _listCustom = new DetailsListView();
4157 int cnt = ListTab.TabPages.Count;
4159 ///ToDo:Create and set controls follow tabtypes
4161 using (ControlTransaction.Update(_listCustom))
4162 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4163 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4164 using (ControlTransaction.Layout(this.SplitContainer1, false))
4165 using (ControlTransaction.Layout(this.ListTab, false))
4166 using (ControlTransaction.Layout(this))
4167 using (ControlTransaction.Layout(_tabPage, false))
4169 _tabPage.Controls.Add(_listCustom);
4172 var userTab = tab as UserTimelineTabModel;
4173 var listTab = tab as ListTimelineTabModel;
4174 var searchTab = tab as PublicSearchTabModel;
4176 if (userTab != null || listTab != null)
4178 var label = new Label();
4179 label.Dock = DockStyle.Top;
4180 label.Name = "labelUser";
4183 if (listTab != null)
4185 label.Text = listTab.ListInfo.ToString();
4187 else if (userTab != null)
4189 label.Text = userTab.ScreenName + "'s Timeline";
4191 label.TextAlign = ContentAlignment.MiddleLeft;
4192 using (ComboBox tmpComboBox = new ComboBox())
4194 label.Height = tmpComboBox.Height;
4196 _tabPage.Controls.Add(label);
4199 else if (searchTab != null)
4201 var pnl = new Panel();
4203 var lbl = new Label();
4204 var cmb = new ComboBox();
4205 var btn = new Button();
4206 var cmbLang = new ComboBox();
4208 using (ControlTransaction.Layout(pnl, false))
4210 pnl.Controls.Add(cmb);
4211 pnl.Controls.Add(cmbLang);
4212 pnl.Controls.Add(btn);
4213 pnl.Controls.Add(lbl);
4214 pnl.Name = "panelSearch";
4216 pnl.Dock = DockStyle.Top;
4217 pnl.Height = cmb.Height;
4218 pnl.Enter += SearchControls_Enter;
4219 pnl.Leave += SearchControls_Leave;
4222 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4223 cmb.Dock = DockStyle.Fill;
4224 cmb.Name = "comboSearch";
4225 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4226 cmb.ImeMode = ImeMode.NoControl;
4227 cmb.TabStop = false;
4229 cmb.AutoCompleteMode = AutoCompleteMode.None;
4230 cmb.KeyDown += SearchComboBox_KeyDown;
4233 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4234 cmbLang.Dock = DockStyle.Right;
4236 cmbLang.Name = "comboLang";
4237 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4238 cmbLang.TabStop = false;
4239 cmbLang.TabIndex = 2;
4240 cmbLang.Items.Add("");
4241 cmbLang.Items.Add("ja");
4242 cmbLang.Items.Add("en");
4243 cmbLang.Items.Add("ar");
4244 cmbLang.Items.Add("da");
4245 cmbLang.Items.Add("nl");
4246 cmbLang.Items.Add("fa");
4247 cmbLang.Items.Add("fi");
4248 cmbLang.Items.Add("fr");
4249 cmbLang.Items.Add("de");
4250 cmbLang.Items.Add("hu");
4251 cmbLang.Items.Add("is");
4252 cmbLang.Items.Add("it");
4253 cmbLang.Items.Add("no");
4254 cmbLang.Items.Add("pl");
4255 cmbLang.Items.Add("pt");
4256 cmbLang.Items.Add("ru");
4257 cmbLang.Items.Add("es");
4258 cmbLang.Items.Add("sv");
4259 cmbLang.Items.Add("th");
4261 lbl.Text = "Search(C-S-f)";
4262 lbl.Name = "label1";
4263 lbl.Dock = DockStyle.Left;
4265 lbl.Height = cmb.Height;
4266 lbl.TextAlign = ContentAlignment.MiddleLeft;
4269 btn.Text = "Search";
4270 btn.Name = "buttonSearch";
4271 btn.UseVisualStyleBackColor = true;
4272 btn.Dock = DockStyle.Right;
4273 btn.TabStop = false;
4275 btn.Click += SearchButton_Click;
4277 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4279 cmb.Items.Add(searchTab.SearchWords);
4280 cmb.Text = searchTab.SearchWords;
4283 cmbLang.Text = searchTab.SearchLang;
4285 _tabPage.Controls.Add(pnl);
4289 _tabPage.Tag = _listCustom;
4290 this.ListTab.Controls.Add(_tabPage);
4292 _tabPage.Location = new Point(4, 4);
4293 _tabPage.Name = "CTab" + cnt;
4294 _tabPage.Size = new Size(380, 260);
4295 _tabPage.TabIndex = 2 + cnt;
4296 _tabPage.Text = tab.TabName;
4297 _tabPage.UseVisualStyleBackColor = true;
4298 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4300 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4301 _listCustom.TabIndex = 1;
4302 _listCustom.AllowColumnReorder = true;
4303 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4304 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4305 _listCustom.Dock = DockStyle.Fill;
4306 _listCustom.FullRowSelect = true;
4307 _listCustom.HideSelection = false;
4308 _listCustom.Location = new Point(0, 0);
4309 _listCustom.Margin = new Padding(0);
4310 _listCustom.Name = "CList" + Environment.TickCount;
4311 _listCustom.ShowItemToolTips = true;
4312 _listCustom.Size = new Size(380, 260);
4313 _listCustom.UseCompatibleStateImageBehavior = false;
4314 _listCustom.View = View.Details;
4315 _listCustom.OwnerDraw = true;
4316 _listCustom.VirtualMode = true;
4317 _listCustom.Font = _fntReaded;
4318 _listCustom.BackColor = _clListBackcolor;
4320 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4321 _listCustom.AllowDrop = true;
4323 _listCustom.SmallImageList = _listViewImageList;
4325 InitColumns(_listCustom, startup);
4327 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4328 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4329 _listCustom.ColumnClick += MyList_ColumnClick;
4330 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4331 _listCustom.DragDrop += TweenMain_DragDrop;
4332 _listCustom.DragEnter += TweenMain_DragEnter;
4333 _listCustom.DragOver += TweenMain_DragOver;
4334 _listCustom.DrawItem += MyList_DrawItem;
4335 _listCustom.MouseClick += MyList_MouseClick;
4336 _listCustom.ColumnReordered += MyList_ColumnReordered;
4337 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4338 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4339 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4340 _listCustom.DrawSubItem += MyList_DrawSubItem;
4341 _listCustom.HScrolled += MyList_HScrolled;
4347 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4349 var tabInfo = _statuses.GetTabByName(TabName);
4350 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4354 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4355 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4356 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4362 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4363 if (_tabPage == null) return false;
4365 SetListProperty(); //他のタブに列幅等を反映
4368 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4369 _tabPage.Tag = null;
4371 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4372 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4373 using (ControlTransaction.Layout(this.SplitContainer1, false))
4374 using (ControlTransaction.Layout(this.ListTab, false))
4375 using (ControlTransaction.Layout(this))
4376 using (ControlTransaction.Layout(_tabPage, false))
4378 if (this.ListTab.SelectedTab == _tabPage)
4380 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4381 this._beforeSelectedTab = null;
4383 this.ListTab.Controls.Remove(_tabPage);
4386 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4388 using (Control label = _tabPage.Controls["labelUser"])
4390 _tabPage.Controls.Remove(label);
4393 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4395 using (Control pnl = _tabPage.Controls["panelSearch"])
4397 pnl.Enter -= SearchControls_Enter;
4398 pnl.Leave -= SearchControls_Leave;
4399 _tabPage.Controls.Remove(pnl);
4401 foreach (Control ctrl in pnl.Controls)
4403 if (ctrl.Name == "buttonSearch")
4405 ctrl.Click -= SearchButton_Click;
4407 else if (ctrl.Name == "comboSearch")
4409 ctrl.KeyDown -= SearchComboBox_KeyDown;
4411 pnl.Controls.Remove(ctrl);
4417 _tabPage.Controls.Remove(_listCustom);
4419 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4420 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4421 _listCustom.ColumnClick -= MyList_ColumnClick;
4422 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4423 _listCustom.DragDrop -= TweenMain_DragDrop;
4424 _listCustom.DragEnter -= TweenMain_DragEnter;
4425 _listCustom.DragOver -= TweenMain_DragOver;
4426 _listCustom.DrawItem -= MyList_DrawItem;
4427 _listCustom.MouseClick -= MyList_MouseClick;
4428 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4429 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4430 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4431 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4432 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4433 _listCustom.HScrolled -= MyList_HScrolled;
4435 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4436 _listCustom.Columns.Clear();
4437 cols.ForEach(col => col.Dispose());
4440 _listCustom.ContextMenuStrip = null;
4441 _listCustom.ColumnHeaderContextMenuStrip = null;
4442 _listCustom.Font = null;
4444 _listCustom.SmallImageList = null;
4445 _listCustom.ListViewItemSorter = null;
4448 if (_curTab.Equals(_tabPage))
4455 this.PurgeListViewItemCache();
4459 _listCustom.Dispose();
4460 _statuses.RemoveTab(TabName);
4462 foreach (TabPage tp in ListTab.TabPages)
4464 DetailsListView lst = (DetailsListView)tp.Tag;
4465 var count = _statuses.Tabs[tp.Text].AllCount;
4466 lst.VirtualListSize = count;
4472 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4474 this.PurgeListViewItemCache();
4475 _beforeSelectedTab = e.TabPage;
4478 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4482 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4485 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4486 if (!dragEnableRectangle.Contains(e.Location))
4488 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4489 tn = ListTab.SelectedTab.Text;
4492 if (string.IsNullOrEmpty(tn)) return;
4494 foreach (TabPage tb in ListTab.TabPages)
4498 ListTab.DoDragDrop(tb, DragDropEffects.All);
4508 Point cpos = new Point(e.X, e.Y);
4509 for (int i = 0; i < ListTab.TabPages.Count; i++)
4511 Rectangle rect = ListTab.GetTabRect(i);
4512 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4513 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4515 _rclickTabName = ListTab.TabPages[i].Text;
4521 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4523 //_curList.Refresh();
4524 SetMainWindowTitle();
4525 SetStatusLabelUrl();
4526 SetApiStatusLabel();
4527 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4528 TabMenuControl(ListTab.SelectedTab.Text);
4529 this.PushSelectPostChain();
4530 await DispSelectedPost();
4533 private void SetListProperty()
4535 //削除などで見つからない場合は処理せず
4536 if (_curList == null) return;
4537 if (!_isColumnChanged) return;
4539 int[] dispOrder = new int[_curList.Columns.Count];
4540 for (int i = 0; i < _curList.Columns.Count; i++)
4542 for (int j = 0; j < _curList.Columns.Count; j++)
4544 if (_curList.Columns[j].DisplayIndex == i)
4553 foreach (TabPage tb in ListTab.TabPages)
4555 if (!tb.Equals(_curTab))
4557 if (tb.Tag != null && tb.Controls.Count > 0)
4559 DetailsListView lst = (DetailsListView)tb.Tag;
4560 for (int i = 0; i < lst.Columns.Count; i++)
4562 lst.Columns[dispOrder[i]].DisplayIndex = i;
4563 lst.Columns[i].Width = _curList.Columns[i].Width;
4569 _isColumnChanged = false;
4572 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4574 if (e.KeyChar == '@')
4576 if (!SettingManager.Common.UseAtIdSupplement) return;
4578 int cnt = AtIdSupl.ItemCount;
4579 ShowSuplDialog(StatusText, AtIdSupl);
4580 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4583 else if (e.KeyChar == '#')
4585 if (!SettingManager.Common.UseHashSupplement) return;
4586 ShowSuplDialog(StatusText, HashSupl);
4591 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4593 ShowSuplDialog(owner, dialog, 0, "");
4596 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4598 ShowSuplDialog(owner, dialog, offset, "");
4601 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4603 dialog.StartsWith = startswith;
4610 dialog.ShowDialog();
4612 this.TopMost = SettingManager.Common.AlwaysTop;
4613 int selStart = owner.SelectionStart;
4616 if (dialog.DialogResult == DialogResult.OK)
4618 if (!string.IsNullOrEmpty(dialog.inputText))
4622 fHalf = owner.Text.Substring(0, selStart - offset);
4624 if (selStart < owner.Text.Length)
4626 eHalf = owner.Text.Substring(selStart);
4628 owner.Text = fHalf + dialog.inputText + eHalf;
4629 owner.SelectionStart = selStart + dialog.inputText.Length;
4636 fHalf = owner.Text.Substring(0, selStart);
4638 if (selStart < owner.Text.Length)
4640 eHalf = owner.Text.Substring(selStart);
4642 owner.Text = fHalf + eHalf;
4645 owner.SelectionStart = selStart;
4651 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4654 if (!e.Alt && !e.Control && !e.Shift)
4656 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4658 bool isSpace = false;
4659 foreach (char c in StatusText.Text)
4661 if (c == ' ' || c == ' ')
4674 StatusText.Text = "";
4675 JumpUnreadMenuItem_Click(null, null);
4679 this.StatusText_TextChanged(null, null);
4682 private void StatusText_TextChanged(object sender, EventArgs e)
4685 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4686 lblLen.Text = pLen.ToString();
4689 StatusText.ForeColor = Color.Red;
4693 StatusText.ForeColor = _clInputFont;
4696 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4698 if (string.IsNullOrEmpty(StatusText.Text))
4700 this.inReplyTo = null;
4705 /// ツイート投稿前のフッター付与などの前処理を行います
4707 private string FormatStatusText(string statusText)
4709 statusText = statusText.Replace("\r\n", "\n");
4711 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4714 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4717 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4719 // 文中の全角スペースを半角スペース1個にする
4720 statusText = statusText.Replace(" ", " ");
4723 // DM の場合はこれ以降の処理を行わない
4724 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4728 if (SettingManager.Common.PostShiftEnter)
4730 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4734 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4735 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4737 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4740 if (statusText.Contains("RT @"))
4741 disableFooter = true;
4746 var hashtag = this.HashMgr.UseHash;
4747 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4750 header = HashMgr.UseHash + " ";
4752 footer = " " + HashMgr.UseHash;
4757 if (SettingManager.Local.UseRecommendStatus)
4760 footer += this.recommendedStatusFooter;
4762 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4764 // テキストボックスに入力されている文字列を使用する
4765 footer += " " + SettingManager.Local.StatusText.Trim();
4769 statusText = header + statusText + footer;
4771 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4773 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4774 // 参照: https://support.twitter.com/articles/14020
4776 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4777 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4779 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4780 statusText = '\u200b' + statusText;
4788 /// 投稿欄に表示する入力可能な文字数を計算します
4790 private int GetRestStatusCount(string statusText)
4793 var remainCount = this.tw.GetTextLengthRemain(statusText);
4795 var uploadService = this.ImageSelector.SelectedService;
4796 if (this.ImageSelector.Visible && uploadService != null)
4798 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4799 remainCount -= uploadService.GetReservedTextLength(1);
4805 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4807 if (sender != this._curList)
4810 var listCache = this._listItemCache;
4811 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4813 // If the newly requested cache is a subset of the old cache,
4814 // no need to rebuild everything, so do nothing.
4818 // Now we need to rebuild the cache.
4819 this.CreateCache(e.StartIndex, e.EndIndex);
4822 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4824 var listCache = this._listItemCache;
4825 if (listCache?.TargetList == sender)
4827 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4834 // A cache miss, so create a new ListViewItem and pass it back.
4835 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4838 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4842 // 不正な要求に対する間に合わせの応答
4843 string[] sitem = {"", "", "", "", "", "", "", ""};
4844 e.Item = new ImageListViewItem(sitem);
4848 private void CreateCache(int startIndex, int endIndex)
4850 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4852 if (tabInfo.AllCount == 0)
4855 // キャッシュ要求(要求範囲±30を作成)
4856 startIndex = Math.Max(startIndex - 30, 0);
4857 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4859 var cacheLength = endIndex - startIndex + 1;
4861 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4862 var listItems = Enumerable.Range(0, cacheLength)
4863 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4866 var listCache = new ListViewItemCache
4868 TargetList = this._curList,
4869 StartIndex = startIndex,
4870 EndIndex = endIndex,
4872 ListItem = listItems,
4875 Interlocked.Exchange(ref this._listItemCache, listCache);
4879 /// DetailsListView のための ListViewItem のキャッシュを消去する
4881 private void PurgeListViewItemCache()
4883 Interlocked.Exchange(ref this._listItemCache, null);
4886 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4888 StringBuilder mk = new StringBuilder();
4889 //if (Post.IsDeleted) mk.Append("×");
4890 //if (Post.IsMark) mk.Append("♪");
4891 //if (Post.IsProtect) mk.Append("Ю");
4892 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4893 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4894 ImageListViewItem itm;
4895 if (Post.RetweetedId == null)
4897 string[] sitem= {"",
4899 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4900 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4905 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4909 string[] sitem = {"",
4911 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4912 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4913 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4917 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4919 itm.StateIndex = Post.StateIndex;
4922 bool read = Post.IsRead;
4923 //未読管理していなかったら既読として扱う
4924 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4925 ChangeItemStyleRead(read, itm, Post, null);
4926 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4931 /// 全てのタブの振り分けルールを反映し直します
4933 private void ApplyPostFilters()
4935 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4937 this.PurgeListViewItemCache();
4938 this._curPost = null;
4939 this._curItemIndex = -1;
4940 this._statuses.FilterAll();
4942 foreach (TabPage tabPage in this.ListTab.TabPages)
4944 var tab = this._statuses.Tabs[tabPage.Text];
4946 var listview = (DetailsListView)tabPage.Tag;
4947 using (ControlTransaction.Update(listview))
4949 listview.VirtualListSize = tab.AllCount;
4952 if (SettingManager.Common.TabIconDisp)
4954 if (tab.UnreadCount > 0)
4955 tabPage.ImageIndex = 0;
4957 tabPage.ImageIndex = -1;
4961 if (!SettingManager.Common.TabIconDisp)
4962 this.ListTab.Refresh();
4964 SetMainWindowTitle();
4965 SetStatusLabelUrl();
4969 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4971 e.DrawDefault = true;
4974 private void MyList_HScrolled(object sender, EventArgs e)
4976 DetailsListView listView = (DetailsListView)sender;
4980 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
4982 if (e.State == 0) return;
4983 e.DrawDefault = false;
4985 SolidBrush brs2 = null;
4986 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
4988 if (e.Item.BackColor == _clSelf)
4989 brs2 = _brsBackColorMine;
4990 else if (e.Item.BackColor == _clAtSelf)
4991 brs2 = _brsBackColorAt;
4992 else if (e.Item.BackColor == _clTarget)
4993 brs2 = _brsBackColorYou;
4994 else if (e.Item.BackColor == _clAtTarget)
4995 brs2 = _brsBackColorAtYou;
4996 else if (e.Item.BackColor == _clAtFromTarget)
4997 brs2 = _brsBackColorAtFromTarget;
4998 else if (e.Item.BackColor == _clAtTo)
4999 brs2 = _brsBackColorAtTo;
5001 brs2 = _brsBackColorNone;
5006 if (((Control)sender).Focused)
5007 brs2 = _brsHighLight;
5009 brs2 = _brsDeactiveSelection;
5011 e.Graphics.FillRectangle(brs2, e.Bounds);
5012 e.DrawFocusRectangle();
5013 this.DrawListViewItemIcon(e);
5016 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5018 if (e.ItemState == 0) return;
5020 if (e.ColumnIndex > 0)
5023 var post = (PostClass)e.Item.Tag;
5025 RectangleF rct = e.Bounds;
5026 rct.Width = e.Header.Width;
5027 int fontHeight = e.Item.Font.Height;
5030 rct.Y += fontHeight;
5031 rct.Height -= fontHeight;
5034 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5036 //if (heightDiff > fontHeight * 0.7)
5038 // rct.Height += fontHeight;
5039 // drawLineCount += 1;
5042 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5043 if (!_iconCol && drawLineCount <= 1)
5045 //rct.Inflate(0, heightDiff / -2);
5046 //rct.Height += fontHeight / 2;
5048 else if (heightDiff < fontHeight * 0.7)
5050 //最終行が70%以上欠けていたら、最終行は表示しない
5051 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5052 rct.Height = (fontHeight * drawLineCount) - 1;
5059 //if (!_iconCol && drawLineCount > 1)
5061 // rct.Y += fontHeight * 0.2;
5062 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5067 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5068 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5073 Rectangle rctB = e.Bounds;
5074 rctB.Width = e.Header.Width;
5075 rctB.Height = fontHeight;
5077 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5079 TextRenderer.DrawText(e.Graphics,
5080 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5082 Rectangle.Round(rct),
5084 TextFormatFlags.WordBreak |
5085 TextFormatFlags.EndEllipsis |
5086 TextFormatFlags.GlyphOverhangPadding |
5087 TextFormatFlags.NoPrefix);
5088 TextRenderer.DrawText(e.Graphics,
5089 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 + "]",
5093 TextFormatFlags.SingleLine |
5094 TextFormatFlags.EndEllipsis |
5095 TextFormatFlags.GlyphOverhangPadding |
5096 TextFormatFlags.NoPrefix);
5102 if (e.ColumnIndex != 2)
5103 text = e.SubItem.Text;
5105 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5107 if (drawLineCount == 1)
5109 TextRenderer.DrawText(e.Graphics,
5112 Rectangle.Round(rct),
5114 TextFormatFlags.SingleLine |
5115 TextFormatFlags.EndEllipsis |
5116 TextFormatFlags.GlyphOverhangPadding |
5117 TextFormatFlags.NoPrefix |
5118 TextFormatFlags.VerticalCenter);
5122 TextRenderer.DrawText(e.Graphics,
5125 Rectangle.Round(rct),
5127 TextFormatFlags.WordBreak |
5128 TextFormatFlags.EndEllipsis |
5129 TextFormatFlags.GlyphOverhangPadding |
5130 TextFormatFlags.NoPrefix);
5133 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5138 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5140 if (_iconSz == 0) return;
5142 ImageListViewItem item = (ImageListViewItem)e.Item;
5144 //e.Bounds.Leftが常に0を指すから自前で計算
5145 Rectangle itemRect = item.Bounds;
5146 var col0 = e.Item.ListView.Columns[0];
5147 itemRect.Width = col0.Width;
5149 if (col0.DisplayIndex > 0)
5151 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5153 if (clm.DisplayIndex < col0.DisplayIndex)
5154 itemRect.X += clm.Width;
5158 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5159 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5160 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5163 var img = item.Image;
5166 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5167 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5169 if (iconRect.Width > 0)
5171 e.Graphics.FillRectangle(Brushes.White, iconRect);
5172 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5175 e.Graphics.DrawImage(img.Image, iconRect);
5177 catch (ArgumentException)
5179 item.RefreshImageAsync();
5185 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5186 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5188 item.GetImageAsync();
5191 if (item.StateIndex > -1)
5193 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5194 if (stateRect.Width > 0)
5196 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5197 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5198 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5203 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5205 base.ScaleControl(factor, specified);
5207 ScaleChildControl(this.TabImage, factor);
5209 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5210 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5212 foreach (var listview in listviews)
5214 ScaleChildControl(listview, factor);
5218 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5220 // ImageListViewItem item = (ImageListViewItem)e.Item;
5221 // if (item.StateImageIndex > -1)
5223 // ////e.Bounds.Leftが常に0を指すから自前で計算
5224 // //Rectangle itemRect = item.Bounds;
5225 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5227 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5229 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5231 // // itemRect.X += clm.Width;
5235 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5236 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5238 // if (rct.Width > 0)
5240 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5241 // //e.Graphics.FillRectangle(Brushes.White, rct);
5242 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5243 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5248 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5250 var tab = this._statuses.Tabs[this._curTab.Text];
5252 if (tab.AllCount == 0)
5254 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5258 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5263 case SEARCHTYPE.NextSearch: // 次を検索
5264 if (selectedIndex != -1)
5265 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5269 case SEARCHTYPE.PrevSearch: // 前を検索
5270 if (selectedIndex != -1)
5271 startIndex = Math.Max(selectedIndex - 1, 0);
5273 startIndex = tab.AllCount - 1;
5275 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5277 if (selectedIndex != -1)
5278 startIndex = selectedIndex;
5284 Func<string, bool> stringComparer;
5287 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5289 catch (ArgumentException)
5291 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5295 var reverse = searchType == SEARCHTYPE.PrevSearch;
5296 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5297 .DefaultIfEmpty(-1).First();
5299 if (foundIndex == -1)
5301 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5305 this.SelectListItem(this._curList, foundIndex);
5306 this._curList.EnsureVisible(foundIndex);
5309 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5312 this.ShowSearchDialog();
5315 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5317 var previousSearch = this.SearchDialog.ResultOptions;
5318 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5320 this.SearchDialog.Reset();
5321 this.ShowSearchDialog();
5327 previousSearch.Query,
5328 previousSearch.CaseSensitive,
5329 previousSearch.UseRegex,
5330 SEARCHTYPE.NextSearch);
5333 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5335 var previousSearch = this.SearchDialog.ResultOptions;
5336 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5338 this.SearchDialog.Reset();
5339 this.ShowSearchDialog();
5345 previousSearch.Query,
5346 previousSearch.CaseSensitive,
5347 previousSearch.UseRegex,
5348 SEARCHTYPE.PrevSearch);
5352 /// 検索ダイアログを表示し、検索を実行します
5354 private void ShowSearchDialog()
5356 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5358 this.TopMost = SettingManager.Common.AlwaysTop;
5361 this.TopMost = SettingManager.Common.AlwaysTop;
5363 var searchOptions = this.SearchDialog.ResultOptions;
5364 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5366 if (searchOptions.NewTab)
5368 var tabName = Properties.Resources.SearchResults_TabName;
5372 tabName = this._statuses.MakeTabName(tabName);
5374 catch (TabException ex)
5376 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5379 var resultTab = new LocalSearchTabModel(tabName);
5380 this.AddNewTab(resultTab, startup: false);
5381 this._statuses.AddTab(resultTab);
5383 var targetTab = this._statuses.Tabs[this._curTab.Text];
5385 Func<string, bool> stringComparer;
5388 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5390 catch (ArgumentException)
5392 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5396 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5397 if (foundIndices.Length == 0)
5399 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5403 var foundPosts = foundIndices.Select(x => targetTab[x]);
5404 foreach (var post in foundPosts)
5406 resultTab.AddPostQueue(post);
5409 this._statuses.DistributePosts();
5410 this.RefreshTimeline();
5412 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5413 .First(x => x.Text == tabName);
5415 this.ListTab.SelectedTab = tabPage;
5420 searchOptions.Query,
5421 searchOptions.CaseSensitive,
5422 searchOptions.UseRegex,
5423 SEARCHTYPE.DialogSearch);
5426 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5428 this.AddNewTabForSearch(searchOptions.Query);
5432 /// <summary>発言検索に使用するメソッドを生成します</summary>
5433 /// <exception cref="ArgumentException">
5434 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5436 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5440 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5441 var regex = new Regex(query, regexOption);
5443 return x => regex.IsMatch(x);
5447 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5449 return x => x.IndexOf(query, comparisonType) != -1;
5453 private void AboutMenuItem_Click(object sender, EventArgs e)
5455 using (TweenAboutBox about = new TweenAboutBox())
5457 about.ShowDialog(this);
5459 this.TopMost = SettingManager.Common.AlwaysTop;
5462 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5464 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5466 if (ImageSelector.Enabled)
5469 TabModel foundTab = null;
5472 DetailsListView lst = null;
5475 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5477 var tabPage = this.ListTab.TabPages[i];
5478 var tab = this._statuses.Tabs[tabPage.Text];
5479 var unreadIndex = tab.NextUnreadIndex;
5481 if (unreadIndex != -1)
5483 ListTab.SelectedIndex = i;
5485 foundIndex = unreadIndex;
5486 lst = (DetailsListView)tabPage.Tag;
5491 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5492 if (foundTab == null && bgnIdx > 0)
5494 for (int i = 0; i < bgnIdx; i++)
5496 var tabPage = this.ListTab.TabPages[i];
5497 var tab = this._statuses.Tabs[tabPage.Text];
5498 var unreadIndex = tab.NextUnreadIndex;
5500 if (unreadIndex != -1)
5502 ListTab.SelectedIndex = i;
5504 foundIndex = unreadIndex;
5505 lst = (DetailsListView)tabPage.Tag;
5511 if (foundTab == null)
5513 //全部調べたが未読見つからず→先頭タブの最新発言へ
5514 ListTab.SelectedIndex = 0;
5515 var tabPage = this.ListTab.TabPages[0];
5516 var tab = this._statuses.Tabs[tabPage.Text];
5518 if (tab.AllCount == 0)
5521 if (_statuses.SortOrder == SortOrder.Ascending)
5522 foundIndex = tab.AllCount - 1;
5526 lst = (DetailsListView)tabPage.Tag;
5529 SelectListItem(lst, foundIndex);
5531 if (_statuses.SortMode == ComparerMode.Id)
5533 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5534 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5540 lst.EnsureVisible(foundIndex);
5545 lst.EnsureVisible(foundIndex);
5551 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5553 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5555 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5556 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5560 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5562 if (_curList.SelectedIndices.Count > 0)
5564 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5565 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5569 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5571 await this.CheckNewVersion(false);
5574 private void RunTweenUp()
5576 ProcessStartInfo pinfo = new ProcessStartInfo();
5577 pinfo.UseShellExecute = true;
5578 pinfo.WorkingDirectory = MyCommon.settingPath;
5579 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5580 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5583 Process.Start(pinfo);
5587 MessageBox.Show("Failed to execute TweenUp3.exe.");
5591 public class VersionInfo
5593 public Version Version { get; set; }
5594 public Uri DownloadUri { get; set; }
5595 public string ReleaseNote { get; set; }
5599 /// OpenTween の最新バージョンの情報を取得します
5601 public async Task<VersionInfo> GetVersionInfoAsync()
5603 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5604 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5606 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5607 .ConfigureAwait(false);
5609 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5610 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5612 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5613 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5615 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5617 return new VersionInfo
5619 Version = Version.Parse(msgHeader[0]),
5620 DownloadUri = new Uri(msgHeader[1]),
5621 ReleaseNote = msgBody,
5625 private async Task CheckNewVersion(bool startup = false)
5627 if (ApplicationSettings.VersionInfoUrl == null)
5628 return; // 更新チェック無効化
5632 var versionInfo = await this.GetVersionInfoAsync();
5634 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5639 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5640 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5641 msgtext = MyCommon.ReplaceAppName(msgtext);
5643 MessageBox.Show(msgtext,
5644 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5645 MessageBoxButtons.OK, MessageBoxIcon.Information);
5650 using (var dialog = new UpdateDialog())
5652 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5653 MyCommon.GetReadableVersion(versionInfo.Version));
5654 dialog.DetailsText = versionInfo.ReleaseNote;
5656 if (dialog.ShowDialog(this) == DialogResult.Yes)
5658 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5664 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5667 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5668 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5669 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5674 private async Task Colorize()
5677 await this.DispSelectedPost();
5678 //件数関連の場合、タイトル即時書き換え
5679 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5680 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5681 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5682 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5684 SetMainWindowTitle();
5686 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5687 SetStatusLabelUrl();
5688 foreach (TabPage tb in ListTab.TabPages)
5690 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5692 if (SettingManager.Common.TabIconDisp)
5694 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5698 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5701 public string createDetailHtml(string orgdata)
5703 if (SettingManager.Local.UseTwemoji)
5704 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5706 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5709 private Task DispSelectedPost()
5711 return this.DispSelectedPost(false);
5714 private PostClass displayPost = new PostClass();
5717 /// サムネイル表示に使用する CancellationToken の生成元
5719 private CancellationTokenSource thumbnailTokenSource = null;
5721 private async Task DispSelectedPost(bool forceupdate)
5723 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5726 var oldDisplayPost = this.displayPost;
5727 this.displayPost = this._curPost;
5729 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5732 var loadTasks = new List<Task>
5734 this.tweetDetailsView.ShowPostDetails(this._curPost),
5737 this.SplitContainer3.Panel2Collapsed = true;
5739 if (SettingManager.Common.PreviewEnable)
5741 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5742 oldTokenSource?.Cancel();
5744 var token = this.thumbnailTokenSource.Token;
5745 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5750 await Task.WhenAll(loadTasks);
5752 catch (OperationCanceledException) { }
5755 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5757 await this.OpenApplicationWebsite();
5760 private async Task OpenApplicationWebsite()
5762 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5765 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5767 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5770 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5772 if (ListTab.SelectedTab != null)
5774 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5776 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5777 if (pnl.Controls["comboSearch"].Focused ||
5778 pnl.Controls["comboLang"].Focused ||
5779 pnl.Controls["buttonSearch"].Focused) return;
5782 if (e.Control || e.Shift || e.Alt)
5783 this._anchorFlag = false;
5785 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5788 e.SuppressKeyPress = true;
5791 if (asyncTask != null)
5796 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5798 private void InitializeShortcuts()
5800 this.shortcutCommands = new[]
5802 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5803 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5804 .FocusedOn(FocusedControl.ListTab)
5805 .Do(() => SendKeys.Send("{DOWN}")),
5807 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5808 .FocusedOn(FocusedControl.ListTab)
5809 .Do(() => SendKeys.Send("{UP}")),
5811 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5812 .FocusedOn(FocusedControl.ListTab)
5813 .Do(() => SendKeys.Send("{PGDN}")),
5815 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5816 .FocusedOn(FocusedControl.ListTab)
5817 .Do(() => SendKeys.Send("{PGUP}")),
5819 ShortcutCommand.Create(Keys.F1)
5820 .Do(() => this.OpenApplicationWebsite()),
5822 ShortcutCommand.Create(Keys.F3)
5823 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5825 ShortcutCommand.Create(Keys.F5)
5826 .Do(() => this.DoRefresh()),
5828 ShortcutCommand.Create(Keys.F6)
5829 .Do(() => this.GetReplyAsync()),
5831 ShortcutCommand.Create(Keys.F7)
5832 .Do(() => this.GetDirectMessagesAsync()),
5834 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5835 .NotFocusedOn(FocusedControl.StatusText)
5836 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5838 ShortcutCommand.Create(Keys.G)
5839 .NotFocusedOn(FocusedControl.StatusText)
5840 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5842 ShortcutCommand.Create(Keys.Right, Keys.N)
5843 .FocusedOn(FocusedControl.ListTab)
5844 .Do(() => this.GoRelPost(forward: true)),
5846 ShortcutCommand.Create(Keys.Left, Keys.P)
5847 .FocusedOn(FocusedControl.ListTab)
5848 .Do(() => this.GoRelPost(forward: false)),
5850 ShortcutCommand.Create(Keys.OemPeriod)
5851 .FocusedOn(FocusedControl.ListTab)
5852 .Do(() => this.GoAnchor()),
5854 ShortcutCommand.Create(Keys.I)
5855 .FocusedOn(FocusedControl.ListTab)
5856 .OnlyWhen(() => this.StatusText.Enabled)
5857 .Do(() => this.StatusText.Focus()),
5859 ShortcutCommand.Create(Keys.Enter)
5860 .FocusedOn(FocusedControl.ListTab)
5861 .Do(() => this.MakeReplyOrDirectStatus()),
5863 ShortcutCommand.Create(Keys.R)
5864 .FocusedOn(FocusedControl.ListTab)
5865 .Do(() => this.DoRefresh()),
5867 ShortcutCommand.Create(Keys.L)
5868 .FocusedOn(FocusedControl.ListTab)
5869 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5871 ShortcutCommand.Create(Keys.H)
5872 .FocusedOn(FocusedControl.ListTab)
5873 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5875 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5876 .FocusedOn(FocusedControl.ListTab)
5877 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5879 ShortcutCommand.Create(Keys.S)
5880 .FocusedOn(FocusedControl.ListTab)
5881 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5883 ShortcutCommand.Create(Keys.A)
5884 .FocusedOn(FocusedControl.ListTab)
5885 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5887 // ] in_reply_to参照元へ戻る
5888 ShortcutCommand.Create(Keys.Oem4)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5892 // [ in_reply_toへジャンプ
5893 ShortcutCommand.Create(Keys.Oem6)
5894 .FocusedOn(FocusedControl.ListTab)
5895 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5897 ShortcutCommand.Create(Keys.Escape)
5898 .FocusedOn(FocusedControl.ListTab)
5900 this._anchorFlag = false;
5901 if (ListTab.SelectedTab != null)
5903 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5904 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5906 var relTp = ListTab.SelectedTab;
5907 RemoveSpecifiedTab(relTp.Text, false);
5913 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5914 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5915 .FocusedOn(FocusedControl.ListTab)
5916 .Do(() => this._anchorFlag = false, preventDefault: false),
5918 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5919 ShortcutCommand.Create(Keys.Up, Keys.Down)
5920 .FocusedOn(FocusedControl.PostBrowser)
5923 ShortcutCommand.Create(Keys.Control | Keys.R)
5924 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5926 ShortcutCommand.Create(Keys.Control | Keys.D)
5927 .Do(() => this.doStatusDelete()),
5929 ShortcutCommand.Create(Keys.Control | Keys.M)
5930 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5932 ShortcutCommand.Create(Keys.Control | Keys.S)
5933 .Do(() => this.FavoriteChange(FavAdd: true)),
5935 ShortcutCommand.Create(Keys.Control | Keys.I)
5936 .Do(() => this.doRepliedStatusOpen()),
5938 ShortcutCommand.Create(Keys.Control | Keys.Q)
5939 .Do(() => this.doQuoteOfficial()),
5941 ShortcutCommand.Create(Keys.Control | Keys.B)
5942 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5944 ShortcutCommand.Create(Keys.Control | Keys.T)
5945 .Do(() => this.HashManageMenuItem_Click(null, null)),
5947 ShortcutCommand.Create(Keys.Control | Keys.L)
5948 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5950 ShortcutCommand.Create(Keys.Control | Keys.Y)
5951 .NotFocusedOn(FocusedControl.PostBrowser)
5952 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5954 ShortcutCommand.Create(Keys.Control | Keys.F)
5955 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5957 ShortcutCommand.Create(Keys.Control | Keys.U)
5958 .Do(() => this.ShowUserTimeline()),
5960 ShortcutCommand.Create(Keys.Control | Keys.H)
5961 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5963 ShortcutCommand.Create(Keys.Control | Keys.G)
5964 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5966 ShortcutCommand.Create(Keys.Control | Keys.O)
5967 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5969 ShortcutCommand.Create(Keys.Control | Keys.E)
5970 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5972 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5973 .FocusedOn(FocusedControl.ListTab)
5974 .Do(() => this._colorize = true, preventDefault: false),
5976 ShortcutCommand.Create(Keys.Control | Keys.N)
5977 .FocusedOn(FocusedControl.ListTab)
5978 .Do(() => this.GoNextTab(forward: true)),
5980 ShortcutCommand.Create(Keys.Control | Keys.P)
5981 .FocusedOn(FocusedControl.ListTab)
5982 .Do(() => this.GoNextTab(forward: false)),
5984 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
5985 .FocusedOn(FocusedControl.ListTab)
5986 .Do(() => this.CopyStot()),
5988 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
5989 ShortcutCommand.Create(Keys.Control | Keys.D1)
5990 .FocusedOn(FocusedControl.ListTab)
5991 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
5992 .Do(() => this.ListTab.SelectedIndex = 0),
5994 ShortcutCommand.Create(Keys.Control | Keys.D2)
5995 .FocusedOn(FocusedControl.ListTab)
5996 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
5997 .Do(() => this.ListTab.SelectedIndex = 1),
5999 ShortcutCommand.Create(Keys.Control | Keys.D3)
6000 .FocusedOn(FocusedControl.ListTab)
6001 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6002 .Do(() => this.ListTab.SelectedIndex = 2),
6004 ShortcutCommand.Create(Keys.Control | Keys.D4)
6005 .FocusedOn(FocusedControl.ListTab)
6006 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6007 .Do(() => this.ListTab.SelectedIndex = 3),
6009 ShortcutCommand.Create(Keys.Control | Keys.D5)
6010 .FocusedOn(FocusedControl.ListTab)
6011 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6012 .Do(() => this.ListTab.SelectedIndex = 4),
6014 ShortcutCommand.Create(Keys.Control | Keys.D6)
6015 .FocusedOn(FocusedControl.ListTab)
6016 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6017 .Do(() => this.ListTab.SelectedIndex = 5),
6019 ShortcutCommand.Create(Keys.Control | Keys.D7)
6020 .FocusedOn(FocusedControl.ListTab)
6021 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6022 .Do(() => this.ListTab.SelectedIndex = 6),
6024 ShortcutCommand.Create(Keys.Control | Keys.D8)
6025 .FocusedOn(FocusedControl.ListTab)
6026 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6027 .Do(() => this.ListTab.SelectedIndex = 7),
6029 ShortcutCommand.Create(Keys.Control | Keys.D9)
6030 .FocusedOn(FocusedControl.ListTab)
6031 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6033 ShortcutCommand.Create(Keys.Control | Keys.A)
6034 .FocusedOn(FocusedControl.StatusText)
6035 .Do(() => this.StatusText.SelectAll()),
6037 ShortcutCommand.Create(Keys.Control | Keys.V)
6038 .FocusedOn(FocusedControl.StatusText)
6039 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6041 ShortcutCommand.Create(Keys.Control | Keys.Up)
6042 .FocusedOn(FocusedControl.StatusText)
6044 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6046 var inReplyToStatusId = this.inReplyTo?.Item1;
6047 var inReplyToScreenName = this.inReplyTo?.Item2;
6048 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6051 if (_hisIdx < 0) _hisIdx = 0;
6053 var historyItem = this._history[this._hisIdx];
6054 StatusText.Text = historyItem.status;
6055 StatusText.SelectionStart = StatusText.Text.Length;
6056 if (historyItem.inReplyToId != null)
6057 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6059 this.inReplyTo = null;
6062 ShortcutCommand.Create(Keys.Control | Keys.Down)
6063 .FocusedOn(FocusedControl.StatusText)
6065 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6067 var inReplyToStatusId = this.inReplyTo?.Item1;
6068 var inReplyToScreenName = this.inReplyTo?.Item2;
6069 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6072 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6074 var historyItem = this._history[this._hisIdx];
6075 StatusText.Text = historyItem.status;
6076 StatusText.SelectionStart = StatusText.Text.Length;
6077 if (historyItem.inReplyToId != null)
6078 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6080 this.inReplyTo = null;
6083 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6084 .FocusedOn(FocusedControl.StatusText)
6086 if (ListTab.SelectedIndex == 0)
6088 ListTab.SelectedIndex = ListTab.TabCount - 1;
6092 ListTab.SelectedIndex -= 1;
6097 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6098 .FocusedOn(FocusedControl.StatusText)
6100 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6102 ListTab.SelectedIndex = 0;
6106 ListTab.SelectedIndex += 1;
6111 ShortcutCommand.Create(Keys.Control | Keys.Y)
6112 .FocusedOn(FocusedControl.PostBrowser)
6114 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6115 MultiLineMenuItem_Click(null, null);
6118 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6119 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6121 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6122 .Do(() => this.DoRefreshMore()),
6124 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6125 .Do(() => this.GetReplyAsync(loadMore: true)),
6127 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6128 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6130 ShortcutCommand.Create(Keys.Shift | Keys.R)
6131 .NotFocusedOn(FocusedControl.StatusText)
6132 .Do(() => this.DoRefreshMore()),
6134 ShortcutCommand.Create(Keys.Shift | Keys.H)
6135 .FocusedOn(FocusedControl.ListTab)
6136 .Do(() => this.GoTopEnd(GoTop: true)),
6138 ShortcutCommand.Create(Keys.Shift | Keys.L)
6139 .FocusedOn(FocusedControl.ListTab)
6140 .Do(() => this.GoTopEnd(GoTop: false)),
6142 ShortcutCommand.Create(Keys.Shift | Keys.M)
6143 .FocusedOn(FocusedControl.ListTab)
6144 .Do(() => this.GoMiddle()),
6146 ShortcutCommand.Create(Keys.Shift | Keys.G)
6147 .FocusedOn(FocusedControl.ListTab)
6148 .Do(() => this.GoLast()),
6150 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6151 .FocusedOn(FocusedControl.ListTab)
6152 .Do(() => this.MoveMiddle()),
6154 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6155 .FocusedOn(FocusedControl.ListTab)
6156 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6158 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6159 .FocusedOn(FocusedControl.ListTab)
6160 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6162 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6163 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6164 .FocusedOn(FocusedControl.ListTab)
6165 .Do(() => this.GoFav(forward: true)),
6167 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6168 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6169 .FocusedOn(FocusedControl.ListTab)
6170 .Do(() => this.GoFav(forward: false)),
6172 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6173 .FocusedOn(FocusedControl.ListTab)
6174 .Do(() => this.GoBackSelectPostChain()),
6176 ShortcutCommand.Create(Keys.Alt | Keys.R)
6177 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6179 ShortcutCommand.Create(Keys.Alt | Keys.P)
6180 .OnlyWhen(() => this._curPost != null)
6181 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6183 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6184 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6186 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6187 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6189 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6190 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6192 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6193 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6195 // 別タブの同じ書き込みへ(ALT+←/→)
6196 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6197 .FocusedOn(FocusedControl.ListTab)
6198 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6200 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6201 .FocusedOn(FocusedControl.ListTab)
6202 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6204 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6205 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6207 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6208 .Do(() => this.CopyIdUri()),
6210 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6211 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6212 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6213 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6215 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6216 .Do(() => this.FavoriteChange(FavAdd: false)),
6218 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6219 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6221 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6222 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6224 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6225 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6227 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6228 .Do(() => this.doMoveToRTHome()),
6230 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6231 .Do(() => this.FavorareMenuItem_Click(null, null)),
6233 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6234 .FocusedOn(FocusedControl.StatusText)
6236 if (_curList != null && _curList.VirtualListSize != 0 &&
6237 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6239 var idx = _curList.SelectedIndices[0] - 1;
6240 SelectListItem(_curList, idx);
6241 _curList.EnsureVisible(idx);
6245 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6246 .FocusedOn(FocusedControl.StatusText)
6248 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6249 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6251 var idx = _curList.SelectedIndices[0] + 1;
6252 SelectListItem(_curList, idx);
6253 _curList.EnsureVisible(idx);
6257 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6258 .FocusedOn(FocusedControl.StatusText)
6260 if (StatusText.SelectionStart > 0)
6262 int endidx = StatusText.SelectionStart - 1;
6263 string startstr = "";
6264 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6266 char c = StatusText.Text[i];
6267 if (Char.IsLetterOrDigit(c) || c == '_')
6273 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6274 int cnt = AtIdSupl.ItemCount;
6275 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6276 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6280 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6281 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6291 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6292 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6293 .FocusedOn(FocusedControl.ListTab)
6294 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6296 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6297 .FocusedOn(FocusedControl.ListTab)
6298 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6300 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6301 .FocusedOn(FocusedControl.ListTab)
6302 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6304 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6305 .FocusedOn(FocusedControl.ListTab)
6306 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6308 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6309 .FocusedOn(FocusedControl.ListTab)
6310 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6312 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6313 .FocusedOn(FocusedControl.ListTab)
6314 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6316 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6317 .FocusedOn(FocusedControl.ListTab)
6318 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6320 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6321 .FocusedOn(FocusedControl.ListTab)
6322 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6324 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6325 .FocusedOn(FocusedControl.ListTab)
6326 .Do(() => this.SetSortLastColumn()),
6328 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6329 .Do(() => this.FavoritesRetweetOfficial()),
6331 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6332 .Do(() => this.FavoritesRetweetUnofficial()),
6334 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6335 .Do(() => this.OpenUserAppointUrl()),
6337 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6338 .FocusedOn(FocusedControl.PostBrowser)
6339 .Do(() => this.doReTweetUnofficial()),
6341 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6342 .OnlyWhen(() => this.ExistCurrentPost)
6343 .Do(() => this.tweetDetailsView.DoTranslation()),
6345 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6346 .Do(() => this.doReTweetUnofficial()),
6348 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6349 .Do(() => this.CopyUserId()),
6351 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6352 .Do(() => this.tweetThumbnail1.ScrollUp()),
6354 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6355 .Do(() => this.tweetThumbnail1.ScrollDown()),
6357 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6358 .FocusedOn(FocusedControl.ListTab)
6359 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6360 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6364 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6366 // Task を返す非同期処理があれば asyncTask に代入する
6369 // ShortcutCommand に対応しているコマンドはここで処理される
6370 foreach (var command in this.shortcutCommands)
6372 if (command.IsMatch(keyData, focusedOn))
6374 asyncTask = command.RunCommand();
6375 return command.PreventDefault;
6382 private void GoNextTab(bool forward)
6384 int idx = ListTab.SelectedIndex;
6388 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6393 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6395 ListTab.SelectedIndex = idx;
6398 private void CopyStot()
6401 StringBuilder sb = new StringBuilder();
6402 bool IsProtected = false;
6404 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6405 foreach (int idx in _curList.SelectedIndices)
6407 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6408 if (post.IsDeleted) continue;
6411 if (post.RetweetedId != null)
6412 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6414 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6418 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6423 MessageBox.Show(Properties.Resources.CopyStotText1);
6427 clstr = sb.ToString();
6430 Clipboard.SetDataObject(clstr, false, 5, 100);
6432 catch (Exception ex)
6434 MessageBox.Show(ex.Message);
6439 private void CopyIdUri()
6441 if (this._curTab == null)
6444 var tab = this._statuses.GetTabByName(this._curTab.Text);
6445 if (tab == null || tab is DirectMessagesTabModel)
6448 var copyUrls = new List<string>();
6449 foreach (int idx in _curList.SelectedIndices)
6451 var post = tab[idx];
6452 copyUrls.Add(MyCommon.GetStatusUrl(post));
6455 if (copyUrls.Count == 0)
6460 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6462 catch (ExternalException ex)
6464 MessageBox.Show(ex.Message);
6468 private void GoFav(bool forward)
6470 if (_curList.VirtualListSize == 0) return;
6477 if (_curList.SelectedIndices.Count == 0)
6483 fIdx = _curList.SelectedIndices[0] + 1;
6484 if (fIdx > _curList.VirtualListSize - 1) return;
6486 toIdx = _curList.VirtualListSize;
6491 if (_curList.SelectedIndices.Count == 0)
6493 fIdx = _curList.VirtualListSize - 1;
6497 fIdx = _curList.SelectedIndices[0] - 1;
6498 if (fIdx < 0) return;
6504 for (int idx = fIdx; idx != toIdx; idx += stp)
6506 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6508 SelectListItem(_curList, idx);
6509 _curList.EnsureVisible(idx);
6515 private void GoSamePostToAnotherTab(bool left)
6517 if (this._curList.SelectedIndices.Count == 0)
6520 var tab = this._statuses.Tabs[this._curTab.Text];
6522 // Directタブは対象外(見つかるはずがない)
6523 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6526 var selectedIndex = this._curList.SelectedIndices[0];
6527 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6529 int fIdx, toIdx, stp;
6534 if (ListTab.SelectedIndex == 0)
6540 fIdx = ListTab.SelectedIndex - 1;
6548 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6554 fIdx = ListTab.SelectedIndex + 1;
6556 toIdx = ListTab.TabCount;
6560 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6562 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6565 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6568 var foundIndex = targetTab.IndexOf(selectedStatusId);
6569 if (foundIndex != -1)
6571 ListTab.SelectedIndex = tabidx;
6572 SelectListItem(_curList, foundIndex);
6573 _curList.EnsureVisible(foundIndex);
6579 private void GoPost(bool forward)
6581 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6584 var tab = this._statuses.Tabs[this._curTab.Text];
6585 var selectedIndex = this._curList.SelectedIndices[0];
6587 int fIdx, toIdx, stp;
6591 fIdx = selectedIndex + 1;
6592 if (fIdx > tab.AllCount - 1) return;
6593 toIdx = tab.AllCount;
6598 fIdx = selectedIndex - 1;
6599 if (fIdx < 0) return;
6605 if (_curPost.RetweetedId == null)
6607 name = _curPost.ScreenName;
6611 name = _curPost.RetweetedBy;
6613 for (int idx = fIdx; idx != toIdx; idx += stp)
6615 var post = tab[idx];
6616 if (post.RetweetedId == null)
6618 if (post.ScreenName == name)
6620 SelectListItem(_curList, idx);
6621 _curList.EnsureVisible(idx);
6627 if (post.RetweetedBy == name)
6629 SelectListItem(_curList, idx);
6630 _curList.EnsureVisible(idx);
6637 private void GoRelPost(bool forward)
6639 if (this._curList.SelectedIndices.Count == 0)
6642 var tab = this._statuses.Tabs[this._curTab.Text];
6643 var selectedIndex = this._curList.SelectedIndices[0];
6645 int fIdx, toIdx, stp;
6649 fIdx = selectedIndex + 1;
6650 if (fIdx > tab.AllCount - 1) return;
6651 toIdx = tab.AllCount;
6656 fIdx = selectedIndex - 1;
6657 if (fIdx < 0) return;
6664 if (_curPost == null) return;
6665 _anchorPost = _curPost;
6670 if (_anchorPost == null) return;
6673 for (int idx = fIdx; idx != toIdx; idx += stp)
6675 var post = tab[idx];
6676 if (post.ScreenName == _anchorPost.ScreenName ||
6677 post.RetweetedBy == _anchorPost.ScreenName ||
6678 post.ScreenName == _anchorPost.RetweetedBy ||
6679 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6680 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6681 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6682 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6683 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6685 SelectListItem(_curList, idx);
6686 _curList.EnsureVisible(idx);
6692 private void GoAnchor()
6694 if (_anchorPost == null) return;
6695 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6696 if (idx == -1) return;
6698 SelectListItem(_curList, idx);
6699 _curList.EnsureVisible(idx);
6702 private void GoTopEnd(bool GoTop)
6704 if (_curList.VirtualListSize == 0)
6712 _item = _curList.GetItemAt(0, 25);
6720 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6722 idx = _curList.VirtualListSize - 1;
6726 SelectListItem(_curList, idx);
6729 private void GoMiddle()
6731 if (_curList.VirtualListSize == 0)
6739 _item = _curList.GetItemAt(0, 0);
6749 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6752 idx2 = _curList.VirtualListSize - 1;
6758 idx3 = (idx1 + idx2) / 2;
6760 SelectListItem(_curList, idx3);
6763 private void GoLast()
6765 if (_curList.VirtualListSize == 0) return;
6767 if (_statuses.SortOrder == SortOrder.Ascending)
6769 SelectListItem(_curList, _curList.VirtualListSize - 1);
6770 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6774 SelectListItem(_curList, 0);
6775 _curList.EnsureVisible(0);
6779 private void MoveTop()
6781 if (_curList.SelectedIndices.Count == 0) return;
6782 int idx = _curList.SelectedIndices[0];
6783 if (_statuses.SortOrder == SortOrder.Ascending)
6785 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6789 _curList.EnsureVisible(0);
6791 _curList.EnsureVisible(idx);
6794 private async Task GoInReplyToPostTree()
6796 if (_curPost == null) return;
6798 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6800 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6804 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6806 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6807 _curPost.InReplyToUser = post.InReplyToUser;
6808 _curPost.IsReply = post.IsReply;
6809 this.PurgeListViewItemCache();
6810 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6812 catch (WebApiException ex)
6814 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6818 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6820 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6822 replyChains = new Stack<ReplyChain>();
6824 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6827 string inReplyToTabName;
6828 long inReplyToId = _curPost.InReplyToStatusId.Value;
6829 string inReplyToUser = _curPost.InReplyToUser;
6830 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6832 var inReplyToPosts = from tab in _statuses.Tabs.Values
6833 orderby tab != curTabClass
6834 from post in tab.Posts.Values
6835 where post.StatusId == inReplyToId
6836 let index = tab.IndexOf(post.StatusId)
6838 select new {Tab = tab, Index = index};
6840 var inReplyPost = inReplyToPosts.FirstOrDefault();
6841 if (inReplyPost == null)
6845 await Task.Run(async () =>
6847 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6848 .ConfigureAwait(false);
6851 _statuses.AddPost(post);
6852 _statuses.DistributePosts();
6855 catch (WebApiException ex)
6857 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6858 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6862 this.RefreshTimeline();
6864 inReplyPost = inReplyToPosts.FirstOrDefault();
6865 if (inReplyPost == null)
6867 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6871 inReplyToTabName = inReplyPost.Tab.TabName;
6872 inReplyToIndex = inReplyPost.Index;
6874 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6875 DetailsListView listView = (DetailsListView)tabPage.Tag;
6877 if (_curTab != tabPage)
6879 this.ListTab.SelectTab(tabPage);
6882 this.SelectListItem(listView, inReplyToIndex);
6883 listView.EnsureVisible(inReplyToIndex);
6886 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6888 if (_curPost == null) return;
6890 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6891 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6895 if (_curPost.InReplyToStatusId != null)
6897 var posts = from t in _statuses.Tabs
6898 from p in t.Value.Posts
6899 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6900 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6902 orderby isForward ? indexOf : indexOf * -1
6903 orderby t.Value != curTabClass
6904 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6907 var postList = posts.ToList();
6908 for (int i = postList.Count - 1; i >= 0; i--)
6911 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6913 postList.RemoveAt(index);
6916 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6917 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6918 if (post == null) post = postList.First();
6919 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6920 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6921 SelectListItem(listView, post.Index);
6922 listView.EnsureVisible(post.Index);
6924 catch (InvalidOperationException)
6932 if (replyChains == null || replyChains.Count < 1)
6934 var posts = from t in _statuses.Tabs
6935 from p in t.Value.Posts
6936 where p.Value.InReplyToStatusId == _curPost.StatusId
6937 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6940 orderby t.Value != curTabClass
6941 select new {Tab = t.Value, Index = indexOf};
6944 var post = posts.First();
6945 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6946 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6947 SelectListItem(listView, post.Index);
6948 listView.EnsureVisible(post.Index);
6950 catch (InvalidOperationException)
6957 ReplyChain chainHead = replyChains.Pop();
6958 if (chainHead.InReplyToId == _curPost.StatusId)
6960 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6969 ListTab.SelectTab(chainHead.OriginalTab);
6975 SelectListItem(_curList, idx);
6976 _curList.EnsureVisible(idx);
6982 this.GoBackInReplyToPostTree(parallel);
6988 private void GoBackSelectPostChain()
6990 if (this.selectPostChains.Count > 1)
6999 this.selectPostChains.Pop();
7000 var (tabPage, post) = this.selectPostChains.Peek();
7002 if (!this.ListTab.TabPages.Contains(tabPage)) continue; //該当タブが存在しないので無視
7006 idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7007 if (idx == -1) continue; //該当ポストが存在しないので無視
7012 this.selectPostChains.Pop();
7014 catch (InvalidOperationException)
7020 while (this.selectPostChains.Count > 1);
7025 //履歴が残り1つであればクリアしておく
7026 if (this.selectPostChains.Count == 1)
7027 this.selectPostChains.Clear();
7031 DetailsListView lst = (DetailsListView)tp.Tag;
7032 this.ListTab.SelectedTab = tp;
7035 SelectListItem(lst, idx);
7036 lst.EnsureVisible(idx);
7042 private void PushSelectPostChain()
7044 int count = this.selectPostChains.Count;
7047 var (tabPage, post) = this.selectPostChains.Peek();
7048 if (tabPage == this._curTab)
7050 if (post == this._curPost) return; //最新の履歴と同一
7051 if (post == null) this.selectPostChains.Pop(); //置き換えるため削除
7054 if (count >= 2500) TrimPostChain();
7055 this.selectPostChains.Push((this._curTab, this._curPost));
7058 private void TrimPostChain()
7060 if (this.selectPostChains.Count <= 2000) return;
7061 var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7062 for (int i = 0; i < 2000; i++)
7064 p.Push(this.selectPostChains.Pop());
7066 this.selectPostChains.Clear();
7067 for (int i = 0; i < 2000; i++)
7069 this.selectPostChains.Push(p.Pop());
7073 private bool GoStatus(long statusId)
7075 if (statusId == 0) return false;
7076 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7078 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7080 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7081 ListTab.SelectedIndex = tabidx;
7082 SelectListItem(_curList, idx);
7083 _curList.EnsureVisible(idx);
7090 private bool GoDirectMessage(long statusId)
7092 if (statusId == 0) return false;
7093 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7095 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7097 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7098 ListTab.SelectedIndex = tabidx;
7099 SelectListItem(_curList, idx);
7100 _curList.EnsureVisible(idx);
7107 private void MyList_MouseClick(object sender, MouseEventArgs e)
7109 _anchorFlag = false;
7112 private void StatusText_Enter(object sender, EventArgs e)
7114 // フォーカスの戻り先を StatusText に設定
7115 this.Tag = StatusText;
7116 StatusText.BackColor = _clInputBackcolor;
7119 public Color InputBackColor
7121 get => _clInputBackcolor;
7122 set => _clInputBackcolor = value;
7125 private void StatusText_Leave(object sender, EventArgs e)
7127 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7128 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7129 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7132 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7134 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7137 e.SuppressKeyPress = true;
7140 this.StatusText_TextChanged(null, null);
7142 if (asyncTask != null)
7146 private void SaveConfigsAll(bool ifModified)
7150 SaveConfigsCommon();
7157 if (ModifySettingCommon) SaveConfigsCommon();
7158 if (ModifySettingLocal) SaveConfigsLocal();
7159 if (ModifySettingAtId) SaveConfigsAtId();
7163 private void SaveConfigsAtId()
7165 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7167 ModifySettingAtId = false;
7168 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7169 SettingManager.SaveAtIdList();
7172 private void SaveConfigsCommon()
7174 if (_ignoreConfigSave) return;
7176 ModifySettingCommon = false;
7179 SettingManager.Common.UserName = tw.Username;
7180 SettingManager.Common.UserId = tw.UserId;
7181 SettingManager.Common.Token = tw.AccessToken;
7182 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7184 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7185 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7187 SettingManager.Common.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7190 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7191 switch (_statuses.SortMode)
7193 case ComparerMode.Nickname: //ニックネーム
7194 SettingManager.Common.SortColumn = 1;
7196 case ComparerMode.Data: //本文
7197 SettingManager.Common.SortColumn = 2;
7199 case ComparerMode.Id: //時刻=発言Id
7200 SettingManager.Common.SortColumn = 3;
7202 case ComparerMode.Name: //名前
7203 SettingManager.Common.SortColumn = 4;
7205 case ComparerMode.Source: //Source
7206 SettingManager.Common.SortColumn = 7;
7210 SettingManager.Common.HashTags = HashMgr.HashHistories;
7211 if (HashMgr.IsPermanent)
7213 SettingManager.Common.HashSelected = HashMgr.UseHash;
7217 SettingManager.Common.HashSelected = "";
7219 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7220 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7221 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7222 if (ToolStripFocusLockMenuItem != null &&
7223 ToolStripFocusLockMenuItem.IsDisposed == false)
7225 SettingManager.Common.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7227 SettingManager.Common.TrackWord = tw.TrackWord;
7228 SettingManager.Common.AllAtReply = tw.AllAtReply;
7229 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7230 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7232 SettingManager.SaveCommon();
7236 private void SaveConfigsLocal()
7238 if (_ignoreConfigSave) return;
7241 ModifySettingLocal = false;
7242 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7243 SettingManager.Local.FormSize = _mySize;
7244 SettingManager.Local.FormLocation = _myLoc;
7245 SettingManager.Local.SplitterDistance = _mySpDis;
7246 SettingManager.Local.PreviewDistance = _mySpDis3;
7247 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7248 SettingManager.Local.StatusTextHeight = _mySpDis2;
7250 SettingManager.Local.FontUnread = _fntUnread;
7251 SettingManager.Local.ColorUnread = _clUnread;
7252 SettingManager.Local.FontRead = _fntReaded;
7253 SettingManager.Local.ColorRead = _clReaded;
7254 SettingManager.Local.FontDetail = _fntDetail;
7255 SettingManager.Local.ColorDetail = _clDetail;
7256 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7257 SettingManager.Local.ColorDetailLink = _clDetailLink;
7258 SettingManager.Local.ColorFav = _clFav;
7259 SettingManager.Local.ColorOWL = _clOWL;
7260 SettingManager.Local.ColorRetweet = _clRetweet;
7261 SettingManager.Local.ColorSelf = _clSelf;
7262 SettingManager.Local.ColorAtSelf = _clAtSelf;
7263 SettingManager.Local.ColorTarget = _clTarget;
7264 SettingManager.Local.ColorAtTarget = _clAtTarget;
7265 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7266 SettingManager.Local.ColorAtTo = _clAtTo;
7267 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7268 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7269 SettingManager.Local.ColorInputFont = _clInputFont;
7270 SettingManager.Local.FontInputFont = _fntInputFont;
7272 if (_ignoreConfigSave) return;
7273 SettingManager.SaveLocal();
7277 private void SaveConfigsTabs()
7279 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7281 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7282 .Select(x => this._statuses.Tabs[x.Text])
7283 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7285 foreach (var tab in tabs)
7287 if (!tab.IsPermanentTabType)
7290 var tabSetting = new SettingTabs.SettingTabItem
7292 TabName = tab.TabName,
7293 TabType = tab.TabType,
7294 UnreadManage = tab.UnreadManage,
7295 Protected = tab.Protected,
7296 Notify = tab.Notify,
7297 SoundFile = tab.SoundFile,
7302 case FilterTabModel filterTab:
7303 tabSetting.FilterArray = filterTab.FilterArray;
7305 case UserTimelineTabModel userTab:
7306 tabSetting.User = userTab.ScreenName;
7308 case PublicSearchTabModel searchTab:
7309 tabSetting.SearchWords = searchTab.SearchWords;
7310 tabSetting.SearchLang = searchTab.SearchLang;
7312 case ListTimelineTabModel listTab:
7313 tabSetting.ListInfo = listTab.ListInfo;
7317 tabSettingList.Add(tabSetting);
7320 SettingManager.Tabs.Tabs = tabSettingList;
7321 SettingManager.SaveTabs();
7324 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7326 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7327 if (ret != DialogResult.OK)
7330 var match = Twitter.StatusUrlRegex.Match(inputText);
7333 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7334 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7340 var statusId = long.Parse(match.Groups["StatusId"].Value);
7341 await this.OpenRelatedTab(statusId);
7343 catch (TabException ex)
7345 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7349 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7351 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7352 Properties.Resources.SaveLogMenuItem_ClickText2,
7353 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7354 if (rslt == DialogResult.Cancel) return;
7356 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7357 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7358 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7359 SaveFileDialog1.FilterIndex = 0;
7360 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7361 SaveFileDialog1.RestoreDirectory = true;
7363 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7365 if (!SaveFileDialog1.ValidateNames) return;
7366 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7368 if (rslt == DialogResult.Yes)
7371 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7373 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7374 string protect = "";
7375 if (post.IsProtect) protect = "Protect";
7376 sw.WriteLine(post.Nickname + "\t" +
7377 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7378 post.CreatedAt + "\t" +
7379 post.ScreenName + "\t" +
7380 post.StatusId + "\t" +
7381 post.ImageUrl + "\t" +
7382 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7388 foreach (int idx in _curList.SelectedIndices)
7390 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7391 string protect = "";
7392 if (post.IsProtect) protect = "Protect";
7393 sw.WriteLine(post.Nickname + "\t" +
7394 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7395 post.CreatedAt + "\t" +
7396 post.ScreenName + "\t" +
7397 post.StatusId + "\t" +
7398 post.ImageUrl + "\t" +
7399 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7405 this.TopMost = SettingManager.Common.AlwaysTop;
7408 public bool TabRename(string origTabName, out string newTabName)
7412 using (InputTabName inputName = new InputTabName())
7414 inputName.TabName = origTabName;
7415 inputName.ShowDialog();
7416 if (inputName.DialogResult == DialogResult.Cancel) return false;
7417 newTabName = inputName.TabName;
7419 this.TopMost = SettingManager.Common.AlwaysTop;
7420 if (!string.IsNullOrEmpty(newTabName))
7423 for (int i = 0; i < ListTab.TabCount; i++)
7425 if (ListTab.TabPages[i].Text == newTabName)
7427 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7428 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7433 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7434 .FirstOrDefault(x => x.Text == origTabName);
7437 if (tabPage != null)
7438 tabPage.Text = newTabName;
7440 _statuses.RenameTab(origTabName, newTabName);
7442 SaveConfigsCommon();
7444 _rclickTabName = newTabName;
7453 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7455 if (e.Button == MouseButtons.Middle)
7457 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7459 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7461 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7462 this.SaveConfigsTabs();
7469 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7471 TabRename(this.ListTab.SelectedTab.Text, out var _);
7474 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7476 if (SettingManager.Common.TabMouseLock) return;
7477 if (e.Button == MouseButtons.Left)
7479 for (int i = 0; i < ListTab.TabPages.Count; i++)
7481 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7484 _tabMouseDownPoint = e.Location;
7495 private void ListTab_DragEnter(object sender, DragEventArgs e)
7497 if (e.Data.GetDataPresent(typeof(TabPage)))
7498 e.Effect = DragDropEffects.Move;
7500 e.Effect = DragDropEffects.None;
7503 private void ListTab_DragDrop(object sender, DragEventArgs e)
7505 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7510 Point cpos = new Point(e.X, e.Y);
7511 Point spos = ListTab.PointToClient(cpos);
7513 for (i = 0; i < ListTab.TabPages.Count; i++)
7515 Rectangle rect = ListTab.GetTabRect(i);
7516 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7517 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7519 tn = ListTab.TabPages[i].Text;
7520 if (spos.X <= (rect.Left + rect.Right) / 2)
7529 //タブのないところにドロップ->最後尾へ移動
7530 if (string.IsNullOrEmpty(tn))
7532 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7534 i = ListTab.TabPages.Count - 1;
7537 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7538 if (tp.Text == tn) return;
7540 ReOrderTab(tp.Text, tn, bef);
7543 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7545 var baseIndex = this.GetTabPageIndex(baseTabText);
7546 if (baseIndex == -1)
7549 var targetIndex = this.GetTabPageIndex(targetTabText);
7550 if (targetIndex == -1)
7553 using (ControlTransaction.Layout(this.ListTab))
7555 var mTp = this.ListTab.TabPages[targetIndex];
7556 this.ListTab.TabPages.Remove(mTp);
7558 if (targetIndex < baseIndex)
7561 if (isBeforeBaseTab)
7562 ListTab.TabPages.Insert(baseIndex, mTp);
7564 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7570 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7572 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7573 //isReply:true=@,false=DM
7574 if (!StatusText.Enabled) return;
7575 if (_curList == null) return;
7576 if (_curTab == null) return;
7577 if (!this.ExistCurrentPost) return;
7579 // 複数あてリプライはReplyではなく通常ポスト
7580 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7581 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7582 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7584 if (_curList.SelectedIndices.Count > 0)
7587 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7590 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7593 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7594 StatusText.SelectionStart = StatusText.Text.Length;
7596 this.inReplyTo = null;
7599 if (string.IsNullOrEmpty(StatusText.Text))
7603 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7604 StatusText.Text = "@" + _curPost.ScreenName + " ";
7606 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7607 var inReplyToScreenName = this._curPost.ScreenName;
7608 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7616 //1件選んでEnter or DoubleClick
7617 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7619 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7622 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7623 var inReplyToScreenName = this._curPost.ScreenName;
7624 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7628 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7631 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7634 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7635 this.inReplyTo = null;
7640 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7641 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7642 var inReplyToScreenName = this._curPost.ScreenName;
7643 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7650 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7651 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7652 this.inReplyTo = null;
7657 //1件選んでCtrl-Rの場合(返信先操作せず)
7658 int sidx = StatusText.SelectionStart;
7659 string id = "@" + _curPost.ScreenName + " ";
7662 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7667 StatusText.Text = StatusText.Text.Insert(sidx, id);
7669 //if (StatusText.Text.StartsWith("@"))
7672 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7673 // sidx += 5 + _curPost.ScreenName.Length;
7678 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7679 // sidx += 3 + _curPost.ScreenName.Length;
7681 StatusText.SelectionStart = sidx;
7684 //_reply_to_name = null;
7692 if (!isAuto && !isReply) return;
7694 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7698 //Enter or DoubleClick
7700 string sTxt = StatusText.Text;
7701 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7704 this.inReplyTo = null;
7706 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7708 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7709 if (!sTxt.Contains("@" + post.ScreenName + " "))
7711 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7712 //sTxt = "@" + post.ScreenName + " " + sTxt;
7715 StatusText.Text = sTxt;
7720 if (_curList.SelectedIndices.Count > 1)
7725 int sidx = StatusText.SelectionStart;
7726 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7728 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7729 if (!ids.Contains("@" + post.ScreenName + " ") &&
7730 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7732 ids += "@" + post.ScreenName + " ";
7736 foreach (string nm in post.ReplyToList)
7738 if (!ids.Contains("@" + nm + " ") &&
7739 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7741 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7743 ids += "@" + m.Result("${id}") + " ";
7745 ids += "@" + nm + " ";
7750 if (ids.Length == 0) return;
7751 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7753 StatusText.Text = ". " + StatusText.Text;
7755 this.inReplyTo = null;
7759 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7764 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7766 //if (StatusText.Text.StartsWith("@"))
7768 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7769 // sidx += 2 + ids.Length;
7773 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7774 // sidx += 1 + ids.Length;
7776 StatusText.SelectionStart = sidx;
7782 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7785 int sidx = StatusText.SelectionStart;
7786 PostClass post = _curPost;
7787 if (!ids.Contains("@" + post.ScreenName + " ") &&
7788 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7790 ids += "@" + post.ScreenName + " ";
7792 foreach (string nm in post.ReplyToList)
7794 if (!ids.Contains("@" + nm + " ") &&
7795 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7797 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7799 ids += "@" + m.Result("${id}") + " ";
7801 ids += "@" + nm + " ";
7804 if (!string.IsNullOrEmpty(post.RetweetedBy))
7806 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7807 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7809 ids += "@" + post.RetweetedBy + " ";
7812 if (ids.Length == 0) return;
7813 if (string.IsNullOrEmpty(StatusText.Text))
7816 StatusText.Text = ids;
7817 StatusText.SelectionStart = ids.Length;
7820 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7821 var inReplyToScreenName = this._curPost.ScreenName;
7822 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7828 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7833 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7835 StatusText.SelectionStart = sidx;
7841 StatusText.SelectionStart = StatusText.Text.Length;
7846 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7851 private static int iconCnt = 0;
7852 private static int blinkCnt = 0;
7853 private static bool blink = false;
7854 private static bool idle = false;
7856 private async Task RefreshTasktrayIcon()
7859 await this.Colorize();
7861 if (!TimerRefreshIcon.Enabled) return;
7862 //Static usCheckCnt As int = 0
7864 //Static iconDlListTopItem As ListViewItem = null
7866 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7867 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7869 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7871 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7877 //if (usCheckCnt > 300) //1min
7880 // if (!this.IsReceivedUserStream)
7882 // TraceOut("ReconnectUserStream");
7883 // tw.ReconnectUserStream();
7887 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7889 if (iconCnt >= this.NIconRefresh.Length)
7897 SaveConfigsAll(true);
7902 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7904 _myStatusError = false;
7908 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7909 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7911 if (blinkCnt > 0) return;
7913 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7915 NotifyIcon1.Icon = ReplyIcon;
7919 NotifyIcon1.Icon = ReplyIconBlink;
7927 //優先度:エラー→オフライン→アイドル
7931 NotifyIcon1.Icon = NIconAtRed;
7934 if (_myStatusOnline)
7936 NotifyIcon1.Icon = NIconAt;
7940 NotifyIcon1.Icon = NIconAtSmoke;
7944 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7947 await this.RefreshTasktrayIcon();
7950 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7952 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7953 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7955 if (ListTab != null && ListTab.SelectedTab != null)
7956 _rclickTabName = ListTab.SelectedTab.Text;
7961 if (_statuses == null) return;
7962 if (_statuses.Tabs == null) return;
7964 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7967 NotifyDispMenuItem.Checked = tb.Notify;
7968 this.NotifyTbMenuItem.Checked = tb.Notify;
7970 soundfileListup = true;
7971 SoundFileComboBox.Items.Clear();
7972 this.SoundFileTbComboBox.Items.Clear();
7973 SoundFileComboBox.Items.Add("");
7974 this.SoundFileTbComboBox.Items.Add("");
7975 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7976 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7978 oDir = oDir.GetDirectories("Sounds")[0];
7980 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
7982 SoundFileComboBox.Items.Add(oFile.Name);
7983 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7985 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7986 if (idx == -1) idx = 0;
7987 SoundFileComboBox.SelectedIndex = idx;
7988 this.SoundFileTbComboBox.SelectedIndex = idx;
7989 soundfileListup = false;
7990 UreadManageMenuItem.Checked = tb.UnreadManage;
7991 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
7993 TabMenuControl(_rclickTabName);
7996 private void TabMenuControl(string tabName)
7998 var tabInfo = _statuses.GetTabByName(tabName);
8000 this.FilterEditMenuItem.Enabled = true;
8001 this.EditRuleTbMenuItem.Enabled = true;
8003 if (tabInfo.IsDefaultTabType)
8005 this.ProtectTabMenuItem.Enabled = false;
8006 this.ProtectTbMenuItem.Enabled = false;
8010 this.ProtectTabMenuItem.Enabled = true;
8011 this.ProtectTbMenuItem.Enabled = true;
8014 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8016 this.ProtectTabMenuItem.Checked = true;
8017 this.ProtectTbMenuItem.Checked = true;
8018 this.DeleteTabMenuItem.Enabled = false;
8019 this.DeleteTbMenuItem.Enabled = false;
8023 this.ProtectTabMenuItem.Checked = false;
8024 this.ProtectTbMenuItem.Checked = false;
8025 this.DeleteTabMenuItem.Enabled = true;
8026 this.DeleteTbMenuItem.Enabled = true;
8030 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8032 var checkState = ((ToolStripMenuItem)sender).Checked;
8035 this.ProtectTbMenuItem.Checked = checkState;
8036 this.ProtectTabMenuItem.Checked = checkState;
8039 this.DeleteTabMenuItem.Enabled = !checkState;
8040 this.DeleteTbMenuItem.Enabled = !checkState;
8042 if (string.IsNullOrEmpty(_rclickTabName)) return;
8043 _statuses.Tabs[_rclickTabName].Protected = checkState;
8048 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8050 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8051 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8053 if (string.IsNullOrEmpty(_rclickTabName)) return;
8054 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8059 public void ChangeTabUnreadManage(string tabName, bool isManage)
8061 var idx = this.GetTabPageIndex(tabName);
8065 _statuses.Tabs[tabName].UnreadManage = isManage;
8066 if (SettingManager.Common.TabIconDisp)
8068 if (_statuses.Tabs[tabName].UnreadCount > 0)
8069 ListTab.TabPages[idx].ImageIndex = 0;
8071 ListTab.TabPages[idx].ImageIndex = -1;
8074 if (_curTab.Text == tabName)
8076 this.PurgeListViewItemCache();
8080 SetMainWindowTitle();
8081 SetStatusLabelUrl();
8082 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8085 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8087 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8088 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8090 if (string.IsNullOrEmpty(_rclickTabName)) return;
8092 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8097 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8099 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8101 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8106 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8108 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8110 RemoveSpecifiedTab(_rclickTabName, true);
8114 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8116 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8118 using (var fltDialog = new FilterDialog())
8120 fltDialog.Owner = this;
8121 fltDialog.SetCurrent(_rclickTabName);
8122 fltDialog.ShowDialog(this);
8124 this.TopMost = SettingManager.Common.AlwaysTop;
8126 this.ApplyPostFilters();
8130 private void AddTabMenuItem_Click(object sender, EventArgs e)
8132 string tabName = null;
8133 MyCommon.TabUsageType tabUsage;
8134 using (InputTabName inputName = new InputTabName())
8136 inputName.TabName = _statuses.MakeTabName("MyTab");
8137 inputName.IsShowUsage = true;
8138 inputName.ShowDialog();
8139 if (inputName.DialogResult == DialogResult.Cancel) return;
8140 tabName = inputName.TabName;
8141 tabUsage = inputName.Usage;
8143 this.TopMost = SettingManager.Common.AlwaysTop;
8144 if (!string.IsNullOrEmpty(tabName))
8147 ListElement list = null;
8148 if (tabUsage == MyCommon.TabUsageType.Lists)
8150 using (ListAvailable listAvail = new ListAvailable())
8152 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8153 if (listAvail.SelectedList == null) return;
8154 list = listAvail.SelectedList;
8161 case MyCommon.TabUsageType.UserDefined:
8162 tab = new FilterTabModel(tabName);
8164 case MyCommon.TabUsageType.PublicSearch:
8165 tab = new PublicSearchTabModel(tabName);
8167 case MyCommon.TabUsageType.Lists:
8168 tab = new ListTimelineTabModel(tabName, list);
8174 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8176 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8177 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8183 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8185 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8186 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8188 if (tabUsage == MyCommon.TabUsageType.Lists)
8190 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8191 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8192 this.GetListTimelineAsync(listTab);
8198 private void TabMenuItem_Click(object sender, EventArgs e)
8200 using (var fltDialog = new FilterDialog())
8202 fltDialog.Owner = this;
8205 foreach (int idx in _curList.SelectedIndices)
8208 if (!SelectTab(out var tabName)) return;
8210 fltDialog.SetCurrent(tabName);
8211 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8213 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8217 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8219 fltDialog.ShowDialog(this);
8220 this.TopMost = SettingManager.Common.AlwaysTop;
8224 this.ApplyPostFilters();
8226 if (this.ListTab.SelectedTab != null &&
8227 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8229 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8233 protected override bool ProcessDialogKey(Keys keyData)
8235 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8236 if ((keyData & Keys.KeyCode) == Keys.Enter)
8238 if (StatusText.Focused)
8240 bool _NewLine = false;
8243 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8245 if (StatusText.Multiline)
8247 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8249 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8253 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8257 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8259 if (StatusText.Multiline)
8261 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8263 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8267 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8273 if (StatusText.Multiline)
8275 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8277 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8278 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8282 if (((keyData & Keys.Shift) == Keys.Shift) ||
8283 (((keyData & Keys.Control) != Keys.Control) &&
8284 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8290 int pos1 = StatusText.SelectionStart;
8291 if (StatusText.SelectionLength > 0)
8293 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8295 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8296 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8301 PostButton_Click(null, null);
8305 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8306 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8307 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8309 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8314 return base.ProcessDialogKey(keyData);
8317 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8319 MakeReplyOrDirectStatus(false, true, true);
8322 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8325 if (_curList.SelectedIndices.Count == 0) return;
8327 var tab = this._statuses.Tabs[this._curTab.Text];
8328 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8329 .Select(x => tab[x])
8330 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8333 this.AddFilterRuleByScreenName(screenNameArray);
8335 if (screenNameArray.Length != 0)
8337 List<string> atids = new List<string>();
8338 foreach (var screenName in screenNameArray)
8340 atids.Add("@" + screenName);
8342 int cnt = AtIdSupl.ItemCount;
8343 AtIdSupl.AddRangeItem(atids.ToArray());
8344 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8348 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8350 if (this._curList.SelectedIndices.Count == 0)
8353 var tab = this._statuses.Tabs[this._curTab.Text];
8354 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8355 .Select(x => tab[x].Source).ToArray();
8357 this.AddFilterRuleBySource(sourceArray);
8360 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8363 if (!SelectTab(out var tabName)) return;
8365 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8369 if (tab.TabType != MyCommon.TabUsageType.Mute)
8371 this.MoveOrCopy(out mv, out mk);
8375 // ミュートタブでは常に MoveMatches を true にする
8380 foreach (var screenName in screenNameArray)
8382 tab.AddFilter(new PostFilterRule
8384 FilterName = screenName,
8385 UseNameField = true,
8389 FilterByUrl = false,
8393 this.ApplyPostFilters();
8397 public void AddFilterRuleBySource(params string[] sourceArray)
8399 // タブ選択ダイアログを表示(or追加)
8400 if (!this.SelectTab(out var tabName))
8403 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8407 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8409 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8410 this.MoveOrCopy(out mv, out mk);
8414 // ミュートタブでは常に MoveMatches を true にする
8419 // 振り分けルールに追加するSource
8420 foreach (var source in sourceArray)
8422 filterTab.AddFilter(new PostFilterRule
8424 FilterSource = source,
8428 FilterByUrl = false,
8432 this.ApplyPostFilters();
8433 this.SaveConfigsTabs();
8436 private bool SelectTab(out string tabName)
8443 using (var dialog = new TabsDialog(_statuses))
8445 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8447 var selectedTab = dialog.SelectedTab;
8448 tabName = selectedTab == null ? null : selectedTab.TabName;
8451 ListTab.SelectedTab.Focus();
8453 if (tabName == null)
8455 using (InputTabName inputName = new InputTabName())
8457 inputName.TabName = _statuses.MakeTabName("MyTab");
8458 inputName.ShowDialog();
8459 if (inputName.DialogResult == DialogResult.Cancel) return false;
8460 tabName = inputName.TabName;
8462 this.TopMost = SettingManager.Common.AlwaysTop;
8463 if (!string.IsNullOrEmpty(tabName))
8465 var tab = new FilterTabModel(tabName);
8466 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8468 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8469 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8487 private void MoveOrCopy(out bool move, out bool mark)
8491 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8492 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8500 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8501 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8511 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8516 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8521 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8523 if (StatusText.Focused)
8526 StatusText.SelectAll();
8530 // ListView上でのCtrl+A
8531 NativeMethods.SelectAllItems(this._curList);
8535 private void MoveMiddle()
8541 if (_curList.SelectedIndices.Count == 0) return;
8543 int idx = _curList.SelectedIndices[0];
8545 _item = _curList.GetItemAt(0, 25);
8551 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8553 idx2 = _curList.VirtualListSize - 1;
8557 idx -= Math.Abs(idx1 - idx2) / 2;
8558 if (idx < 0) idx = 0;
8560 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8561 _curList.EnsureVisible(idx);
8564 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8566 var linkElements = this.tweetDetailsView.GetLinkElements();
8568 if (linkElements.Length > 0)
8570 UrlDialog.ClearUrl();
8572 string openUrlStr = "";
8574 if (linkElements.Length == 1)
8576 // ツイートに含まれる URL が 1 つのみの場合
8577 // => OpenURL ダイアログを表示せずにリンクを開く
8582 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8584 catch (ArgumentException)
8593 if (string.IsNullOrEmpty(urlStr)) return;
8594 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8596 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8597 await this.OpenUriAsync(new Uri(openUrlStr));
8601 // ツイートに含まれる URL が複数ある場合
8602 // => OpenURL を表示しユーザーが選択したリンクを開く
8604 foreach (var linkElm in linkElements)
8607 string linkText = "";
8611 urlStr = linkElm.GetAttribute("title");
8612 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8613 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8614 linkText = linkElm.InnerText;
8616 catch (ArgumentException)
8625 if (string.IsNullOrEmpty(urlStr)) continue;
8626 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8630 if (UrlDialog.ShowDialog() == DialogResult.OK)
8632 openUrlStr = UrlDialog.SelectedUrl;
8634 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8635 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8642 this.TopMost = SettingManager.Common.AlwaysTop;
8647 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8649 if (string.IsNullOrEmpty(_rclickTabName)) return;
8650 ClearTab(_rclickTabName, true);
8653 private void ClearTab(string tabName, bool showWarning)
8657 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8658 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8664 _statuses.ClearTabIds(tabName);
8665 if (ListTab.SelectedTab.Text == tabName)
8668 _anchorFlag = false;
8669 this.PurgeListViewItemCache();
8673 foreach (TabPage tb in ListTab.TabPages)
8675 if (tb.Text == tabName)
8677 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8682 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8684 SetMainWindowTitle();
8685 SetStatusLabelUrl();
8688 private static long followers = 0;
8690 private void SetMainWindowTitle()
8693 StringBuilder ttl = new StringBuilder(256);
8696 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8697 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8698 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8699 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8701 foreach (var tab in _statuses.Tabs.Values)
8703 ur += tab.UnreadCount;
8708 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8709 ttl.Append(Application.ProductName);
8711 switch (SettingManager.Common.DispLatestPost)
8713 case MyCommon.DispTitleEnum.Ver:
8714 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8716 case MyCommon.DispTitleEnum.Post:
8717 if (_history != null && _history.Count > 1)
8718 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8720 case MyCommon.DispTitleEnum.UnreadRepCount:
8721 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8723 case MyCommon.DispTitleEnum.UnreadAllCount:
8724 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8726 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8727 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8729 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8730 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8732 case MyCommon.DispTitleEnum.OwnStatus:
8733 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8734 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8740 this.Text = ttl.ToString();
8742 catch (AccessViolationException)
8744 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8748 private string GetStatusLabelText()
8751 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8752 if (_statuses == null) return "";
8753 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8754 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8755 if (tbRep == null || tbDm == null) return "";
8756 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8761 StringBuilder slbl = new StringBuilder(256);
8764 foreach (var tab in _statuses.Tabs.Values)
8766 ur += tab.UnreadCount;
8768 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8770 tur = tab.UnreadCount;
8781 UnreadAtCounter = urat;
8783 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8785 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8786 if (SettingManager.Common.TimelinePeriod == 0)
8788 slbl.Append(Properties.Resources.SetStatusLabelText2);
8792 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8794 return slbl.ToString();
8797 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8801 if (this.InvokeRequired && !this.IsDisposed)
8803 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8807 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8808 SetApiStatusLabel(endpointName);
8811 catch (ObjectDisposedException)
8815 catch (InvalidOperationException)
8821 private void SetApiStatusLabel(string endpointName = null)
8823 if (_curTab == null)
8825 this.toolStripApiGauge.ApiEndpoint = null;
8829 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8831 if (endpointName == null)
8836 case MyCommon.TabUsageType.Home:
8837 case MyCommon.TabUsageType.UserDefined:
8838 endpointName = "/statuses/home_timeline";
8841 case MyCommon.TabUsageType.Mentions:
8842 endpointName = "/statuses/mentions_timeline";
8845 case MyCommon.TabUsageType.Favorites:
8846 endpointName = "/favorites/list";
8849 case MyCommon.TabUsageType.DirectMessage:
8850 endpointName = "/direct_messages";
8853 case MyCommon.TabUsageType.UserTimeline:
8854 endpointName = "/statuses/user_timeline";
8857 case MyCommon.TabUsageType.Lists:
8858 endpointName = "/lists/statuses";
8861 case MyCommon.TabUsageType.PublicSearch:
8862 endpointName = "/search/tweets";
8865 case MyCommon.TabUsageType.Related:
8866 endpointName = "/statuses/show/:id";
8873 this.toolStripApiGauge.ApiEndpoint = endpointName;
8877 // 表示中のタブに関連する endpoint であれば更新
8880 switch (endpointName)
8882 case "/statuses/home_timeline":
8883 update = tabType == MyCommon.TabUsageType.Home ||
8884 tabType == MyCommon.TabUsageType.UserDefined;
8887 case "/statuses/mentions_timeline":
8888 update = tabType == MyCommon.TabUsageType.Mentions;
8891 case "/favorites/list":
8892 update = tabType == MyCommon.TabUsageType.Favorites;
8895 case "/direct_messages:":
8896 update = tabType == MyCommon.TabUsageType.DirectMessage;
8899 case "/statuses/user_timeline":
8900 update = tabType == MyCommon.TabUsageType.UserTimeline;
8903 case "/lists/statuses":
8904 update = tabType == MyCommon.TabUsageType.Lists;
8907 case "/search/tweets":
8908 update = tabType == MyCommon.TabUsageType.PublicSearch;
8911 case "/statuses/show/:id":
8912 update = tabType == MyCommon.TabUsageType.Related;
8921 this.toolStripApiGauge.ApiEndpoint = endpointName;
8927 private void SetStatusLabelUrl()
8929 StatusLabelUrl.Text = GetStatusLabelText();
8932 public void SetStatusLabel(string text)
8934 StatusLabel.Text = text;
8937 private void SetNotifyIconText()
8939 var ur = new StringBuilder(64);
8941 // タスクトレイアイコンのツールチップテキスト書き換え
8943 ur.Remove(0, ur.Length);
8944 if (SettingManager.Common.DispUsername)
8946 ur.Append(tw.Username);
8949 ur.Append(Application.ProductName);
8951 ur.Append("(Debug Build)");
8953 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8956 ur.Append(UnreadCounter);
8958 ur.Append(UnreadAtCounter);
8961 NotifyIcon1.Text = ur.ToString();
8964 internal void CheckReplyTo(string StatusText)
8968 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8970 foreach (Match hm in m)
8972 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8974 hstr += "#" + hm.Result("$3") + " ";
8975 HashSupl.AddItem("#" + hm.Result("$3"));
8978 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8980 hstr += HashMgr.UseHash;
8982 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8984 // 本当にリプライ先指定すべきかどうかの判定
8985 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8987 if (SettingManager.Common.UseAtIdSupplement)
8989 int bCnt = AtIdSupl.ItemCount;
8990 foreach (Match mid in m)
8992 AtIdSupl.AddItem(mid.Result("${id}"));
8994 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
8997 // リプライ先ステータスIDの指定がない場合は指定しない
8998 if (this.inReplyTo == null)
9002 // 次の条件を満たす場合に in_reply_to_status_id 指定
9003 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9004 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9005 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9009 var inReplyToScreenName = this.inReplyTo.Item2;
9010 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9012 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9016 foreach (Match mid in m)
9018 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9023 this.inReplyTo = null;
9026 private void TweenMain_Resize(object sender, EventArgs e)
9028 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9030 this.Visible = false;
9032 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9034 // 現在の DPI と設定保存時の DPI との比を取得する
9035 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9037 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9038 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9039 this.DesktopLocation = SettingManager.Local.FormLocation;
9040 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9043 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9044 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9045 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9047 this.SplitContainer1.SplitterDistance = splitterDistance;
9051 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9052 if (StatusText.Multiline)
9054 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9055 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9056 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9058 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9060 StatusText.Height = statusTextHeight;
9064 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9066 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9070 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9071 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9073 this.SplitContainer3.SplitterDistance = previewDistance;
9076 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9077 this.SplitContainer3.Panel2Collapsed = true;
9079 _initialLayout = false;
9081 if (this.WindowState != FormWindowState.Minimized)
9083 _formWindowState = this.WindowState;
9087 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9089 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9090 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9091 if (PlaySoundMenuItem.Checked)
9093 SettingManager.Common.PlaySound = true;
9097 SettingManager.Common.PlaySound = false;
9099 ModifySettingCommon = true;
9102 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9104 if (this._initialLayout)
9107 int splitterDistance;
9108 switch (this.WindowState)
9110 case FormWindowState.Normal:
9111 splitterDistance = this.SplitContainer1.SplitterDistance;
9113 case FormWindowState.Maximized:
9114 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9115 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9116 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9117 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9123 this._mySpDis = splitterDistance;
9124 this.ModifySettingLocal = true;
9127 private async Task doRepliedStatusOpen()
9129 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9131 if (MyCommon.IsKeyDown(Keys.Shift))
9133 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9136 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9138 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9139 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9143 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9145 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9146 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9147 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9150 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9155 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9157 await this.doRepliedStatusOpen();
9160 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9162 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9163 if (multiline != this.StatusText.Multiline)
9165 this.StatusText.Multiline = multiline;
9166 MultiLineMenuItem.Checked = multiline;
9167 ModifySettingLocal = true;
9171 private void StatusText_MultilineChanged(object sender, EventArgs e)
9173 if (this.StatusText.Multiline)
9174 this.StatusText.ScrollBars = ScrollBars.Vertical;
9176 this.StatusText.ScrollBars = ScrollBars.None;
9178 ModifySettingLocal = true;
9181 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9184 StatusText.Multiline = MultiLineMenuItem.Checked;
9185 SettingManager.Local.StatusMultiline = MultiLineMenuItem.Checked;
9186 if (MultiLineMenuItem.Checked)
9188 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9189 SplitContainer2.SplitterDistance = 0;
9191 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9195 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9197 ModifySettingLocal = true;
9200 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9202 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9203 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9205 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9206 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9207 //Appendix A. Collected ABNF for URI
9208 //http://www.ietf.org/rfc/rfc3986.txt
9212 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9214 if (StatusText.SelectionLength > 0)
9216 string tmp = StatusText.SelectedText;
9217 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9218 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9220 // 文字列が選択されている場合はその文字列について処理
9222 //nico.ms使用、nicovideoにマッチしたら変換
9223 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9225 result = nicoms.Shorten(tmp);
9227 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9229 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9232 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9233 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9234 result = resultUri.AbsoluteUri;
9236 catch (WebApiException e)
9238 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9241 catch (UriFormatException e)
9243 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9252 if (!string.IsNullOrEmpty(result))
9254 urlUndo undotmp = new urlUndo();
9256 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9257 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9258 if (origUrlIndex == -1)
9261 StatusText.Select(origUrlIndex, tmp.Length);
9262 StatusText.SelectedText = result;
9265 undotmp.Before = tmp;
9266 undotmp.After = result;
9268 if (urlUndoBuffer == null)
9270 urlUndoBuffer = new List<urlUndo>();
9271 UrlUndoToolStripMenuItem.Enabled = true;
9274 urlUndoBuffer.Add(undotmp);
9280 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9281 @"(?<url>(?<protocol>https?://)" +
9282 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9283 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9284 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9285 // 正規表現にマッチしたURL文字列をtinyurl化
9286 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9288 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9289 string tmp = mt.Result("${url}");
9290 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9291 urlUndo undotmp = new urlUndo();
9294 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9296 //nico.ms使用、nicovideoにマッチしたら変換
9297 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9299 result = nicoms.Shorten(tmp);
9301 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9303 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9306 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9307 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9308 result = resultUri.AbsoluteUri;
9310 catch (HttpRequestException e)
9312 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9313 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9314 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9316 this.StatusLabel.Text = Converter_Type + ":" + message;
9319 catch (WebApiException e)
9321 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9324 catch (UriFormatException e)
9326 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9335 if (!string.IsNullOrEmpty(result))
9337 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9338 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9339 if (origUrlIndex == -1)
9342 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9343 StatusText.SelectedText = result;
9345 undotmp.Before = mt.Result("${url}");
9346 undotmp.After = result;
9348 if (urlUndoBuffer == null)
9350 urlUndoBuffer = new List<urlUndo>();
9351 UrlUndoToolStripMenuItem.Enabled = true;
9354 urlUndoBuffer.Add(undotmp);
9362 private void doUrlUndo()
9364 if (urlUndoBuffer != null)
9366 string tmp = StatusText.Text;
9367 foreach (urlUndo data in urlUndoBuffer)
9369 tmp = tmp.Replace(data.After, data.Before);
9371 StatusText.Text = tmp;
9372 urlUndoBuffer = null;
9373 UrlUndoToolStripMenuItem.Enabled = false;
9374 StatusText.SelectionStart = 0;
9375 StatusText.SelectionLength = 0;
9379 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9381 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9384 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9386 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9389 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9391 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9394 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9396 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9399 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9401 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9403 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9404 Random rnd = new Random();
9405 // 前回使用した短縮URLサービス以外を選択する
9408 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9410 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9411 await UrlConvertAsync(svc);
9415 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9420 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9422 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9423 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9424 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9425 ModifySettingCommon = true;
9428 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9430 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9431 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9432 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9433 ModifySettingCommon = true;
9436 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9438 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9439 MenuStrip1.Tag = new Object();
9440 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9443 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9445 if (this.Tag != null) // 設定された戻り先へ遷移
9447 if (this.Tag == this.ListTab.SelectedTab)
9448 ((Control)this.ListTab.SelectedTab.Tag).Select();
9450 ((Control)this.Tag).Select();
9452 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9454 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9456 this.Tag = ListTab.SelectedTab.Tag;
9457 ((Control)this.Tag).Select();
9460 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9461 MenuStrip1.Tag = null;
9464 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9466 DetailsListView lst = (DetailsListView)sender;
9467 if (SettingManager.Local == null) return;
9471 SettingManager.Local.Width1 = lst.Columns[0].Width;
9472 SettingManager.Local.Width3 = lst.Columns[1].Width;
9476 int[] darr = new int[lst.Columns.Count];
9477 for (int i = 0; i < lst.Columns.Count; i++)
9479 darr[lst.Columns[i].DisplayIndex] = i;
9481 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9483 for (int i = 0; i < lst.Columns.Count; i++)
9488 SettingManager.Local.DisplayIndex1 = i;
9491 SettingManager.Local.DisplayIndex2 = i;
9494 SettingManager.Local.DisplayIndex3 = i;
9497 SettingManager.Local.DisplayIndex4 = i;
9500 SettingManager.Local.DisplayIndex5 = i;
9503 SettingManager.Local.DisplayIndex6 = i;
9506 SettingManager.Local.DisplayIndex7 = i;
9509 SettingManager.Local.DisplayIndex8 = i;
9513 SettingManager.Local.Width1 = lst.Columns[0].Width;
9514 SettingManager.Local.Width2 = lst.Columns[1].Width;
9515 SettingManager.Local.Width3 = lst.Columns[2].Width;
9516 SettingManager.Local.Width4 = lst.Columns[3].Width;
9517 SettingManager.Local.Width5 = lst.Columns[4].Width;
9518 SettingManager.Local.Width6 = lst.Columns[5].Width;
9519 SettingManager.Local.Width7 = lst.Columns[6].Width;
9520 SettingManager.Local.Width8 = lst.Columns[7].Width;
9522 ModifySettingLocal = true;
9523 _isColumnChanged = true;
9526 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9528 DetailsListView lst = (DetailsListView)sender;
9529 if (SettingManager.Local == null) return;
9532 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9534 SettingManager.Local.Width1 = lst.Columns[0].Width;
9535 ModifySettingLocal = true;
9536 _isColumnChanged = true;
9538 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9540 SettingManager.Local.Width3 = lst.Columns[1].Width;
9541 ModifySettingLocal = true;
9542 _isColumnChanged = true;
9547 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9549 SettingManager.Local.Width1 = lst.Columns[0].Width;
9550 ModifySettingLocal = true;
9551 _isColumnChanged = true;
9553 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9555 SettingManager.Local.Width2 = lst.Columns[1].Width;
9556 ModifySettingLocal = true;
9557 _isColumnChanged = true;
9559 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9561 SettingManager.Local.Width3 = lst.Columns[2].Width;
9562 ModifySettingLocal = true;
9563 _isColumnChanged = true;
9565 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9567 SettingManager.Local.Width4 = lst.Columns[3].Width;
9568 ModifySettingLocal = true;
9569 _isColumnChanged = true;
9571 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9573 SettingManager.Local.Width5 = lst.Columns[4].Width;
9574 ModifySettingLocal = true;
9575 _isColumnChanged = true;
9577 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9579 SettingManager.Local.Width6 = lst.Columns[5].Width;
9580 ModifySettingLocal = true;
9581 _isColumnChanged = true;
9583 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9585 SettingManager.Local.Width7 = lst.Columns[6].Width;
9586 ModifySettingLocal = true;
9587 _isColumnChanged = true;
9589 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9591 SettingManager.Local.Width8 = lst.Columns[7].Width;
9592 ModifySettingLocal = true;
9593 _isColumnChanged = true;
9596 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9599 // SaveConfigsLocal();
9603 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9605 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9606 ModifySettingLocal = true;
9609 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9611 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9613 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9615 SelectMedia_DragDrop(e);
9618 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9620 var (url, title) = GetUrlFromDataObject(e.Data);
9626 appendText = title + " " + url;
9628 if (this.StatusText.TextLength == 0)
9629 this.StatusText.Text = appendText;
9631 this.StatusText.Text += " " + appendText;
9633 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9635 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9637 this.StatusText.Text += text;
9639 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9641 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9642 if (data != null) StatusText.Text += data;
9647 /// IDataObject から URL とタイトルの対を取得します
9650 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9652 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9653 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9654 internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9656 if (data.GetDataPresent("text/x-moz-url"))
9658 // Firefox, Google Chrome で利用可能
9659 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9661 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9663 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9664 if (lines.Length < 2)
9665 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9667 return (lines[0], lines[1]);
9670 else if (data.GetDataPresent("IESiteModeToUrl"))
9672 // Internet Exproler 用
9673 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9675 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9677 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9678 if (lines.Length < 2)
9679 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9681 return (lines[0], lines[1]);
9684 else if (data.GetDataPresent("UniformResourceLocatorW"))
9688 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9690 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9695 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9698 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9700 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9702 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9704 SelectMedia_DragEnter(e);
9708 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9710 e.Effect = DragDropEffects.Copy;
9713 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9715 e.Effect = DragDropEffects.Copy;
9718 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9720 e.Effect = DragDropEffects.Copy;
9724 e.Effect = DragDropEffects.None;
9727 private void TweenMain_DragOver(object sender, DragEventArgs e)
9731 public bool IsNetworkAvailable()
9734 nw = MyCommon.IsNetworkAvailable();
9735 _myStatusOnline = nw;
9739 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9741 var uriStr = uri.AbsoluteUri;
9743 // OpenTween 内部で使用する URL
9744 if (uri.Authority == "opentween")
9746 await this.OpenInternalUriAsync(uri);
9750 // ハッシュタグを含む Twitter 検索
9751 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9754 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9755 var pos = unescapedQuery.IndexOf('#');
9756 if (pos == -1) return;
9758 var hash = unescapedQuery.Substring(pos);
9759 this.HashSupl.AddItem(hash);
9760 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9761 this.AddNewTabForSearch(hash);
9766 // フラグが立っている場合は設定と逆の動作をする
9767 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9768 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9770 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9771 if (userUriMatch.Success)
9773 var screenName = userUriMatch.Groups["ScreenName"].Value;
9774 if (this.IsTwitterId(screenName))
9776 this.AddNewTabForUserTimeline(screenName);
9783 await this.OpenUriInBrowserAsync(uriStr);
9787 /// OpenTween 内部の機能を呼び出すための URL を開きます
9789 private async Task OpenInternalUriAsync(Uri uri)
9791 // ツイートを開く (//opentween/status/:status_id)
9792 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9795 var statusId = long.Parse(match.Groups[1].Value);
9796 await this.OpenRelatedTab(statusId);
9801 public Task OpenUriInBrowserAsync(string UriString)
9803 return Task.Run(() =>
9805 string myPath = UriString;
9809 var configBrowserPath = SettingManager.Local.BrowserPath;
9810 if (!string.IsNullOrEmpty(configBrowserPath))
9812 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9814 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9815 string browserPath = configBrowserPath.Substring(1, sep - 1);
9817 if (sep < configBrowserPath.Length - 1)
9819 arg = configBrowserPath.Substring(sep + 1);
9821 myPath = arg + " " + myPath;
9822 System.Diagnostics.Process.Start(browserPath, myPath);
9826 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9831 System.Diagnostics.Process.Start(myPath);
9836 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9841 private void ListTabSelect(TabPage _tab)
9845 this.PurgeListViewItemCache();
9848 _curList = (DetailsListView)_tab.Tag;
9850 if (_curList.SelectedIndices.Count > 0)
9852 _curItemIndex = _curList.SelectedIndices[0];
9853 _curPost = GetCurTabPost(_curItemIndex);
9862 _anchorFlag = false;
9866 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9870 for (int i = 0; i < _curList.Columns.Count; i++)
9872 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9877 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9879 ListTabSelect(e.TabPage);
9882 private void SelectListItem(DetailsListView LView, int Index)
9885 Rectangle bnd = new Rectangle();
9887 var item = LView.FocusedItem;
9896 LView.SelectedIndices.Clear();
9898 while (LView.SelectedIndices.Count > 0);
9899 item = LView.Items[Index];
9900 item.Selected = true;
9901 item.Focused = true;
9903 if (flg) LView.Invalidate(bnd);
9906 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9909 Rectangle bnd = new Rectangle();
9911 var item = LView.FocusedItem;
9922 LView.SelectedIndices.Clear();
9924 while (LView.SelectedIndices.Count > 0);
9925 LView.SelectItems(Index);
9927 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9929 LView.SelectionMark = selectionMarkIndex;
9931 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9933 LView.Items[focusedIndex].Focused = true;
9935 else if (Index != null && Index.Length != 0)
9937 LView.Items[Index.Last()].Focused = true;
9940 if (flg) LView.Invalidate(bnd);
9943 private void StartUserStream()
9945 tw.NewPostFromStream += tw_NewPostFromStream;
9946 tw.UserStreamStarted += tw_UserStreamStarted;
9947 tw.UserStreamStopped += tw_UserStreamStopped;
9948 tw.PostDeleted += tw_PostDeleted;
9949 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9951 this.RefreshUserStreamsMenu();
9953 if (SettingManager.Common.UserstreamStartup)
9954 tw.StartUserStream();
9957 private async void TweenMain_Shown(object sender, EventArgs e)
9959 NotifyIcon1.Visible = true;
9961 if (this.IsNetworkAvailable())
9965 var loadTasks = new List<Task>
9967 this.RefreshMuteUserIdsAsync(),
9968 this.RefreshBlockIdsAsync(),
9969 this.RefreshNoRetweetIdsAsync(),
9970 this.RefreshTwitterConfigurationAsync(),
9971 this.GetHomeTimelineAsync(),
9972 this.GetReplyAsync(),
9973 this.GetDirectMessagesAsync(),
9974 this.GetPublicSearchAllAsync(),
9975 this.GetUserTimelineAllAsync(),
9976 this.GetListTimelineAllAsync(),
9979 if (SettingManager.Common.StartupFollowers)
9980 loadTasks.Add(this.RefreshFollowerIdsAsync());
9982 if (SettingManager.Common.GetFav)
9983 loadTasks.Add(this.GetFavoritesAsync());
9985 var allTasks = Task.WhenAll(loadTasks);
9990 var timeout = Task.Delay(5000);
9991 if (await Task.WhenAny(allTasks, timeout) != timeout)
9995 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9997 if (MyCommon._endingFlag)
10001 if (MyCommon._endingFlag) return;
10003 if (ApplicationSettings.VersionInfoUrl != null)
10005 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10006 if (SettingManager.Common.StartupVersion)
10007 await this.CheckNewVersion(true);
10011 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10012 this.VerUpMenuItem.Enabled = false;
10013 this.VerUpMenuItem.Available = false;
10014 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10017 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10018 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10020 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10021 SettingStripMenuItem_Click(null, null);
10025 var reloadTasks = new List<Task>();
10027 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10028 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10030 if (!tw.GetNoRetweetSuccess)
10031 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10033 if (this.tw.Configuration.PhotoSizeLimit == 0)
10034 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10036 await Task.WhenAll(reloadTasks);
10041 TimerTimeline.Enabled = true;
10044 private async Task doGetFollowersMenu()
10046 await this.RefreshFollowerIdsAsync();
10047 await this.DispSelectedPost(true);
10050 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10052 await this.doGetFollowersMenu();
10055 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10057 doReTweetUnofficial();
10060 private async Task doReTweetOfficial(bool isConfirm)
10063 if (this.ExistCurrentPost)
10065 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10067 if (this._curPost.IsProtect)
10068 MessageBox.Show("Protected.");
10070 _DoFavRetweetFlags = false;
10073 if (_curList.SelectedIndices.Count > 15)
10075 MessageBox.Show(Properties.Resources.RetweetLimitText);
10076 _DoFavRetweetFlags = false;
10079 else if (_curList.SelectedIndices.Count > 1)
10081 string QuestionText = Properties.Resources.RetweetQuestion2;
10082 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10083 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10085 case DialogResult.Cancel:
10086 case DialogResult.No:
10087 _DoFavRetweetFlags = false;
10093 if (!SettingManager.Common.RetweetNoConfirm)
10095 string Questiontext = Properties.Resources.RetweetQuestion1;
10096 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10097 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10099 _DoFavRetweetFlags = false;
10105 var statusIds = new List<long>();
10106 foreach (int idx in _curList.SelectedIndices)
10108 PostClass post = GetCurTabPost(idx);
10109 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10110 statusIds.Add(post.StatusId);
10113 await this.RetweetAsync(statusIds);
10117 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10119 await this.doReTweetOfficial(true);
10122 private async Task FavoritesRetweetOfficial()
10124 if (!this.ExistCurrentPost) return;
10125 _DoFavRetweetFlags = true;
10126 var retweetTask = this.doReTweetOfficial(true);
10127 if (_DoFavRetweetFlags)
10129 _DoFavRetweetFlags = false;
10130 var favoriteTask = this.FavoriteChange(true, false);
10132 await Task.WhenAll(retweetTask, favoriteTask);
10140 private async Task FavoritesRetweetUnofficial()
10142 if (this.ExistCurrentPost && !_curPost.IsDm)
10144 _DoFavRetweetFlags = true;
10145 var favoriteTask = this.FavoriteChange(true);
10146 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10148 _DoFavRetweetFlags = false;
10149 doReTweetUnofficial();
10152 await favoriteTask;
10157 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10159 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10160 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10161 /// <returns>復元されたツイート本文</returns>
10162 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10164 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10167 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10169 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10171 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10175 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10177 statusHtml = statusHtml.Replace("<br>", " ");
10179 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10180 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10181 statusHtml = statusHtml.Replace(" ", " ");
10183 return WebUtility.HtmlDecode(statusHtml);
10186 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10188 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10190 if (_curPost != null)
10191 await this.DispSelectedPost(true);
10194 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10196 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10197 DebugModeToolStripMenuItem.Visible = true;
10199 DebugModeToolStripMenuItem.Visible = false;
10202 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10204 SettingManager.Common.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10207 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10209 ToolStripMenuItemUrlAutoShorten.Checked = SettingManager.Common.UrlConvertAuto;
10212 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10214 if (TraceOutToolStripMenuItem.Checked)
10215 MyCommon.TraceFlag = true;
10217 MyCommon.TraceFlag = false;
10220 private void TweenMain_Deactivate(object sender, EventArgs e)
10222 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10223 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10226 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10228 if (string.IsNullOrEmpty(_rclickTabName)) return;
10230 TabRename(_rclickTabName, out var _);
10233 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10235 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10238 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10240 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10243 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10245 TwitterApiStatus apiStatus;
10247 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10249 var cancellationToken = dialog.EnableCancellation();
10253 var task = this.tw.GetInfoApi();
10254 apiStatus = await dialog.WaitForAsync(this, task);
10256 catch (WebApiException)
10261 if (cancellationToken.IsCancellationRequested)
10264 if (apiStatus == null)
10266 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10271 using (var apiDlg = new ApiInfoDialog())
10273 apiDlg.ShowDialog(this);
10277 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10279 var id = _curPost?.ScreenName ?? "";
10281 await this.FollowCommand(id);
10284 internal async Task FollowCommand(string id)
10286 using (var inputName = new InputTabName())
10288 inputName.FormTitle = "Follow";
10289 inputName.FormDescription = Properties.Resources.FRMessage1;
10290 inputName.TabName = id;
10292 if (inputName.ShowDialog(this) != DialogResult.OK)
10294 if (string.IsNullOrWhiteSpace(inputName.TabName))
10297 id = inputName.TabName.Trim();
10300 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10304 var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10305 await dialog.WaitForAsync(this, task);
10307 catch (WebApiException ex)
10309 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10314 MessageBox.Show(Properties.Resources.FRMessage3);
10317 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10319 var id = _curPost?.ScreenName ?? "";
10321 await this.RemoveCommand(id, false);
10324 internal async Task RemoveCommand(string id, bool skipInput)
10328 using (var inputName = new InputTabName())
10330 inputName.FormTitle = "Unfollow";
10331 inputName.FormDescription = Properties.Resources.FRMessage1;
10332 inputName.TabName = id;
10334 if (inputName.ShowDialog(this) != DialogResult.OK)
10336 if (string.IsNullOrWhiteSpace(inputName.TabName))
10339 id = inputName.TabName.Trim();
10343 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10347 var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10348 await dialog.WaitForAsync(this, task);
10350 catch (WebApiException ex)
10352 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10357 MessageBox.Show(Properties.Resources.FRMessage3);
10360 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10362 var id = _curPost?.ScreenName ?? "";
10364 await this.ShowFriendship(id);
10367 internal async Task ShowFriendship(string id)
10369 using (var inputName = new InputTabName())
10371 inputName.FormTitle = "Show Friendships";
10372 inputName.FormDescription = Properties.Resources.FRMessage1;
10373 inputName.TabName = id;
10375 if (inputName.ShowDialog(this) != DialogResult.OK)
10377 if (string.IsNullOrWhiteSpace(inputName.TabName))
10380 id = inputName.TabName.Trim();
10383 bool isFollowing, isFollowed;
10385 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10387 var cancellationToken = dialog.EnableCancellation();
10391 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10392 var friendship = await dialog.WaitForAsync(this, task);
10394 isFollowing = friendship.Relationship.Source.Following;
10395 isFollowed = friendship.Relationship.Source.FollowedBy;
10397 catch (WebApiException ex)
10399 if (!cancellationToken.IsCancellationRequested)
10400 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10404 if (cancellationToken.IsCancellationRequested)
10408 string result = "";
10411 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10415 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10419 result += Properties.Resources.GetFriendshipInfo3;
10423 result += Properties.Resources.GetFriendshipInfo4;
10425 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10426 MessageBox.Show(result);
10429 internal async Task ShowFriendship(string[] ids)
10431 foreach (string id in ids)
10433 bool isFollowing, isFollowed;
10435 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10437 var cancellationToken = dialog.EnableCancellation();
10441 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10442 var friendship = await dialog.WaitForAsync(this, task);
10444 isFollowing = friendship.Relationship.Source.Following;
10445 isFollowed = friendship.Relationship.Source.FollowedBy;
10447 catch (WebApiException ex)
10449 if (!cancellationToken.IsCancellationRequested)
10450 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10454 if (cancellationToken.IsCancellationRequested)
10458 string result = "";
10464 ff += Properties.Resources.GetFriendshipInfo1;
10468 ff += Properties.Resources.GetFriendshipInfo2;
10471 ff += System.Environment.NewLine + " ";
10474 ff += Properties.Resources.GetFriendshipInfo3;
10478 ff += Properties.Resources.GetFriendshipInfo4;
10480 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10483 if (MessageBox.Show(
10484 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10485 MessageBoxButtons.YesNo,
10486 MessageBoxIcon.Question,
10487 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10489 await this.RemoveCommand(id, true);
10494 MessageBox.Show(result);
10499 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10501 await this.doShowUserStatus(tw.Username, false);
10502 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10504 // doShowUserStatus(tw.Username, false);
10508 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10513 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10514 // URLから切り出した文字列を渡す
10516 public bool IsTwitterId(string name)
10518 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10519 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10521 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10524 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10526 ModifySettingCommon = true;
10529 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10531 ModifySettingCommon = true;
10534 private void doQuoteOfficial()
10536 if (this.ExistCurrentPost)
10538 if (_curPost.IsDm ||
10539 !StatusText.Enabled) return;
10541 if (_curPost.IsProtect)
10543 MessageBox.Show("Protected.");
10547 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10549 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10551 this.inReplyTo = null;
10553 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10554 StatusText.Focus();
10558 private void doReTweetUnofficial()
10561 if (this.ExistCurrentPost)
10563 if (_curPost.IsDm || !StatusText.Enabled)
10566 if (_curPost.IsProtect)
10568 MessageBox.Show("Protected.");
10571 string rtdata = _curPost.Text;
10572 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10574 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10576 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10578 // 投稿時に in_reply_to_status_id を付加する
10579 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10580 var inReplyToScreenName = this._curPost.ScreenName;
10581 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10583 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10584 StatusText.Focus();
10588 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10593 private void SearchButton_Click(object sender, EventArgs e)
10596 Control pnl = ((Control)sender).Parent;
10597 if (pnl == null) return;
10598 string tbName = pnl.Parent.Text;
10599 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10600 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10601 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10602 cmb.Text = cmb.Text.Trim();
10603 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10604 bool Quote = false;
10605 StringBuilder buf = new StringBuilder();
10606 char[] c = cmb.Text.ToCharArray();
10607 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10609 if (cnt > cmb.Text.Length - 4)
10611 buf.Append(cmb.Text.Substring(cnt));
10620 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10622 buf.Append(" OR ");
10627 buf.Append(c[cnt]);
10629 cmb.Text = buf.ToString();
10631 var listView = (DetailsListView)pnl.Parent.Tag;
10633 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10635 tb.SearchWords = cmb.Text;
10636 tb.SearchLang = cmbLang.Text;
10637 if (string.IsNullOrEmpty(cmb.Text))
10645 int idx = cmb.Items.IndexOf(tb.SearchWords);
10646 if (idx > -1) cmb.Items.RemoveAt(idx);
10647 cmb.Items.Insert(0, tb.SearchWords);
10648 cmb.Text = tb.SearchWords;
10650 this.PurgeListViewItemCache();
10651 listView.VirtualListSize = 0;
10652 _statuses.ClearTabIds(tbName);
10653 SaveConfigsTabs(); //検索条件の保存
10656 this.GetPublicSearchAsync(tb);
10660 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10663 await this.DoRefreshMore();
10667 /// 指定されたタブのListTabにおける位置を返します
10670 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10672 public int GetTabPageIndex(string tabName)
10675 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10677 if (tabPage.Text == tabName)
10686 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10688 if (_statuses.RemovedTab.Count == 0)
10690 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10695 DetailsListView listView = null;
10697 TabModel tb = _statuses.RemovedTab.Pop();
10698 if (tb.TabType == MyCommon.TabUsageType.Related)
10700 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10701 if (relatedTab != null)
10703 // 関連発言なら既存のタブを置き換える
10704 tb.TabName = relatedTab.TabName;
10705 this.ClearTab(tb.TabName, false);
10706 _statuses.Tabs[tb.TabName] = tb;
10708 for (int i = 0; i < ListTab.TabPages.Count; i++)
10710 var tabPage = ListTab.TabPages[i];
10711 if (tb.TabName == tabPage.Text)
10713 listView = (DetailsListView)tabPage.Tag;
10714 ListTab.SelectedIndex = i;
10721 const string TabName = "Related Tweets";
10722 string renamed = TabName;
10723 for (int i = 2; i <= 100; i++)
10725 if (!_statuses.ContainsTab(renamed)) break;
10726 renamed = TabName + i;
10728 tb.TabName = renamed;
10730 _statuses.AddTab(tb);
10731 AddNewTab(tb, startup: false);
10733 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10734 listView = (DetailsListView)tabPage.Tag;
10735 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10740 string renamed = tb.TabName;
10741 for (int i = 1; i < int.MaxValue; i++)
10743 if (!_statuses.ContainsTab(renamed)) break;
10744 renamed = tb.TabName + "(" + i + ")";
10746 tb.TabName = renamed;
10748 _statuses.AddTab(tb);
10749 AddNewTab(tb, startup: false);
10751 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10752 listView = (DetailsListView)tabPage.Tag;
10753 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10757 if (listView != null)
10759 using (ControlTransaction.Update(listView))
10761 listView.VirtualListSize = tb.AllCount;
10767 private async Task doMoveToRTHome()
10769 if (_curList.SelectedIndices.Count > 0)
10771 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10772 if (post.RetweetedId != null)
10774 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10779 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10781 await this.doMoveToRTHome();
10784 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10786 var screenName = this._curPost?.ScreenName;
10787 if (screenName != null)
10788 this.ListManageUserContext(screenName);
10791 public void ListManageUserContext(string screenName)
10793 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10795 listSelectForm.ShowDialog(this);
10799 private void SearchControls_Enter(object sender, EventArgs e)
10801 Control pnl = (Control)sender;
10802 foreach (Control ctl in pnl.Controls)
10804 ctl.TabStop = true;
10808 private void SearchControls_Leave(object sender, EventArgs e)
10810 Control pnl = (Control)sender;
10811 foreach (Control ctl in pnl.Controls)
10813 ctl.TabStop = false;
10817 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10819 if (ListTab.SelectedTab != null)
10821 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10822 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10826 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10828 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10831 private void HashManageMenuItem_Click(object sender, EventArgs e)
10833 DialogResult rslt = DialogResult.Cancel;
10836 rslt = HashMgr.ShowDialog();
10842 this.TopMost = SettingManager.Common.AlwaysTop;
10843 if (rslt == DialogResult.Cancel) return;
10844 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10846 HashStripSplitButton.Text = HashMgr.UseHash;
10847 HashToggleMenuItem.Checked = true;
10848 HashToggleToolStripMenuItem.Checked = true;
10852 HashStripSplitButton.Text = "#[-]";
10853 HashToggleMenuItem.Checked = false;
10854 HashToggleToolStripMenuItem.Checked = false;
10856 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10858 // int sidx = StatusText.SelectionStart;
10859 // string hash = HashMgr.UseHash + " ";
10862 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10863 // hash = " " + hash;
10865 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10866 // sidx += hash.Length;
10867 // StatusText.SelectionStart = sidx;
10868 // StatusText.Focus();
10870 ModifySettingCommon = true;
10871 this.StatusText_TextChanged(null, null);
10874 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10876 HashMgr.ToggleHash();
10877 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10879 HashStripSplitButton.Text = HashMgr.UseHash;
10880 HashToggleMenuItem.Checked = true;
10881 HashToggleToolStripMenuItem.Checked = true;
10885 HashStripSplitButton.Text = "#[-]";
10886 HashToggleMenuItem.Checked = false;
10887 HashToggleToolStripMenuItem.Checked = false;
10889 ModifySettingCommon = true;
10890 this.StatusText_TextChanged(null, null);
10893 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10895 HashToggleMenuItem_Click(null, null);
10898 public void SetPermanentHashtag(string hashtag)
10900 HashMgr.SetPermanentHash("#" + hashtag);
10901 HashStripSplitButton.Text = HashMgr.UseHash;
10902 HashToggleMenuItem.Checked = true;
10903 HashToggleToolStripMenuItem.Checked = true;
10905 ModifySettingCommon = true;
10908 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10910 if (ListTab.SelectedTab == null) return;
10911 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10912 if (!this.ExistCurrentPost)
10914 this.ReplyOpMenuItem.Enabled = false;
10915 this.ReplyAllOpMenuItem.Enabled = false;
10916 this.DmOpMenuItem.Enabled = false;
10917 this.ShowProfMenuItem.Enabled = false;
10918 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10919 this.ListManageMenuItem.Enabled = false;
10920 this.OpenFavOpMenuItem.Enabled = false;
10921 this.CreateTabRuleOpMenuItem.Enabled = false;
10922 this.CreateIdRuleOpMenuItem.Enabled = false;
10923 this.CreateSourceRuleOpMenuItem.Enabled = false;
10924 this.ReadOpMenuItem.Enabled = false;
10925 this.UnreadOpMenuItem.Enabled = false;
10929 this.ReplyOpMenuItem.Enabled = true;
10930 this.ReplyAllOpMenuItem.Enabled = true;
10931 this.DmOpMenuItem.Enabled = true;
10932 this.ShowProfMenuItem.Enabled = true;
10933 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10934 this.ListManageMenuItem.Enabled = true;
10935 this.OpenFavOpMenuItem.Enabled = true;
10936 this.CreateTabRuleOpMenuItem.Enabled = true;
10937 this.CreateIdRuleOpMenuItem.Enabled = true;
10938 this.CreateSourceRuleOpMenuItem.Enabled = true;
10939 this.ReadOpMenuItem.Enabled = true;
10940 this.UnreadOpMenuItem.Enabled = true;
10943 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10945 this.FavOpMenuItem.Enabled = false;
10946 this.UnFavOpMenuItem.Enabled = false;
10947 this.OpenStatusOpMenuItem.Enabled = false;
10948 this.OpenFavotterOpMenuItem.Enabled = false;
10949 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10950 this.RtOpMenuItem.Enabled = false;
10951 this.RtUnOpMenuItem.Enabled = false;
10952 this.QtOpMenuItem.Enabled = false;
10953 this.FavoriteRetweetMenuItem.Enabled = false;
10954 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10958 this.FavOpMenuItem.Enabled = true;
10959 this.UnFavOpMenuItem.Enabled = true;
10960 this.OpenStatusOpMenuItem.Enabled = true;
10961 this.OpenFavotterOpMenuItem.Enabled = true;
10962 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10964 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10966 this.RtOpMenuItem.Enabled = false;
10967 this.RtUnOpMenuItem.Enabled = false;
10968 this.QtOpMenuItem.Enabled = false;
10969 this.FavoriteRetweetMenuItem.Enabled = false;
10970 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10974 this.RtOpMenuItem.Enabled = true;
10975 this.RtUnOpMenuItem.Enabled = true;
10976 this.QtOpMenuItem.Enabled = true;
10977 this.FavoriteRetweetMenuItem.Enabled = true;
10978 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10982 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
10984 this.RefreshPrevOpMenuItem.Enabled = true;
10988 this.RefreshPrevOpMenuItem.Enabled = false;
10990 if (!this.ExistCurrentPost
10991 || _curPost.InReplyToStatusId == null)
10993 OpenRepSourceOpMenuItem.Enabled = false;
10997 OpenRepSourceOpMenuItem.Enabled = true;
10999 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11001 OpenRterHomeMenuItem.Enabled = false;
11005 OpenRterHomeMenuItem.Enabled = true;
11008 if (this.ExistCurrentPost)
11010 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11014 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11016 ContextMenuTabProperty_Opening(sender, null);
11019 public Twitter TwitterInstance
11024 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11026 if (this._initialLayout)
11029 int splitterDistance;
11030 switch (this.WindowState)
11032 case FormWindowState.Normal:
11033 splitterDistance = this.SplitContainer3.SplitterDistance;
11035 case FormWindowState.Maximized:
11036 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11037 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11038 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11039 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11045 this._mySpDis3 = splitterDistance;
11046 this.ModifySettingLocal = true;
11049 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11051 if (_statuses.RemovedTab.Count == 0)
11053 UndoRemoveTabMenuItem.Enabled = false;
11057 UndoRemoveTabMenuItem.Enabled = true;
11059 if (ListTab.SelectedTab != null)
11061 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11062 PublicSearchQueryMenuItem.Enabled = true;
11064 PublicSearchQueryMenuItem.Enabled = false;
11068 PublicSearchQueryMenuItem.Enabled = false;
11070 if (!this.ExistCurrentPost)
11072 this.CopySTOTMenuItem.Enabled = false;
11073 this.CopyURLMenuItem.Enabled = false;
11074 this.CopyUserIdStripMenuItem.Enabled = false;
11078 this.CopySTOTMenuItem.Enabled = true;
11079 this.CopyURLMenuItem.Enabled = true;
11080 this.CopyUserIdStripMenuItem.Enabled = true;
11081 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11082 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11086 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11088 SetNotifyIconText();
11091 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11093 var id = _curPost?.ScreenName ?? "";
11095 await this.ShowUserStatus(id);
11098 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11100 TwitterUser user = null;
11102 if (ShowInputDialog)
11104 using (var inputName = new InputTabName())
11106 inputName.FormTitle = "Show UserStatus";
11107 inputName.FormDescription = Properties.Resources.FRMessage1;
11108 inputName.TabName = id;
11110 if (inputName.ShowDialog(this) != DialogResult.OK)
11112 if (string.IsNullOrWhiteSpace(inputName.TabName))
11115 id = inputName.TabName.Trim();
11119 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11121 var cancellationToken = dialog.EnableCancellation();
11125 var task = this.twitterApi.UsersShow(id);
11126 user = await dialog.WaitForAsync(this, task);
11128 catch (WebApiException ex)
11130 if (!cancellationToken.IsCancellationRequested)
11131 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11135 if (cancellationToken.IsCancellationRequested)
11139 await this.doShowUserStatus(user);
11142 private async Task doShowUserStatus(TwitterUser user)
11144 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11146 var showUserTask = userDialog.ShowUserAsync(user);
11147 userDialog.ShowDialog(this);
11150 this.BringToFront();
11152 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11153 await showUserTask;
11157 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11159 return this.doShowUserStatus(id, ShowInputDialog);
11162 internal Task ShowUserStatus(string id)
11164 return this.doShowUserStatus(id, true);
11167 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11169 if (_curPost != null)
11171 await this.ShowUserStatus(_curPost.ScreenName, false);
11175 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11177 if (!this.ExistCurrentPost)
11180 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11181 TwitterStatus status;
11183 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11185 var cancellationToken = dialog.EnableCancellation();
11189 var task = this.twitterApi.StatusesShow(statusId);
11190 status = await dialog.WaitForAsync(this, task);
11192 catch (WebApiException ex)
11194 if (!cancellationToken.IsCancellationRequested)
11195 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11199 if (cancellationToken.IsCancellationRequested)
11203 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11206 private HookGlobalHotkey _hookGlobalHotkey;
11209 _hookGlobalHotkey = new HookGlobalHotkey(this);
11211 // この呼び出しは、Windows フォーム デザイナで必要です。
11212 InitializeComponent();
11214 // InitializeComponent() 呼び出しの後で初期化を追加します。
11216 if (!this.DesignMode)
11218 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11219 this.StatusText.Dock = DockStyle.Fill;
11222 this.tweetDetailsView.Owner = this;
11224 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11225 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11226 this.gh.NotifyClicked += GrowlHelper_Callback;
11228 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11229 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11231 this.ImageSelector.Visible = false;
11232 this.ImageSelector.Enabled = false;
11233 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11235 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11237 this.ReplaceAppName();
11238 this.InitializeShortcuts();
11241 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11243 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11246 this.Visible = false;
11248 else if (Form.ActiveForm == null)
11250 this.Visible = true;
11251 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11253 this.BringToFront();
11254 this.StatusText.Focus();
11258 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11260 this.MultiLineMenuItem.PerformClick();
11263 public PostClass CurPost
11265 get { return _curPost; }
11269 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11271 if (ImageSelector.Visible)
11272 ImageSelector.EndSelection();
11274 ImageSelector.BeginSelection();
11277 private void SelectMedia_DragEnter(DragEventArgs e)
11279 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11281 e.Effect = DragDropEffects.Copy;
11284 e.Effect = DragDropEffects.None;
11287 private void SelectMedia_DragDrop(DragEventArgs e)
11290 this.BringToFront();
11291 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11292 StatusText.Focus();
11295 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11297 TimelinePanel.Visible = false;
11298 TimelinePanel.Enabled = false;
11301 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11303 TimelinePanel.Visible = true;
11304 TimelinePanel.Enabled = true;
11305 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11308 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11310 this.AllowDrop = false;
11313 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11315 this.AllowDrop = true;
11318 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11320 if (ImageSelector.Visible)
11322 ModifySettingCommon = true;
11323 SaveConfigsAll(true);
11325 this.StatusText_TextChanged(null, null);
11329 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11331 this.StatusText_TextChanged(null, null);
11335 /// StatusTextでCtrl+Vが押下された時の処理
11337 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11341 if (Clipboard.ContainsText())
11343 // clipboardにテキストがある場合は貼り付け処理
11344 this.StatusText.Paste(Clipboard.GetText());
11346 else if (Clipboard.ContainsImage())
11349 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11350 Properties.Resources.PostPictureWarn4,
11351 MessageBoxButtons.OKCancel,
11352 MessageBoxIcon.Question,
11353 MessageBoxDefaultButton.Button2)
11354 == DialogResult.OK)
11356 // clipboardから画像を取得
11357 using (var image = Clipboard.GetImage())
11359 this.ImageSelector.BeginSelection(image);
11364 catch (ExternalException ex)
11366 MessageBox.Show(ex.Message);
11371 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11373 using (ListManage form = new ListManage(tw))
11375 form.ShowDialog(this);
11379 public bool ModifySettingCommon { get; set; }
11380 public bool ModifySettingLocal { get; set; }
11381 public bool ModifySettingAtId { get; set; }
11383 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11385 if (this.ExistCurrentPost && !_curPost.IsDm)
11386 RtCountMenuItem.Enabled = true;
11388 RtCountMenuItem.Enabled = false;
11390 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11391 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11393 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11396 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11401 private void CopyUserId()
11403 if (_curPost == null) return;
11404 string clstr = _curPost.ScreenName;
11407 Clipboard.SetDataObject(clstr, false, 5, 100);
11409 catch (Exception ex)
11411 MessageBox.Show(ex.Message);
11415 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11417 if (this.ExistCurrentPost && !_curPost.IsDm)
11421 await this.OpenRelatedTab(this._curPost);
11423 catch (TabException ex)
11425 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11431 /// 指定されたツイートに対する関連発言タブを開きます
11433 /// <param name="statusId">表示するツイートのID</param>
11434 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11435 private async Task OpenRelatedTab(long statusId)
11437 var post = this._statuses[statusId];
11442 post = await this.tw.GetStatusApi(false, statusId);
11444 catch (WebApiException ex)
11446 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11451 await this.OpenRelatedTab(post);
11455 /// 指定されたツイートに対する関連発言タブを開きます
11457 /// <param name="post">表示する対象となるツイート</param>
11458 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11459 private async Task OpenRelatedTab(PostClass post)
11461 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11462 if (tabRelated != null)
11464 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11467 var tabName = this._statuses.MakeTabName("Related Tweets");
11469 tabRelated = new RelatedPostsTabModel(tabName, post);
11470 tabRelated.UnreadManage = false;
11471 tabRelated.Notify = false;
11473 this._statuses.AddTab(tabRelated);
11474 this.AddNewTab(tabRelated, startup: false);
11477 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11479 tabPage = this.ListTab.TabPages[i];
11480 if (tabName == tabPage.Text)
11482 this.ListTab.SelectedIndex = i;
11487 await this.GetRelatedTweetsAsync(tabRelated);
11489 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11490 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11492 if (tabPage != null)
11494 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11496 var listView = (DetailsListView)tabPage.Tag;
11497 var targetPost = tabRelated.TargetPost;
11498 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11500 if (index != -1 && index < listView.Items.Count)
11502 listView.SelectedIndices.Add(index);
11503 listView.Items[index].Focused = true;
11508 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11510 StringBuilder buf = new StringBuilder();
11511 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11512 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11513 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11514 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11515 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11518 private void tw_UserIdChanged()
11520 this.ModifySettingCommon = true;
11523 #region "Userstream"
11524 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11528 if (InvokeRequired && !IsDisposed)
11530 await this.InvokeAsync(async () =>
11532 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11533 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11535 this.PurgeListViewItemCache();
11536 ((DetailsListView)_curTab.Tag).Update();
11537 if (_curPost != null && _curPost.StatusId == e.StatusId)
11538 await this.DispSelectedPost(true);
11544 catch (ObjectDisposedException)
11548 catch (InvalidOperationException)
11554 private int userStreamsRefreshing = 0;
11556 private async void tw_NewPostFromStream(object sender, EventArgs e)
11558 if (SettingManager.Common.ReadOldPosts)
11560 _statuses.SetReadHomeTab(); //新着時未読クリア
11563 this._statuses.DistributePosts();
11565 if (SettingManager.Common.UserstreamPeriod > 0) return;
11567 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11568 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11572 await this.InvokeAsync(() => this.RefreshTimeline())
11573 .ConfigureAwait(false);
11577 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11582 private async void tw_UserStreamStarted(object sender, EventArgs e)
11586 if (InvokeRequired && !IsDisposed)
11588 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11592 catch (ObjectDisposedException)
11596 catch (InvalidOperationException)
11601 this.RefreshUserStreamsMenu();
11602 this.MenuItemUserStream.Enabled = true;
11604 StatusLabel.Text = "UserStream Started.";
11607 private async void tw_UserStreamStopped(object sender, EventArgs e)
11611 if (InvokeRequired && !IsDisposed)
11613 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11617 catch (ObjectDisposedException)
11621 catch (InvalidOperationException)
11626 this.RefreshUserStreamsMenu();
11627 this.MenuItemUserStream.Enabled = true;
11629 StatusLabel.Text = "UserStream Stopped.";
11632 private void RefreshUserStreamsMenu()
11634 if (this.tw.UserStreamActive)
11636 this.MenuItemUserStream.Text = "&UserStream ▶";
11637 this.StopToolStripMenuItem.Text = "&Stop";
11641 this.MenuItemUserStream.Text = "&UserStream ■";
11642 this.StopToolStripMenuItem.Text = "&Start";
11646 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11650 if (InvokeRequired && !IsDisposed)
11652 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11656 catch (ObjectDisposedException)
11660 catch (InvalidOperationException)
11664 var ev = e.EventData;
11665 StatusLabel.Text = "Event: " + ev.Event;
11666 //if (ev.Event == "favorite")
11668 // NotifyFavorite(ev);
11671 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11673 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11675 this.PurgeListViewItemCache();
11676 ((DetailsListView)_curTab.Tag).Update();
11678 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11680 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11681 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11686 private void NotifyEvent(Twitter.FormattedEvent ev)
11689 if (BalloonRequired(ev))
11691 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11692 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11693 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11694 StringBuilder title = new StringBuilder();
11695 if (SettingManager.Common.DispUsername)
11697 title.Append(tw.Username);
11698 title.Append(" - ");
11704 title.Append(Application.ProductName);
11705 title.Append(" [");
11706 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11707 title.Append("] by ");
11708 if (!string.IsNullOrEmpty(ev.Username))
11710 title.Append(ev.Username);
11714 //title.Append("");
11717 if (!string.IsNullOrEmpty(ev.Target))
11719 //NotifyIcon1.BalloonTipText = ev.Target;
11724 //NotifyIcon1.BalloonTipText = " ";
11727 //NotifyIcon1.ShowBalloonTip(500);
11728 if (SettingManager.Common.IsUseNotifyGrowl)
11730 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11731 ev.Id.ToString(), title.ToString(), text);
11735 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11736 NotifyIcon1.BalloonTipTitle = title.ToString();
11737 NotifyIcon1.BalloonTipText = text;
11738 NotifyIcon1.ShowBalloonTip(500);
11743 string snd = SettingManager.Common.EventSoundFile;
11744 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11746 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11750 string dir = Application.StartupPath;
11751 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11753 dir = Path.Combine(dir, "Sounds");
11755 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11767 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11769 MenuItemUserStream.Enabled = false;
11770 if (StopRefreshAllMenuItem.Checked)
11772 StopRefreshAllMenuItem.Checked = false;
11775 if (this.tw.UserStreamActive)
11777 tw.StopUserStream();
11781 tw.StartUserStream();
11785 private static string inputTrack = "";
11787 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11789 if (TrackToolStripMenuItem.Checked)
11791 using (InputTabName inputForm = new InputTabName())
11793 inputForm.TabName = inputTrack;
11794 inputForm.FormTitle = "Input track word";
11795 inputForm.FormDescription = "Track word";
11796 if (inputForm.ShowDialog() != DialogResult.OK)
11798 TrackToolStripMenuItem.Checked = false;
11801 inputTrack = inputForm.TabName.Trim();
11803 if (!inputTrack.Equals(tw.TrackWord))
11805 tw.TrackWord = inputTrack;
11806 this.ModifySettingCommon = true;
11807 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11808 tw.ReconnectUserStream();
11814 tw.ReconnectUserStream();
11816 this.ModifySettingCommon = true;
11819 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11821 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11822 this.ModifySettingCommon = true;
11823 tw.ReconnectUserStream();
11826 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11828 if (evtDialog == null || evtDialog.IsDisposed)
11831 evtDialog = new EventViewerDialog();
11832 evtDialog.Owner = this;
11834 Point pos = evtDialog.Location;
11835 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11836 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11837 evtDialog.Location = pos;
11839 evtDialog.EventSource = tw.StoredEvent;
11840 if (!evtDialog.Visible)
11842 evtDialog.Show(this);
11846 evtDialog.Activate();
11848 this.TopMost = SettingManager.Common.AlwaysTop;
11852 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11854 MyCommon._endingFlag = true;
11858 Application.Restart();
11862 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11866 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11868 if (!string.IsNullOrEmpty(tw.Username))
11869 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11872 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11874 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11877 private bool ExistCurrentPost
11881 if (_curPost == null) return false;
11882 if (_curPost.IsDeleted) return false;
11887 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11889 ShowUserTimeline();
11892 private string GetUserIdFromCurPostOrInput(string caption)
11894 var id = _curPost?.ScreenName ?? "";
11896 using (InputTabName inputName = new InputTabName())
11898 inputName.FormTitle = caption;
11899 inputName.FormDescription = Properties.Resources.FRMessage1;
11900 inputName.TabName = id;
11901 if (inputName.ShowDialog() == DialogResult.OK &&
11902 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11904 id = inputName.TabName.Trim();
11914 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11916 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11917 if (!string.IsNullOrEmpty(id))
11919 AddNewTabForUserTimeline(id);
11923 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11925 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11926 if (!string.IsNullOrEmpty(id))
11928 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11932 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11934 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11937 private void TimelineRefreshEnableChange(bool isEnable)
11941 tw.StartUserStream();
11945 tw.StopUserStream();
11947 TimerTimeline.Enabled = isEnable;
11950 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11952 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11955 private async Task OpenUserAppointUrl()
11957 if (SettingManager.Common.UserAppointUrl != null)
11959 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11961 if (_curPost != null)
11963 string xUrl = SettingManager.Common.UserAppointUrl;
11964 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11966 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11967 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11969 await this.OpenUriInBrowserAsync(xUrl);
11974 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11979 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11981 await this.OpenUserAppointUrl();
11984 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11986 if (Form.ActiveForm == null)
11988 await this.InvokeAsync(() =>
11990 this.Visible = true;
11991 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11993 this.BringToFront();
11994 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11996 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12000 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12006 private void ReplaceAppName()
12008 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12009 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12012 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12014 this.SplitContainer3.Panel2Collapsed = false;
12017 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12019 await this.OpenThumbnailPicture(e.Thumbnail);
12022 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12024 await this.OpenUriInBrowserAsync(e.ImageUrl);
12027 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12029 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12031 await this.OpenUriInBrowserAsync(url);
12034 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12036 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12039 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12041 if (e.KeyCode == Keys.Space)
12043 this.JumpUnreadMenuItem_Click(null, null);
12045 e.SuppressKeyPress = true;
12049 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12051 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12052 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12053 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12054 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12055 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12057 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12060 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12062 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12065 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12067 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12070 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12072 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12075 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12077 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12080 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12082 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12085 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12087 if (SettingManager.Common.IconSize == iconSize) return;
12089 var oldIconCol = _iconCol;
12091 SettingManager.Common.IconSize = iconSize;
12092 ApplyListViewIconSize(iconSize);
12094 if (_iconCol != oldIconCol)
12096 foreach (TabPage tp in ListTab.TabPages)
12098 ResetColumns((DetailsListView)tp.Tag);
12102 _curList?.Refresh();
12104 ModifySettingCommon = true;
12107 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12109 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12110 if (SettingManager.Common.SortOrderLock == state) return;
12112 SettingManager.Common.SortOrderLock = state;
12114 ModifySettingCommon = true;
12117 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12119 if (!string.IsNullOrEmpty(e.StatusText))
12121 this.StatusLabelUrl.Text = e.StatusText;
12125 this.SetStatusLabelUrl();