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.Thumbnail;
59 public partial class TweenMain : OTBaseForm
62 private Size _mySize; //画面サイズ
63 private Point _myLoc; //画面位置
64 private int _mySpDis; //区切り位置
65 private int _mySpDis2; //発言欄区切り位置
66 private int _mySpDis3; //プレビュー区切り位置
67 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
68 private bool _iconCol; //1列表示の時true(48サイズのとき)
71 private bool _initial; //true:起動時処理中
72 private bool _initialLayout = true;
73 private bool _ignoreConfigSave; //true:起動時処理中
74 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
75 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
76 private Point _tabMouseDownPoint;
77 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
78 private readonly object _syncObject = new object(); //ロック用
80 private const string detailHtmlFormatHeaderMono =
81 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
82 + "<style type=\"text/css\"><!-- "
83 + "body, p, pre {margin: 0;} "
84 + "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%);} "
85 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
86 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
87 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
88 + ".quote-tweet.reply {border-color: #f33;} "
89 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
91 + "</head><body><pre>";
92 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
93 private const string detailHtmlFormatHeaderColor =
94 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
95 + "<style type=\"text/css\"><!-- "
96 + "body, p, pre {margin: 0;} "
97 + "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%);} "
98 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
99 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
100 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
101 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
102 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
104 + "</head><body><p>";
105 private const string detailHtmlFormatFooterColor = "</p></body></html>";
106 private string detailHtmlFormatHeader;
107 private string detailHtmlFormatFooter;
109 private bool _myStatusError = false;
110 private bool _myStatusOnline = false;
111 private bool soundfileListup = false;
112 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
115 //private SettingToConfig _cfg; //旧
116 internal SettingLocal _cfgLocal;
117 private SettingCommon _cfgCommon;
120 private TwitterApi twitterApi = new TwitterApi();
124 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
127 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
128 private OpenURL UrlDialog = new OpenURL();
129 public AtIdSupplement AtIdSupl; //@id補助
130 public AtIdSupplement HashSupl; //Hashtag補助
131 public HashtagManage HashMgr;
132 private EventViewerDialog evtDialog;
135 private Font _fntUnread; //未読用フォント
136 private Color _clUnread; //未読用文字色
137 private Font _fntReaded; //既読用フォント
138 private Color _clReaded; //既読用文字色
139 private Color _clFav; //Fav用文字色
140 private Color _clOWL; //片思い用文字色
141 private Color _clRetweet; //Retweet用文字色
142 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
143 private Font _fntDetail; //発言詳細部用フォント
144 private Color _clDetail; //発言詳細部用色
145 private Color _clDetailLink; //発言詳細部用リンク文字色
146 private Color _clDetailBackcolor; //発言詳細部用背景色
147 private Color _clSelf; //自分の発言用背景色
148 private Color _clAtSelf; //自分宛返信用背景色
149 private Color _clTarget; //選択発言者の他の発言用背景色
150 private Color _clAtTarget; //選択発言中の返信先用背景色
151 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
152 private Color _clAtTo; //選択発言の唯一@先
153 private Color _clListBackcolor; //リスト部通常発言背景色
154 private Color _clInputBackcolor; //入力欄背景色
155 private Color _clInputFont; //入力欄文字色
156 private Font _fntInputFont; //入力欄フォント
157 private ImageCache IconCache; //アイコン画像リスト
158 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
159 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
160 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
161 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
162 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
163 private Icon MainIcon; //Main.ico 画面左上のアイコン
164 private Icon ReplyIcon; //5g
165 private Icon ReplyIconBlink; //6g
167 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
169 private PostClass _anchorPost;
170 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
172 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
173 private int _hisIdx; //発言履歴カレントインデックス
175 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
176 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
179 private List<DateTime> _postTimestamps = new List<DateTime>();
180 private List<DateTime> _favTimestamps = new List<DateTime>();
183 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
184 private SolidBrush _brsBackColorMine;
185 private SolidBrush _brsBackColorAt;
186 private SolidBrush _brsBackColorYou;
187 private SolidBrush _brsBackColorAtYou;
188 private SolidBrush _brsBackColorAtFromTarget;
189 private SolidBrush _brsBackColorAtTo;
190 private SolidBrush _brsBackColorNone;
191 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
192 private StringFormat sfTab = new StringFormat();
194 //////////////////////////////////////////////////////////////////////////////////////////////////////////
195 private TabInformations _statuses;
198 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
201 /// キャッシュクリアのために null が代入されることがあるため、
202 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
203 /// 一旦ローカル変数に代入してから参照すること。
205 private ListViewItemCache _listItemCache = null;
207 internal class ListViewItemCache
209 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
210 public ListView TargetList { get; set; }
212 /// <summary>キャッシュする範囲の開始インデックス</summary>
213 public int StartIndex { get; set; }
215 /// <summary>キャッシュする範囲の終了インデックス</summary>
216 public int EndIndex { get; set; }
218 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
219 public ListViewItem[] ListItem { get; set; }
221 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
222 public PostClass[] Post { get; set; }
224 /// <summary>キャッシュされたアイテムの件数</summary>
226 => this.EndIndex - this.StartIndex + 1;
228 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
229 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
230 public bool Contains(int index)
231 => index >= this.StartIndex && index <= this.EndIndex;
233 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
234 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
235 public bool IsSupersetOf(int rangeStart, int rangeEnd)
236 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
238 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
239 /// <returns>取得に成功すれば true、それ以外は false</returns>
240 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
242 if (this.Contains(index))
244 item = this.ListItem[index - this.StartIndex];
245 post = this.Post[index - this.StartIndex];
257 private TabPage _curTab;
258 private int _curItemIndex;
259 private DetailsListView _curList;
260 private PostClass _curPost;
261 private bool _isColumnChanged = false;
263 // 各タブの発言一覧のスクロール位置・選択状態を保持するフィールド
264 private IDictionary<string, ListViewScroll> listViewScroll = new Dictionary<string, ListViewScroll>();
265 private IDictionary<string, ListViewSelection> listViewSelection = new Dictionary<string, ListViewSelection>();
267 private const int MAX_WORKER_THREADS = 20;
268 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
269 private CancellationTokenSource workerCts = new CancellationTokenSource();
270 private IProgress<string> workerProgress;
272 private int UnreadCounter = -1;
273 private int UnreadAtCounter = -1;
275 private string[] ColumnOrgText = new string[9];
276 private string[] ColumnText = new string[9];
278 private bool _DoFavRetweetFlags = false;
279 private bool osResumed = false;
281 //////////////////////////////////////////////////////////////////////////////////////////////////////////
282 private bool _colorize = false;
284 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
286 private string recommendedStatusFooter;
289 private struct urlUndo
291 public string Before;
295 private List<urlUndo> urlUndoBuffer = null;
297 private struct ReplyChain
299 public long OriginalId;
300 public long InReplyToId;
301 public TabPage OriginalTab;
303 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
305 this.OriginalId = originalId;
306 this.InReplyToId = inReplyToId;
307 this.OriginalTab = originalTab;
311 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
312 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
315 internal enum SEARCHTYPE
322 private class PostingStatus
324 public string status = "";
325 public long? inReplyToId = null;
326 public string inReplyToName = null;
327 public string imageService = ""; //画像投稿サービス名
328 public IMediaItem[] mediaItems = null;
329 public PostingStatus()
332 public PostingStatus(string status, long? replyToId, string replyToName)
334 this.status = status;
335 this.inReplyToId = replyToId;
336 this.inReplyToName = replyToName;
340 private void TweenMain_Activated(object sender, EventArgs e)
342 //画面がアクティブになったら、発言欄の背景色戻す
343 if (StatusText.Focused)
345 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
349 private bool disposed = false;
352 /// 使用中のリソースをすべてクリーンアップします。
354 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
355 protected override void Dispose(bool disposing)
357 base.Dispose(disposing);
364 this.components?.Dispose();
367 SearchDialog.Dispose();
370 NIconAtRed?.Dispose();
371 NIconAtSmoke?.Dispose();
372 foreach (var iconRefresh in this.NIconRefresh)
374 iconRefresh?.Dispose();
378 ReplyIcon?.Dispose();
379 ReplyIconBlink?.Dispose();
380 _listViewImageList.Dispose();
381 _brsHighLight.Dispose();
382 _brsBackColorMine?.Dispose();
383 _brsBackColorAt?.Dispose();
384 _brsBackColorYou?.Dispose();
385 _brsBackColorAtYou?.Dispose();
386 _brsBackColorAtFromTarget?.Dispose();
387 _brsBackColorAtTo?.Dispose();
388 _brsBackColorNone?.Dispose();
389 _brsDeactiveSelection?.Dispose();
393 this.workerCts.Cancel();
395 if (IconCache != null)
397 this.IconCache.CancelAsync();
398 this.IconCache.Dispose();
401 this.thumbnailTokenSource?.Dispose();
404 this.twitterApi.Dispose();
405 this._hookGlobalHotkey.Dispose();
408 // 終了時にRemoveHandlerしておかないとメモリリークする
409 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
410 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
412 this.disposed = true;
415 private void LoadIcons()
417 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
418 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
421 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
424 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
427 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
430 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
432 // タスクトレイ: オフライン時アイコン
433 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
435 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
436 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
437 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
439 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
440 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
441 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
442 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
443 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
445 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
447 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
448 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
449 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
450 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
451 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
453 if (iconReply != null && iconReplyBlink != null)
455 this.ReplyIcon = iconReply;
456 this.ReplyIconBlink = iconReplyBlink;
460 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
461 this.ReplyIconBlink = this.NIconAt;
464 if (iconRefresh1 == null)
466 this.NIconRefresh = new[] {
467 Properties.Resources.Refresh, Properties.Resources.Refresh2,
468 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
471 else if (iconRefresh2 == null)
473 this.NIconRefresh = new[] { iconRefresh1 };
475 else if (iconRefresh3 == null)
477 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
479 else if (iconRefresh4 == null)
481 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
483 else // iconRefresh1 から iconRefresh4 まで全て揃っている
485 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
489 private Icon LoadIcon(string filePath)
491 if (!File.Exists(filePath))
496 return new Icon(filePath);
504 private void InitColumns(ListView list, bool startup)
506 this.InitColumnText();
508 ColumnHeader[] columns = null;
515 new ColumnHeader(), // アイコン
516 new ColumnHeader(), // 本文
519 columns[0].Text = this.ColumnText[0];
520 columns[1].Text = this.ColumnText[2];
524 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
526 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
527 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
528 columns[0].DisplayIndex = 0;
529 columns[1].DisplayIndex = 1;
534 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
536 columns[idx].Width = curListColumn.Width;
537 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
546 new ColumnHeader(), // アイコン
547 new ColumnHeader(), // ニックネーム
548 new ColumnHeader(), // 本文
549 new ColumnHeader(), // 日付
550 new ColumnHeader(), // ユーザID
551 new ColumnHeader(), // 未読
552 new ColumnHeader(), // マーク&プロテクト
553 new ColumnHeader(), // ソース
556 foreach (var i in Enumerable.Range(0, columns.Length))
557 columns[i].Text = this.ColumnText[i];
561 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
563 columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
564 columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
565 columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
566 columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
567 columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
568 columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
569 columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
570 columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
572 var displayIndex = new[] {
573 this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
574 this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
575 this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
576 this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
579 foreach (var i in Enumerable.Range(0, displayIndex.Length))
581 columns[i].DisplayIndex = displayIndex[i];
587 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
589 columns[idx].Width = curListColumn.Width;
590 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
596 list.Columns.AddRange(columns);
604 foreach (var column in columns)
610 private void InitColumnText()
613 ColumnText[1] = Properties.Resources.AddNewTabText2;
614 ColumnText[2] = Properties.Resources.AddNewTabText3;
615 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
616 ColumnText[4] = Properties.Resources.AddNewTabText5;
619 ColumnText[7] = "Source";
621 ColumnOrgText[0] = "";
622 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
623 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
624 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
625 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
626 ColumnOrgText[5] = "";
627 ColumnOrgText[6] = "";
628 ColumnOrgText[7] = "Source";
631 switch (_statuses.SortMode)
633 case ComparerMode.Nickname: //ニックネーム
636 case ComparerMode.Data: //本文
639 case ComparerMode.Id: //時刻=発言Id
642 case ComparerMode.Name: //名前
645 case ComparerMode.Source: //Source
652 if (_statuses.SortOrder == SortOrder.Descending)
654 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
655 ColumnText[2] = ColumnOrgText[2] + "▾";
659 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
660 ColumnText[2] = ColumnOrgText[2] + "▴";
665 if (_statuses.SortOrder == SortOrder.Descending)
667 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
668 ColumnText[c] = ColumnOrgText[c] + "▾";
672 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
673 ColumnText[c] = ColumnOrgText[c] + "▴";
678 private void InitializeTraceFrag()
681 TraceOutToolStripMenuItem.Checked = true;
682 MyCommon.TraceFlag = true;
684 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
686 TraceOutToolStripMenuItem.Checked = true;
687 MyCommon.TraceFlag = true;
691 private void TweenMain_Load(object sender, EventArgs e)
693 _ignoreConfigSave = true;
694 this.Visible = false;
696 if (MyApplication.StartupOptions.ContainsKey("d"))
697 MyCommon.TraceFlag = true;
699 InitializeTraceFrag();
701 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
703 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
704 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
706 Regex.CacheSize = 100;
709 _statuses = TabInformations.GetInstance();
713 this.Icon = MainIcon; //メインフォーム(TweenMain)
714 NotifyIcon1.Icon = NIconAt; //タスクトレイ
715 TabImage.Images.Add(TabIcon); //タブ見出し
717 //<<<<<<<<<設定関連>>>>>>>>>
721 // 現在の DPI と設定保存時の DPI との比を取得する
722 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
725 var fontUIGlobal = this._cfgLocal.FontUIGlobal;
726 if (fontUIGlobal != null)
728 OTBaseForm.GlobalFont = fontUIGlobal;
729 this.Font = fontUIGlobal;
733 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
735 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
736 this._cfgCommon.TimelinePeriod = 15;
738 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
739 this._cfgCommon.ReplyPeriod = 15;
741 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
742 this._cfgCommon.DMPeriod = 15;
744 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
745 this._cfgCommon.PubSearchPeriod = 30;
747 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
748 this._cfgCommon.UserTimelinePeriod = 15;
750 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
751 this._cfgCommon.ListsPeriod = 15;
754 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
755 this._cfgCommon.CountApi = 60;
756 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
757 this._cfgCommon.CountApiReply = 40;
759 if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
760 this._cfgCommon.MoreCountApi = 200;
761 if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
762 this._cfgCommon.FirstCountApi = 100;
764 if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
765 this._cfgCommon.FavoritesCountApi = 40;
766 if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
767 this._cfgCommon.ListCountApi = 100;
768 if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
769 this._cfgCommon.SearchCountApi = 100;
770 if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
771 this._cfgCommon.UserTimelineCountApi = 20;
773 //廃止サービスが選択されていた場合ux.nuへ読み替え
774 if (this._cfgCommon.AutoShortUrlFirst < 0)
775 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
777 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
778 this.tw = new Twitter(this.twitterApi);
781 if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
782 tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
786 Networking.Initialize();
788 bool saveRequired = false;
789 bool firstRun = false;
791 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
792 if (string.IsNullOrEmpty(tw.Username))
797 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
798 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
799 string.IsNullOrEmpty(tw.Username))
801 Application.Exit(); //強制終了
807 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
808 Networking.SetWebProxy(this._cfgLocal.ProxyType,
809 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
810 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
811 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
813 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
814 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
815 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
816 tw.TrackWord = this._cfgCommon.TrackWord;
817 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
818 tw.AllAtReply = this._cfgCommon.AllAtReply;
819 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
820 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
821 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
822 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
824 // アクセストークンが有効であるか確認する
825 // ここが Twitter API への最初のアクセスになるようにすること
828 this.tw.VerifyCredentials();
830 catch (WebApiException ex)
832 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
833 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
837 //プロキシ設定等の通信まわりの初期化が済んでから処理する
838 ThumbnailGenerator.InitializeGenerator();
840 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
841 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
842 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
844 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
847 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
850 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
851 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
852 HashMgr = new HashtagManage(HashSupl,
853 _cfgCommon.HashTags.ToArray(),
854 _cfgCommon.HashSelected,
855 _cfgCommon.HashIsPermanent,
856 _cfgCommon.HashIsHead,
857 _cfgCommon.HashIsNotAddToAtReply);
858 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
861 this.IconCache = new ImageCache();
862 this.tweetDetailsView.IconCache = this.IconCache;
865 _fntUnread = this._cfgLocal.FontUnread;
866 _clUnread = this._cfgLocal.ColorUnread;
867 _fntReaded = this._cfgLocal.FontRead;
868 _clReaded = this._cfgLocal.ColorRead;
869 _clFav = this._cfgLocal.ColorFav;
870 _clOWL = this._cfgLocal.ColorOWL;
871 _clRetweet = this._cfgLocal.ColorRetweet;
872 _fntDetail = this._cfgLocal.FontDetail;
873 _clDetail = this._cfgLocal.ColorDetail;
874 _clDetailLink = this._cfgLocal.ColorDetailLink;
875 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
876 _clSelf = this._cfgLocal.ColorSelf;
877 _clAtSelf = this._cfgLocal.ColorAtSelf;
878 _clTarget = this._cfgLocal.ColorTarget;
879 _clAtTarget = this._cfgLocal.ColorAtTarget;
880 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
881 _clAtTo = this._cfgLocal.ColorAtTo;
882 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
883 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
884 _clInputFont = this._cfgLocal.ColorInputFont;
885 _fntInputFont = this._cfgLocal.FontInputFont;
887 _brsBackColorMine = new SolidBrush(_clSelf);
888 _brsBackColorAt = new SolidBrush(_clAtSelf);
889 _brsBackColorYou = new SolidBrush(_clTarget);
890 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
891 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
892 _brsBackColorAtTo = new SolidBrush(_clAtTo);
893 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
894 _brsBackColorNone = new SolidBrush(_clListBackcolor);
896 // StringFormatオブジェクトへの事前設定
897 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
898 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
899 //sf.FormatFlags = StringFormatFlags.LineLimit; //
900 sfTab.Alignment = StringAlignment.Center;
901 sfTab.LineAlignment = StringAlignment.Center;
903 InitDetailHtmlFormat();
905 //Regex statregex = new Regex("^0*");
906 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
908 _history.Add(new PostingStatus());
910 this.inReplyTo = null;
913 SearchDialog.Owner = this;
914 UrlDialog.Owner = this;
917 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
918 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
920 //新着取得時のリストスクロールをするか。trueならスクロールしない
921 ListLockMenuItem.Checked = _cfgCommon.ListLock;
922 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
924 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
925 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
927 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
928 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
931 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
932 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
933 _myLoc = _cfgLocal.FormLocation;
935 if (this.WindowState != FormWindowState.Minimized)
937 this.DesktopLocation = _cfgLocal.FormLocation;
938 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
939 bool outOfScreen = true;
940 if (Screen.AllScreens.Length == 1) //ハングするとの報告
942 foreach (Screen scr in Screen.AllScreens)
944 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
952 this.DesktopLocation = new Point(0, 0);
953 _myLoc = this.DesktopLocation;
957 this.TopMost = this._cfgCommon.AlwaysTop;
958 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
959 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
960 if (_cfgLocal.PreviewDistance == -1)
962 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
963 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
964 _cfgLocal.PreviewDistance = _mySpDis3;
968 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
970 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
971 //this.Tween_ClientSizeChanged(this, null);
972 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
973 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
975 StatusText.Font = _fntInputFont;
976 StatusText.ForeColor = _clInputFont;
978 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
979 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
980 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
982 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
983 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
985 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
986 if (this._cfgCommon.UnreadManage == false)
988 ReadedStripMenuItem.Enabled = false;
989 UnreadStripMenuItem.Enabled = false;
992 //リンク先URL表示部の初期化(画面左下)
993 StatusLabelUrl.Text = "";
995 StatusLabel.Text = "";
996 StatusLabel.AutoToolTip = false;
997 StatusLabel.ToolTipText = "";
999 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1001 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1002 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1003 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1004 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1006 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1007 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1008 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1009 this.SplitContainer2.Panel2.AccessibleName = "";
1011 ////////////////////////////////////////////////////////////////////////////////
1012 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1013 var mode = ComparerMode.Id;
1014 switch (_cfgCommon.SortColumn)
1016 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1020 mode = ComparerMode.Id; //Idソートに読み替え
1023 mode = ComparerMode.Nickname;
1026 mode = ComparerMode.Data;
1029 mode = ComparerMode.Id;
1032 mode = ComparerMode.Name;
1035 mode = ComparerMode.Source;
1038 _statuses.SetSortMode(mode, sortOrder);
1039 ////////////////////////////////////////////////////////////////////////////////
1041 ApplyListViewIconSize(this._cfgCommon.IconSize);
1043 //<<<<<<<<タブ関連>>>>>>>
1047 //デフォルトタブの存在チェック、ない場合には追加
1048 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1049 this._statuses.AddTab(new HomeTabModel());
1051 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1052 this._statuses.AddTab(new MentionsTabModel());
1054 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1055 this._statuses.AddTab(new DirectMessagesTabModel());
1057 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1058 this._statuses.AddTab(new FavoritesTabModel());
1060 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1061 this._statuses.AddTab(new MuteTabModel());
1063 foreach (var tab in _statuses.Tabs.Values)
1066 if (tab.TabType == MyCommon.TabUsageType.Mute)
1069 if (!AddNewTab(tab, startup: true))
1070 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1073 _curTab = ListTab.SelectedTab;
1075 _curList = (DetailsListView)_curTab.Tag;
1077 if (this._cfgCommon.TabIconDisp)
1079 ListTab.DrawMode = TabDrawMode.Normal;
1083 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1084 ListTab.DrawItem += ListTab_DrawItem;
1085 ListTab.ImageList = null;
1088 if (this._cfgCommon.HotkeyEnabled)
1091 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1092 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1093 modKey |= HookGlobalHotkey.ModKeys.Alt;
1094 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1095 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1096 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1097 modKey |= HookGlobalHotkey.ModKeys.Shift;
1098 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1099 modKey |= HookGlobalHotkey.ModKeys.Win;
1101 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1104 if (this._cfgCommon.IsUseNotifyGrowl)
1107 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1109 SetMainWindowTitle();
1110 SetNotifyIconText();
1112 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1114 this.Visible = true;
1118 TimerTimeline.AutoReset = true;
1119 TimerTimeline.SynchronizingObject = this;
1121 TimerTimeline.Interval = 1000;
1122 TimerTimeline.Enabled = true;
1124 TimerRefreshIcon.Interval = 200;
1125 TimerRefreshIcon.Enabled = true;
1127 _ignoreConfigSave = false;
1128 this.TweenMain_Resize(null, null);
1129 if (saveRequired) SaveConfigsAll(false);
1131 foreach (var ua in this._cfgCommon.UserAccounts)
1133 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1135 ua.UserId = tw.UserId;
1142 // 初回起動時だけ右下のメニューを目立たせる
1143 HashStripSplitButton.ShowDropDown();
1147 private void InitDetailHtmlFormat()
1149 if (this._cfgCommon.IsMonospace)
1151 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1152 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1156 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1157 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1160 detailHtmlFormatHeader = detailHtmlFormatHeader
1161 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1162 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1163 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1164 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1165 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1166 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1169 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1174 txt = ListTab.TabPages[e.Index].Text;
1181 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1182 if (e.State == DrawItemState.Selected)
1184 e.DrawFocusRectangle();
1189 if (_statuses.Tabs[txt].UnreadCount > 0)
1192 fore = System.Drawing.SystemBrushes.ControlText;
1196 fore = System.Drawing.SystemBrushes.ControlText;
1198 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1201 private void LoadConfig()
1203 _cfgCommon = SettingCommon.Load();
1204 SettingCommon.Instance = this._cfgCommon;
1205 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1207 _cfgCommon.UserAccounts = new List<UserAccount>();
1208 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1210 UserAccount account = new UserAccount();
1211 account.Username = _cfgCommon.UserName;
1212 account.UserId = _cfgCommon.UserId;
1213 account.Token = _cfgCommon.Token;
1214 account.TokenSecret = _cfgCommon.TokenSecret;
1216 _cfgCommon.UserAccounts.Add(account);
1220 _cfgLocal = SettingLocal.Load();
1222 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1223 if (_cfgLocal.ScaleDimension.IsEmpty)
1224 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1226 var tabsSetting = SettingTabs.Load().Tabs;
1227 foreach (var tabSetting in tabsSetting)
1230 switch (tabSetting.TabType)
1232 case MyCommon.TabUsageType.Home:
1233 tab = new HomeTabModel(tabSetting.TabName);
1235 case MyCommon.TabUsageType.Mentions:
1236 tab = new MentionsTabModel(tabSetting.TabName);
1238 case MyCommon.TabUsageType.DirectMessage:
1239 tab = new DirectMessagesTabModel(tabSetting.TabName);
1241 case MyCommon.TabUsageType.Favorites:
1242 tab = new FavoritesTabModel(tabSetting.TabName);
1244 case MyCommon.TabUsageType.UserDefined:
1245 tab = new FilterTabModel(tabSetting.TabName);
1247 case MyCommon.TabUsageType.UserTimeline:
1248 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1250 case MyCommon.TabUsageType.PublicSearch:
1251 tab = new PublicSearchTabModel(tabSetting.TabName)
1253 SearchWords = tabSetting.SearchWords,
1254 SearchLang = tabSetting.SearchLang,
1257 case MyCommon.TabUsageType.Lists:
1258 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1260 case MyCommon.TabUsageType.Mute:
1261 tab = new MuteTabModel(tabSetting.TabName);
1267 tab.UnreadManage = tabSetting.UnreadManage;
1268 tab.Protected = tabSetting.Protected;
1269 tab.Notify = tabSetting.Notify;
1270 tab.SoundFile = tabSetting.SoundFile;
1272 if (tab.IsDistributableTabType)
1274 var filterTab = (FilterTabModel)tab;
1275 filterTab.FilterArray = tabSetting.FilterArray;
1276 filterTab.FilterModified = false;
1279 if (this._statuses.ContainsTab(tab.TabName))
1280 tab.TabName = this._statuses.MakeTabName("MyTab");
1282 this._statuses.AddTab(tab);
1284 if (_statuses.Tabs.Count == 0)
1286 _statuses.AddTab(new HomeTabModel());
1287 _statuses.AddTab(new MentionsTabModel());
1288 _statuses.AddTab(new DirectMessagesTabModel());
1289 _statuses.AddTab(new FavoritesTabModel());
1293 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1295 if (!TimerTimeline.Enabled) return;
1299 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1301 private static int homeCounter = 0;
1302 private static int mentionCounter = 0;
1303 private static int dmCounter = 0;
1304 private static int pubSearchCounter = 0;
1305 private static int userTimelineCounter = 0;
1306 private static int listsCounter = 0;
1307 private static int usCounter = 0;
1308 private static int ResumeWait = 0;
1309 private static int refreshFollowers = 0;
1311 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1313 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1314 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1315 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1316 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1317 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1318 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1319 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1320 Interlocked.Increment(ref refreshFollowers);
1322 var refreshTasks = new List<Task>();
1325 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1327 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1328 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1329 refreshTasks.Add(this.GetHomeTimelineAsync());
1330 ResetTimers.Timeline = false;
1332 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1334 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1335 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1336 refreshTasks.Add(this.GetReplyAsync());
1337 ResetTimers.Reply = false;
1339 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1341 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1342 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1343 refreshTasks.Add(this.GetDirectMessagesAsync());
1344 ResetTimers.DirectMessage = false;
1346 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1348 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1349 if (!ResetTimers.PublicSearch)
1350 refreshTasks.Add(this.GetPublicSearchAllAsync());
1351 ResetTimers.PublicSearch = false;
1353 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1355 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1356 if (!ResetTimers.UserTimeline)
1357 refreshTasks.Add(this.GetUserTimelineAllAsync());
1358 ResetTimers.UserTimeline = false;
1360 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1362 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1363 if (!ResetTimers.Lists)
1364 refreshTasks.Add(this.GetListTimelineAllAsync());
1365 ResetTimers.Lists = false;
1367 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1369 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1370 if (this.tw.UserStreamActive)
1371 this.RefreshTimeline();
1372 ResetTimers.UserStream = false;
1374 if (refreshFollowers > 6 * 3600)
1376 Interlocked.Exchange(ref refreshFollowers, 0);
1377 refreshTasks.AddRange(new[]
1379 this.doGetFollowersMenu(),
1380 this.RefreshNoRetweetIdsAsync(),
1381 this.RefreshTwitterConfigurationAsync(),
1386 Interlocked.Increment(ref ResumeWait);
1387 if (ResumeWait > 30)
1390 Interlocked.Exchange(ref ResumeWait, 0);
1391 refreshTasks.AddRange(new[]
1393 this.GetHomeTimelineAsync(),
1394 this.GetReplyAsync(),
1395 this.GetDirectMessagesAsync(),
1396 this.GetPublicSearchAllAsync(),
1397 this.GetUserTimelineAllAsync(),
1398 this.GetListTimelineAllAsync(),
1399 this.doGetFollowersMenu(),
1400 this.RefreshTwitterConfigurationAsync(),
1405 await Task.WhenAll(refreshTasks);
1408 private void RefreshTimeline()
1410 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1412 // 現在表示中のタブのスクロール位置を退避
1413 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1415 // 現在表示中のタブのリスト上の選択位置などを退避
1416 var curListSelection = this.SaveListViewSelection(this._curList, curTabModel);
1419 PostClass[] notifyPosts;
1422 bool newMentionOrDm;
1424 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1426 if (MyCommon._endingFlag) return;
1430 if (this._cfgCommon.TabIconDisp)
1432 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1434 var tabModel = this._statuses.Tabs[tabPage.Text];
1435 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1436 tabPage.ImageIndex = 0; // 未読アイコン
1441 this.ListTab.Refresh();
1446 if (this._curList.VirtualListSize != curTabModel.AllCount || isDelete)
1448 using (ControlTransaction.Update(this._curList))
1450 this.PurgeListViewItemCache();
1453 this._curList.VirtualListSize = curTabModel.AllCount;
1456 this.RestoreListViewSelection(this._curList, curTabModel, curListSelection);
1459 // スクロール位置の復元は Begin/EndUpdate の外で行う
1460 // 参照: https://github.com/opentween/OpenTween/commit/7dbf6491
1461 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1465 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1467 SetMainWindowTitle();
1468 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1470 HashSupl.AddRangeItem(tw.GetHashList());
1474 internal struct ListViewScroll
1476 public ScrollLockMode ScrollLockMode { get; set; }
1477 public long? TopItemStatusId { get; set; }
1480 internal enum ScrollLockMode
1482 /// <summary>固定しない</summary>
1485 /// <summary>最上部に固定する</summary>
1488 /// <summary>最下部に固定する</summary>
1491 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1496 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1498 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1500 var listScroll = new ListViewScroll
1502 ScrollLockMode = this.GetScrollLockMode(listView),
1505 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1507 var topItem = listView.TopItem;
1508 if (topItem != null)
1509 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1515 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1517 if (this._statuses.SortMode == ComparerMode.Id)
1519 if (this._statuses.SortOrder == SortOrder.Ascending)
1522 if (this.ListLockMenuItem.Checked)
1523 return ScrollLockMode.None;
1525 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1528 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1529 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1530 return ScrollLockMode.FixedToBottom;
1532 return ScrollLockMode.None;
1537 if (this.ListLockMenuItem.Checked)
1538 return ScrollLockMode.FixedToItem;
1540 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1541 var topItem = listView.TopItem;
1542 if (topItem == null || topItem.Index == 0)
1543 return ScrollLockMode.FixedToTop;
1545 return ScrollLockMode.FixedToItem;
1550 return ScrollLockMode.FixedToItem;
1554 internal struct ListViewSelection
1556 public long[] SelectedStatusIds { get; set; }
1557 public long? SelectionMarkStatusId { get; set; }
1558 public long? FocusedStatusId { get; set; }
1562 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1564 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1566 var listsDict = new Dictionary<string, ListViewSelection>();
1568 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1570 var listView = (DetailsListView)tabPage.Tag;
1571 var tab = _statuses.Tabs[tabPage.Text];
1573 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1580 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1582 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1584 if (listView.VirtualListSize == 0)
1586 return new ListViewSelection
1588 SelectedStatusIds = new long[0],
1589 SelectionMarkStatusId = null,
1590 FocusedStatusId = null,
1594 return new ListViewSelection
1596 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1597 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1598 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1602 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1604 var selectedIndices = listView.SelectedIndices;
1605 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1606 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1611 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1613 var focusedItem = listView.FocusedItem;
1615 return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1618 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1620 var selectionMarkIndex = listView.SelectionMark;
1622 return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1626 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1628 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1630 if (listView.VirtualListSize == 0)
1633 switch (listScroll.ScrollLockMode)
1635 case ScrollLockMode.FixedToTop:
1636 listView.EnsureVisible(0);
1638 case ScrollLockMode.FixedToBottom:
1639 listView.EnsureVisible(listView.VirtualListSize - 1);
1641 case ScrollLockMode.FixedToItem:
1642 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1644 listView.TopItem = listView.Items[topIndex];
1646 case ScrollLockMode.None:
1653 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1655 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1657 // status_id から ListView 上のインデックスに変換
1658 int[] selectedIndices = null;
1659 if (listSelection.SelectedStatusIds != null)
1660 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1662 var focusedIndex = -1;
1663 if (listSelection.FocusedStatusId != null)
1664 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1666 var selectionMarkIndex = -1;
1667 if (listSelection.SelectionMarkStatusId != null)
1668 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1670 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1673 private bool BalloonRequired()
1675 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1676 ev.Eventtype = MyCommon.EVENTTYPE.None;
1678 return BalloonRequired(ev);
1681 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1683 if (type == MyCommon.EVENTTYPE.None)
1686 if (!this._cfgCommon.EventNotifyEnabled)
1689 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1692 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1697 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1700 private bool BalloonRequired(Twitter.FormattedEvent ev)
1705 if (NativeMethods.IsScreenSaverRunning())
1709 if (!this.NewPostPopMenuItem.Checked)
1711 // 「新着通知が無効でもイベントを通知する」にも該当しない
1712 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1716 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1717 if (this._cfgCommon.LimitBalloon)
1719 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1723 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1726 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1728 if (this._cfgCommon.ReadOwnPost)
1730 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1735 if (BalloonRequired())
1737 if (notifyPosts != null && notifyPosts.Length > 0)
1739 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1740 if (this._cfgCommon.IsUseNotifyGrowl)
1742 StringBuilder sb = new StringBuilder();
1746 foreach (PostClass post in notifyPosts)
1748 if (!(notifyPosts.Length > 3))
1754 if (post.IsReply && !post.IsExcludeReply) reply = true;
1755 if (post.IsDm) dm = true;
1756 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1757 switch (this._cfgCommon.NameBalloon)
1759 case MyCommon.NameBalloonEnum.UserID:
1760 sb.Append(post.ScreenName).Append(" : ");
1762 case MyCommon.NameBalloonEnum.NickName:
1763 sb.Append(post.Nickname).Append(" : ");
1766 sb.Append(post.TextFromApi);
1767 if (notifyPosts.Length > 3)
1769 if (notifyPosts.Last() != post) continue;
1772 StringBuilder title = new StringBuilder();
1773 GrowlHelper.NotifyType nt;
1774 if (this._cfgCommon.DispUsername)
1776 title.Append(tw.Username);
1777 title.Append(" - ");
1785 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1786 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1787 title.Append(Application.ProductName);
1788 title.Append(" [DM] ");
1789 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1790 nt = GrowlHelper.NotifyType.DirectMessage;
1794 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1795 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1796 title.Append(Application.ProductName);
1797 title.Append(" [Reply!] ");
1798 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1799 nt = GrowlHelper.NotifyType.Reply;
1803 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1804 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1805 title.Append(Application.ProductName);
1807 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1808 nt = GrowlHelper.NotifyType.Notify;
1810 string bText = sb.ToString();
1811 if (string.IsNullOrEmpty(bText)) return;
1813 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1814 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1819 StringBuilder sb = new StringBuilder();
1822 foreach (PostClass post in notifyPosts)
1824 if (post.IsReply && !post.IsExcludeReply) reply = true;
1825 if (post.IsDm) dm = true;
1826 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1827 switch (this._cfgCommon.NameBalloon)
1829 case MyCommon.NameBalloonEnum.UserID:
1830 sb.Append(post.ScreenName).Append(" : ");
1832 case MyCommon.NameBalloonEnum.NickName:
1833 sb.Append(post.Nickname).Append(" : ");
1836 sb.Append(post.TextFromApi);
1839 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1840 StringBuilder title = new StringBuilder();
1842 if (this._cfgCommon.DispUsername)
1844 title.Append(tw.Username);
1845 title.Append(" - ");
1853 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1854 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1855 ntIcon = ToolTipIcon.Warning;
1856 title.Append(Application.ProductName);
1857 title.Append(" [DM] ");
1858 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1862 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1863 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1864 ntIcon = ToolTipIcon.Warning;
1865 title.Append(Application.ProductName);
1866 title.Append(" [Reply!] ");
1867 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1871 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1872 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1873 ntIcon = ToolTipIcon.Info;
1874 title.Append(Application.ProductName);
1876 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1878 string bText = sb.ToString();
1879 if (string.IsNullOrEmpty(bText)) return;
1880 //NotifyIcon1.BalloonTipText = sb.ToString();
1881 //NotifyIcon1.ShowBalloonTip(500);
1882 NotifyIcon1.BalloonTipTitle = title.ToString();
1883 NotifyIcon1.BalloonTipText = bText;
1884 NotifyIcon1.BalloonTipIcon = ntIcon;
1885 NotifyIcon1.ShowBalloonTip(500);
1891 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1895 string dir = Application.StartupPath;
1896 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1898 dir = Path.Combine(dir, "Sounds");
1900 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1910 //mentions新着時に画面ブリンク
1911 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1913 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1917 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1919 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1921 _curItemIndex = _curList.SelectedIndices[0];
1922 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1926 this._curPost = GetCurTabPost(_curItemIndex);
1928 catch (ArgumentException)
1933 this.PushSelectPostChain();
1935 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1937 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1943 private void ChangeCacheStyleRead(bool Read, int Index)
1945 var tabInfo = _statuses.Tabs[_curTab.Text];
1946 //Read:true=既読 false=未読
1947 //未読管理していなかったら既読として扱う
1948 if (!tabInfo.UnreadManage ||
1949 !this._cfgCommon.UnreadManage) Read = true;
1951 var listCache = this._listItemCache;
1952 if (listCache == null)
1955 // キャッシュに含まれていないアイテムは対象外
1958 if (!listCache.TryGetValue(Index, out itm, out post))
1961 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1964 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1971 Item.SubItems[5].Text = "";
1976 Item.SubItems[5].Text = "★";
1982 else if (Post.RetweetedId != null)
1984 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1986 else if (Read || !this._cfgCommon.UseUnreadStyle)
1991 if (DList == null || Item.Index == -1)
1993 Item.ForeColor = cl;
1994 if (this._cfgCommon.UseUnreadStyle)
2000 if (this._cfgCommon.UseUnreadStyle)
2001 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2003 DList.ChangeItemForeColor(Item.Index, cl);
2004 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2008 private void ColorizeList()
2010 //Index:更新対象のListviewItem.Index。Colorを返す。
2011 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2014 _post = _anchorPost;
2018 if (_post == null) return;
2020 var listCache = this._listItemCache;
2021 if (listCache == null)
2024 var index = listCache.StartIndex;
2025 foreach (var cachedPost in listCache.Post)
2027 var backColor = this.JudgeColor(_post, cachedPost);
2028 this._curList.ChangeItemBackColor(index++, backColor);
2032 private void ColorizeList(ListViewItem Item, int Index)
2034 //Index:更新対象のListviewItem.Index。Colorを返す。
2035 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2038 _post = _anchorPost;
2042 PostClass tPost = GetCurTabPost(Index);
2044 if (_post == null) return;
2046 if (Item.Index == -1)
2047 Item.BackColor = JudgeColor(_post, tPost);
2049 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2052 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2055 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2058 else if (TargetPost.IsMe)
2061 else if (TargetPost.IsReply)
2064 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2066 cl = _clAtFromTarget;
2067 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2070 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2075 cl = _clListBackcolor;
2080 private async void PostButton_Click(object sender, EventArgs e)
2082 if (StatusText.Text.Trim().Length == 0)
2084 if (!ImageSelector.Enabled)
2086 await this.DoRefresh();
2091 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2093 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2095 MessageBoxButtons.YesNoCancel,
2096 MessageBoxIcon.Question);
2099 case DialogResult.Yes:
2100 StatusText.Text = "";
2101 await this.doReTweetOfficial(false);
2103 case DialogResult.Cancel:
2108 var inReplyToStatusId = this.inReplyTo?.Item1;
2109 var inReplyToScreenName = this.inReplyTo?.Item2;
2110 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2112 if (this._cfgCommon.Nicoms)
2114 StatusText.SelectionStart = StatusText.Text.Length;
2115 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2117 //if (SettingDialog.UrlConvertAuto)
2119 // StatusText.SelectionStart = StatusText.Text.Length;
2120 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2122 //else if (SettingDialog.Nicoms)
2124 // StatusText.SelectionStart = StatusText.Text.Length;
2125 // UrlConvert(UrlConverter.Nicoms);
2127 StatusText.SelectionStart = StatusText.Text.Length;
2128 CheckReplyTo(StatusText.Text);
2130 var statusText = this.FormatStatusText(this.StatusText.Text);
2132 if (this.GetRestStatusCount(statusText) < 0)
2134 // 文字数制限を超えているが強制的に投稿するか
2135 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2136 if (ret != DialogResult.OK)
2140 var status = new PostingStatus();
2141 status.status = statusText;
2143 status.inReplyToId = this.inReplyTo?.Item1;
2144 status.inReplyToName = this.inReplyTo?.Item2;
2145 if (ImageSelector.Visible)
2148 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2152 this.inReplyTo = null;
2153 StatusText.Text = "";
2154 _history.Add(new PostingStatus());
2155 _hisIdx = _history.Count - 1;
2156 if (!ToolStripFocusLockMenuItem.Checked)
2157 ((Control)ListTab.SelectedTab.Tag).Focus();
2158 urlUndoBuffer = null;
2159 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2162 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2164 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2165 await this.OpenUriInBrowserAsync(tmp);
2168 await this.PostMessageAsync(status);
2171 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2173 MyCommon._endingFlag = true;
2177 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2179 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2181 //_endingFlag=false:フォームの×ボタン
2183 this.Visible = false;
2187 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2188 _ignoreConfigSave = true;
2189 MyCommon._endingFlag = true;
2190 TimerTimeline.Enabled = false;
2191 TimerRefreshIcon.Enabled = false;
2195 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2197 this.Visible = true;
2198 if (this.WindowState == FormWindowState.Minimized)
2200 this.WindowState = FormWindowState.Normal;
2203 this.BringToFront();
2206 private static int errorCount = 0;
2208 private static bool CheckAccountValid()
2210 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2216 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2225 private Task GetHomeTimelineAsync()
2227 return this.GetHomeTimelineAsync(loadMore: false);
2230 private async Task GetHomeTimelineAsync(bool loadMore)
2232 await this.workerSemaphore.WaitAsync();
2236 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2237 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2239 this.RefreshTimeline();
2241 catch (WebApiException ex)
2243 this._myStatusError = true;
2244 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2248 this.workerSemaphore.Release();
2252 private Task GetReplyAsync()
2254 return this.GetReplyAsync(loadMore: false);
2257 private async Task GetReplyAsync(bool loadMore)
2259 await this.workerSemaphore.WaitAsync();
2263 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2264 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2266 this.RefreshTimeline();
2268 catch (WebApiException ex)
2270 this._myStatusError = true;
2271 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2275 this.workerSemaphore.Release();
2279 private Task GetDirectMessagesAsync()
2281 return this.GetDirectMessagesAsync(loadMore: false);
2284 private async Task GetDirectMessagesAsync(bool loadMore)
2286 await this.workerSemaphore.WaitAsync();
2290 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2291 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2293 this.RefreshTimeline();
2295 catch (WebApiException ex)
2297 this._myStatusError = true;
2298 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2302 this.workerSemaphore.Release();
2306 private Task GetFavoritesAsync()
2308 return this.GetFavoritesAsync(loadMore: false);
2311 private async Task GetFavoritesAsync(bool loadMore)
2313 await this.workerSemaphore.WaitAsync();
2317 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2318 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2320 this.RefreshTimeline();
2322 catch (WebApiException ex)
2324 this._myStatusError = true;
2325 this.StatusLabel.Text = ex.Message;
2329 this.workerSemaphore.Release();
2333 private Task GetPublicSearchAllAsync()
2335 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2337 return this.GetPublicSearchAsync(tabs, loadMore: false);
2340 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2342 return this.GetPublicSearchAsync(tab, loadMore: false);
2345 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2347 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2350 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2352 await this.workerSemaphore.WaitAsync();
2356 foreach (var tab in tabs)
2360 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2362 catch (WebApiException ex)
2364 this._myStatusError = true;
2365 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2369 this.RefreshTimeline();
2373 this.workerSemaphore.Release();
2377 private Task GetUserTimelineAllAsync()
2379 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2381 return this.GetUserTimelineAsync(tabs, loadMore: false);
2384 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2386 return this.GetUserTimelineAsync(tab, loadMore: false);
2389 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2391 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2394 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2396 await this.workerSemaphore.WaitAsync();
2400 foreach (var tab in tabs)
2404 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2406 catch (WebApiException ex)
2408 this._myStatusError = true;
2409 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2413 this.RefreshTimeline();
2417 this.workerSemaphore.Release();
2421 private Task GetListTimelineAllAsync()
2423 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2425 return this.GetListTimelineAsync(tabs, loadMore: false);
2428 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2430 return this.GetListTimelineAsync(tab, loadMore: false);
2433 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2435 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2438 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2440 await this.workerSemaphore.WaitAsync();
2444 foreach (var tab in tabs)
2448 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2450 catch (WebApiException ex)
2452 this._myStatusError = true;
2453 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2457 this.RefreshTimeline();
2461 this.workerSemaphore.Release();
2465 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2467 await this.workerSemaphore.WaitAsync();
2471 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2473 this.RefreshTimeline();
2475 catch (WebApiException ex)
2477 this._myStatusError = true;
2478 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2482 this.workerSemaphore.Release();
2486 private async Task FavAddAsync(long statusId, TabModel tab)
2488 await this.workerSemaphore.WaitAsync();
2492 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2494 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2496 catch (WebApiException ex)
2498 this._myStatusError = true;
2499 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2503 this.workerSemaphore.Release();
2507 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2509 if (ct.IsCancellationRequested)
2512 if (!CheckAccountValid())
2513 throw new WebApiException("Auth error. Check your account");
2516 if (!tab.Posts.TryGetValue(statusId, out post))
2522 await Task.Run(async () =>
2524 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2528 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2530 .ConfigureAwait(false);
2532 if (this._cfgCommon.RestrictFavCheck)
2534 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2535 .ConfigureAwait(false);
2537 if (status.Favorited != true)
2538 throw new WebApiException("NG(Restricted?)");
2541 this._favTimestamps.Add(DateTime.Now);
2544 if (this._statuses.ContainsKey(statusId))
2546 var postTl = this._statuses[statusId];
2547 postTl.IsFav = true;
2549 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2550 favTab.AddPostQueue(postTl);
2553 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2554 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2556 if (tb.Contains(statusId))
2557 tb.Posts[statusId].IsFav = true;
2560 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2562 catch (WebApiException)
2564 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2569 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2570 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2572 if (this._favTimestamps[i] < oneHour)
2573 this._favTimestamps.RemoveAt(i);
2576 this._statuses.DistributePosts();
2579 if (ct.IsCancellationRequested)
2582 this.RefreshTimeline();
2584 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2586 using (ControlTransaction.Update(this._curList))
2588 var idx = tab.IndexOf(statusId);
2590 this.ChangeCacheStyleRead(post.IsRead, idx);
2593 if (statusId == this._curPost.StatusId)
2594 await this.DispSelectedPost(true); // 選択アイテム再表示
2598 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2600 await this.workerSemaphore.WaitAsync();
2604 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2606 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2608 catch (WebApiException ex)
2610 this._myStatusError = true;
2611 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2615 this.workerSemaphore.Release();
2619 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2621 if (ct.IsCancellationRequested)
2624 if (!CheckAccountValid())
2625 throw new WebApiException("Auth error. Check your account");
2627 var successIds = new List<long>();
2629 await Task.Run(async () =>
2633 var failedCount = 0;
2634 foreach (var statusId in statusIds)
2638 var post = tab.Posts[statusId];
2640 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2647 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2649 .ConfigureAwait(false);
2651 catch (WebApiException)
2657 successIds.Add(statusId);
2658 post.IsFav = false; // リスト再描画必要
2660 if (this._statuses.ContainsKey(statusId))
2662 this._statuses[statusId].IsFav = false;
2665 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2666 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2668 if (tb.Contains(statusId))
2669 tb.Posts[statusId].IsFav = false;
2674 if (ct.IsCancellationRequested)
2677 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2678 foreach (var statusId in successIds)
2680 // ツイートが削除された訳ではないので IsDeleted はセットしない
2681 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2684 this.RefreshTimeline();
2686 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2688 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2694 using (ControlTransaction.Update(this._curList))
2696 foreach (var statusId in successIds)
2698 var idx = tab.IndexOf(statusId);
2702 var post = tab.Posts[statusId];
2703 this.ChangeCacheStyleRead(post.IsRead, idx);
2707 if (successIds.Contains(this._curPost.StatusId))
2708 await this.DispSelectedPost(true); // 選択アイテム再表示
2713 private async Task PostMessageAsync(PostingStatus status)
2715 await this.workerSemaphore.WaitAsync();
2719 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2721 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2723 catch (WebApiException ex)
2725 this._myStatusError = true;
2726 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2730 this.workerSemaphore.Release();
2734 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2736 if (ct.IsCancellationRequested)
2739 if (!CheckAccountValid())
2740 throw new WebApiException("Auth error. Check your account");
2742 p.Report("Posting...");
2748 await Task.Run(async () =>
2750 if (status.mediaItems == null || status.mediaItems.Length == 0)
2752 await this.tw.PostStatus(status.status, status.inReplyToId)
2753 .ConfigureAwait(false);
2757 var service = ImageSelector.GetService(status.imageService);
2758 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2759 .ConfigureAwait(false);
2763 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2765 catch (WebApiException ex)
2767 // 処理は中断せずエラーの表示のみ行う
2768 errMsg = $"Err:{ex.Message}(PostMessage)";
2770 this._myStatusError = true;
2772 catch (UnauthorizedAccessException ex)
2774 // アップロード対象のファイルが開けなかった場合など
2775 errMsg = $"Err:{ex.Message}(PostMessage)";
2777 this._myStatusError = true;
2781 // 使い終わった MediaItem は破棄する
2782 if (status.mediaItems != null)
2784 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2786 disposableItem.Dispose();
2791 if (ct.IsCancellationRequested)
2794 if (!string.IsNullOrEmpty(errMsg) &&
2795 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2796 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2798 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2800 var ret = MessageBox.Show(
2802 "Failed to update status",
2803 MessageBoxButtons.RetryCancel,
2804 MessageBoxIcon.Question);
2806 if (ret == DialogResult.Retry)
2808 await this.PostMessageAsync(status);
2812 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2813 if (this.ToolStripFocusLockMenuItem.Checked)
2814 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2819 this._postTimestamps.Add(DateTime.Now);
2821 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2822 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2824 if (this._postTimestamps[i] < oneHour)
2825 this._postTimestamps.RemoveAt(i);
2828 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2830 this.HashMgr.ClearHashtag();
2831 this.HashStripSplitButton.Text = "#[-]";
2832 this.HashToggleMenuItem.Checked = false;
2833 this.HashToggleToolStripMenuItem.Checked = false;
2836 this.SetMainWindowTitle();
2838 if (this._cfgCommon.PostAndGet)
2840 if (this.tw.UserStreamActive)
2841 this.RefreshTimeline();
2843 await this.GetHomeTimelineAsync();
2847 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2849 await this.workerSemaphore.WaitAsync();
2853 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2855 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2857 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
2858 await this.GetHomeTimelineAsync();
2860 catch (WebApiException ex)
2862 this._myStatusError = true;
2863 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2867 this.workerSemaphore.Release();
2871 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2873 if (ct.IsCancellationRequested)
2876 if (!CheckAccountValid())
2877 throw new WebApiException("Auth error. Check your account");
2880 if (!this._cfgCommon.UnreadManage)
2883 read = this._initial && this._cfgCommon.Read;
2885 p.Report("Posting...");
2887 foreach (var statusId in statusIds)
2889 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2892 if (ct.IsCancellationRequested)
2895 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2897 this._postTimestamps.Add(DateTime.Now);
2899 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2900 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2902 if (this._postTimestamps[i] < oneHour)
2903 this._postTimestamps.RemoveAt(i);
2907 private async Task RefreshFollowerIdsAsync()
2909 await this.workerSemaphore.WaitAsync();
2912 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2914 await this.tw.RefreshFollowerIds();
2916 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2918 this.RefreshTimeline();
2919 this.PurgeListViewItemCache();
2920 this._curList?.Refresh();
2922 catch (WebApiException ex)
2924 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2928 this.workerSemaphore.Release();
2932 private async Task RefreshNoRetweetIdsAsync()
2934 await this.workerSemaphore.WaitAsync();
2937 await this.tw.RefreshNoRetweetIds();
2939 this.StatusLabel.Text = "NoRetweetIds refreshed";
2941 catch (WebApiException ex)
2943 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2947 this.workerSemaphore.Release();
2951 private async Task RefreshBlockIdsAsync()
2953 await this.workerSemaphore.WaitAsync();
2956 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2958 await this.tw.RefreshBlockIds();
2960 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2962 catch (WebApiException ex)
2964 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2968 this.workerSemaphore.Release();
2972 private async Task RefreshTwitterConfigurationAsync()
2974 await this.workerSemaphore.WaitAsync();
2977 await this.tw.RefreshConfiguration();
2979 if (this.tw.Configuration.PhotoSizeLimit != 0)
2981 foreach (var service in this.ImageSelector.GetServices())
2983 service.UpdateTwitterConfiguration(this.tw.Configuration);
2987 this.PurgeListViewItemCache();
2989 this._curList?.Refresh();
2991 catch (WebApiException ex)
2993 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2997 this.workerSemaphore.Release();
3001 private async Task RefreshMuteUserIdsAsync()
3003 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3007 await tw.RefreshMuteUserIdsAsync();
3009 catch (WebApiException ex)
3011 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3015 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3018 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3020 if (e.Button == MouseButtons.Left)
3022 this.Visible = true;
3023 if (this.WindowState == FormWindowState.Minimized)
3025 this.WindowState = _formWindowState;
3028 this.BringToFront();
3032 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3034 switch (this._cfgCommon.ListDoubleClickAction)
3037 MakeReplyOrDirectStatus();
3040 await this.FavoriteChange(true);
3043 if (_curPost != null)
3044 await this.ShowUserStatus(_curPost.ScreenName, false);
3050 ShowRelatedStatusesMenuItem_Click(null, null);
3053 MoveToHomeToolStripMenuItem_Click(null, null);
3056 StatusOpenMenuItem_Click(null, null);
3064 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3066 await this.FavoriteChange(true);
3069 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3071 await this.FavoriteChange(false);
3075 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3077 await this.FavoritesRetweetOfficial();
3080 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3082 await this.FavoritesRetweetUnofficial();
3085 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3088 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3091 //trueでFavAdd,falseでFavRemove
3092 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3093 || !this.ExistCurrentPost) return;
3095 if (this._curList.SelectedIndices.Count > 1)
3100 // https://support.twitter.com/articles/76915#favoriting
3101 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3102 _DoFavRetweetFlags = false;
3107 if (multiFavoriteChangeDialogEnable)
3109 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3110 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3111 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3113 if (confirm == DialogResult.Cancel)
3121 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3122 if (selectedPost.IsFav)
3124 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3128 await this.FavAddAsync(selectedPost.StatusId, tab);
3132 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3133 .Select(x => this.GetCurTabPost(x))
3134 .Where(x => x.IsFav);
3136 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3137 if (statusIds.Length == 0)
3139 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3143 await this.FavRemoveAsync(statusIds, tab);
3147 private PostClass GetCurTabPost(int Index)
3149 var listCache = this._listItemCache;
3150 if (listCache != null)
3154 if (listCache.TryGetValue(Index, out item, out post))
3158 return _statuses.Tabs[_curTab.Text][Index];
3161 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3163 if (_curList.SelectedIndices.Count > 0)
3164 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3165 else if (_curList.SelectedIndices.Count == 0)
3166 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3169 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3171 if (_curList.SelectedIndices.Count > 0)
3172 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3175 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3177 if ((!_initialLayout) && this.Visible)
3179 if (this.WindowState == FormWindowState.Normal)
3181 _mySize = this.ClientSize;
3182 _mySpDis = this.SplitContainer1.SplitterDistance;
3183 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3184 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3185 ModifySettingLocal = true;
3190 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3192 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3193 if (comparerMode == null)
3196 this.SetSortColumn(comparerMode.Value);
3200 /// 列インデックスからソートを行う ComparerMode を求める
3202 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3203 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3204 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3207 return ComparerMode.Id;
3209 switch (columnIndex)
3212 return ComparerMode.Nickname;
3214 return ComparerMode.Data;
3216 return ComparerMode.Id;
3218 return ComparerMode.Name;
3220 return ComparerMode.Source;
3222 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3228 /// 発言一覧の指定した位置の列でソートする
3230 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3231 private void SetSortColumnByDisplayIndex(int columnIndex)
3233 // 表示上の列の位置から ColumnHeader を求める
3234 var col = this._curList.Columns.Cast<ColumnHeader>()
3235 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3240 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3241 if (comparerMode == null)
3244 this.SetSortColumn(comparerMode.Value);
3248 /// 発言一覧の最後列の項目でソートする
3250 private void SetSortLastColumn()
3252 // 表示上の最後列にある ColumnHeader を求める
3253 var col = this._curList.Columns.Cast<ColumnHeader>()
3254 .OrderByDescending(x => x.DisplayIndex)
3257 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3258 if (comparerMode == null)
3261 this.SetSortColumn(comparerMode.Value);
3265 /// 発言一覧を指定された ComparerMode に基づいてソートする
3267 private void SetSortColumn(ComparerMode sortColumn)
3269 if (this._cfgCommon.SortOrderLock)
3272 this._statuses.ToggleSortOrder(sortColumn);
3273 this.InitColumnText();
3275 var list = this._curList;
3278 list.Columns[0].Text = this.ColumnText[0];
3279 list.Columns[1].Text = this.ColumnText[2];
3283 for (var i = 0; i <= 7; i++)
3285 list.Columns[i].Text = this.ColumnText[i];
3289 this.PurgeListViewItemCache();
3291 var tab = this._statuses.Tabs[this._curTab.Text];
3292 if (tab.AllCount > 0 && this._curPost != null)
3294 var idx = tab.IndexOf(this._curPost.StatusId);
3297 this.SelectListItem(list, idx);
3298 list.EnsureVisible(idx);
3303 this.ModifySettingCommon = true;
3306 private void TweenMain_LocationChanged(object sender, EventArgs e)
3308 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3310 _myLoc = this.DesktopLocation;
3311 ModifySettingLocal = true;
3315 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3317 if (ListTab.SelectedTab == null) return;
3318 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3319 if (!this.ExistCurrentPost)
3321 ReplyStripMenuItem.Enabled = false;
3322 ReplyAllStripMenuItem.Enabled = false;
3323 DMStripMenuItem.Enabled = false;
3324 ShowProfileMenuItem.Enabled = false;
3325 ShowUserTimelineContextMenuItem.Enabled = false;
3326 ListManageUserContextToolStripMenuItem2.Enabled = false;
3327 MoveToFavToolStripMenuItem.Enabled = false;
3328 TabMenuItem.Enabled = false;
3329 IDRuleMenuItem.Enabled = false;
3330 SourceRuleMenuItem.Enabled = false;
3331 ReadedStripMenuItem.Enabled = false;
3332 UnreadStripMenuItem.Enabled = false;
3336 ShowProfileMenuItem.Enabled = true;
3337 ListManageUserContextToolStripMenuItem2.Enabled = true;
3338 ReplyStripMenuItem.Enabled = true;
3339 ReplyAllStripMenuItem.Enabled = true;
3340 DMStripMenuItem.Enabled = true;
3341 ShowUserTimelineContextMenuItem.Enabled = true;
3342 MoveToFavToolStripMenuItem.Enabled = true;
3343 TabMenuItem.Enabled = true;
3344 IDRuleMenuItem.Enabled = true;
3345 SourceRuleMenuItem.Enabled = true;
3346 ReadedStripMenuItem.Enabled = true;
3347 UnreadStripMenuItem.Enabled = true;
3349 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3351 FavAddToolStripMenuItem.Enabled = false;
3352 FavRemoveToolStripMenuItem.Enabled = false;
3353 StatusOpenMenuItem.Enabled = false;
3354 FavorareMenuItem.Enabled = false;
3355 ShowRelatedStatusesMenuItem.Enabled = false;
3357 ReTweetStripMenuItem.Enabled = false;
3358 ReTweetUnofficialStripMenuItem.Enabled = false;
3359 QuoteStripMenuItem.Enabled = false;
3360 FavoriteRetweetContextMenu.Enabled = false;
3361 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3365 FavAddToolStripMenuItem.Enabled = true;
3366 FavRemoveToolStripMenuItem.Enabled = true;
3367 StatusOpenMenuItem.Enabled = true;
3368 FavorareMenuItem.Enabled = true;
3369 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3371 if (_curPost.IsProtect)
3373 ReTweetStripMenuItem.Enabled = false;
3374 ReTweetUnofficialStripMenuItem.Enabled = false;
3375 QuoteStripMenuItem.Enabled = false;
3376 FavoriteRetweetContextMenu.Enabled = false;
3377 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3381 ReTweetStripMenuItem.Enabled = true;
3382 ReTweetUnofficialStripMenuItem.Enabled = true;
3383 QuoteStripMenuItem.Enabled = true;
3384 FavoriteRetweetContextMenu.Enabled = true;
3385 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3388 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3390 // RefreshMoreStripMenuItem.Enabled = true;
3394 // RefreshMoreStripMenuItem.Enabled = false;
3396 if (!this.ExistCurrentPost
3397 || _curPost.InReplyToStatusId == null)
3399 RepliedStatusOpenMenuItem.Enabled = false;
3403 RepliedStatusOpenMenuItem.Enabled = true;
3405 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3407 MoveToRTHomeMenuItem.Enabled = false;
3411 MoveToRTHomeMenuItem.Enabled = true;
3414 if (this.ExistCurrentPost)
3416 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3417 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3418 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3420 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3424 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3426 MakeReplyOrDirectStatus(false, true);
3429 private void DMStripMenuItem_Click(object sender, EventArgs e)
3431 MakeReplyOrDirectStatus(false, false);
3434 private async Task doStatusDelete()
3436 if (this._curTab == null || this._curList == null)
3439 if (this._curList.SelectedIndices.Count == 0)
3442 var posts = this._curList.SelectedIndices.Cast<int>()
3443 .Select(x => this.GetCurTabPost(x))
3446 // 選択されたツイートの中に削除可能なものが一つでもあるか
3447 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3450 var ret = MessageBox.Show(this,
3451 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3452 Properties.Resources.DeleteStripMenuItem_ClickText2,
3453 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3455 if (ret != DialogResult.OK)
3458 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3460 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3462 Exception lastException = null;
3463 foreach (var post in posts)
3465 if (!post.CanDeleteBy(this.tw.UserId))
3472 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3477 if (post.RetweetedByUserId == this.tw.UserId)
3478 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3480 await this.twitterApi.StatusesDestroy(post.StatusId)
3483 if (post.UserId == this.tw.UserId)
3485 if (post.RetweetedId != null)
3486 // 他人に RT された自分のツイート
3487 // => RT 元の自分のツイートを削除
3488 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3493 await this.twitterApi.StatusesDestroy(post.StatusId)
3498 catch (WebApiException ex)
3504 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3507 if (lastException == null)
3508 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3510 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3512 this.PurgeListViewItemCache();
3513 this._curPost = null;
3514 this._curItemIndex = -1;
3516 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3518 var listView = (DetailsListView)tabPage.Tag;
3519 var tab = this._statuses.Tabs[tabPage.Text];
3521 using (ControlTransaction.Update(listView))
3523 listView.VirtualListSize = tab.AllCount;
3525 if (tabPage == this._curTab)
3527 listView.SelectedIndices.Clear();
3529 if (tab.AllCount != 0)
3532 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3533 selectedIndex = focusedIndex;
3535 selectedIndex = tab.AllCount - 1;
3537 listView.SelectedIndices.Add(selectedIndex);
3538 listView.EnsureVisible(selectedIndex);
3539 listView.FocusedItem = listView.Items[selectedIndex];
3544 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3546 if (tabPage.ImageIndex == 0)
3547 tabPage.ImageIndex = -1; // タブアイコン
3551 if (!this._cfgCommon.TabIconDisp)
3552 this.ListTab.Refresh();
3556 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3558 await this.doStatusDelete();
3561 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3563 using (ControlTransaction.Update(this._curList))
3565 foreach (int idx in _curList.SelectedIndices)
3567 var post = this._statuses.Tabs[this._curTab.Text][idx];
3568 this._statuses.SetReadAllTab(post.StatusId, read: true);
3569 ChangeCacheStyleRead(true, idx);
3573 foreach (TabPage tb in ListTab.TabPages)
3575 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3577 if (this._cfgCommon.TabIconDisp)
3579 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3583 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3586 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3588 using (ControlTransaction.Update(this._curList))
3590 foreach (int idx in _curList.SelectedIndices)
3592 var post = this._statuses.Tabs[this._curTab.Text][idx];
3593 this._statuses.SetReadAllTab(post.StatusId, read: false);
3594 ChangeCacheStyleRead(false, idx);
3598 foreach (TabPage tb in ListTab.TabPages)
3600 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3602 if (this._cfgCommon.TabIconDisp)
3604 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3608 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3611 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3613 await this.DoRefresh();
3616 private async Task DoRefresh()
3618 if (_curTab != null)
3621 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3624 switch (_statuses.Tabs[_curTab.Text].TabType)
3626 case MyCommon.TabUsageType.Mentions:
3627 await this.GetReplyAsync();
3629 case MyCommon.TabUsageType.DirectMessage:
3630 await this.GetDirectMessagesAsync();
3632 case MyCommon.TabUsageType.Favorites:
3633 await this.GetFavoritesAsync();
3635 //case MyCommon.TabUsageType.Profile:
3637 case MyCommon.TabUsageType.PublicSearch:
3638 var searchTab = (PublicSearchTabModel)tab;
3639 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3640 await this.GetPublicSearchAsync(searchTab);
3642 case MyCommon.TabUsageType.UserTimeline:
3643 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3645 case MyCommon.TabUsageType.Lists:
3646 var listTab = (ListTimelineTabModel)tab;
3647 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3648 await this.GetListTimelineAsync(listTab);
3651 await this.GetHomeTimelineAsync();
3657 await this.GetHomeTimelineAsync();
3661 private async Task DoRefreshMore()
3664 if (_curTab != null)
3667 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3670 switch (_statuses.Tabs[_curTab.Text].TabType)
3672 case MyCommon.TabUsageType.Mentions:
3673 await this.GetReplyAsync(loadMore: true);
3675 case MyCommon.TabUsageType.DirectMessage:
3676 await this.GetDirectMessagesAsync(loadMore: true);
3678 case MyCommon.TabUsageType.Favorites:
3679 await this.GetFavoritesAsync(loadMore: true);
3681 case MyCommon.TabUsageType.Profile:
3684 case MyCommon.TabUsageType.PublicSearch:
3685 var searchTab = (PublicSearchTabModel)tab;
3686 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3687 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3689 case MyCommon.TabUsageType.UserTimeline:
3690 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3692 case MyCommon.TabUsageType.Lists:
3693 var listTab = (ListTimelineTabModel)tab;
3694 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3695 await this.GetListTimelineAsync(listTab, loadMore: true);
3698 await this.GetHomeTimelineAsync(loadMore: true);
3704 await this.GetHomeTimelineAsync(loadMore: true);
3708 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3710 DialogResult result = DialogResult.Abort;
3712 using (var settingDialog = new AppendSettingDialog())
3714 settingDialog.Icon = this.MainIcon;
3715 settingDialog.Owner = this;
3716 settingDialog.ShowInTaskbar = showTaskbarIcon;
3717 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3719 settingDialog.tw = this.tw;
3720 settingDialog.twitterApi = this.twitterApi;
3722 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
3726 result = settingDialog.ShowDialog(this);
3730 return DialogResult.Abort;
3733 if (result == DialogResult.OK)
3737 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3745 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3748 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3750 var oldIconSz = this._cfgCommon.IconSize;
3752 if (ShowSettingDialog() == DialogResult.OK)
3756 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3757 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3758 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3759 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3760 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3761 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
3763 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3764 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3765 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3766 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3767 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
3769 ImageSelector.Reset(tw, this.tw.Configuration);
3773 if (this._cfgCommon.TabIconDisp)
3775 ListTab.DrawItem -= ListTab_DrawItem;
3776 ListTab.DrawMode = TabDrawMode.Normal;
3777 ListTab.ImageList = this.TabImage;
3781 ListTab.DrawItem -= ListTab_DrawItem;
3782 ListTab.DrawItem += ListTab_DrawItem;
3783 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3784 ListTab.ImageList = null;
3787 catch (Exception ex)
3789 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3790 ex.Data["IsTerminatePermission"] = false;
3796 if (!this._cfgCommon.UnreadManage)
3798 ReadedStripMenuItem.Enabled = false;
3799 UnreadStripMenuItem.Enabled = false;
3800 if (this._cfgCommon.TabIconDisp)
3802 foreach (TabPage myTab in ListTab.TabPages)
3804 myTab.ImageIndex = -1;
3810 ReadedStripMenuItem.Enabled = true;
3811 UnreadStripMenuItem.Enabled = true;
3814 catch (Exception ex)
3816 ex.Data["Instance"] = "ListTab(UnreadManage)";
3817 ex.Data["IsTerminatePermission"] = false;
3824 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3826 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3827 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3828 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3830 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3831 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3832 _fntUnread = this._cfgLocal.FontUnread;
3833 _clUnread = this._cfgLocal.ColorUnread;
3834 _fntReaded = this._cfgLocal.FontRead;
3835 _clReaded = this._cfgLocal.ColorRead;
3836 _clFav = this._cfgLocal.ColorFav;
3837 _clOWL = this._cfgLocal.ColorOWL;
3838 _clRetweet = this._cfgLocal.ColorRetweet;
3839 _fntDetail = this._cfgLocal.FontDetail;
3840 _clDetail = this._cfgLocal.ColorDetail;
3841 _clDetailLink = this._cfgLocal.ColorDetailLink;
3842 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3843 _clSelf = this._cfgLocal.ColorSelf;
3844 _clAtSelf = this._cfgLocal.ColorAtSelf;
3845 _clTarget = this._cfgLocal.ColorTarget;
3846 _clAtTarget = this._cfgLocal.ColorAtTarget;
3847 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3848 _clAtTo = this._cfgLocal.ColorAtTo;
3849 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3850 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3851 _clInputFont = this._cfgLocal.ColorInputFont;
3852 _fntInputFont = this._cfgLocal.FontInputFont;
3853 _brsBackColorMine.Dispose();
3854 _brsBackColorAt.Dispose();
3855 _brsBackColorYou.Dispose();
3856 _brsBackColorAtYou.Dispose();
3857 _brsBackColorAtFromTarget.Dispose();
3858 _brsBackColorAtTo.Dispose();
3859 _brsBackColorNone.Dispose();
3860 _brsBackColorMine = new SolidBrush(_clSelf);
3861 _brsBackColorAt = new SolidBrush(_clAtSelf);
3862 _brsBackColorYou = new SolidBrush(_clTarget);
3863 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3864 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3865 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3866 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3870 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3871 StatusText.Font = _fntInputFont;
3872 StatusText.ForeColor = _clInputFont;
3874 catch (Exception ex)
3876 MessageBox.Show(ex.Message);
3881 InitDetailHtmlFormat();
3883 catch (Exception ex)
3885 ex.Data["Instance"] = "Font";
3886 ex.Data["IsTerminatePermission"] = false;
3892 foreach (TabPage tb in ListTab.TabPages)
3894 if (this._cfgCommon.TabIconDisp)
3896 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3903 catch (Exception ex)
3905 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3906 ex.Data["IsTerminatePermission"] = false;
3912 var oldIconCol = _iconCol;
3914 if (this._cfgCommon.IconSize != oldIconSz)
3915 ApplyListViewIconSize(this._cfgCommon.IconSize);
3917 foreach (TabPage tp in ListTab.TabPages)
3919 DetailsListView lst = (DetailsListView)tp.Tag;
3921 using (ControlTransaction.Update(lst))
3923 lst.GridLines = this._cfgCommon.ShowGrid;
3924 lst.Font = _fntReaded;
3925 lst.BackColor = _clListBackcolor;
3927 if (_iconCol != oldIconCol)
3932 catch (Exception ex)
3934 ex.Data["Instance"] = "ListView(IconSize)";
3935 ex.Data["IsTerminatePermission"] = false;
3939 SetMainWindowTitle();
3940 SetNotifyIconText();
3942 this.PurgeListViewItemCache();
3943 _curList?.Refresh();
3946 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3947 if (this._cfgCommon.HotkeyEnabled)
3949 ///グローバルホットキーの登録。設定で変更可能にするかも
3950 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3951 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
3952 modKey |= HookGlobalHotkey.ModKeys.Alt;
3953 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
3954 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3955 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
3956 modKey |= HookGlobalHotkey.ModKeys.Shift;
3957 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
3958 modKey |= HookGlobalHotkey.ModKeys.Win;
3960 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
3963 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
3966 StatusText_TextChanged(null, null);
3975 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3976 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3979 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3981 this.TopMost = this._cfgCommon.AlwaysTop;
3982 SaveConfigsAll(false);
3984 if (tw.Username != oldUser.Username)
3985 await this.doGetFollowersMenu();
3991 private void SetTabAlignment()
3993 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3994 if (ListTab.Alignment == newAlignment) return;
3996 // 各タブのリスト上の選択位置などを退避
3997 var listSelections = this.SaveListViewSelection();
3999 ListTab.Alignment = newAlignment;
4001 foreach (TabPage tab in ListTab.TabPages)
4003 DetailsListView lst = (DetailsListView)tab.Tag;
4004 TabModel tabInfo = _statuses.Tabs[tab.Text];
4005 using (ControlTransaction.Update(lst))
4008 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4013 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4019 case MyCommon.IconSizes.IconNone:
4022 case MyCommon.IconSizes.Icon16:
4025 case MyCommon.IconSizes.Icon24:
4028 case MyCommon.IconSizes.Icon48:
4031 case MyCommon.IconSizes.Icon48_2:
4039 // ディスプレイの DPI 設定を考慮したサイズを設定する
4040 _listViewImageList.ImageSize = new Size(
4042 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4046 _listViewImageList.ImageSize = new Size(1, 1);
4050 private void ResetColumns(DetailsListView list)
4052 using (ControlTransaction.Update(list))
4053 using (ControlTransaction.Layout(list, false))
4056 list.ColumnClick -= MyList_ColumnClick;
4057 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4058 list.ColumnReordered -= MyList_ColumnReordered;
4059 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4061 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4062 list.Columns.Clear();
4063 cols.ForEach(col => col.Dispose());
4066 InitColumns(list, true);
4068 list.ColumnClick += MyList_ColumnClick;
4069 list.DrawColumnHeader += MyList_DrawColumnHeader;
4070 list.ColumnReordered += MyList_ColumnReordered;
4071 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4075 public void AddNewTabForSearch(string searchWord)
4077 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4078 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4080 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4082 foreach (TabPage tp in ListTab.TabPages)
4084 if (tb.TabName == tp.Text)
4086 ListTab.SelectedTab = tp;
4093 string tabName = searchWord;
4094 for (int i = 0; i <= 100; i++)
4096 if (_statuses.ContainsTab(tabName))
4102 var tab = new PublicSearchTabModel(tabName);
4103 _statuses.AddTab(tab);
4104 AddNewTab(tab, startup: false);
4106 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4108 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4109 cmb.Items.Add(searchWord);
4110 cmb.Text = searchWord;
4113 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4116 private void ShowUserTimeline()
4118 if (!this.ExistCurrentPost) return;
4119 AddNewTabForUserTimeline(_curPost.ScreenName);
4122 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4124 if (e.KeyCode == Keys.Escape)
4126 TabPage relTp = ListTab.SelectedTab;
4127 RemoveSpecifiedTab(relTp.Text, false);
4129 e.SuppressKeyPress = true;
4133 public void AddNewTabForUserTimeline(string user)
4135 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4136 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4138 if (tb.ScreenName == user)
4140 foreach (TabPage tp in ListTab.TabPages)
4142 if (tb.TabName == tp.Text)
4144 ListTab.SelectedTab = tp;
4151 string tabName = "user:" + user;
4152 while (_statuses.ContainsTab(tabName))
4157 var tab = new UserTimelineTabModel(tabName, user);
4158 this._statuses.AddTab(tab);
4159 this.AddNewTab(tab, startup: false);
4161 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4164 this.GetUserTimelineAsync(tab);
4167 public bool AddNewTab(TabModel tab, bool startup)
4170 foreach (TabPage tb in ListTab.TabPages)
4172 if (tb.Text == tab.TabName) return false;
4176 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4178 var _tabPage = new TabPage();
4179 var _listCustom = new DetailsListView();
4181 int cnt = ListTab.TabPages.Count;
4183 ///ToDo:Create and set controls follow tabtypes
4185 using (ControlTransaction.Update(_listCustom))
4186 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4187 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4188 using (ControlTransaction.Layout(this.SplitContainer1, false))
4189 using (ControlTransaction.Layout(this.ListTab, false))
4190 using (ControlTransaction.Layout(this))
4191 using (ControlTransaction.Layout(_tabPage, false))
4193 _tabPage.Controls.Add(_listCustom);
4196 var userTab = tab as UserTimelineTabModel;
4197 var listTab = tab as ListTimelineTabModel;
4198 var searchTab = tab as PublicSearchTabModel;
4200 if (userTab != null || listTab != null)
4202 var label = new Label();
4203 label.Dock = DockStyle.Top;
4204 label.Name = "labelUser";
4207 if (listTab != null)
4209 label.Text = listTab.ListInfo.ToString();
4211 else if (userTab != null)
4213 label.Text = userTab.ScreenName + "'s Timeline";
4215 label.TextAlign = ContentAlignment.MiddleLeft;
4216 using (ComboBox tmpComboBox = new ComboBox())
4218 label.Height = tmpComboBox.Height;
4220 _tabPage.Controls.Add(label);
4223 else if (searchTab != null)
4225 var pnl = new Panel();
4227 var lbl = new Label();
4228 var cmb = new ComboBox();
4229 var btn = new Button();
4230 var cmbLang = new ComboBox();
4232 using (ControlTransaction.Layout(pnl, false))
4234 pnl.Controls.Add(cmb);
4235 pnl.Controls.Add(cmbLang);
4236 pnl.Controls.Add(btn);
4237 pnl.Controls.Add(lbl);
4238 pnl.Name = "panelSearch";
4240 pnl.Dock = DockStyle.Top;
4241 pnl.Height = cmb.Height;
4242 pnl.Enter += SearchControls_Enter;
4243 pnl.Leave += SearchControls_Leave;
4246 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4247 cmb.Dock = DockStyle.Fill;
4248 cmb.Name = "comboSearch";
4249 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4250 cmb.ImeMode = ImeMode.NoControl;
4251 cmb.TabStop = false;
4253 cmb.AutoCompleteMode = AutoCompleteMode.None;
4254 cmb.KeyDown += SearchComboBox_KeyDown;
4257 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4258 cmbLang.Dock = DockStyle.Right;
4260 cmbLang.Name = "comboLang";
4261 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4262 cmbLang.TabStop = false;
4263 cmbLang.TabIndex = 2;
4264 cmbLang.Items.Add("");
4265 cmbLang.Items.Add("ja");
4266 cmbLang.Items.Add("en");
4267 cmbLang.Items.Add("ar");
4268 cmbLang.Items.Add("da");
4269 cmbLang.Items.Add("nl");
4270 cmbLang.Items.Add("fa");
4271 cmbLang.Items.Add("fi");
4272 cmbLang.Items.Add("fr");
4273 cmbLang.Items.Add("de");
4274 cmbLang.Items.Add("hu");
4275 cmbLang.Items.Add("is");
4276 cmbLang.Items.Add("it");
4277 cmbLang.Items.Add("no");
4278 cmbLang.Items.Add("pl");
4279 cmbLang.Items.Add("pt");
4280 cmbLang.Items.Add("ru");
4281 cmbLang.Items.Add("es");
4282 cmbLang.Items.Add("sv");
4283 cmbLang.Items.Add("th");
4285 lbl.Text = "Search(C-S-f)";
4286 lbl.Name = "label1";
4287 lbl.Dock = DockStyle.Left;
4289 lbl.Height = cmb.Height;
4290 lbl.TextAlign = ContentAlignment.MiddleLeft;
4293 btn.Text = "Search";
4294 btn.Name = "buttonSearch";
4295 btn.UseVisualStyleBackColor = true;
4296 btn.Dock = DockStyle.Right;
4297 btn.TabStop = false;
4299 btn.Click += SearchButton_Click;
4301 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4303 cmb.Items.Add(searchTab.SearchWords);
4304 cmb.Text = searchTab.SearchWords;
4307 cmbLang.Text = searchTab.SearchLang;
4309 _tabPage.Controls.Add(pnl);
4313 _tabPage.Tag = _listCustom;
4314 this.ListTab.Controls.Add(_tabPage);
4316 _tabPage.Location = new Point(4, 4);
4317 _tabPage.Name = "CTab" + cnt;
4318 _tabPage.Size = new Size(380, 260);
4319 _tabPage.TabIndex = 2 + cnt;
4320 _tabPage.Text = tab.TabName;
4321 _tabPage.UseVisualStyleBackColor = true;
4322 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4324 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4325 _listCustom.TabIndex = 1;
4326 _listCustom.AllowColumnReorder = true;
4327 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4328 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4329 _listCustom.Dock = DockStyle.Fill;
4330 _listCustom.FullRowSelect = true;
4331 _listCustom.HideSelection = false;
4332 _listCustom.Location = new Point(0, 0);
4333 _listCustom.Margin = new Padding(0);
4334 _listCustom.Name = "CList" + Environment.TickCount;
4335 _listCustom.ShowItemToolTips = true;
4336 _listCustom.Size = new Size(380, 260);
4337 _listCustom.UseCompatibleStateImageBehavior = false;
4338 _listCustom.View = View.Details;
4339 _listCustom.OwnerDraw = true;
4340 _listCustom.VirtualMode = true;
4341 _listCustom.Font = _fntReaded;
4342 _listCustom.BackColor = _clListBackcolor;
4344 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4345 _listCustom.AllowDrop = true;
4347 _listCustom.SmallImageList = _listViewImageList;
4349 InitColumns(_listCustom, startup);
4351 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4352 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4353 _listCustom.ColumnClick += MyList_ColumnClick;
4354 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4355 _listCustom.DragDrop += TweenMain_DragDrop;
4356 _listCustom.DragEnter += TweenMain_DragEnter;
4357 _listCustom.DragOver += TweenMain_DragOver;
4358 _listCustom.DrawItem += MyList_DrawItem;
4359 _listCustom.MouseClick += MyList_MouseClick;
4360 _listCustom.ColumnReordered += MyList_ColumnReordered;
4361 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4362 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4363 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4364 _listCustom.DrawSubItem += MyList_DrawSubItem;
4365 _listCustom.HScrolled += MyList_HScrolled;
4371 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4373 var tabInfo = _statuses.GetTabByName(TabName);
4374 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4378 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4379 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4380 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4386 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4387 if (_tabPage == null) return false;
4389 SetListProperty(); //他のタブに列幅等を反映
4392 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4393 _tabPage.Tag = null;
4395 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4396 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4397 using (ControlTransaction.Layout(this.SplitContainer1, false))
4398 using (ControlTransaction.Layout(this.ListTab, false))
4399 using (ControlTransaction.Layout(this))
4400 using (ControlTransaction.Layout(_tabPage, false))
4402 if (this.ListTab.SelectedTab == _tabPage)
4404 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4405 this._beforeSelectedTab = null;
4407 this.ListTab.Controls.Remove(_tabPage);
4410 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4412 using (Control label = _tabPage.Controls["labelUser"])
4414 _tabPage.Controls.Remove(label);
4417 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4419 using (Control pnl = _tabPage.Controls["panelSearch"])
4421 pnl.Enter -= SearchControls_Enter;
4422 pnl.Leave -= SearchControls_Leave;
4423 _tabPage.Controls.Remove(pnl);
4425 foreach (Control ctrl in pnl.Controls)
4427 if (ctrl.Name == "buttonSearch")
4429 ctrl.Click -= SearchButton_Click;
4431 else if (ctrl.Name == "comboSearch")
4433 ctrl.KeyDown -= SearchComboBox_KeyDown;
4435 pnl.Controls.Remove(ctrl);
4441 _tabPage.Controls.Remove(_listCustom);
4443 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4444 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4445 _listCustom.ColumnClick -= MyList_ColumnClick;
4446 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4447 _listCustom.DragDrop -= TweenMain_DragDrop;
4448 _listCustom.DragEnter -= TweenMain_DragEnter;
4449 _listCustom.DragOver -= TweenMain_DragOver;
4450 _listCustom.DrawItem -= MyList_DrawItem;
4451 _listCustom.MouseClick -= MyList_MouseClick;
4452 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4453 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4454 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4455 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4456 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4457 _listCustom.HScrolled -= MyList_HScrolled;
4459 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4460 _listCustom.Columns.Clear();
4461 cols.ForEach(col => col.Dispose());
4464 _listCustom.ContextMenuStrip = null;
4465 _listCustom.ColumnHeaderContextMenuStrip = null;
4466 _listCustom.Font = null;
4468 _listCustom.SmallImageList = null;
4469 _listCustom.ListViewItemSorter = null;
4472 if (_curTab.Equals(_tabPage))
4479 this.PurgeListViewItemCache();
4483 _listCustom.Dispose();
4484 _statuses.RemoveTab(TabName);
4486 foreach (TabPage tp in ListTab.TabPages)
4488 DetailsListView lst = (DetailsListView)tp.Tag;
4489 var count = _statuses.Tabs[tp.Text].AllCount;
4490 lst.VirtualListSize = count;
4496 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4498 this.PurgeListViewItemCache();
4499 _beforeSelectedTab = e.TabPage;
4502 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4506 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4509 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4510 if (!dragEnableRectangle.Contains(e.Location))
4512 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4513 tn = ListTab.SelectedTab.Text;
4516 if (string.IsNullOrEmpty(tn)) return;
4518 foreach (TabPage tb in ListTab.TabPages)
4522 ListTab.DoDragDrop(tb, DragDropEffects.All);
4532 Point cpos = new Point(e.X, e.Y);
4533 for (int i = 0; i < ListTab.TabPages.Count; i++)
4535 Rectangle rect = ListTab.GetTabRect(i);
4536 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4537 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4539 _rclickTabName = ListTab.TabPages[i].Text;
4545 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4547 //_curList.Refresh();
4548 SetMainWindowTitle();
4549 SetStatusLabelUrl();
4550 SetApiStatusLabel();
4551 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4552 TabMenuControl(ListTab.SelectedTab.Text);
4553 this.PushSelectPostChain();
4554 await DispSelectedPost();
4557 private void SetListProperty()
4559 //削除などで見つからない場合は処理せず
4560 if (_curList == null) return;
4561 if (!_isColumnChanged) return;
4563 int[] dispOrder = new int[_curList.Columns.Count];
4564 for (int i = 0; i < _curList.Columns.Count; i++)
4566 for (int j = 0; j < _curList.Columns.Count; j++)
4568 if (_curList.Columns[j].DisplayIndex == i)
4577 foreach (TabPage tb in ListTab.TabPages)
4579 if (!tb.Equals(_curTab))
4581 if (tb.Tag != null && tb.Controls.Count > 0)
4583 DetailsListView lst = (DetailsListView)tb.Tag;
4584 for (int i = 0; i < lst.Columns.Count; i++)
4586 lst.Columns[dispOrder[i]].DisplayIndex = i;
4587 lst.Columns[i].Width = _curList.Columns[i].Width;
4593 _isColumnChanged = false;
4596 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4598 if (e.KeyChar == '@')
4600 if (!this._cfgCommon.UseAtIdSupplement) return;
4602 int cnt = AtIdSupl.ItemCount;
4603 ShowSuplDialog(StatusText, AtIdSupl);
4604 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4607 else if (e.KeyChar == '#')
4609 if (!this._cfgCommon.UseHashSupplement) return;
4610 ShowSuplDialog(StatusText, HashSupl);
4615 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4617 ShowSuplDialog(owner, dialog, 0, "");
4620 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4622 ShowSuplDialog(owner, dialog, offset, "");
4625 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4627 dialog.StartsWith = startswith;
4634 dialog.ShowDialog();
4636 this.TopMost = this._cfgCommon.AlwaysTop;
4637 int selStart = owner.SelectionStart;
4640 if (dialog.DialogResult == DialogResult.OK)
4642 if (!string.IsNullOrEmpty(dialog.inputText))
4646 fHalf = owner.Text.Substring(0, selStart - offset);
4648 if (selStart < owner.Text.Length)
4650 eHalf = owner.Text.Substring(selStart);
4652 owner.Text = fHalf + dialog.inputText + eHalf;
4653 owner.SelectionStart = selStart + dialog.inputText.Length;
4660 fHalf = owner.Text.Substring(0, selStart);
4662 if (selStart < owner.Text.Length)
4664 eHalf = owner.Text.Substring(selStart);
4666 owner.Text = fHalf + eHalf;
4669 owner.SelectionStart = selStart;
4675 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4678 if (!e.Alt && !e.Control && !e.Shift)
4680 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4682 bool isSpace = false;
4683 foreach (char c in StatusText.Text)
4685 if (c == ' ' || c == ' ')
4698 StatusText.Text = "";
4699 JumpUnreadMenuItem_Click(null, null);
4703 this.StatusText_TextChanged(null, null);
4706 private void StatusText_TextChanged(object sender, EventArgs e)
4709 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4710 lblLen.Text = pLen.ToString();
4713 StatusText.ForeColor = Color.Red;
4717 StatusText.ForeColor = _clInputFont;
4720 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4722 if (string.IsNullOrEmpty(StatusText.Text))
4724 this.inReplyTo = null;
4729 /// ツイート投稿前のフッター付与などの前処理を行います
4731 private string FormatStatusText(string statusText)
4733 statusText = statusText.Replace("\r\n", "\n");
4735 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4738 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4741 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4743 // 文中の全角スペースを半角スペース1個にする
4744 statusText = statusText.Replace(" ", " ");
4747 // DM の場合はこれ以降の処理を行わない
4748 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4752 if (this._cfgCommon.PostShiftEnter)
4754 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4758 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
4759 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4761 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4764 if (statusText.Contains("RT @"))
4765 disableFooter = true;
4770 var hashtag = this.HashMgr.UseHash;
4771 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4774 header = HashMgr.UseHash + " ";
4776 footer = " " + HashMgr.UseHash;
4781 if (this._cfgLocal.UseRecommendStatus)
4784 footer += this.recommendedStatusFooter;
4786 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
4788 // テキストボックスに入力されている文字列を使用する
4789 footer += " " + this._cfgLocal.StatusText.Trim();
4793 statusText = header + statusText + footer;
4795 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4797 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4798 // 参照: https://support.twitter.com/articles/14020
4800 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4801 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4803 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4804 statusText = '\u200b' + statusText;
4812 /// 投稿欄に表示する入力可能な文字数を計算します
4814 private int GetRestStatusCount(string statusText)
4817 var remainCount = this.tw.GetTextLengthRemain(statusText);
4819 var uploadService = this.ImageSelector.SelectedService;
4820 if (this.ImageSelector.Visible && uploadService != null)
4822 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4823 remainCount -= uploadService.GetReservedTextLength(1);
4829 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4831 if (sender != this._curList)
4834 var listCache = this._listItemCache;
4835 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4837 // If the newly requested cache is a subset of the old cache,
4838 // no need to rebuild everything, so do nothing.
4842 // Now we need to rebuild the cache.
4843 this.CreateCache(e.StartIndex, e.EndIndex);
4846 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4848 var listCache = this._listItemCache;
4849 if (listCache?.TargetList == sender)
4852 PostClass cacheItemPost;
4853 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4860 // A cache miss, so create a new ListViewItem and pass it back.
4861 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4864 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4868 // 不正な要求に対する間に合わせの応答
4869 string[] sitem = {"", "", "", "", "", "", "", ""};
4870 e.Item = new ImageListViewItem(sitem);
4874 private void CreateCache(int startIndex, int endIndex)
4876 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4878 if (tabInfo.AllCount == 0)
4881 // キャッシュ要求(要求範囲±30を作成)
4882 startIndex = Math.Max(startIndex - 30, 0);
4883 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4885 var cacheLength = endIndex - startIndex + 1;
4887 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4888 var listItems = Enumerable.Range(0, cacheLength)
4889 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4892 var listCache = new ListViewItemCache
4894 TargetList = this._curList,
4895 StartIndex = startIndex,
4896 EndIndex = endIndex,
4898 ListItem = listItems,
4901 Interlocked.Exchange(ref this._listItemCache, listCache);
4905 /// DetailsListView のための ListViewItem のキャッシュを消去する
4907 private void PurgeListViewItemCache()
4909 Interlocked.Exchange(ref this._listItemCache, null);
4912 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4914 StringBuilder mk = new StringBuilder();
4915 //if (Post.IsDeleted) mk.Append("×");
4916 //if (Post.IsMark) mk.Append("♪");
4917 //if (Post.IsProtect) mk.Append("Ю");
4918 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4919 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4920 ImageListViewItem itm;
4921 if (Post.RetweetedId == null)
4923 string[] sitem= {"",
4925 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4926 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4931 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4935 string[] sitem = {"",
4937 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4938 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4939 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4943 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4945 itm.StateIndex = Post.StateIndex;
4948 bool read = Post.IsRead;
4949 //未読管理していなかったら既読として扱う
4950 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
4951 ChangeItemStyleRead(read, itm, Post, null);
4952 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4957 /// 全てのタブの振り分けルールを反映し直します
4959 private void ApplyPostFilters()
4961 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4963 this.PurgeListViewItemCache();
4964 this._curPost = null;
4965 this._curItemIndex = -1;
4966 this._statuses.FilterAll();
4968 foreach (TabPage tabPage in this.ListTab.TabPages)
4970 var tab = this._statuses.Tabs[tabPage.Text];
4972 var listview = (DetailsListView)tabPage.Tag;
4973 using (ControlTransaction.Update(listview))
4975 listview.VirtualListSize = tab.AllCount;
4978 if (this._cfgCommon.TabIconDisp)
4980 if (tab.UnreadCount > 0)
4981 tabPage.ImageIndex = 0;
4983 tabPage.ImageIndex = -1;
4987 if (!this._cfgCommon.TabIconDisp)
4988 this.ListTab.Refresh();
4990 SetMainWindowTitle();
4991 SetStatusLabelUrl();
4995 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4997 e.DrawDefault = true;
5000 private void MyList_HScrolled(object sender, EventArgs e)
5002 DetailsListView listView = (DetailsListView)sender;
5006 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5008 if (e.State == 0) return;
5009 e.DrawDefault = false;
5011 SolidBrush brs2 = null;
5012 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5014 if (e.Item.BackColor == _clSelf)
5015 brs2 = _brsBackColorMine;
5016 else if (e.Item.BackColor == _clAtSelf)
5017 brs2 = _brsBackColorAt;
5018 else if (e.Item.BackColor == _clTarget)
5019 brs2 = _brsBackColorYou;
5020 else if (e.Item.BackColor == _clAtTarget)
5021 brs2 = _brsBackColorAtYou;
5022 else if (e.Item.BackColor == _clAtFromTarget)
5023 brs2 = _brsBackColorAtFromTarget;
5024 else if (e.Item.BackColor == _clAtTo)
5025 brs2 = _brsBackColorAtTo;
5027 brs2 = _brsBackColorNone;
5032 if (((Control)sender).Focused)
5033 brs2 = _brsHighLight;
5035 brs2 = _brsDeactiveSelection;
5037 e.Graphics.FillRectangle(brs2, e.Bounds);
5038 e.DrawFocusRectangle();
5039 this.DrawListViewItemIcon(e);
5042 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5044 if (e.ItemState == 0) return;
5046 if (e.ColumnIndex > 0)
5049 var post = (PostClass)e.Item.Tag;
5051 RectangleF rct = e.Bounds;
5052 rct.Width = e.Header.Width;
5053 int fontHeight = e.Item.Font.Height;
5056 rct.Y += fontHeight;
5057 rct.Height -= fontHeight;
5061 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5063 //if (heightDiff > fontHeight * 0.7)
5065 // rct.Height += fontHeight;
5066 // drawLineCount += 1;
5069 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5070 if (!_iconCol && drawLineCount <= 1)
5072 //rct.Inflate(0, heightDiff / -2);
5073 //rct.Height += fontHeight / 2;
5075 else if (heightDiff < fontHeight * 0.7)
5077 //最終行が70%以上欠けていたら、最終行は表示しない
5078 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5079 rct.Height = (fontHeight * drawLineCount) - 1;
5086 //if (!_iconCol && drawLineCount > 1)
5088 // rct.Y += fontHeight * 0.2;
5089 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5094 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5095 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5100 Rectangle rctB = e.Bounds;
5101 rctB.Width = e.Header.Width;
5102 rctB.Height = fontHeight;
5104 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5106 TextRenderer.DrawText(e.Graphics,
5107 post.TextSingleLine,
5109 Rectangle.Round(rct),
5111 TextFormatFlags.WordBreak |
5112 TextFormatFlags.EndEllipsis |
5113 TextFormatFlags.GlyphOverhangPadding |
5114 TextFormatFlags.NoPrefix);
5115 TextRenderer.DrawText(e.Graphics,
5116 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 + "]",
5120 TextFormatFlags.SingleLine |
5121 TextFormatFlags.EndEllipsis |
5122 TextFormatFlags.GlyphOverhangPadding |
5123 TextFormatFlags.NoPrefix);
5126 else if (drawLineCount == 1)
5128 TextRenderer.DrawText(e.Graphics,
5129 e.ColumnIndex != 2 ? e.SubItem.Text : post.TextSingleLine,
5131 Rectangle.Round(rct),
5133 TextFormatFlags.SingleLine |
5134 TextFormatFlags.EndEllipsis |
5135 TextFormatFlags.GlyphOverhangPadding |
5136 TextFormatFlags.NoPrefix |
5137 TextFormatFlags.VerticalCenter);
5141 TextRenderer.DrawText(e.Graphics,
5142 e.ColumnIndex != 2 ? e.SubItem.Text : post.TextSingleLine,
5144 Rectangle.Round(rct),
5146 TextFormatFlags.WordBreak |
5147 TextFormatFlags.EndEllipsis |
5148 TextFormatFlags.GlyphOverhangPadding |
5149 TextFormatFlags.NoPrefix);
5151 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5156 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5158 if (_iconSz == 0) return;
5160 ImageListViewItem item = (ImageListViewItem)e.Item;
5162 //e.Bounds.Leftが常に0を指すから自前で計算
5163 Rectangle itemRect = item.Bounds;
5164 var col0 = e.Item.ListView.Columns[0];
5165 itemRect.Width = col0.Width;
5167 if (col0.DisplayIndex > 0)
5169 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5171 if (clm.DisplayIndex < col0.DisplayIndex)
5172 itemRect.X += clm.Width;
5176 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5177 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5178 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5181 var img = item.Image;
5184 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5185 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5187 if (iconRect.Width > 0)
5189 e.Graphics.FillRectangle(Brushes.White, iconRect);
5190 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5193 e.Graphics.DrawImage(img.Image, iconRect);
5195 catch (ArgumentException)
5197 item.RefreshImageAsync();
5203 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5204 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5206 item.GetImageAsync();
5209 if (item.StateIndex > -1)
5211 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5212 if (stateRect.Width > 0)
5214 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5215 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5216 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5221 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5223 base.ScaleControl(factor, specified);
5225 ScaleChildControl(this.TabImage, factor);
5227 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5228 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5230 foreach (var listview in listviews)
5232 ScaleChildControl(listview, factor);
5236 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5238 // ImageListViewItem item = (ImageListViewItem)e.Item;
5239 // if (item.StateImageIndex > -1)
5241 // ////e.Bounds.Leftが常に0を指すから自前で計算
5242 // //Rectangle itemRect = item.Bounds;
5243 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5245 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5247 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5249 // // itemRect.X += clm.Width;
5253 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5254 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5256 // if (rct.Width > 0)
5258 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5259 // //e.Graphics.FillRectangle(Brushes.White, rct);
5260 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5261 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5266 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5268 var tab = this._statuses.Tabs[this._curTab.Text];
5270 if (tab.AllCount == 0)
5272 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5276 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5281 case SEARCHTYPE.NextSearch: // 次を検索
5282 if (selectedIndex != -1)
5283 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5287 case SEARCHTYPE.PrevSearch: // 前を検索
5288 if (selectedIndex != -1)
5289 startIndex = Math.Max(selectedIndex - 1, 0);
5291 startIndex = tab.AllCount - 1;
5293 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5295 if (selectedIndex != -1)
5296 startIndex = selectedIndex;
5302 Func<string, bool> stringComparer;
5305 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5307 catch (ArgumentException)
5309 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5313 var reverse = searchType == SEARCHTYPE.PrevSearch;
5314 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5315 .DefaultIfEmpty(-1).First();
5317 if (foundIndex == -1)
5319 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5323 this.SelectListItem(this._curList, foundIndex);
5324 this._curList.EnsureVisible(foundIndex);
5327 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5330 this.ShowSearchDialog();
5333 private void MenuItemSearchNext_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.NextSearch);
5351 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5353 var previousSearch = this.SearchDialog.ResultOptions;
5354 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5356 this.SearchDialog.Reset();
5357 this.ShowSearchDialog();
5363 previousSearch.Query,
5364 previousSearch.CaseSensitive,
5365 previousSearch.UseRegex,
5366 SEARCHTYPE.PrevSearch);
5370 /// 検索ダイアログを表示し、検索を実行します
5372 private void ShowSearchDialog()
5374 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5376 this.TopMost = this._cfgCommon.AlwaysTop;
5379 this.TopMost = this._cfgCommon.AlwaysTop;
5381 var searchOptions = this.SearchDialog.ResultOptions;
5382 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5384 if (searchOptions.NewTab)
5386 var tabName = Properties.Resources.SearchResults_TabName;
5390 tabName = this._statuses.MakeTabName(tabName);
5392 catch (TabException ex)
5394 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5397 var resultTab = new LocalSearchTabModel(tabName);
5398 this.AddNewTab(resultTab, startup: false);
5399 this._statuses.AddTab(resultTab);
5401 var targetTab = this._statuses.Tabs[this._curTab.Text];
5403 Func<string, bool> stringComparer;
5406 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5408 catch (ArgumentException)
5410 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5414 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5415 if (foundIndices.Length == 0)
5417 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5421 var foundPosts = foundIndices.Select(x => targetTab[x]);
5422 foreach (var post in foundPosts)
5424 resultTab.AddPostQueue(post);
5427 this._statuses.DistributePosts();
5428 this.RefreshTimeline();
5430 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5431 .First(x => x.Text == tabName);
5433 this.ListTab.SelectedTab = tabPage;
5438 searchOptions.Query,
5439 searchOptions.CaseSensitive,
5440 searchOptions.UseRegex,
5441 SEARCHTYPE.DialogSearch);
5444 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5446 this.AddNewTabForSearch(searchOptions.Query);
5450 /// <summary>発言検索に使用するメソッドを生成します</summary>
5451 /// <exception cref="ArgumentException">
5452 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5454 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5458 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5459 var regex = new Regex(query, regexOption);
5461 return x => regex.IsMatch(x);
5465 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5467 return x => x.IndexOf(query, comparisonType) != -1;
5471 private void AboutMenuItem_Click(object sender, EventArgs e)
5473 using (TweenAboutBox about = new TweenAboutBox())
5475 about.ShowDialog(this);
5477 this.TopMost = this._cfgCommon.AlwaysTop;
5480 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5482 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5484 if (ImageSelector.Enabled)
5487 TabModel foundTab = null;
5488 DetailsListView lst = null;
5491 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5493 var tabPage = this.ListTab.TabPages[i];
5494 var tab = this._statuses.Tabs[tabPage.Text];
5496 if (tab.NextUnreadIndex != -1)
5498 ListTab.SelectedIndex = i;
5500 lst = (DetailsListView)tabPage.Tag;
5505 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5506 if (foundTab == null && bgnIdx > 0)
5508 for (int i = 0; i < bgnIdx; i++)
5510 var tabPage = this.ListTab.TabPages[i];
5511 var tab = this._statuses.Tabs[tabPage.Text];
5513 if (tab.NextUnreadIndex != -1)
5515 ListTab.SelectedIndex = i;
5517 lst = (DetailsListView)tabPage.Tag;
5524 if (foundTab != null)
5526 idx = foundTab.NextUnreadIndex;
5530 //全部調べたが未読見つからず→先頭タブの最新発言へ
5531 ListTab.SelectedIndex = 0;
5532 var tabPage = this.ListTab.TabPages[0];
5533 var tab = this._statuses.Tabs[tabPage.Text];
5535 if (tab.AllCount == 0)
5538 if (_statuses.SortOrder == SortOrder.Ascending)
5539 idx = tab.AllCount - 1;
5543 lst = (DetailsListView)tabPage.Tag;
5546 SelectListItem(lst, idx);
5548 if (_statuses.SortMode == ComparerMode.Id)
5550 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5551 _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5557 lst.EnsureVisible(idx);
5562 lst.EnsureVisible(idx);
5568 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5570 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5572 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5573 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5577 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5579 if (_curList.SelectedIndices.Count > 0)
5581 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5582 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5586 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5588 await this.CheckNewVersion(false);
5591 private void RunTweenUp()
5593 ProcessStartInfo pinfo = new ProcessStartInfo();
5594 pinfo.UseShellExecute = true;
5595 pinfo.WorkingDirectory = MyCommon.settingPath;
5596 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5597 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5600 Process.Start(pinfo);
5604 MessageBox.Show("Failed to execute TweenUp3.exe.");
5608 public class VersionInfo
5610 public Version Version { get; set; }
5611 public Uri DownloadUri { get; set; }
5612 public string ReleaseNote { get; set; }
5616 /// OpenTween の最新バージョンの情報を取得します
5618 public async Task<VersionInfo> GetVersionInfoAsync()
5620 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5621 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5623 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5624 .ConfigureAwait(false);
5626 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5627 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5629 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5630 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5632 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5634 return new VersionInfo
5636 Version = Version.Parse(msgHeader[0]),
5637 DownloadUri = new Uri(msgHeader[1]),
5638 ReleaseNote = msgBody,
5642 private async Task CheckNewVersion(bool startup = false)
5644 if (ApplicationSettings.VersionInfoUrl == null)
5645 return; // 更新チェック無効化
5649 var versionInfo = await this.GetVersionInfoAsync();
5651 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5656 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5657 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5658 msgtext = MyCommon.ReplaceAppName(msgtext);
5660 MessageBox.Show(msgtext,
5661 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5662 MessageBoxButtons.OK, MessageBoxIcon.Information);
5667 using (var dialog = new UpdateDialog())
5669 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5670 MyCommon.GetReadableVersion(versionInfo.Version));
5671 dialog.DetailsText = versionInfo.ReleaseNote;
5673 if (dialog.ShowDialog(this) == DialogResult.Yes)
5675 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5681 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5684 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5685 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5686 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5691 private async Task Colorize()
5694 await this.DispSelectedPost();
5695 //件数関連の場合、タイトル即時書き換え
5696 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5697 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5698 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5699 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5701 SetMainWindowTitle();
5703 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5704 SetStatusLabelUrl();
5705 foreach (TabPage tb in ListTab.TabPages)
5707 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5709 if (this._cfgCommon.TabIconDisp)
5711 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5715 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5718 public string createDetailHtml(string orgdata)
5720 if (this._cfgLocal.UseTwemoji)
5721 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5723 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5726 private Task DispSelectedPost()
5728 return this.DispSelectedPost(false);
5731 private PostClass displayPost = new PostClass();
5734 /// サムネイル表示に使用する CancellationToken の生成元
5736 private CancellationTokenSource thumbnailTokenSource = null;
5738 private async Task DispSelectedPost(bool forceupdate)
5740 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5743 var oldDisplayPost = this.displayPost;
5744 this.displayPost = this._curPost;
5746 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5749 var loadTasks = new List<Task>
5751 this.tweetDetailsView.ShowPostDetails(this._curPost),
5754 this.SplitContainer3.Panel2Collapsed = true;
5756 if (this._cfgCommon.PreviewEnable)
5758 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5759 oldTokenSource?.Cancel();
5761 var token = this.thumbnailTokenSource.Token;
5762 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5767 await Task.WhenAll(loadTasks);
5769 catch (OperationCanceledException) { }
5772 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5774 await this.OpenApplicationWebsite();
5777 private async Task OpenApplicationWebsite()
5779 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5782 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5784 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5787 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5789 if (ListTab.SelectedTab != null)
5791 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5793 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5794 if (pnl.Controls["comboSearch"].Focused ||
5795 pnl.Controls["comboLang"].Focused ||
5796 pnl.Controls["buttonSearch"].Focused) return;
5799 if (e.Control || e.Shift || e.Alt)
5800 this._anchorFlag = false;
5803 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5806 e.SuppressKeyPress = true;
5809 if (asyncTask != null)
5814 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5816 private void InitializeShortcuts()
5818 this.shortcutCommands = new[]
5820 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5821 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5822 .FocusedOn(FocusedControl.ListTab)
5823 .Do(() => SendKeys.Send("{DOWN}")),
5825 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5826 .FocusedOn(FocusedControl.ListTab)
5827 .Do(() => SendKeys.Send("{UP}")),
5829 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5830 .FocusedOn(FocusedControl.ListTab)
5831 .Do(() => SendKeys.Send("{PGDN}")),
5833 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5834 .FocusedOn(FocusedControl.ListTab)
5835 .Do(() => SendKeys.Send("{PGUP}")),
5837 ShortcutCommand.Create(Keys.F1)
5838 .Do(() => this.OpenApplicationWebsite()),
5840 ShortcutCommand.Create(Keys.F3)
5841 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5843 ShortcutCommand.Create(Keys.F5)
5844 .Do(() => this.DoRefresh()),
5846 ShortcutCommand.Create(Keys.F6)
5847 .Do(() => this.GetReplyAsync()),
5849 ShortcutCommand.Create(Keys.F7)
5850 .Do(() => this.GetDirectMessagesAsync()),
5852 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5853 .NotFocusedOn(FocusedControl.StatusText)
5854 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5856 ShortcutCommand.Create(Keys.G)
5857 .NotFocusedOn(FocusedControl.StatusText)
5858 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5860 ShortcutCommand.Create(Keys.Right, Keys.N)
5861 .FocusedOn(FocusedControl.ListTab)
5862 .Do(() => this.GoRelPost(forward: true)),
5864 ShortcutCommand.Create(Keys.Left, Keys.P)
5865 .FocusedOn(FocusedControl.ListTab)
5866 .Do(() => this.GoRelPost(forward: false)),
5868 ShortcutCommand.Create(Keys.OemPeriod)
5869 .FocusedOn(FocusedControl.ListTab)
5870 .Do(() => this.GoAnchor()),
5872 ShortcutCommand.Create(Keys.I)
5873 .FocusedOn(FocusedControl.ListTab)
5874 .OnlyWhen(() => this.StatusText.Enabled)
5875 .Do(() => this.StatusText.Focus()),
5877 ShortcutCommand.Create(Keys.Enter)
5878 .FocusedOn(FocusedControl.ListTab)
5879 .Do(() => this.MakeReplyOrDirectStatus()),
5881 ShortcutCommand.Create(Keys.R)
5882 .FocusedOn(FocusedControl.ListTab)
5883 .Do(() => this.DoRefresh()),
5885 ShortcutCommand.Create(Keys.L)
5886 .FocusedOn(FocusedControl.ListTab)
5887 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5889 ShortcutCommand.Create(Keys.H)
5890 .FocusedOn(FocusedControl.ListTab)
5891 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5893 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5894 .FocusedOn(FocusedControl.ListTab)
5895 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5897 ShortcutCommand.Create(Keys.S)
5898 .FocusedOn(FocusedControl.ListTab)
5899 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5901 ShortcutCommand.Create(Keys.A)
5902 .FocusedOn(FocusedControl.ListTab)
5903 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5905 // ] in_reply_to参照元へ戻る
5906 ShortcutCommand.Create(Keys.Oem4)
5907 .FocusedOn(FocusedControl.ListTab)
5908 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5910 // [ in_reply_toへジャンプ
5911 ShortcutCommand.Create(Keys.Oem6)
5912 .FocusedOn(FocusedControl.ListTab)
5913 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5915 ShortcutCommand.Create(Keys.Escape)
5916 .FocusedOn(FocusedControl.ListTab)
5918 this._anchorFlag = false;
5919 if (ListTab.SelectedTab != null)
5921 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5922 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5924 var relTp = ListTab.SelectedTab;
5925 RemoveSpecifiedTab(relTp.Text, false);
5931 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5932 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5933 .FocusedOn(FocusedControl.ListTab)
5934 .Do(() => this._anchorFlag = false, preventDefault: false),
5936 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5937 ShortcutCommand.Create(Keys.Up, Keys.Down)
5938 .FocusedOn(FocusedControl.PostBrowser)
5941 ShortcutCommand.Create(Keys.Control | Keys.R)
5942 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5944 ShortcutCommand.Create(Keys.Control | Keys.D)
5945 .Do(() => this.doStatusDelete()),
5947 ShortcutCommand.Create(Keys.Control | Keys.M)
5948 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5950 ShortcutCommand.Create(Keys.Control | Keys.S)
5951 .Do(() => this.FavoriteChange(FavAdd: true)),
5953 ShortcutCommand.Create(Keys.Control | Keys.I)
5954 .Do(() => this.doRepliedStatusOpen()),
5956 ShortcutCommand.Create(Keys.Control | Keys.Q)
5957 .Do(() => this.doQuoteOfficial()),
5959 ShortcutCommand.Create(Keys.Control | Keys.B)
5960 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5962 ShortcutCommand.Create(Keys.Control | Keys.T)
5963 .Do(() => this.HashManageMenuItem_Click(null, null)),
5965 ShortcutCommand.Create(Keys.Control | Keys.L)
5966 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5968 ShortcutCommand.Create(Keys.Control | Keys.Y)
5969 .NotFocusedOn(FocusedControl.PostBrowser)
5970 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5972 ShortcutCommand.Create(Keys.Control | Keys.F)
5973 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5975 ShortcutCommand.Create(Keys.Control | Keys.U)
5976 .Do(() => this.ShowUserTimeline()),
5978 ShortcutCommand.Create(Keys.Control | Keys.H)
5979 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5981 ShortcutCommand.Create(Keys.Control | Keys.G)
5982 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5984 ShortcutCommand.Create(Keys.Control | Keys.O)
5985 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5987 ShortcutCommand.Create(Keys.Control | Keys.E)
5988 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5990 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5991 .FocusedOn(FocusedControl.ListTab)
5992 .Do(() => this._colorize = true, preventDefault: false),
5994 ShortcutCommand.Create(Keys.Control | Keys.N)
5995 .FocusedOn(FocusedControl.ListTab)
5996 .Do(() => this.GoNextTab(forward: true)),
5998 ShortcutCommand.Create(Keys.Control | Keys.P)
5999 .FocusedOn(FocusedControl.ListTab)
6000 .Do(() => this.GoNextTab(forward: false)),
6002 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6003 .FocusedOn(FocusedControl.ListTab)
6004 .Do(() => this.CopyStot()),
6006 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6007 ShortcutCommand.Create(Keys.Control | Keys.D1)
6008 .FocusedOn(FocusedControl.ListTab)
6009 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6010 .Do(() => this.ListTab.SelectedIndex = 0),
6012 ShortcutCommand.Create(Keys.Control | Keys.D2)
6013 .FocusedOn(FocusedControl.ListTab)
6014 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6015 .Do(() => this.ListTab.SelectedIndex = 1),
6017 ShortcutCommand.Create(Keys.Control | Keys.D3)
6018 .FocusedOn(FocusedControl.ListTab)
6019 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6020 .Do(() => this.ListTab.SelectedIndex = 2),
6022 ShortcutCommand.Create(Keys.Control | Keys.D4)
6023 .FocusedOn(FocusedControl.ListTab)
6024 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6025 .Do(() => this.ListTab.SelectedIndex = 3),
6027 ShortcutCommand.Create(Keys.Control | Keys.D5)
6028 .FocusedOn(FocusedControl.ListTab)
6029 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6030 .Do(() => this.ListTab.SelectedIndex = 4),
6032 ShortcutCommand.Create(Keys.Control | Keys.D6)
6033 .FocusedOn(FocusedControl.ListTab)
6034 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6035 .Do(() => this.ListTab.SelectedIndex = 5),
6037 ShortcutCommand.Create(Keys.Control | Keys.D7)
6038 .FocusedOn(FocusedControl.ListTab)
6039 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6040 .Do(() => this.ListTab.SelectedIndex = 6),
6042 ShortcutCommand.Create(Keys.Control | Keys.D8)
6043 .FocusedOn(FocusedControl.ListTab)
6044 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6045 .Do(() => this.ListTab.SelectedIndex = 7),
6047 ShortcutCommand.Create(Keys.Control | Keys.D9)
6048 .FocusedOn(FocusedControl.ListTab)
6049 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6051 ShortcutCommand.Create(Keys.Control | Keys.A)
6052 .FocusedOn(FocusedControl.StatusText)
6053 .Do(() => this.StatusText.SelectAll()),
6055 ShortcutCommand.Create(Keys.Control | Keys.V)
6056 .FocusedOn(FocusedControl.StatusText)
6057 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6059 ShortcutCommand.Create(Keys.Control | Keys.Up)
6060 .FocusedOn(FocusedControl.StatusText)
6062 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6064 var inReplyToStatusId = this.inReplyTo?.Item1;
6065 var inReplyToScreenName = this.inReplyTo?.Item2;
6066 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6069 if (_hisIdx < 0) _hisIdx = 0;
6071 var historyItem = this._history[this._hisIdx];
6072 StatusText.Text = historyItem.status;
6073 StatusText.SelectionStart = StatusText.Text.Length;
6074 if (historyItem.inReplyToId != null)
6075 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6077 this.inReplyTo = null;
6080 ShortcutCommand.Create(Keys.Control | Keys.Down)
6081 .FocusedOn(FocusedControl.StatusText)
6083 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6085 var inReplyToStatusId = this.inReplyTo?.Item1;
6086 var inReplyToScreenName = this.inReplyTo?.Item2;
6087 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6090 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6092 var historyItem = this._history[this._hisIdx];
6093 StatusText.Text = historyItem.status;
6094 StatusText.SelectionStart = StatusText.Text.Length;
6095 if (historyItem.inReplyToId != null)
6096 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6098 this.inReplyTo = null;
6101 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6102 .FocusedOn(FocusedControl.StatusText)
6104 if (ListTab.SelectedIndex == 0)
6106 ListTab.SelectedIndex = ListTab.TabCount - 1;
6110 ListTab.SelectedIndex -= 1;
6115 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6116 .FocusedOn(FocusedControl.StatusText)
6118 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6120 ListTab.SelectedIndex = 0;
6124 ListTab.SelectedIndex += 1;
6129 ShortcutCommand.Create(Keys.Control | Keys.Y)
6130 .FocusedOn(FocusedControl.PostBrowser)
6132 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6133 MultiLineMenuItem_Click(null, null);
6136 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6137 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6139 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6140 .Do(() => this.DoRefreshMore()),
6142 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6143 .Do(() => this.GetReplyAsync(loadMore: true)),
6145 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6146 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6148 ShortcutCommand.Create(Keys.Shift | Keys.R)
6149 .NotFocusedOn(FocusedControl.StatusText)
6150 .Do(() => this.DoRefreshMore()),
6152 ShortcutCommand.Create(Keys.Shift | Keys.H)
6153 .FocusedOn(FocusedControl.ListTab)
6154 .Do(() => this.GoTopEnd(GoTop: true)),
6156 ShortcutCommand.Create(Keys.Shift | Keys.L)
6157 .FocusedOn(FocusedControl.ListTab)
6158 .Do(() => this.GoTopEnd(GoTop: false)),
6160 ShortcutCommand.Create(Keys.Shift | Keys.M)
6161 .FocusedOn(FocusedControl.ListTab)
6162 .Do(() => this.GoMiddle()),
6164 ShortcutCommand.Create(Keys.Shift | Keys.G)
6165 .FocusedOn(FocusedControl.ListTab)
6166 .Do(() => this.GoLast()),
6168 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6169 .FocusedOn(FocusedControl.ListTab)
6170 .Do(() => this.MoveMiddle()),
6172 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6173 .FocusedOn(FocusedControl.ListTab)
6174 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6176 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6177 .FocusedOn(FocusedControl.ListTab)
6178 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6180 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6181 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6182 .FocusedOn(FocusedControl.ListTab)
6183 .Do(() => this.GoFav(forward: true)),
6185 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6186 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6187 .FocusedOn(FocusedControl.ListTab)
6188 .Do(() => this.GoFav(forward: false)),
6190 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6191 .FocusedOn(FocusedControl.ListTab)
6192 .Do(() => this.GoBackSelectPostChain()),
6194 ShortcutCommand.Create(Keys.Alt | Keys.R)
6195 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6197 ShortcutCommand.Create(Keys.Alt | Keys.P)
6198 .OnlyWhen(() => this._curPost != null)
6199 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6201 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6202 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6204 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6205 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6207 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6208 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6210 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6211 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6213 // 別タブの同じ書き込みへ(ALT+←/→)
6214 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6215 .FocusedOn(FocusedControl.ListTab)
6216 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6218 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6219 .FocusedOn(FocusedControl.ListTab)
6220 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6222 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6223 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6225 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6226 .Do(() => this.CopyIdUri()),
6228 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6229 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6230 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6231 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6233 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6234 .Do(() => this.FavoriteChange(FavAdd: false)),
6236 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6237 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6239 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6240 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6242 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6243 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6245 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6246 .Do(() => this.doMoveToRTHome()),
6248 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6249 .Do(() => this.FavorareMenuItem_Click(null, null)),
6251 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6252 .FocusedOn(FocusedControl.StatusText)
6254 if (_curList != null && _curList.VirtualListSize != 0 &&
6255 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6257 var idx = _curList.SelectedIndices[0] - 1;
6258 SelectListItem(_curList, idx);
6259 _curList.EnsureVisible(idx);
6263 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6264 .FocusedOn(FocusedControl.StatusText)
6266 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6267 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6269 var idx = _curList.SelectedIndices[0] + 1;
6270 SelectListItem(_curList, idx);
6271 _curList.EnsureVisible(idx);
6275 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6276 .FocusedOn(FocusedControl.StatusText)
6278 if (StatusText.SelectionStart > 0)
6280 int endidx = StatusText.SelectionStart - 1;
6281 string startstr = "";
6282 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6284 char c = StatusText.Text[i];
6285 if (Char.IsLetterOrDigit(c) || c == '_')
6291 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6292 int cnt = AtIdSupl.ItemCount;
6293 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6294 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6298 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6299 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6309 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6310 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6311 .FocusedOn(FocusedControl.ListTab)
6312 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6314 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6315 .FocusedOn(FocusedControl.ListTab)
6316 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6318 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6319 .FocusedOn(FocusedControl.ListTab)
6320 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6322 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6323 .FocusedOn(FocusedControl.ListTab)
6324 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6326 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6327 .FocusedOn(FocusedControl.ListTab)
6328 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6330 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6331 .FocusedOn(FocusedControl.ListTab)
6332 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6334 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6335 .FocusedOn(FocusedControl.ListTab)
6336 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6338 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6339 .FocusedOn(FocusedControl.ListTab)
6340 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6342 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6343 .FocusedOn(FocusedControl.ListTab)
6344 .Do(() => this.SetSortLastColumn()),
6346 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6347 .Do(() => this.FavoritesRetweetOfficial()),
6349 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6350 .Do(() => this.FavoritesRetweetUnofficial()),
6352 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6353 .Do(() => this.OpenUserAppointUrl()),
6355 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6356 .FocusedOn(FocusedControl.PostBrowser)
6357 .Do(() => this.doReTweetUnofficial()),
6359 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6360 .OnlyWhen(() => this.ExistCurrentPost)
6361 .Do(() => this.tweetDetailsView.DoTranslation()),
6363 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6364 .Do(() => this.doReTweetUnofficial()),
6366 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6367 .Do(() => this.CopyUserId()),
6369 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6370 .Do(() => this.tweetThumbnail1.ScrollUp()),
6372 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6373 .Do(() => this.tweetThumbnail1.ScrollDown()),
6375 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6376 .FocusedOn(FocusedControl.ListTab)
6377 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6378 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6382 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6384 // Task を返す非同期処理があれば asyncTask に代入する
6387 // ShortcutCommand に対応しているコマンドはここで処理される
6388 foreach (var command in this.shortcutCommands)
6390 if (command.IsMatch(keyData, focusedOn))
6392 asyncTask = command.RunCommand();
6393 return command.PreventDefault;
6400 private void GoNextTab(bool forward)
6402 int idx = ListTab.SelectedIndex;
6406 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6411 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6413 ListTab.SelectedIndex = idx;
6416 private void CopyStot()
6419 StringBuilder sb = new StringBuilder();
6420 bool IsProtected = false;
6422 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6423 foreach (int idx in _curList.SelectedIndices)
6425 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6426 if (post.IsDeleted) continue;
6429 if (post.RetweetedId != null)
6430 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6432 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6436 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6441 MessageBox.Show(Properties.Resources.CopyStotText1);
6445 clstr = sb.ToString();
6448 Clipboard.SetDataObject(clstr, false, 5, 100);
6450 catch (Exception ex)
6452 MessageBox.Show(ex.Message);
6457 private void CopyIdUri()
6459 if (this._curTab == null)
6462 var tab = this._statuses.GetTabByName(this._curTab.Text);
6463 if (tab == null || tab is DirectMessagesTabModel)
6466 var sb = new StringBuilder();
6467 foreach (int idx in _curList.SelectedIndices)
6469 var post = tab[idx];
6470 sb.Append(MyCommon.GetStatusUrl(post));
6471 sb.Append(Environment.NewLine);
6479 Clipboard.SetDataObject(sb.ToString(), false, 5, 100);
6481 catch (ExternalException ex)
6483 MessageBox.Show(ex.Message);
6487 private void GoFav(bool forward)
6489 if (_curList.VirtualListSize == 0) return;
6496 if (_curList.SelectedIndices.Count == 0)
6502 fIdx = _curList.SelectedIndices[0] + 1;
6503 if (fIdx > _curList.VirtualListSize - 1) return;
6505 toIdx = _curList.VirtualListSize;
6510 if (_curList.SelectedIndices.Count == 0)
6512 fIdx = _curList.VirtualListSize - 1;
6516 fIdx = _curList.SelectedIndices[0] - 1;
6517 if (fIdx < 0) return;
6523 for (int idx = fIdx; idx != toIdx; idx += stp)
6525 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6527 SelectListItem(_curList, idx);
6528 _curList.EnsureVisible(idx);
6534 private void GoSamePostToAnotherTab(bool left)
6536 if (this._curList.SelectedIndices.Count == 0)
6539 var tab = this._statuses.Tabs[this._curTab.Text];
6541 // Directタブは対象外(見つかるはずがない)
6542 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6545 var selectedIndex = this._curList.SelectedIndices[0];
6546 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6548 int fIdx, toIdx, stp;
6553 if (ListTab.SelectedIndex == 0)
6559 fIdx = ListTab.SelectedIndex - 1;
6567 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6573 fIdx = ListTab.SelectedIndex + 1;
6575 toIdx = ListTab.TabCount;
6579 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6581 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6584 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6587 var foundIndex = targetTab.IndexOf(selectedStatusId);
6588 if (foundIndex != -1)
6590 ListTab.SelectedIndex = tabidx;
6591 SelectListItem(_curList, foundIndex);
6592 _curList.EnsureVisible(foundIndex);
6598 private void GoPost(bool forward)
6600 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6603 var tab = this._statuses.Tabs[this._curTab.Text];
6604 var selectedIndex = this._curList.SelectedIndices[0];
6606 int fIdx, toIdx, stp;
6610 fIdx = selectedIndex + 1;
6611 if (fIdx > tab.AllCount - 1) return;
6612 toIdx = tab.AllCount;
6617 fIdx = selectedIndex - 1;
6618 if (fIdx < 0) return;
6624 if (_curPost.RetweetedId == null)
6626 name = _curPost.ScreenName;
6630 name = _curPost.RetweetedBy;
6632 for (int idx = fIdx; idx != toIdx; idx += stp)
6634 var post = tab[idx];
6635 if (post.RetweetedId == null)
6637 if (post.ScreenName == name)
6639 SelectListItem(_curList, idx);
6640 _curList.EnsureVisible(idx);
6646 if (post.RetweetedBy == name)
6648 SelectListItem(_curList, idx);
6649 _curList.EnsureVisible(idx);
6656 private void GoRelPost(bool forward)
6658 if (this._curList.SelectedIndices.Count == 0)
6661 var tab = this._statuses.Tabs[this._curTab.Text];
6662 var selectedIndex = this._curList.SelectedIndices[0];
6664 int fIdx, toIdx, stp;
6668 fIdx = selectedIndex + 1;
6669 if (fIdx > tab.AllCount - 1) return;
6670 toIdx = tab.AllCount;
6675 fIdx = selectedIndex - 1;
6676 if (fIdx < 0) return;
6683 if (_curPost == null) return;
6684 _anchorPost = _curPost;
6689 if (_anchorPost == null) return;
6692 for (int idx = fIdx; idx != toIdx; idx += stp)
6694 var post = tab[idx];
6695 if (post.ScreenName == _anchorPost.ScreenName ||
6696 post.RetweetedBy == _anchorPost.ScreenName ||
6697 post.ScreenName == _anchorPost.RetweetedBy ||
6698 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6699 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6700 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6701 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6702 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6704 SelectListItem(_curList, idx);
6705 _curList.EnsureVisible(idx);
6711 private void GoAnchor()
6713 if (_anchorPost == null) return;
6714 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6715 if (idx == -1) return;
6717 SelectListItem(_curList, idx);
6718 _curList.EnsureVisible(idx);
6721 private void GoTopEnd(bool GoTop)
6723 if (_curList.VirtualListSize == 0)
6731 _item = _curList.GetItemAt(0, 25);
6739 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6741 idx = _curList.VirtualListSize - 1;
6745 SelectListItem(_curList, idx);
6748 private void GoMiddle()
6750 if (_curList.VirtualListSize == 0)
6758 _item = _curList.GetItemAt(0, 0);
6768 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6771 idx2 = _curList.VirtualListSize - 1;
6777 idx3 = (idx1 + idx2) / 2;
6779 SelectListItem(_curList, idx3);
6782 private void GoLast()
6784 if (_curList.VirtualListSize == 0) return;
6786 if (_statuses.SortOrder == SortOrder.Ascending)
6788 SelectListItem(_curList, _curList.VirtualListSize - 1);
6789 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6793 SelectListItem(_curList, 0);
6794 _curList.EnsureVisible(0);
6798 private void MoveTop()
6800 if (_curList.SelectedIndices.Count == 0) return;
6801 int idx = _curList.SelectedIndices[0];
6802 if (_statuses.SortOrder == SortOrder.Ascending)
6804 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6808 _curList.EnsureVisible(0);
6810 _curList.EnsureVisible(idx);
6813 private async Task GoInReplyToPostTree()
6815 if (_curPost == null) return;
6817 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6819 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6823 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6825 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6826 _curPost.InReplyToUser = post.InReplyToUser;
6827 _curPost.IsReply = post.IsReply;
6828 this.PurgeListViewItemCache();
6829 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6831 catch (WebApiException ex)
6833 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6837 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6839 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6841 replyChains = new Stack<ReplyChain>();
6843 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6846 string inReplyToTabName;
6847 long inReplyToId = _curPost.InReplyToStatusId.Value;
6848 string inReplyToUser = _curPost.InReplyToUser;
6849 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6851 var inReplyToPosts = from tab in _statuses.Tabs.Values
6852 orderby tab != curTabClass
6853 from post in tab.Posts.Values
6854 where post.StatusId == inReplyToId
6855 let index = tab.IndexOf(post.StatusId)
6857 select new {Tab = tab, Index = index};
6859 var inReplyPost = inReplyToPosts.FirstOrDefault();
6860 if (inReplyPost == null)
6864 await Task.Run(async () =>
6866 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6867 .ConfigureAwait(false);
6870 _statuses.AddPost(post);
6871 _statuses.DistributePosts();
6874 catch (WebApiException ex)
6876 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6877 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6881 this.RefreshTimeline();
6883 inReplyPost = inReplyToPosts.FirstOrDefault();
6884 if (inReplyPost == null)
6886 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6890 inReplyToTabName = inReplyPost.Tab.TabName;
6891 inReplyToIndex = inReplyPost.Index;
6893 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6894 DetailsListView listView = (DetailsListView)tabPage.Tag;
6896 if (_curTab != tabPage)
6898 this.ListTab.SelectTab(tabPage);
6901 this.SelectListItem(listView, inReplyToIndex);
6902 listView.EnsureVisible(inReplyToIndex);
6905 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6907 if (_curPost == null) return;
6909 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6910 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6914 if (_curPost.InReplyToStatusId != null)
6916 var posts = from t in _statuses.Tabs
6917 from p in t.Value.Posts
6918 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6919 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6921 orderby isForward ? indexOf : indexOf * -1
6922 orderby t.Value != curTabClass
6923 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6926 var postList = posts.ToList();
6927 for (int i = postList.Count - 1; i >= 0; i--)
6930 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6932 postList.RemoveAt(index);
6935 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6936 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6937 if (post == null) post = postList.First();
6938 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6939 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6940 SelectListItem(listView, post.Index);
6941 listView.EnsureVisible(post.Index);
6943 catch (InvalidOperationException)
6951 if (replyChains == null || replyChains.Count < 1)
6953 var posts = from t in _statuses.Tabs
6954 from p in t.Value.Posts
6955 where p.Value.InReplyToStatusId == _curPost.StatusId
6956 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6959 orderby t.Value != curTabClass
6960 select new {Tab = t.Value, Index = indexOf};
6963 var post = posts.First();
6964 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6965 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6966 SelectListItem(listView, post.Index);
6967 listView.EnsureVisible(post.Index);
6969 catch (InvalidOperationException)
6976 ReplyChain chainHead = replyChains.Pop();
6977 if (chainHead.InReplyToId == _curPost.StatusId)
6979 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6988 ListTab.SelectTab(chainHead.OriginalTab);
6994 SelectListItem(_curList, idx);
6995 _curList.EnsureVisible(idx);
7001 this.GoBackInReplyToPostTree(parallel);
7007 private void GoBackSelectPostChain()
7009 if (this.selectPostChains.Count > 1)
7018 this.selectPostChains.Pop();
7019 var tabPostPair = this.selectPostChains.Peek();
7021 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7023 if (tabPostPair.Item2 != null)
7025 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7026 if (idx == -1) continue; //該当ポストが存在しないので無視
7029 tp = tabPostPair.Item1;
7031 this.selectPostChains.Pop();
7033 catch (InvalidOperationException)
7039 while (this.selectPostChains.Count > 1);
7044 //履歴が残り1つであればクリアしておく
7045 if (this.selectPostChains.Count == 1)
7046 this.selectPostChains.Clear();
7050 DetailsListView lst = (DetailsListView)tp.Tag;
7051 this.ListTab.SelectedTab = tp;
7054 SelectListItem(lst, idx);
7055 lst.EnsureVisible(idx);
7061 private void PushSelectPostChain()
7063 int count = this.selectPostChains.Count;
7066 var p = this.selectPostChains.Peek();
7067 if (p.Item1 == this._curTab)
7069 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7070 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7073 if (count >= 2500) TrimPostChain();
7074 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7077 private void TrimPostChain()
7079 if (this.selectPostChains.Count <= 2000) return;
7080 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7081 for (int i = 0; i < 2000; i++)
7083 p.Push(this.selectPostChains.Pop());
7085 this.selectPostChains.Clear();
7086 for (int i = 0; i < 2000; i++)
7088 this.selectPostChains.Push(p.Pop());
7092 private bool GoStatus(long statusId)
7094 if (statusId == 0) return false;
7095 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7097 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7099 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7100 ListTab.SelectedIndex = tabidx;
7101 SelectListItem(_curList, idx);
7102 _curList.EnsureVisible(idx);
7109 private bool GoDirectMessage(long statusId)
7111 if (statusId == 0) return false;
7112 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7114 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7116 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7117 ListTab.SelectedIndex = tabidx;
7118 SelectListItem(_curList, idx);
7119 _curList.EnsureVisible(idx);
7126 private void MyList_MouseClick(object sender, MouseEventArgs e)
7128 _anchorFlag = false;
7131 private void StatusText_Enter(object sender, EventArgs e)
7133 // フォーカスの戻り先を StatusText に設定
7134 this.Tag = StatusText;
7135 StatusText.BackColor = _clInputBackcolor;
7138 public Color InputBackColor
7140 get { return _clInputBackcolor; }
7141 set { _clInputBackcolor = value; }
7144 private void StatusText_Leave(object sender, EventArgs e)
7146 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7147 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7148 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7151 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7154 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7157 e.SuppressKeyPress = true;
7160 this.StatusText_TextChanged(null, null);
7162 if (asyncTask != null)
7166 private void SaveConfigsAll(bool ifModified)
7170 SaveConfigsCommon();
7177 if (ModifySettingCommon) SaveConfigsCommon();
7178 if (ModifySettingLocal) SaveConfigsLocal();
7179 if (ModifySettingAtId) SaveConfigsAtId();
7183 private void SaveConfigsAtId()
7185 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7187 ModifySettingAtId = false;
7188 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7192 private void SaveConfigsCommon()
7194 if (_ignoreConfigSave) return;
7196 ModifySettingCommon = false;
7199 _cfgCommon.UserName = tw.Username;
7200 _cfgCommon.UserId = tw.UserId;
7201 _cfgCommon.Token = tw.AccessToken;
7202 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7204 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7205 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7207 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7210 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7211 switch (_statuses.SortMode)
7213 case ComparerMode.Nickname: //ニックネーム
7214 _cfgCommon.SortColumn = 1;
7216 case ComparerMode.Data: //本文
7217 _cfgCommon.SortColumn = 2;
7219 case ComparerMode.Id: //時刻=発言Id
7220 _cfgCommon.SortColumn = 3;
7222 case ComparerMode.Name: //名前
7223 _cfgCommon.SortColumn = 4;
7225 case ComparerMode.Source: //Source
7226 _cfgCommon.SortColumn = 7;
7230 _cfgCommon.HashTags = HashMgr.HashHistories;
7231 if (HashMgr.IsPermanent)
7233 _cfgCommon.HashSelected = HashMgr.UseHash;
7237 _cfgCommon.HashSelected = "";
7239 _cfgCommon.HashIsHead = HashMgr.IsHead;
7240 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7241 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7242 if (ToolStripFocusLockMenuItem != null &&
7243 ToolStripFocusLockMenuItem.IsDisposed == false)
7245 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7247 _cfgCommon.TrackWord = tw.TrackWord;
7248 _cfgCommon.AllAtReply = tw.AllAtReply;
7249 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7250 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7256 private void SaveConfigsLocal()
7258 if (_ignoreConfigSave) return;
7261 ModifySettingLocal = false;
7262 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7263 _cfgLocal.FormSize = _mySize;
7264 _cfgLocal.FormLocation = _myLoc;
7265 _cfgLocal.SplitterDistance = _mySpDis;
7266 _cfgLocal.PreviewDistance = _mySpDis3;
7267 _cfgLocal.StatusMultiline = StatusText.Multiline;
7268 _cfgLocal.StatusTextHeight = _mySpDis2;
7270 _cfgLocal.FontUnread = _fntUnread;
7271 _cfgLocal.ColorUnread = _clUnread;
7272 _cfgLocal.FontRead = _fntReaded;
7273 _cfgLocal.ColorRead = _clReaded;
7274 _cfgLocal.FontDetail = _fntDetail;
7275 _cfgLocal.ColorDetail = _clDetail;
7276 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7277 _cfgLocal.ColorDetailLink = _clDetailLink;
7278 _cfgLocal.ColorFav = _clFav;
7279 _cfgLocal.ColorOWL = _clOWL;
7280 _cfgLocal.ColorRetweet = _clRetweet;
7281 _cfgLocal.ColorSelf = _clSelf;
7282 _cfgLocal.ColorAtSelf = _clAtSelf;
7283 _cfgLocal.ColorTarget = _clTarget;
7284 _cfgLocal.ColorAtTarget = _clAtTarget;
7285 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7286 _cfgLocal.ColorAtTo = _clAtTo;
7287 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7288 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7289 _cfgLocal.ColorInputFont = _clInputFont;
7290 _cfgLocal.FontInputFont = _fntInputFont;
7292 if (_ignoreConfigSave) return;
7297 private void SaveConfigsTabs()
7299 var tabsSetting = new SettingTabs();
7301 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7302 .Select(x => this._statuses.Tabs[x.Text])
7303 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7305 foreach (var tab in tabs)
7307 if (!tab.IsPermanentTabType)
7310 var tabSetting = new SettingTabs.SettingTabItem
7312 TabName = tab.TabName,
7313 TabType = tab.TabType,
7314 UnreadManage = tab.UnreadManage,
7315 Protected = tab.Protected,
7316 Notify = tab.Notify,
7317 SoundFile = tab.SoundFile,
7320 var filterTab = tab as FilterTabModel;
7321 if (filterTab != null)
7322 tabSetting.FilterArray = filterTab.FilterArray;
7324 var userTab = tab as UserTimelineTabModel;
7325 if (userTab != null)
7326 tabSetting.User = userTab.ScreenName;
7328 var searchTab = tab as PublicSearchTabModel;
7329 if (searchTab != null)
7331 tabSetting.SearchWords = searchTab.SearchWords;
7332 tabSetting.SearchLang = searchTab.SearchLang;
7335 var listTab = tab as ListTimelineTabModel;
7336 if (listTab != null)
7337 tabSetting.ListInfo = listTab.ListInfo;
7339 tabsSetting.Tabs.Add(tabSetting);
7345 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7348 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7349 if (ret != DialogResult.OK)
7352 var match = Twitter.StatusUrlRegex.Match(inputText);
7355 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7356 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7362 var statusId = long.Parse(match.Groups["StatusId"].Value);
7363 await this.OpenRelatedTab(statusId);
7365 catch (TabException ex)
7367 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7371 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7373 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7374 Properties.Resources.SaveLogMenuItem_ClickText2,
7375 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7376 if (rslt == DialogResult.Cancel) return;
7378 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7379 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7380 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7381 SaveFileDialog1.FilterIndex = 0;
7382 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7383 SaveFileDialog1.RestoreDirectory = true;
7385 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7387 if (!SaveFileDialog1.ValidateNames) return;
7388 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7390 if (rslt == DialogResult.Yes)
7393 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7395 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7396 string protect = "";
7397 if (post.IsProtect) protect = "Protect";
7398 sw.WriteLine(post.Nickname + "\t" +
7399 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7400 post.CreatedAt + "\t" +
7401 post.ScreenName + "\t" +
7402 post.StatusId + "\t" +
7403 post.ImageUrl + "\t" +
7404 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7410 foreach (int idx in _curList.SelectedIndices)
7412 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7413 string protect = "";
7414 if (post.IsProtect) protect = "Protect";
7415 sw.WriteLine(post.Nickname + "\t" +
7416 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7417 post.CreatedAt + "\t" +
7418 post.ScreenName + "\t" +
7419 post.StatusId + "\t" +
7420 post.ImageUrl + "\t" +
7421 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7427 this.TopMost = this._cfgCommon.AlwaysTop;
7430 public bool TabRename(string origTabName, out string newTabName)
7434 using (InputTabName inputName = new InputTabName())
7436 inputName.TabName = origTabName;
7437 inputName.ShowDialog();
7438 if (inputName.DialogResult == DialogResult.Cancel) return false;
7439 newTabName = inputName.TabName;
7441 this.TopMost = this._cfgCommon.AlwaysTop;
7442 if (!string.IsNullOrEmpty(newTabName))
7445 for (int i = 0; i < ListTab.TabCount; i++)
7447 if (ListTab.TabPages[i].Text == newTabName)
7449 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7450 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7455 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7456 .First(x => x.Text == origTabName);
7458 ListViewScroll scrollInfo;
7459 if (this.listViewScroll.TryGetValue(origTabName, out scrollInfo))
7461 this.listViewScroll.Remove(origTabName);
7462 this.listViewScroll[newTabName] = scrollInfo;
7465 ListViewSelection selectionInfo;
7466 if (this.listViewSelection.TryGetValue(origTabName, out selectionInfo))
7468 this.listViewSelection.Remove(origTabName);
7469 this.listViewSelection[newTabName] = selectionInfo;
7473 tabPage.Text = newTabName;
7474 _statuses.RenameTab(origTabName, newTabName);
7476 SaveConfigsCommon();
7478 _rclickTabName = newTabName;
7487 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7489 if (e.Button == MouseButtons.Middle)
7491 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7493 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7495 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7496 this.SaveConfigsTabs();
7503 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7506 TabRename(this.ListTab.SelectedTab.Text, out _);
7509 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7511 if (this._cfgCommon.TabMouseLock) return;
7512 if (e.Button == MouseButtons.Left)
7514 for (int i = 0; i < ListTab.TabPages.Count; i++)
7516 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7519 _tabMouseDownPoint = e.Location;
7530 private void ListTab_DragEnter(object sender, DragEventArgs e)
7532 if (e.Data.GetDataPresent(typeof(TabPage)))
7533 e.Effect = DragDropEffects.Move;
7535 e.Effect = DragDropEffects.None;
7538 private void ListTab_DragDrop(object sender, DragEventArgs e)
7540 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7545 Point cpos = new Point(e.X, e.Y);
7546 Point spos = ListTab.PointToClient(cpos);
7548 for (i = 0; i < ListTab.TabPages.Count; i++)
7550 Rectangle rect = ListTab.GetTabRect(i);
7551 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7552 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7554 tn = ListTab.TabPages[i].Text;
7555 if (spos.X <= (rect.Left + rect.Right) / 2)
7564 //タブのないところにドロップ->最後尾へ移動
7565 if (string.IsNullOrEmpty(tn))
7567 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7569 i = ListTab.TabPages.Count - 1;
7572 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7573 if (tp.Text == tn) return;
7575 ReOrderTab(tp.Text, tn, bef);
7578 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7580 var baseIndex = this.GetTabPageIndex(baseTabText);
7581 if (baseIndex == -1)
7584 var targetIndex = this.GetTabPageIndex(targetTabText);
7585 if (targetIndex == -1)
7588 using (ControlTransaction.Layout(this.ListTab))
7590 var mTp = this.ListTab.TabPages[targetIndex];
7591 this.ListTab.TabPages.Remove(mTp);
7593 if (targetIndex < baseIndex)
7596 if (isBeforeBaseTab)
7597 ListTab.TabPages.Insert(baseIndex, mTp);
7599 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7605 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7607 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7608 //isReply:true=@,false=DM
7609 if (!StatusText.Enabled) return;
7610 if (_curList == null) return;
7611 if (_curTab == null) return;
7612 if (!this.ExistCurrentPost) return;
7614 // 複数あてリプライはReplyではなく通常ポスト
7615 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7616 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7617 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7619 if (_curList.SelectedIndices.Count > 0)
7622 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7625 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7628 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7629 StatusText.SelectionStart = StatusText.Text.Length;
7631 this.inReplyTo = null;
7634 if (string.IsNullOrEmpty(StatusText.Text))
7638 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7639 StatusText.Text = "@" + _curPost.ScreenName + " ";
7641 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7642 var inReplyToScreenName = this._curPost.ScreenName;
7643 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7651 //1件選んでEnter or DoubleClick
7652 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7654 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7657 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7658 var inReplyToScreenName = this._curPost.ScreenName;
7659 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7663 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7666 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7669 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7670 this.inReplyTo = null;
7675 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7676 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7677 var inReplyToScreenName = this._curPost.ScreenName;
7678 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7685 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7686 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7687 this.inReplyTo = null;
7692 //1件選んでCtrl-Rの場合(返信先操作せず)
7693 int sidx = StatusText.SelectionStart;
7694 string id = "@" + _curPost.ScreenName + " ";
7697 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7702 StatusText.Text = StatusText.Text.Insert(sidx, id);
7704 //if (StatusText.Text.StartsWith("@"))
7707 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7708 // sidx += 5 + _curPost.ScreenName.Length;
7713 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7714 // sidx += 3 + _curPost.ScreenName.Length;
7716 StatusText.SelectionStart = sidx;
7719 //_reply_to_name = null;
7727 if (!isAuto && !isReply) return;
7729 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7733 //Enter or DoubleClick
7735 string sTxt = StatusText.Text;
7736 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7739 this.inReplyTo = null;
7741 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7743 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7744 if (!sTxt.Contains("@" + post.ScreenName + " "))
7746 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7747 //sTxt = "@" + post.ScreenName + " " + sTxt;
7750 StatusText.Text = sTxt;
7755 if (_curList.SelectedIndices.Count > 1)
7760 int sidx = StatusText.SelectionStart;
7761 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7763 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7764 if (!ids.Contains("@" + post.ScreenName + " ") &&
7765 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7767 ids += "@" + post.ScreenName + " ";
7771 foreach (string nm in post.ReplyToList)
7773 if (!ids.Contains("@" + nm + " ") &&
7774 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7776 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7778 ids += "@" + m.Result("${id}") + " ";
7780 ids += "@" + nm + " ";
7785 if (ids.Length == 0) return;
7786 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7788 StatusText.Text = ". " + StatusText.Text;
7790 this.inReplyTo = null;
7794 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7799 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7801 //if (StatusText.Text.StartsWith("@"))
7803 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7804 // sidx += 2 + ids.Length;
7808 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7809 // sidx += 1 + ids.Length;
7811 StatusText.SelectionStart = sidx;
7817 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7820 int sidx = StatusText.SelectionStart;
7821 PostClass post = _curPost;
7822 if (!ids.Contains("@" + post.ScreenName + " ") &&
7823 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7825 ids += "@" + post.ScreenName + " ";
7827 foreach (string nm in post.ReplyToList)
7829 if (!ids.Contains("@" + nm + " ") &&
7830 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7832 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7834 ids += "@" + m.Result("${id}") + " ";
7836 ids += "@" + nm + " ";
7839 if (!string.IsNullOrEmpty(post.RetweetedBy))
7841 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7842 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7844 ids += "@" + post.RetweetedBy + " ";
7847 if (ids.Length == 0) return;
7848 if (string.IsNullOrEmpty(StatusText.Text))
7851 StatusText.Text = ids;
7852 StatusText.SelectionStart = ids.Length;
7855 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7856 var inReplyToScreenName = this._curPost.ScreenName;
7857 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7863 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7868 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7870 StatusText.SelectionStart = sidx;
7876 StatusText.SelectionStart = StatusText.Text.Length;
7881 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7886 private static int iconCnt = 0;
7887 private static int blinkCnt = 0;
7888 private static bool blink = false;
7889 private static bool idle = false;
7891 private async Task RefreshTasktrayIcon()
7894 await this.Colorize();
7896 if (!TimerRefreshIcon.Enabled) return;
7897 //Static usCheckCnt As int = 0
7899 //Static iconDlListTopItem As ListViewItem = null
7901 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7902 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7904 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7906 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7912 //if (usCheckCnt > 300) //1min
7915 // if (!this.IsReceivedUserStream)
7917 // TraceOut("ReconnectUserStream");
7918 // tw.ReconnectUserStream();
7922 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7924 if (iconCnt >= this.NIconRefresh.Length)
7932 SaveConfigsAll(true);
7937 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7939 _myStatusError = false;
7943 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7944 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7946 if (blinkCnt > 0) return;
7948 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7950 NotifyIcon1.Icon = ReplyIcon;
7954 NotifyIcon1.Icon = ReplyIconBlink;
7962 //優先度:エラー→オフライン→アイドル
7966 NotifyIcon1.Icon = NIconAtRed;
7969 if (_myStatusOnline)
7971 NotifyIcon1.Icon = NIconAt;
7975 NotifyIcon1.Icon = NIconAtSmoke;
7979 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7982 await this.RefreshTasktrayIcon();
7985 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7987 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7988 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7990 if (ListTab != null && ListTab.SelectedTab != null)
7991 _rclickTabName = ListTab.SelectedTab.Text;
7996 if (_statuses == null) return;
7997 if (_statuses.Tabs == null) return;
8000 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
8003 NotifyDispMenuItem.Checked = tb.Notify;
8004 this.NotifyTbMenuItem.Checked = tb.Notify;
8006 soundfileListup = true;
8007 SoundFileComboBox.Items.Clear();
8008 this.SoundFileTbComboBox.Items.Clear();
8009 SoundFileComboBox.Items.Add("");
8010 this.SoundFileTbComboBox.Items.Add("");
8011 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8012 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8014 oDir = oDir.GetDirectories("Sounds")[0];
8016 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8018 SoundFileComboBox.Items.Add(oFile.Name);
8019 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8021 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8022 if (idx == -1) idx = 0;
8023 SoundFileComboBox.SelectedIndex = idx;
8024 this.SoundFileTbComboBox.SelectedIndex = idx;
8025 soundfileListup = false;
8026 UreadManageMenuItem.Checked = tb.UnreadManage;
8027 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8029 TabMenuControl(_rclickTabName);
8032 private void TabMenuControl(string tabName)
8034 var tabInfo = _statuses.GetTabByName(tabName);
8036 this.FilterEditMenuItem.Enabled = true;
8037 this.EditRuleTbMenuItem.Enabled = true;
8039 if (tabInfo.IsDefaultTabType)
8041 this.ProtectTabMenuItem.Enabled = false;
8042 this.ProtectTbMenuItem.Enabled = false;
8046 this.ProtectTabMenuItem.Enabled = true;
8047 this.ProtectTbMenuItem.Enabled = true;
8050 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8052 this.ProtectTabMenuItem.Checked = true;
8053 this.ProtectTbMenuItem.Checked = true;
8054 this.DeleteTabMenuItem.Enabled = false;
8055 this.DeleteTbMenuItem.Enabled = false;
8059 this.ProtectTabMenuItem.Checked = false;
8060 this.ProtectTbMenuItem.Checked = false;
8061 this.DeleteTabMenuItem.Enabled = true;
8062 this.DeleteTbMenuItem.Enabled = true;
8066 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8068 var checkState = ((ToolStripMenuItem)sender).Checked;
8071 this.ProtectTbMenuItem.Checked = checkState;
8072 this.ProtectTabMenuItem.Checked = checkState;
8075 this.DeleteTabMenuItem.Enabled = !checkState;
8076 this.DeleteTbMenuItem.Enabled = !checkState;
8078 if (string.IsNullOrEmpty(_rclickTabName)) return;
8079 _statuses.Tabs[_rclickTabName].Protected = checkState;
8084 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8086 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8087 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8089 if (string.IsNullOrEmpty(_rclickTabName)) return;
8090 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8095 public void ChangeTabUnreadManage(string tabName, bool isManage)
8097 var idx = this.GetTabPageIndex(tabName);
8101 _statuses.Tabs[tabName].UnreadManage = isManage;
8102 if (this._cfgCommon.TabIconDisp)
8104 if (_statuses.Tabs[tabName].UnreadCount > 0)
8105 ListTab.TabPages[idx].ImageIndex = 0;
8107 ListTab.TabPages[idx].ImageIndex = -1;
8110 if (_curTab.Text == tabName)
8112 this.PurgeListViewItemCache();
8116 SetMainWindowTitle();
8117 SetStatusLabelUrl();
8118 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8121 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8123 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8124 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8126 if (string.IsNullOrEmpty(_rclickTabName)) return;
8128 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8133 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8135 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8137 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8142 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8144 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8146 RemoveSpecifiedTab(_rclickTabName, true);
8150 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8152 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8154 using (var fltDialog = new FilterDialog())
8156 fltDialog.Owner = this;
8157 fltDialog.SetCurrent(_rclickTabName);
8158 fltDialog.ShowDialog(this);
8160 this.TopMost = this._cfgCommon.AlwaysTop;
8162 this.ApplyPostFilters();
8166 private void AddTabMenuItem_Click(object sender, EventArgs e)
8168 string tabName = null;
8169 MyCommon.TabUsageType tabUsage;
8170 using (InputTabName inputName = new InputTabName())
8172 inputName.TabName = _statuses.MakeTabName("MyTab");
8173 inputName.IsShowUsage = true;
8174 inputName.ShowDialog();
8175 if (inputName.DialogResult == DialogResult.Cancel) return;
8176 tabName = inputName.TabName;
8177 tabUsage = inputName.Usage;
8179 this.TopMost = this._cfgCommon.AlwaysTop;
8180 if (!string.IsNullOrEmpty(tabName))
8183 ListElement list = null;
8184 if (tabUsage == MyCommon.TabUsageType.Lists)
8186 using (ListAvailable listAvail = new ListAvailable())
8188 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8189 if (listAvail.SelectedList == null) return;
8190 list = listAvail.SelectedList;
8197 case MyCommon.TabUsageType.UserDefined:
8198 tab = new FilterTabModel(tabName);
8200 case MyCommon.TabUsageType.PublicSearch:
8201 tab = new PublicSearchTabModel(tabName);
8203 case MyCommon.TabUsageType.Lists:
8204 tab = new ListTimelineTabModel(tabName, list);
8210 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8212 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8213 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8219 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8221 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8222 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8224 if (tabUsage == MyCommon.TabUsageType.Lists)
8226 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8227 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8228 this.GetListTimelineAsync(listTab);
8234 private void TabMenuItem_Click(object sender, EventArgs e)
8236 using (var fltDialog = new FilterDialog())
8238 fltDialog.Owner = this;
8241 foreach (int idx in _curList.SelectedIndices)
8245 if (!SelectTab(out tabName)) return;
8247 fltDialog.SetCurrent(tabName);
8248 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8250 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8254 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8256 fltDialog.ShowDialog(this);
8257 this.TopMost = this._cfgCommon.AlwaysTop;
8261 this.ApplyPostFilters();
8263 if (this.ListTab.SelectedTab != null &&
8264 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8266 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8270 protected override bool ProcessDialogKey(Keys keyData)
8272 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8273 if ((keyData & Keys.KeyCode) == Keys.Enter)
8275 if (StatusText.Focused)
8277 bool _NewLine = false;
8280 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8282 if (StatusText.Multiline)
8284 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8286 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8290 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8294 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8296 if (StatusText.Multiline)
8298 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8300 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8304 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8310 if (StatusText.Multiline)
8312 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8314 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8315 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8319 if (((keyData & Keys.Shift) == Keys.Shift) ||
8320 (((keyData & Keys.Control) != Keys.Control) &&
8321 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8327 int pos1 = StatusText.SelectionStart;
8328 if (StatusText.SelectionLength > 0)
8330 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8332 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8333 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8338 PostButton_Click(null, null);
8342 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8343 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8344 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8346 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8351 return base.ProcessDialogKey(keyData);
8354 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8356 MakeReplyOrDirectStatus(false, true, true);
8359 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8362 if (_curList.SelectedIndices.Count == 0) return;
8364 var tab = this._statuses.Tabs[this._curTab.Text];
8365 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8366 .Select(x => tab[x])
8367 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8370 this.AddFilterRuleByScreenName(screenNameArray);
8372 if (screenNameArray.Length != 0)
8374 List<string> atids = new List<string>();
8375 foreach (var screenName in screenNameArray)
8377 atids.Add("@" + screenName);
8379 int cnt = AtIdSupl.ItemCount;
8380 AtIdSupl.AddRangeItem(atids.ToArray());
8381 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8385 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8387 if (this._curList.SelectedIndices.Count == 0)
8390 var tab = this._statuses.Tabs[this._curTab.Text];
8391 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8392 .Select(x => tab[x].Source).ToArray();
8394 this.AddFilterRuleBySource(sourceArray);
8397 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8401 if (!SelectTab(out tabName)) return;
8403 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8407 if (tab.TabType != MyCommon.TabUsageType.Mute)
8409 this.MoveOrCopy(out mv, out mk);
8413 // ミュートタブでは常に MoveMatches を true にする
8418 foreach (var screenName in screenNameArray)
8420 tab.AddFilter(new PostFilterRule
8422 FilterName = screenName,
8423 UseNameField = true,
8427 FilterByUrl = false,
8431 this.ApplyPostFilters();
8435 public void AddFilterRuleBySource(params string[] sourceArray)
8437 // タブ選択ダイアログを表示(or追加)
8439 if (!this.SelectTab(out tabName))
8442 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8446 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8448 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8449 this.MoveOrCopy(out mv, out mk);
8453 // ミュートタブでは常に MoveMatches を true にする
8458 // 振り分けルールに追加するSource
8459 foreach (var source in sourceArray)
8461 filterTab.AddFilter(new PostFilterRule
8463 FilterSource = source,
8467 FilterByUrl = false,
8471 this.ApplyPostFilters();
8472 this.SaveConfigsTabs();
8475 private bool SelectTab(out string tabName)
8482 using (var dialog = new TabsDialog(_statuses))
8484 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8486 var selectedTab = dialog.SelectedTab;
8487 tabName = selectedTab == null ? null : selectedTab.TabName;
8490 ListTab.SelectedTab.Focus();
8492 if (tabName == null)
8494 using (InputTabName inputName = new InputTabName())
8496 inputName.TabName = _statuses.MakeTabName("MyTab");
8497 inputName.ShowDialog();
8498 if (inputName.DialogResult == DialogResult.Cancel) return false;
8499 tabName = inputName.TabName;
8501 this.TopMost = this._cfgCommon.AlwaysTop;
8502 if (!string.IsNullOrEmpty(tabName))
8504 var tab = new FilterTabModel(tabName);
8505 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8507 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8508 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8526 private void MoveOrCopy(out bool move, out bool mark)
8530 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8531 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8539 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8540 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8550 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8555 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8560 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8562 if (StatusText.Focused)
8565 StatusText.SelectAll();
8569 // ListView上でのCtrl+A
8570 NativeMethods.SelectAllItems(this._curList);
8574 private void MoveMiddle()
8580 if (_curList.SelectedIndices.Count == 0) return;
8582 int idx = _curList.SelectedIndices[0];
8584 _item = _curList.GetItemAt(0, 25);
8590 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8592 idx2 = _curList.VirtualListSize - 1;
8596 idx -= Math.Abs(idx1 - idx2) / 2;
8597 if (idx < 0) idx = 0;
8599 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8600 _curList.EnsureVisible(idx);
8603 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8605 var linkElements = this.tweetDetailsView.GetLinkElements();
8607 if (linkElements.Length > 0)
8609 UrlDialog.ClearUrl();
8611 string openUrlStr = "";
8613 if (linkElements.Length == 1)
8615 // ツイートに含まれる URL が 1 つのみの場合
8616 // => OpenURL ダイアログを表示せずにリンクを開く
8621 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8623 catch (ArgumentException)
8632 if (string.IsNullOrEmpty(urlStr)) return;
8633 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8635 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8636 await this.OpenUriAsync(new Uri(openUrlStr));
8640 // ツイートに含まれる URL が複数ある場合
8641 // => OpenURL を表示しユーザーが選択したリンクを開く
8643 foreach (var linkElm in linkElements)
8646 string linkText = "";
8650 urlStr = linkElm.GetAttribute("title");
8651 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8652 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8653 linkText = linkElm.InnerText;
8655 catch (ArgumentException)
8664 if (string.IsNullOrEmpty(urlStr)) continue;
8665 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8669 if (UrlDialog.ShowDialog() == DialogResult.OK)
8671 openUrlStr = UrlDialog.SelectedUrl;
8673 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8674 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8681 this.TopMost = this._cfgCommon.AlwaysTop;
8686 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8688 if (string.IsNullOrEmpty(_rclickTabName)) return;
8689 ClearTab(_rclickTabName, true);
8692 private void ClearTab(string tabName, bool showWarning)
8696 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8697 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8703 _statuses.ClearTabIds(tabName);
8704 if (ListTab.SelectedTab.Text == tabName)
8707 _anchorFlag = false;
8708 this.PurgeListViewItemCache();
8712 foreach (TabPage tb in ListTab.TabPages)
8714 if (tb.Text == tabName)
8716 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8721 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8723 SetMainWindowTitle();
8724 SetStatusLabelUrl();
8727 private static long followers = 0;
8729 private void SetMainWindowTitle()
8732 StringBuilder ttl = new StringBuilder(256);
8735 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
8736 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8737 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8738 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8740 foreach (var tab in _statuses.Tabs.Values)
8742 ur += tab.UnreadCount;
8747 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
8748 ttl.Append(Application.ProductName);
8750 switch (this._cfgCommon.DispLatestPost)
8752 case MyCommon.DispTitleEnum.Ver:
8753 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8755 case MyCommon.DispTitleEnum.Post:
8756 if (_history != null && _history.Count > 1)
8757 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8759 case MyCommon.DispTitleEnum.UnreadRepCount:
8760 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8762 case MyCommon.DispTitleEnum.UnreadAllCount:
8763 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8765 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8766 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8768 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8769 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8771 case MyCommon.DispTitleEnum.OwnStatus:
8772 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8773 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8779 this.Text = ttl.ToString();
8781 catch (AccessViolationException)
8783 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8787 private string GetStatusLabelText()
8790 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8791 if (_statuses == null) return "";
8792 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8793 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8794 if (tbRep == null || tbDm == null) return "";
8795 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8800 StringBuilder slbl = new StringBuilder(256);
8803 foreach (var tab in _statuses.Tabs.Values)
8805 ur += tab.UnreadCount;
8807 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8809 tur = tab.UnreadCount;
8820 UnreadAtCounter = urat;
8822 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8824 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8825 if (this._cfgCommon.TimelinePeriod == 0)
8827 slbl.Append(Properties.Resources.SetStatusLabelText2);
8831 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8833 return slbl.ToString();
8836 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8840 if (this.InvokeRequired && !this.IsDisposed)
8842 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8846 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8847 SetApiStatusLabel(endpointName);
8850 catch (ObjectDisposedException)
8854 catch (InvalidOperationException)
8860 private void SetApiStatusLabel(string endpointName = null)
8862 if (_curTab == null)
8864 this.toolStripApiGauge.ApiEndpoint = null;
8868 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8870 if (endpointName == null)
8875 case MyCommon.TabUsageType.Home:
8876 case MyCommon.TabUsageType.UserDefined:
8877 endpointName = "/statuses/home_timeline";
8880 case MyCommon.TabUsageType.Mentions:
8881 endpointName = "/statuses/mentions_timeline";
8884 case MyCommon.TabUsageType.Favorites:
8885 endpointName = "/favorites/list";
8888 case MyCommon.TabUsageType.DirectMessage:
8889 endpointName = "/direct_messages";
8892 case MyCommon.TabUsageType.UserTimeline:
8893 endpointName = "/statuses/user_timeline";
8896 case MyCommon.TabUsageType.Lists:
8897 endpointName = "/lists/statuses";
8900 case MyCommon.TabUsageType.PublicSearch:
8901 endpointName = "/search/tweets";
8904 case MyCommon.TabUsageType.Related:
8905 endpointName = "/statuses/show/:id";
8912 this.toolStripApiGauge.ApiEndpoint = endpointName;
8916 // 表示中のタブに関連する endpoint であれば更新
8919 switch (endpointName)
8921 case "/statuses/home_timeline":
8922 update = tabType == MyCommon.TabUsageType.Home ||
8923 tabType == MyCommon.TabUsageType.UserDefined;
8926 case "/statuses/mentions_timeline":
8927 update = tabType == MyCommon.TabUsageType.Mentions;
8930 case "/favorites/list":
8931 update = tabType == MyCommon.TabUsageType.Favorites;
8934 case "/direct_messages:":
8935 update = tabType == MyCommon.TabUsageType.DirectMessage;
8938 case "/statuses/user_timeline":
8939 update = tabType == MyCommon.TabUsageType.UserTimeline;
8942 case "/lists/statuses":
8943 update = tabType == MyCommon.TabUsageType.Lists;
8946 case "/search/tweets":
8947 update = tabType == MyCommon.TabUsageType.PublicSearch;
8950 case "/statuses/show/:id":
8951 update = tabType == MyCommon.TabUsageType.Related;
8960 this.toolStripApiGauge.ApiEndpoint = endpointName;
8966 private void SetStatusLabelUrl()
8968 StatusLabelUrl.Text = GetStatusLabelText();
8971 public void SetStatusLabel(string text)
8973 StatusLabel.Text = text;
8976 private void SetNotifyIconText()
8978 var ur = new StringBuilder(64);
8980 // タスクトレイアイコンのツールチップテキスト書き換え
8982 ur.Remove(0, ur.Length);
8983 if (this._cfgCommon.DispUsername)
8985 ur.Append(tw.Username);
8988 ur.Append(Application.ProductName);
8990 ur.Append("(Debug Build)");
8992 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8995 ur.Append(UnreadCounter);
8997 ur.Append(UnreadAtCounter);
9000 NotifyIcon1.Text = ur.ToString();
9003 internal void CheckReplyTo(string StatusText)
9007 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9009 foreach (Match hm in m)
9011 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9013 hstr += "#" + hm.Result("$3") + " ";
9014 HashSupl.AddItem("#" + hm.Result("$3"));
9017 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9019 hstr += HashMgr.UseHash;
9021 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9023 // 本当にリプライ先指定すべきかどうかの判定
9024 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9026 if (this._cfgCommon.UseAtIdSupplement)
9028 int bCnt = AtIdSupl.ItemCount;
9029 foreach (Match mid in m)
9031 AtIdSupl.AddItem(mid.Result("${id}"));
9033 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9036 // リプライ先ステータスIDの指定がない場合は指定しない
9037 if (this.inReplyTo == null)
9041 // 次の条件を満たす場合に in_reply_to_status_id 指定
9042 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9043 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9044 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9048 var inReplyToScreenName = this.inReplyTo.Item2;
9049 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9051 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9055 foreach (Match mid in m)
9057 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9062 this.inReplyTo = null;
9065 private void TweenMain_Resize(object sender, EventArgs e)
9067 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9069 this.Visible = false;
9071 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9073 // 現在の DPI と設定保存時の DPI との比を取得する
9074 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9076 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9077 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9078 this.DesktopLocation = _cfgLocal.FormLocation;
9079 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9082 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9083 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9084 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9086 this.SplitContainer1.SplitterDistance = splitterDistance;
9090 StatusText.Multiline = _cfgLocal.StatusMultiline;
9091 if (StatusText.Multiline)
9093 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9094 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9095 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9097 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9099 StatusText.Height = statusTextHeight;
9103 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9105 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9109 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9110 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9112 this.SplitContainer3.SplitterDistance = previewDistance;
9115 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9116 this.SplitContainer3.Panel2Collapsed = true;
9118 _initialLayout = false;
9120 if (this.WindowState != FormWindowState.Minimized)
9122 _formWindowState = this.WindowState;
9126 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9128 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9129 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9130 if (PlaySoundMenuItem.Checked)
9132 this._cfgCommon.PlaySound = true;
9136 this._cfgCommon.PlaySound = false;
9138 ModifySettingCommon = true;
9141 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9143 if (this._initialLayout)
9146 int splitterDistance;
9147 switch (this.WindowState)
9149 case FormWindowState.Normal:
9150 splitterDistance = this.SplitContainer1.SplitterDistance;
9152 case FormWindowState.Maximized:
9153 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9154 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9155 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9156 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9162 this._mySpDis = splitterDistance;
9163 this.ModifySettingLocal = true;
9166 private async Task doRepliedStatusOpen()
9168 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9170 if (MyCommon.IsKeyDown(Keys.Shift))
9172 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9175 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9177 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9178 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9182 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9184 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9185 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9186 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9189 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9194 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9196 await this.doRepliedStatusOpen();
9199 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9201 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9202 if (multiline != this.StatusText.Multiline)
9204 this.StatusText.Multiline = multiline;
9205 MultiLineMenuItem.Checked = multiline;
9206 ModifySettingLocal = true;
9210 private void StatusText_MultilineChanged(object sender, EventArgs e)
9212 if (this.StatusText.Multiline)
9213 this.StatusText.ScrollBars = ScrollBars.Vertical;
9215 this.StatusText.ScrollBars = ScrollBars.None;
9217 ModifySettingLocal = true;
9220 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9223 StatusText.Multiline = MultiLineMenuItem.Checked;
9224 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9225 if (MultiLineMenuItem.Checked)
9227 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9228 SplitContainer2.SplitterDistance = 0;
9230 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9234 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9236 ModifySettingLocal = true;
9239 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9241 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9242 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9244 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9245 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9246 //Appendix A. Collected ABNF for URI
9247 //http://www.ietf.org/rfc/rfc3986.txt
9251 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9253 if (StatusText.SelectionLength > 0)
9255 string tmp = StatusText.SelectedText;
9256 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9257 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9259 // 文字列が選択されている場合はその文字列について処理
9261 //nico.ms使用、nicovideoにマッチしたら変換
9262 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9264 result = nicoms.Shorten(tmp);
9266 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9268 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9271 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9272 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9273 result = resultUri.AbsoluteUri;
9275 catch (WebApiException e)
9277 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9280 catch (UriFormatException e)
9282 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9291 if (!string.IsNullOrEmpty(result))
9293 urlUndo undotmp = new urlUndo();
9295 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9296 StatusText.SelectedText = result;
9299 undotmp.Before = tmp;
9300 undotmp.After = result;
9302 if (urlUndoBuffer == null)
9304 urlUndoBuffer = new List<urlUndo>();
9305 UrlUndoToolStripMenuItem.Enabled = true;
9308 urlUndoBuffer.Add(undotmp);
9314 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9315 @"(?<url>(?<protocol>https?://)" +
9316 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9317 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9318 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9319 // 正規表現にマッチしたURL文字列をtinyurl化
9320 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9322 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9323 string tmp = mt.Result("${url}");
9324 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9325 urlUndo undotmp = new urlUndo();
9328 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9330 //nico.ms使用、nicovideoにマッチしたら変換
9331 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9333 result = nicoms.Shorten(tmp);
9335 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9337 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9340 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9341 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9342 result = resultUri.AbsoluteUri;
9344 catch (HttpRequestException e)
9346 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9347 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9348 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9350 this.StatusLabel.Text = Converter_Type + ":" + message;
9353 catch (WebApiException e)
9355 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9358 catch (UriFormatException e)
9360 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9369 if (!string.IsNullOrEmpty(result))
9371 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9372 StatusText.SelectedText = result;
9374 undotmp.Before = mt.Result("${url}");
9375 undotmp.After = result;
9377 if (urlUndoBuffer == null)
9379 urlUndoBuffer = new List<urlUndo>();
9380 UrlUndoToolStripMenuItem.Enabled = true;
9383 urlUndoBuffer.Add(undotmp);
9391 private void doUrlUndo()
9393 if (urlUndoBuffer != null)
9395 string tmp = StatusText.Text;
9396 foreach (urlUndo data in urlUndoBuffer)
9398 tmp = tmp.Replace(data.After, data.Before);
9400 StatusText.Text = tmp;
9401 urlUndoBuffer = null;
9402 UrlUndoToolStripMenuItem.Enabled = false;
9403 StatusText.SelectionStart = 0;
9404 StatusText.SelectionLength = 0;
9408 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9410 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9413 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9415 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9418 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9420 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9423 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9425 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9428 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9430 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9432 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9433 Random rnd = new Random();
9434 // 前回使用した短縮URLサービス以外を選択する
9437 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9439 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9440 await UrlConvertAsync(svc);
9444 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9449 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9451 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9452 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9453 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9454 ModifySettingCommon = true;
9457 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9459 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9460 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9461 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9462 ModifySettingCommon = true;
9465 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9467 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9468 MenuStrip1.Tag = new Object();
9469 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9472 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9474 if (this.Tag != null) // 設定された戻り先へ遷移
9476 if (this.Tag == this.ListTab.SelectedTab)
9477 ((Control)this.ListTab.SelectedTab.Tag).Select();
9479 ((Control)this.Tag).Select();
9481 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9483 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9485 this.Tag = ListTab.SelectedTab.Tag;
9486 ((Control)this.Tag).Select();
9489 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9490 MenuStrip1.Tag = null;
9493 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9495 DetailsListView lst = (DetailsListView)sender;
9496 if (_cfgLocal == null) return;
9500 _cfgLocal.Width1 = lst.Columns[0].Width;
9501 _cfgLocal.Width3 = lst.Columns[1].Width;
9505 int[] darr = new int[lst.Columns.Count];
9506 for (int i = 0; i < lst.Columns.Count; i++)
9508 darr[lst.Columns[i].DisplayIndex] = i;
9510 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9512 for (int i = 0; i < lst.Columns.Count; i++)
9517 _cfgLocal.DisplayIndex1 = i;
9520 _cfgLocal.DisplayIndex2 = i;
9523 _cfgLocal.DisplayIndex3 = i;
9526 _cfgLocal.DisplayIndex4 = i;
9529 _cfgLocal.DisplayIndex5 = i;
9532 _cfgLocal.DisplayIndex6 = i;
9535 _cfgLocal.DisplayIndex7 = i;
9538 _cfgLocal.DisplayIndex8 = i;
9542 _cfgLocal.Width1 = lst.Columns[0].Width;
9543 _cfgLocal.Width2 = lst.Columns[1].Width;
9544 _cfgLocal.Width3 = lst.Columns[2].Width;
9545 _cfgLocal.Width4 = lst.Columns[3].Width;
9546 _cfgLocal.Width5 = lst.Columns[4].Width;
9547 _cfgLocal.Width6 = lst.Columns[5].Width;
9548 _cfgLocal.Width7 = lst.Columns[6].Width;
9549 _cfgLocal.Width8 = lst.Columns[7].Width;
9551 ModifySettingLocal = true;
9552 _isColumnChanged = true;
9555 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9557 DetailsListView lst = (DetailsListView)sender;
9558 if (_cfgLocal == null) return;
9561 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9563 _cfgLocal.Width1 = lst.Columns[0].Width;
9564 ModifySettingLocal = true;
9565 _isColumnChanged = true;
9567 if (_cfgLocal.Width3 != lst.Columns[1].Width)
9569 _cfgLocal.Width3 = lst.Columns[1].Width;
9570 ModifySettingLocal = true;
9571 _isColumnChanged = true;
9576 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9578 _cfgLocal.Width1 = lst.Columns[0].Width;
9579 ModifySettingLocal = true;
9580 _isColumnChanged = true;
9582 if (_cfgLocal.Width2 != lst.Columns[1].Width)
9584 _cfgLocal.Width2 = lst.Columns[1].Width;
9585 ModifySettingLocal = true;
9586 _isColumnChanged = true;
9588 if (_cfgLocal.Width3 != lst.Columns[2].Width)
9590 _cfgLocal.Width3 = lst.Columns[2].Width;
9591 ModifySettingLocal = true;
9592 _isColumnChanged = true;
9594 if (_cfgLocal.Width4 != lst.Columns[3].Width)
9596 _cfgLocal.Width4 = lst.Columns[3].Width;
9597 ModifySettingLocal = true;
9598 _isColumnChanged = true;
9600 if (_cfgLocal.Width5 != lst.Columns[4].Width)
9602 _cfgLocal.Width5 = lst.Columns[4].Width;
9603 ModifySettingLocal = true;
9604 _isColumnChanged = true;
9606 if (_cfgLocal.Width6 != lst.Columns[5].Width)
9608 _cfgLocal.Width6 = lst.Columns[5].Width;
9609 ModifySettingLocal = true;
9610 _isColumnChanged = true;
9612 if (_cfgLocal.Width7 != lst.Columns[6].Width)
9614 _cfgLocal.Width7 = lst.Columns[6].Width;
9615 ModifySettingLocal = true;
9616 _isColumnChanged = true;
9618 if (_cfgLocal.Width8 != lst.Columns[7].Width)
9620 _cfgLocal.Width8 = lst.Columns[7].Width;
9621 ModifySettingLocal = true;
9622 _isColumnChanged = true;
9625 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9628 // SaveConfigsLocal();
9632 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9634 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9635 ModifySettingLocal = true;
9638 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9640 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9642 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9644 SelectMedia_DragDrop(e);
9647 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9649 var url = GetUrlFromDataObject(e.Data);
9652 if (url.Item2 == null)
9653 appendText = url.Item1;
9655 appendText = url.Item2 + " " + url.Item1;
9657 if (this.StatusText.TextLength == 0)
9658 this.StatusText.Text = appendText;
9660 this.StatusText.Text += " " + appendText;
9662 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9664 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9666 this.StatusText.Text += text;
9668 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9670 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9671 if (data != null) StatusText.Text += data;
9676 /// IDataObject から URL とタイトルの対を取得します
9679 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9681 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9682 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9683 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9685 if (data.GetDataPresent("text/x-moz-url"))
9687 // Firefox, Google Chrome で利用可能
9688 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9690 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9692 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9693 if (lines.Length < 2)
9694 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9696 return new Tuple<string, string>(lines[0], lines[1]);
9699 else if (data.GetDataPresent("IESiteModeToUrl"))
9701 // Internet Exproler 用
9702 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9704 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9706 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9707 if (lines.Length < 2)
9708 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9710 return new Tuple<string, string>(lines[0], lines[1]);
9713 else if (data.GetDataPresent("UniformResourceLocatorW"))
9717 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9719 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9720 return new Tuple<string, string>(url, null);
9724 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9727 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9729 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9731 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9733 SelectMedia_DragEnter(e);
9737 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9739 e.Effect = DragDropEffects.Copy;
9742 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9744 e.Effect = DragDropEffects.Copy;
9747 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9749 e.Effect = DragDropEffects.Copy;
9753 e.Effect = DragDropEffects.None;
9756 private void TweenMain_DragOver(object sender, DragEventArgs e)
9760 public bool IsNetworkAvailable()
9763 nw = MyCommon.IsNetworkAvailable();
9764 _myStatusOnline = nw;
9768 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9770 var uriStr = uri.AbsoluteUri;
9772 // OpenTween 内部で使用する URL
9773 if (uri.Authority == "opentween")
9775 await this.OpenInternalUriAsync(uri);
9779 // ハッシュタグを含む Twitter 検索
9780 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9783 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9784 var pos = unescapedQuery.IndexOf('#');
9785 if (pos == -1) return;
9787 var hash = unescapedQuery.Substring(pos);
9788 this.HashSupl.AddItem(hash);
9789 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9790 this.AddNewTabForSearch(hash);
9795 // フラグが立っている場合は設定と逆の動作をする
9796 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
9797 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
9799 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9800 if (userUriMatch.Success)
9802 var screenName = userUriMatch.Groups["ScreenName"].Value;
9803 if (this.IsTwitterId(screenName))
9805 this.AddNewTabForUserTimeline(screenName);
9812 await this.OpenUriInBrowserAsync(uriStr);
9816 /// OpenTween 内部の機能を呼び出すための URL を開きます
9818 private async Task OpenInternalUriAsync(Uri uri)
9820 // ツイートを開く (//opentween/status/:status_id)
9821 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9824 var statusId = long.Parse(match.Groups[1].Value);
9825 await this.OpenRelatedTab(statusId);
9830 public Task OpenUriInBrowserAsync(string UriString)
9832 return Task.Run(() =>
9834 string myPath = UriString;
9838 var configBrowserPath = this._cfgLocal.BrowserPath;
9839 if (!string.IsNullOrEmpty(configBrowserPath))
9841 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9843 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9844 string browserPath = configBrowserPath.Substring(1, sep - 1);
9846 if (sep < configBrowserPath.Length - 1)
9848 arg = configBrowserPath.Substring(sep + 1);
9850 myPath = arg + " " + myPath;
9851 System.Diagnostics.Process.Start(browserPath, myPath);
9855 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9860 System.Diagnostics.Process.Start(myPath);
9865 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9870 private void ListTabSelect(TabPage _tab)
9874 if (this._curList != null)
9876 var beforeSelectedList = this._curList;
9877 var beforeSelectedTabModel = this._statuses.Tabs[this._curTab.Text];
9879 // 発言一覧のスクロール位置・選択状態を退避
9880 this.listViewScroll[beforeSelectedTabModel.TabName] = this.SaveListViewScroll(beforeSelectedList, beforeSelectedTabModel);
9881 this.listViewSelection[beforeSelectedTabModel.TabName] = this.SaveListViewSelection(beforeSelectedList, beforeSelectedTabModel);
9884 this.PurgeListViewItemCache();
9887 _curList = (DetailsListView)_tab.Tag;
9889 var curTabModel = this._statuses.Tabs[this._curTab.Text];
9891 this._curList.VirtualListSize = curTabModel.AllCount;
9894 ListViewScroll scrollInfo;
9895 if (this.listViewScroll.TryGetValue(curTabModel.TabName, out scrollInfo))
9896 this.RestoreListViewScroll(this._curList, curTabModel, scrollInfo);
9899 ListViewSelection selectionInfo;
9900 if (this.listViewSelection.TryGetValue(curTabModel.TabName, out selectionInfo))
9901 this.RestoreListViewSelection(this._curList, curTabModel, selectionInfo);
9903 if (_curList.SelectedIndices.Count > 0)
9905 _curItemIndex = _curList.SelectedIndices[0];
9906 _curPost = GetCurTabPost(_curItemIndex);
9915 _anchorFlag = false;
9919 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9923 for (int i = 0; i < _curList.Columns.Count; i++)
9925 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9930 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9932 ListTabSelect(e.TabPage);
9935 private void SelectListItem(DetailsListView LView, int Index)
9938 Rectangle bnd = new Rectangle();
9940 var item = LView.FocusedItem;
9949 LView.SelectedIndices.Clear();
9951 while (LView.SelectedIndices.Count > 0);
9952 item = LView.Items[Index];
9953 item.Selected = true;
9954 item.Focused = true;
9956 if (flg) LView.Invalidate(bnd);
9959 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9962 Rectangle bnd = new Rectangle();
9964 var item = LView.FocusedItem;
9975 LView.SelectedIndices.Clear();
9977 while (LView.SelectedIndices.Count > 0);
9978 LView.SelectItems(Index);
9980 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9982 LView.SelectionMark = selectionMarkIndex;
9984 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9986 LView.Items[focusedIndex].Focused = true;
9988 else if (Index != null && Index.Length != 0)
9990 LView.Items[Index.Last()].Focused = true;
9993 if (flg) LView.Invalidate(bnd);
9996 private void StartUserStream()
9998 tw.NewPostFromStream += tw_NewPostFromStream;
9999 tw.UserStreamStarted += tw_UserStreamStarted;
10000 tw.UserStreamStopped += tw_UserStreamStopped;
10001 tw.PostDeleted += tw_PostDeleted;
10002 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10004 this.RefreshUserStreamsMenu();
10006 if (this._cfgCommon.UserstreamStartup)
10007 tw.StartUserStream();
10010 private async void TweenMain_Shown(object sender, EventArgs e)
10012 NotifyIcon1.Visible = true;
10014 if (this.IsNetworkAvailable())
10018 var loadTasks = new List<Task>
10020 this.RefreshMuteUserIdsAsync(),
10021 this.RefreshBlockIdsAsync(),
10022 this.RefreshNoRetweetIdsAsync(),
10023 this.RefreshTwitterConfigurationAsync(),
10024 this.GetHomeTimelineAsync(),
10025 this.GetReplyAsync(),
10026 this.GetDirectMessagesAsync(),
10027 this.GetPublicSearchAllAsync(),
10028 this.GetUserTimelineAllAsync(),
10029 this.GetListTimelineAllAsync(),
10032 if (this._cfgCommon.StartupFollowers)
10033 loadTasks.Add(this.RefreshFollowerIdsAsync());
10035 if (this._cfgCommon.GetFav)
10036 loadTasks.Add(this.GetFavoritesAsync());
10038 var allTasks = Task.WhenAll(loadTasks);
10043 var timeout = Task.Delay(5000);
10044 if (await Task.WhenAny(allTasks, timeout) != timeout)
10048 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10050 if (MyCommon._endingFlag)
10054 if (MyCommon._endingFlag) return;
10056 if (ApplicationSettings.VersionInfoUrl != null)
10058 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10059 if (this._cfgCommon.StartupVersion)
10060 await this.CheckNewVersion(true);
10064 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10065 this.VerUpMenuItem.Enabled = false;
10066 this.VerUpMenuItem.Available = false;
10067 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10070 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10071 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10073 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10074 SettingStripMenuItem_Click(null, null);
10078 var reloadTasks = new List<Task>();
10080 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10081 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10083 if (!tw.GetNoRetweetSuccess)
10084 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10086 if (this.tw.Configuration.PhotoSizeLimit == 0)
10087 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10089 await Task.WhenAll(reloadTasks);
10094 TimerTimeline.Enabled = true;
10097 private async Task doGetFollowersMenu()
10099 await this.RefreshFollowerIdsAsync();
10100 await this.DispSelectedPost(true);
10103 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10105 await this.doGetFollowersMenu();
10108 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10110 doReTweetUnofficial();
10113 private async Task doReTweetOfficial(bool isConfirm)
10116 if (this.ExistCurrentPost)
10118 if (_curPost.IsProtect)
10120 MessageBox.Show("Protected.");
10121 _DoFavRetweetFlags = false;
10124 if (_curList.SelectedIndices.Count > 15)
10126 MessageBox.Show(Properties.Resources.RetweetLimitText);
10127 _DoFavRetweetFlags = false;
10130 else if (_curList.SelectedIndices.Count > 1)
10132 string QuestionText = Properties.Resources.RetweetQuestion2;
10133 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10134 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10136 case DialogResult.Cancel:
10137 case DialogResult.No:
10138 _DoFavRetweetFlags = false;
10146 _DoFavRetweetFlags = false;
10149 if (!this._cfgCommon.RetweetNoConfirm)
10151 string Questiontext = Properties.Resources.RetweetQuestion1;
10152 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10153 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10155 _DoFavRetweetFlags = false;
10161 var statusIds = new List<long>();
10162 foreach (int idx in _curList.SelectedIndices)
10164 PostClass post = GetCurTabPost(idx);
10165 if (!post.IsProtect && !post.IsDm)
10166 statusIds.Add(post.StatusId);
10169 await this.RetweetAsync(statusIds);
10173 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10175 await this.doReTweetOfficial(true);
10178 private async Task FavoritesRetweetOfficial()
10180 if (!this.ExistCurrentPost) return;
10181 _DoFavRetweetFlags = true;
10182 var retweetTask = this.doReTweetOfficial(true);
10183 if (_DoFavRetweetFlags)
10185 _DoFavRetweetFlags = false;
10186 var favoriteTask = this.FavoriteChange(true, false);
10188 await Task.WhenAll(retweetTask, favoriteTask);
10196 private async Task FavoritesRetweetUnofficial()
10198 if (this.ExistCurrentPost && !_curPost.IsDm)
10200 _DoFavRetweetFlags = true;
10201 var favoriteTask = this.FavoriteChange(true);
10202 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10204 _DoFavRetweetFlags = false;
10205 doReTweetUnofficial();
10208 await favoriteTask;
10213 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10215 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10216 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10217 /// <returns>復元されたツイート本文</returns>
10218 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10220 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10223 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10225 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10227 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10231 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10233 statusHtml = statusHtml.Replace("<br>", " ");
10235 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10236 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10237 statusHtml = statusHtml.Replace(" ", " ");
10239 return WebUtility.HtmlDecode(statusHtml);
10242 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10244 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10246 if (_curPost != null)
10247 await this.DispSelectedPost(true);
10250 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10252 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10253 DebugModeToolStripMenuItem.Visible = true;
10255 DebugModeToolStripMenuItem.Visible = false;
10258 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10260 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10263 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10265 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10268 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10270 if (TraceOutToolStripMenuItem.Checked)
10271 MyCommon.TraceFlag = true;
10273 MyCommon.TraceFlag = false;
10276 private void TweenMain_Deactivate(object sender, EventArgs e)
10278 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10279 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10282 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10284 if (string.IsNullOrEmpty(_rclickTabName)) return;
10287 TabRename(_rclickTabName, out _);
10290 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10292 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10295 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10297 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10300 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10302 TwitterApiStatus apiStatus;
10304 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10306 var cancellationToken = dialog.EnableCancellation();
10310 var task = this.tw.GetInfoApi();
10311 apiStatus = await dialog.WaitForAsync(this, task);
10313 catch (WebApiException)
10318 if (cancellationToken.IsCancellationRequested)
10321 if (apiStatus == null)
10323 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10328 using (var apiDlg = new ApiInfoDialog())
10330 apiDlg.ShowDialog(this);
10334 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10336 var id = _curPost?.ScreenName ?? "";
10338 await this.FollowCommand(id);
10341 internal async Task FollowCommand(string id)
10343 using (var inputName = new InputTabName())
10345 inputName.FormTitle = "Follow";
10346 inputName.FormDescription = Properties.Resources.FRMessage1;
10347 inputName.TabName = id;
10349 if (inputName.ShowDialog(this) != DialogResult.OK)
10351 if (string.IsNullOrWhiteSpace(inputName.TabName))
10354 id = inputName.TabName.Trim();
10357 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10361 var task = this.twitterApi.FriendshipsCreate(id);
10362 await dialog.WaitForAsync(this, task);
10364 catch (WebApiException ex)
10366 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10371 MessageBox.Show(Properties.Resources.FRMessage3);
10374 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10376 var id = _curPost?.ScreenName ?? "";
10378 await this.RemoveCommand(id, false);
10381 internal async Task RemoveCommand(string id, bool skipInput)
10385 using (var inputName = new InputTabName())
10387 inputName.FormTitle = "Unfollow";
10388 inputName.FormDescription = Properties.Resources.FRMessage1;
10389 inputName.TabName = id;
10391 if (inputName.ShowDialog(this) != DialogResult.OK)
10393 if (string.IsNullOrWhiteSpace(inputName.TabName))
10396 id = inputName.TabName.Trim();
10400 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10404 var task = this.twitterApi.FriendshipsDestroy(id);
10405 await dialog.WaitForAsync(this, task);
10407 catch (WebApiException ex)
10409 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10414 MessageBox.Show(Properties.Resources.FRMessage3);
10417 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10419 var id = _curPost?.ScreenName ?? "";
10421 await this.ShowFriendship(id);
10424 internal async Task ShowFriendship(string id)
10426 using (var inputName = new InputTabName())
10428 inputName.FormTitle = "Show Friendships";
10429 inputName.FormDescription = Properties.Resources.FRMessage1;
10430 inputName.TabName = id;
10432 if (inputName.ShowDialog(this) != DialogResult.OK)
10434 if (string.IsNullOrWhiteSpace(inputName.TabName))
10437 id = inputName.TabName.Trim();
10440 bool isFollowing, isFollowed;
10442 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10444 var cancellationToken = dialog.EnableCancellation();
10448 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10449 var friendship = await dialog.WaitForAsync(this, task);
10451 isFollowing = friendship.Relationship.Source.Following;
10452 isFollowed = friendship.Relationship.Source.FollowedBy;
10454 catch (WebApiException ex)
10456 if (!cancellationToken.IsCancellationRequested)
10457 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10461 if (cancellationToken.IsCancellationRequested)
10465 string result = "";
10468 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10472 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10476 result += Properties.Resources.GetFriendshipInfo3;
10480 result += Properties.Resources.GetFriendshipInfo4;
10482 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10483 MessageBox.Show(result);
10486 internal async Task ShowFriendship(string[] ids)
10488 foreach (string id in ids)
10490 bool isFollowing, isFollowed;
10492 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10494 var cancellationToken = dialog.EnableCancellation();
10498 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10499 var friendship = await dialog.WaitForAsync(this, task);
10501 isFollowing = friendship.Relationship.Source.Following;
10502 isFollowed = friendship.Relationship.Source.FollowedBy;
10504 catch (WebApiException ex)
10506 if (!cancellationToken.IsCancellationRequested)
10507 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10511 if (cancellationToken.IsCancellationRequested)
10515 string result = "";
10521 ff += Properties.Resources.GetFriendshipInfo1;
10525 ff += Properties.Resources.GetFriendshipInfo2;
10528 ff += System.Environment.NewLine + " ";
10531 ff += Properties.Resources.GetFriendshipInfo3;
10535 ff += Properties.Resources.GetFriendshipInfo4;
10537 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10540 if (MessageBox.Show(
10541 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10542 MessageBoxButtons.YesNo,
10543 MessageBoxIcon.Question,
10544 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10546 await this.RemoveCommand(id, true);
10551 MessageBox.Show(result);
10556 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10558 await this.doShowUserStatus(tw.Username, false);
10559 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10561 // doShowUserStatus(tw.Username, false);
10565 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10570 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10571 // URLから切り出した文字列を渡す
10573 public bool IsTwitterId(string name)
10575 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10576 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10578 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10581 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10583 ModifySettingCommon = true;
10586 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10588 ModifySettingCommon = true;
10591 private void doQuoteOfficial()
10593 if (this.ExistCurrentPost)
10595 if (_curPost.IsDm ||
10596 !StatusText.Enabled) return;
10598 if (_curPost.IsProtect)
10600 MessageBox.Show("Protected.");
10604 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10606 this.inReplyTo = null;
10608 StatusText.SelectionStart = 0;
10609 StatusText.Focus();
10613 private void doReTweetUnofficial()
10616 if (this.ExistCurrentPost)
10618 if (_curPost.IsDm || !StatusText.Enabled)
10621 if (_curPost.IsProtect)
10623 MessageBox.Show("Protected.");
10626 string rtdata = _curPost.Text;
10627 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10629 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10631 // 投稿時に in_reply_to_status_id を付加する
10632 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10633 var inReplyToScreenName = this._curPost.ScreenName;
10634 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10636 StatusText.SelectionStart = 0;
10637 StatusText.Focus();
10641 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10646 private void SearchButton_Click(object sender, EventArgs e)
10649 Control pnl = ((Control)sender).Parent;
10650 if (pnl == null) return;
10651 string tbName = pnl.Parent.Text;
10652 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10653 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10654 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10655 cmb.Text = cmb.Text.Trim();
10656 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10657 bool Quote = false;
10658 StringBuilder buf = new StringBuilder();
10659 char[] c = cmb.Text.ToCharArray();
10660 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10662 if (cnt > cmb.Text.Length - 4)
10664 buf.Append(cmb.Text.Substring(cnt));
10673 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10675 buf.Append(" OR ");
10680 buf.Append(c[cnt]);
10682 cmb.Text = buf.ToString();
10684 var listView = (DetailsListView)pnl.Parent.Tag;
10686 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10688 tb.SearchWords = cmb.Text;
10689 tb.SearchLang = cmbLang.Text;
10690 if (string.IsNullOrEmpty(cmb.Text))
10698 int idx = cmb.Items.IndexOf(tb.SearchWords);
10699 if (idx > -1) cmb.Items.RemoveAt(idx);
10700 cmb.Items.Insert(0, tb.SearchWords);
10701 cmb.Text = tb.SearchWords;
10703 this.PurgeListViewItemCache();
10704 listView.VirtualListSize = 0;
10705 _statuses.ClearTabIds(tbName);
10706 SaveConfigsTabs(); //検索条件の保存
10709 this.GetPublicSearchAsync(tb);
10713 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10716 await this.DoRefreshMore();
10720 /// 指定されたタブのListTabにおける位置を返します
10723 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10725 public int GetTabPageIndex(string tabName)
10728 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10730 if (tabPage.Text == tabName)
10739 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10741 if (_statuses.RemovedTab.Count == 0)
10743 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10748 DetailsListView listView = null;
10750 TabModel tb = _statuses.RemovedTab.Pop();
10751 if (tb.TabType == MyCommon.TabUsageType.Related)
10753 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10754 if (relatedTab != null)
10756 // 関連発言なら既存のタブを置き換える
10757 tb.TabName = relatedTab.TabName;
10758 this.ClearTab(tb.TabName, false);
10759 _statuses.Tabs[tb.TabName] = tb;
10761 for (int i = 0; i < ListTab.TabPages.Count; i++)
10763 var tabPage = ListTab.TabPages[i];
10764 if (tb.TabName == tabPage.Text)
10766 listView = (DetailsListView)tabPage.Tag;
10767 ListTab.SelectedIndex = i;
10774 const string TabName = "Related Tweets";
10775 string renamed = TabName;
10776 for (int i = 2; i <= 100; i++)
10778 if (!_statuses.ContainsTab(renamed)) break;
10779 renamed = TabName + i;
10781 tb.TabName = renamed;
10783 _statuses.AddTab(tb);
10784 AddNewTab(tb, startup: false);
10786 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10787 listView = (DetailsListView)tabPage.Tag;
10788 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10793 string renamed = tb.TabName;
10794 for (int i = 1; i < int.MaxValue; i++)
10796 if (!_statuses.ContainsTab(renamed)) break;
10797 renamed = tb.TabName + "(" + i + ")";
10799 tb.TabName = renamed;
10801 _statuses.AddTab(tb);
10802 AddNewTab(tb, startup: false);
10804 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10805 listView = (DetailsListView)tabPage.Tag;
10806 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10810 if (listView != null)
10812 using (ControlTransaction.Update(listView))
10814 listView.VirtualListSize = tb.AllCount;
10820 private async Task doMoveToRTHome()
10822 if (_curList.SelectedIndices.Count > 0)
10824 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10825 if (post.RetweetedId != null)
10827 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10832 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10834 await this.doMoveToRTHome();
10837 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10839 var screenName = this._curPost?.ScreenName;
10840 if (screenName != null)
10841 this.ListManageUserContext(screenName);
10844 public void ListManageUserContext(string screenName)
10846 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10848 listSelectForm.ShowDialog(this);
10852 private void SearchControls_Enter(object sender, EventArgs e)
10854 Control pnl = (Control)sender;
10855 foreach (Control ctl in pnl.Controls)
10857 ctl.TabStop = true;
10861 private void SearchControls_Leave(object sender, EventArgs e)
10863 Control pnl = (Control)sender;
10864 foreach (Control ctl in pnl.Controls)
10866 ctl.TabStop = false;
10870 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10872 if (ListTab.SelectedTab != null)
10874 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10875 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10879 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10881 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10884 private void HashManageMenuItem_Click(object sender, EventArgs e)
10886 DialogResult rslt = DialogResult.Cancel;
10889 rslt = HashMgr.ShowDialog();
10895 this.TopMost = this._cfgCommon.AlwaysTop;
10896 if (rslt == DialogResult.Cancel) return;
10897 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10899 HashStripSplitButton.Text = HashMgr.UseHash;
10900 HashToggleMenuItem.Checked = true;
10901 HashToggleToolStripMenuItem.Checked = true;
10905 HashStripSplitButton.Text = "#[-]";
10906 HashToggleMenuItem.Checked = false;
10907 HashToggleToolStripMenuItem.Checked = false;
10909 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10911 // int sidx = StatusText.SelectionStart;
10912 // string hash = HashMgr.UseHash + " ";
10915 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10916 // hash = " " + hash;
10918 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10919 // sidx += hash.Length;
10920 // StatusText.SelectionStart = sidx;
10921 // StatusText.Focus();
10923 ModifySettingCommon = true;
10924 this.StatusText_TextChanged(null, null);
10927 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10929 HashMgr.ToggleHash();
10930 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10932 HashStripSplitButton.Text = HashMgr.UseHash;
10933 HashToggleMenuItem.Checked = true;
10934 HashToggleToolStripMenuItem.Checked = true;
10938 HashStripSplitButton.Text = "#[-]";
10939 HashToggleMenuItem.Checked = false;
10940 HashToggleToolStripMenuItem.Checked = false;
10942 ModifySettingCommon = true;
10943 this.StatusText_TextChanged(null, null);
10946 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10948 HashToggleMenuItem_Click(null, null);
10951 public void SetPermanentHashtag(string hashtag)
10953 HashMgr.SetPermanentHash("#" + hashtag);
10954 HashStripSplitButton.Text = HashMgr.UseHash;
10955 HashToggleMenuItem.Checked = true;
10956 HashToggleToolStripMenuItem.Checked = true;
10958 ModifySettingCommon = true;
10961 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10963 if (ListTab.SelectedTab == null) return;
10964 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10965 if (!this.ExistCurrentPost)
10967 this.ReplyOpMenuItem.Enabled = false;
10968 this.ReplyAllOpMenuItem.Enabled = false;
10969 this.DmOpMenuItem.Enabled = false;
10970 this.ShowProfMenuItem.Enabled = false;
10971 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10972 this.ListManageMenuItem.Enabled = false;
10973 this.OpenFavOpMenuItem.Enabled = false;
10974 this.CreateTabRuleOpMenuItem.Enabled = false;
10975 this.CreateIdRuleOpMenuItem.Enabled = false;
10976 this.CreateSourceRuleOpMenuItem.Enabled = false;
10977 this.ReadOpMenuItem.Enabled = false;
10978 this.UnreadOpMenuItem.Enabled = false;
10982 this.ReplyOpMenuItem.Enabled = true;
10983 this.ReplyAllOpMenuItem.Enabled = true;
10984 this.DmOpMenuItem.Enabled = true;
10985 this.ShowProfMenuItem.Enabled = true;
10986 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10987 this.ListManageMenuItem.Enabled = true;
10988 this.OpenFavOpMenuItem.Enabled = true;
10989 this.CreateTabRuleOpMenuItem.Enabled = true;
10990 this.CreateIdRuleOpMenuItem.Enabled = true;
10991 this.CreateSourceRuleOpMenuItem.Enabled = true;
10992 this.ReadOpMenuItem.Enabled = true;
10993 this.UnreadOpMenuItem.Enabled = true;
10996 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10998 this.FavOpMenuItem.Enabled = false;
10999 this.UnFavOpMenuItem.Enabled = false;
11000 this.OpenStatusOpMenuItem.Enabled = false;
11001 this.OpenFavotterOpMenuItem.Enabled = false;
11002 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11003 this.RtOpMenuItem.Enabled = false;
11004 this.RtUnOpMenuItem.Enabled = false;
11005 this.QtOpMenuItem.Enabled = false;
11006 this.FavoriteRetweetMenuItem.Enabled = false;
11007 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11011 this.FavOpMenuItem.Enabled = true;
11012 this.UnFavOpMenuItem.Enabled = true;
11013 this.OpenStatusOpMenuItem.Enabled = true;
11014 this.OpenFavotterOpMenuItem.Enabled = true;
11015 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11017 if (_curPost.IsProtect)
11019 this.RtOpMenuItem.Enabled = false;
11020 this.RtUnOpMenuItem.Enabled = false;
11021 this.QtOpMenuItem.Enabled = false;
11022 this.FavoriteRetweetMenuItem.Enabled = false;
11023 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11027 this.RtOpMenuItem.Enabled = true;
11028 this.RtUnOpMenuItem.Enabled = true;
11029 this.QtOpMenuItem.Enabled = true;
11030 this.FavoriteRetweetMenuItem.Enabled = true;
11031 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11035 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11037 this.RefreshPrevOpMenuItem.Enabled = true;
11041 this.RefreshPrevOpMenuItem.Enabled = false;
11043 if (!this.ExistCurrentPost
11044 || _curPost.InReplyToStatusId == null)
11046 OpenRepSourceOpMenuItem.Enabled = false;
11050 OpenRepSourceOpMenuItem.Enabled = true;
11052 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11054 OpenRterHomeMenuItem.Enabled = false;
11058 OpenRterHomeMenuItem.Enabled = true;
11061 if (this.ExistCurrentPost)
11063 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11067 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11069 ContextMenuTabProperty_Opening(sender, null);
11072 public Twitter TwitterInstance
11077 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11079 if (this._initialLayout)
11082 int splitterDistance;
11083 switch (this.WindowState)
11085 case FormWindowState.Normal:
11086 splitterDistance = this.SplitContainer3.SplitterDistance;
11088 case FormWindowState.Maximized:
11089 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11090 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11091 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11092 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11098 this._mySpDis3 = splitterDistance;
11099 this.ModifySettingLocal = true;
11102 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11104 if (_statuses.RemovedTab.Count == 0)
11106 UndoRemoveTabMenuItem.Enabled = false;
11110 UndoRemoveTabMenuItem.Enabled = true;
11112 if (ListTab.SelectedTab != null)
11114 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11115 PublicSearchQueryMenuItem.Enabled = true;
11117 PublicSearchQueryMenuItem.Enabled = false;
11121 PublicSearchQueryMenuItem.Enabled = false;
11123 if (!this.ExistCurrentPost)
11125 this.CopySTOTMenuItem.Enabled = false;
11126 this.CopyURLMenuItem.Enabled = false;
11127 this.CopyUserIdStripMenuItem.Enabled = false;
11131 this.CopySTOTMenuItem.Enabled = true;
11132 this.CopyURLMenuItem.Enabled = true;
11133 this.CopyUserIdStripMenuItem.Enabled = true;
11134 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11135 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11139 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11141 SetNotifyIconText();
11144 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11146 var id = _curPost?.ScreenName ?? "";
11148 await this.ShowUserStatus(id);
11151 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11153 TwitterUser user = null;
11155 if (ShowInputDialog)
11157 using (var inputName = new InputTabName())
11159 inputName.FormTitle = "Show UserStatus";
11160 inputName.FormDescription = Properties.Resources.FRMessage1;
11161 inputName.TabName = id;
11163 if (inputName.ShowDialog(this) != DialogResult.OK)
11165 if (string.IsNullOrWhiteSpace(inputName.TabName))
11168 id = inputName.TabName.Trim();
11172 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11174 var cancellationToken = dialog.EnableCancellation();
11178 var task = this.twitterApi.UsersShow(id);
11179 user = await dialog.WaitForAsync(this, task);
11181 catch (WebApiException ex)
11183 if (!cancellationToken.IsCancellationRequested)
11184 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11188 if (cancellationToken.IsCancellationRequested)
11192 await this.doShowUserStatus(user);
11195 private async Task doShowUserStatus(TwitterUser user)
11197 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11199 var showUserTask = userDialog.ShowUserAsync(user);
11200 userDialog.ShowDialog(this);
11203 this.BringToFront();
11205 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11206 await showUserTask;
11210 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11212 return this.doShowUserStatus(id, ShowInputDialog);
11215 internal Task ShowUserStatus(string id)
11217 return this.doShowUserStatus(id, true);
11220 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11222 if (_curPost != null)
11224 await this.ShowUserStatus(_curPost.ScreenName, false);
11228 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11230 if (!this.ExistCurrentPost)
11233 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11234 TwitterStatus status;
11236 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11238 var cancellationToken = dialog.EnableCancellation();
11242 var task = this.twitterApi.StatusesShow(statusId);
11243 status = await dialog.WaitForAsync(this, task);
11245 catch (WebApiException ex)
11247 if (!cancellationToken.IsCancellationRequested)
11248 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11252 if (cancellationToken.IsCancellationRequested)
11256 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11259 private HookGlobalHotkey _hookGlobalHotkey;
11262 _hookGlobalHotkey = new HookGlobalHotkey(this);
11264 // この呼び出しは、Windows フォーム デザイナで必要です。
11265 InitializeComponent();
11267 // InitializeComponent() 呼び出しの後で初期化を追加します。
11269 if (!this.DesignMode)
11271 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11272 this.StatusText.Dock = DockStyle.Fill;
11275 this.tweetDetailsView.Owner = this;
11277 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11278 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11279 this.gh.NotifyClicked += GrowlHelper_Callback;
11281 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11282 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11284 this.ImageSelector.Visible = false;
11285 this.ImageSelector.Enabled = false;
11286 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11288 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11290 this.ReplaceAppName();
11291 this.InitializeShortcuts();
11294 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11296 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11299 this.Visible = false;
11301 else if (Form.ActiveForm == null)
11303 this.Visible = true;
11304 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11306 this.BringToFront();
11307 this.StatusText.Focus();
11311 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11313 this.MultiLineMenuItem.PerformClick();
11316 public PostClass CurPost
11318 get { return _curPost; }
11322 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11324 if (ImageSelector.Visible)
11325 ImageSelector.EndSelection();
11327 ImageSelector.BeginSelection();
11330 private void SelectMedia_DragEnter(DragEventArgs e)
11332 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11334 e.Effect = DragDropEffects.Copy;
11337 e.Effect = DragDropEffects.None;
11340 private void SelectMedia_DragDrop(DragEventArgs e)
11343 this.BringToFront();
11344 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11345 StatusText.Focus();
11348 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11350 TimelinePanel.Visible = false;
11351 TimelinePanel.Enabled = false;
11354 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11356 TimelinePanel.Visible = true;
11357 TimelinePanel.Enabled = true;
11358 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11361 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11363 this.AllowDrop = false;
11366 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11368 this.AllowDrop = true;
11371 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11373 if (ImageSelector.Visible)
11375 ModifySettingCommon = true;
11376 SaveConfigsAll(true);
11378 this.StatusText_TextChanged(null, null);
11382 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11384 this.StatusText_TextChanged(null, null);
11388 /// StatusTextでCtrl+Vが押下された時の処理
11390 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11394 if (Clipboard.ContainsText())
11396 // clipboardにテキストがある場合は貼り付け処理
11397 this.StatusText.Paste(Clipboard.GetText());
11399 else if (Clipboard.ContainsImage())
11402 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11403 Properties.Resources.PostPictureWarn4,
11404 MessageBoxButtons.OKCancel,
11405 MessageBoxIcon.Question,
11406 MessageBoxDefaultButton.Button2)
11407 == DialogResult.OK)
11409 // clipboardから画像を取得
11410 using (var image = Clipboard.GetImage())
11412 this.ImageSelector.BeginSelection(image);
11417 catch (ExternalException ex)
11419 MessageBox.Show(ex.Message);
11424 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11426 using (ListManage form = new ListManage(tw))
11428 form.ShowDialog(this);
11432 public bool ModifySettingCommon { get; set; }
11433 public bool ModifySettingLocal { get; set; }
11434 public bool ModifySettingAtId { get; set; }
11436 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11438 if (this.ExistCurrentPost && !_curPost.IsDm)
11439 RtCountMenuItem.Enabled = true;
11441 RtCountMenuItem.Enabled = false;
11443 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11444 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11446 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11449 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11454 private void CopyUserId()
11456 if (_curPost == null) return;
11457 string clstr = _curPost.ScreenName;
11460 Clipboard.SetDataObject(clstr, false, 5, 100);
11462 catch (Exception ex)
11464 MessageBox.Show(ex.Message);
11468 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11470 if (this.ExistCurrentPost && !_curPost.IsDm)
11474 await this.OpenRelatedTab(this._curPost);
11476 catch (TabException ex)
11478 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11484 /// 指定されたツイートに対する関連発言タブを開きます
11486 /// <param name="statusId">表示するツイートのID</param>
11487 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11488 private async Task OpenRelatedTab(long statusId)
11490 var post = this._statuses[statusId];
11495 post = await this.tw.GetStatusApi(false, statusId);
11497 catch (WebApiException ex)
11499 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11504 await this.OpenRelatedTab(post);
11508 /// 指定されたツイートに対する関連発言タブを開きます
11510 /// <param name="post">表示する対象となるツイート</param>
11511 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11512 private async Task OpenRelatedTab(PostClass post)
11514 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11515 if (tabRelated != null)
11517 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11520 var tabName = this._statuses.MakeTabName("Related Tweets");
11522 tabRelated = new RelatedPostsTabModel(tabName, post);
11523 tabRelated.UnreadManage = false;
11524 tabRelated.Notify = false;
11526 this._statuses.AddTab(tabRelated);
11527 this.AddNewTab(tabRelated, startup: false);
11530 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11532 tabPage = this.ListTab.TabPages[i];
11533 if (tabName == tabPage.Text)
11535 this.ListTab.SelectedIndex = i;
11540 await this.GetRelatedTweetsAsync(tabRelated);
11542 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11543 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11545 if (tabPage != null)
11547 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11549 var listView = (DetailsListView)tabPage.Tag;
11550 var targetPost = tabRelated.TargetPost;
11551 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11553 if (index != -1 && index < listView.Items.Count)
11555 listView.SelectedIndices.Add(index);
11556 listView.Items[index].Focused = true;
11561 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11563 StringBuilder buf = new StringBuilder();
11564 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11565 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11566 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11567 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11568 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11571 private void tw_UserIdChanged()
11573 this.ModifySettingCommon = true;
11576 #region "Userstream"
11577 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11581 if (InvokeRequired && !IsDisposed)
11583 await this.InvokeAsync(async () =>
11585 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11586 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11588 this.PurgeListViewItemCache();
11589 ((DetailsListView)_curTab.Tag).Update();
11590 if (_curPost != null && _curPost.StatusId == e.StatusId)
11591 await this.DispSelectedPost(true);
11597 catch (ObjectDisposedException)
11601 catch (InvalidOperationException)
11607 private int userStreamsRefreshing = 0;
11609 private async void tw_NewPostFromStream(object sender, EventArgs e)
11611 if (this._cfgCommon.ReadOldPosts)
11613 _statuses.SetReadHomeTab(); //新着時未読クリア
11616 this._statuses.DistributePosts();
11618 if (this._cfgCommon.UserstreamPeriod > 0) return;
11620 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11621 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11625 await this.InvokeAsync(() => this.RefreshTimeline())
11626 .ConfigureAwait(false);
11630 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11635 private async void tw_UserStreamStarted(object sender, EventArgs e)
11639 if (InvokeRequired && !IsDisposed)
11641 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11645 catch (ObjectDisposedException)
11649 catch (InvalidOperationException)
11654 this.RefreshUserStreamsMenu();
11655 this.MenuItemUserStream.Enabled = true;
11657 StatusLabel.Text = "UserStream Started.";
11660 private async void tw_UserStreamStopped(object sender, EventArgs e)
11664 if (InvokeRequired && !IsDisposed)
11666 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11670 catch (ObjectDisposedException)
11674 catch (InvalidOperationException)
11679 this.RefreshUserStreamsMenu();
11680 this.MenuItemUserStream.Enabled = true;
11682 StatusLabel.Text = "UserStream Stopped.";
11685 private void RefreshUserStreamsMenu()
11687 if (this.tw.UserStreamActive)
11689 this.MenuItemUserStream.Text = "&UserStream ▶";
11690 this.StopToolStripMenuItem.Text = "&Stop";
11694 this.MenuItemUserStream.Text = "&UserStream ■";
11695 this.StopToolStripMenuItem.Text = "&Start";
11699 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11703 if (InvokeRequired && !IsDisposed)
11705 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11709 catch (ObjectDisposedException)
11713 catch (InvalidOperationException)
11717 var ev = e.EventData;
11718 StatusLabel.Text = "Event: " + ev.Event;
11719 //if (ev.Event == "favorite")
11721 // NotifyFavorite(ev);
11724 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11726 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11728 this.PurgeListViewItemCache();
11729 ((DetailsListView)_curTab.Tag).Update();
11731 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11733 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11734 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11739 private void NotifyEvent(Twitter.FormattedEvent ev)
11742 if (BalloonRequired(ev))
11744 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11745 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11746 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11747 StringBuilder title = new StringBuilder();
11748 if (this._cfgCommon.DispUsername)
11750 title.Append(tw.Username);
11751 title.Append(" - ");
11757 title.Append(Application.ProductName);
11758 title.Append(" [");
11759 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11760 title.Append("] by ");
11761 if (!string.IsNullOrEmpty(ev.Username))
11763 title.Append(ev.Username);
11767 //title.Append("");
11770 if (!string.IsNullOrEmpty(ev.Target))
11772 //NotifyIcon1.BalloonTipText = ev.Target;
11777 //NotifyIcon1.BalloonTipText = " ";
11780 //NotifyIcon1.ShowBalloonTip(500);
11781 if (this._cfgCommon.IsUseNotifyGrowl)
11783 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11784 ev.Id.ToString(), title.ToString(), text);
11788 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11789 NotifyIcon1.BalloonTipTitle = title.ToString();
11790 NotifyIcon1.BalloonTipText = text;
11791 NotifyIcon1.ShowBalloonTip(500);
11796 string snd = this._cfgCommon.EventSoundFile;
11797 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
11799 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11803 string dir = Application.StartupPath;
11804 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11806 dir = Path.Combine(dir, "Sounds");
11808 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11820 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11822 MenuItemUserStream.Enabled = false;
11823 if (StopRefreshAllMenuItem.Checked)
11825 StopRefreshAllMenuItem.Checked = false;
11828 if (this.tw.UserStreamActive)
11830 tw.StopUserStream();
11834 tw.StartUserStream();
11838 private static string inputTrack = "";
11840 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11842 if (TrackToolStripMenuItem.Checked)
11844 using (InputTabName inputForm = new InputTabName())
11846 inputForm.TabName = inputTrack;
11847 inputForm.FormTitle = "Input track word";
11848 inputForm.FormDescription = "Track word";
11849 if (inputForm.ShowDialog() != DialogResult.OK)
11851 TrackToolStripMenuItem.Checked = false;
11854 inputTrack = inputForm.TabName.Trim();
11856 if (!inputTrack.Equals(tw.TrackWord))
11858 tw.TrackWord = inputTrack;
11859 this.ModifySettingCommon = true;
11860 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11861 tw.ReconnectUserStream();
11867 tw.ReconnectUserStream();
11869 this.ModifySettingCommon = true;
11872 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11874 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11875 this.ModifySettingCommon = true;
11876 tw.ReconnectUserStream();
11879 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11881 if (evtDialog == null || evtDialog.IsDisposed)
11884 evtDialog = new EventViewerDialog();
11885 evtDialog.Owner = this;
11887 Point pos = evtDialog.Location;
11888 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11889 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11890 evtDialog.Location = pos;
11892 evtDialog.EventSource = tw.StoredEvent;
11893 if (!evtDialog.Visible)
11895 evtDialog.Show(this);
11899 evtDialog.Activate();
11901 this.TopMost = this._cfgCommon.AlwaysTop;
11905 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11907 MyCommon._endingFlag = true;
11911 Application.Restart();
11915 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11919 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11921 if (!string.IsNullOrEmpty(tw.Username))
11922 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11925 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11927 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11930 private bool ExistCurrentPost
11934 if (_curPost == null) return false;
11935 if (_curPost.IsDeleted) return false;
11940 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11942 ShowUserTimeline();
11945 private string GetUserIdFromCurPostOrInput(string caption)
11947 var id = _curPost?.ScreenName ?? "";
11949 using (InputTabName inputName = new InputTabName())
11951 inputName.FormTitle = caption;
11952 inputName.FormDescription = Properties.Resources.FRMessage1;
11953 inputName.TabName = id;
11954 if (inputName.ShowDialog() == DialogResult.OK &&
11955 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11957 id = inputName.TabName.Trim();
11967 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11969 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11970 if (!string.IsNullOrEmpty(id))
11972 AddNewTabForUserTimeline(id);
11976 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11978 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11979 if (!string.IsNullOrEmpty(id))
11981 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11985 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11987 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11990 private void TimelineRefreshEnableChange(bool isEnable)
11994 tw.StartUserStream();
11998 tw.StopUserStream();
12000 TimerTimeline.Enabled = isEnable;
12003 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12005 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12008 private async Task OpenUserAppointUrl()
12010 if (this._cfgCommon.UserAppointUrl != null)
12012 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
12014 if (_curPost != null)
12016 string xUrl = this._cfgCommon.UserAppointUrl;
12017 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12019 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12020 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12022 await this.OpenUriInBrowserAsync(xUrl);
12027 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
12032 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12034 await this.OpenUserAppointUrl();
12037 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12039 if (Form.ActiveForm == null)
12041 await this.InvokeAsync(() =>
12043 this.Visible = true;
12044 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12046 this.BringToFront();
12047 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12049 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12053 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12059 private void ReplaceAppName()
12061 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12062 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12065 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12067 this.SplitContainer3.Panel2Collapsed = false;
12070 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12072 await this.OpenThumbnailPicture(e.Thumbnail);
12075 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12077 await this.OpenUriInBrowserAsync(e.ImageUrl);
12080 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12082 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12084 await this.OpenUriInBrowserAsync(url);
12087 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12089 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12092 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12094 if (e.KeyCode == Keys.Space)
12096 this.JumpUnreadMenuItem_Click(null, null);
12098 e.SuppressKeyPress = true;
12102 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12104 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
12105 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
12106 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
12107 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
12108 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
12110 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
12113 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12115 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12118 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12120 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12123 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12125 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12128 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12130 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12133 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12135 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12138 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12140 if (this._cfgCommon.IconSize == iconSize) return;
12142 var oldIconCol = _iconCol;
12144 this._cfgCommon.IconSize = iconSize;
12145 ApplyListViewIconSize(iconSize);
12147 if (_iconCol != oldIconCol)
12149 foreach (TabPage tp in ListTab.TabPages)
12151 ResetColumns((DetailsListView)tp.Tag);
12155 _curList?.Refresh();
12157 ModifySettingCommon = true;
12160 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12162 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12163 if (this._cfgCommon.SortOrderLock == state) return;
12165 this._cfgCommon.SortOrderLock = state;
12167 ModifySettingCommon = true;
12170 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12172 if (!string.IsNullOrEmpty(e.StatusText))
12174 this.StatusLabelUrl.Text = e.StatusText;
12178 this.SetStatusLabelUrl();