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.UploadImageTimeout = TimeSpan.FromSeconds(this._cfgCommon.UploadImageTimeout);
809 Networking.SetWebProxy(this._cfgLocal.ProxyType,
810 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
811 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
812 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
814 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
815 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
816 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
817 tw.TrackWord = this._cfgCommon.TrackWord;
818 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
819 tw.AllAtReply = this._cfgCommon.AllAtReply;
820 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
821 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
822 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
823 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
825 // アクセストークンが有効であるか確認する
826 // ここが Twitter API への最初のアクセスになるようにすること
829 this.tw.VerifyCredentials();
831 catch (WebApiException ex)
833 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
834 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
838 //プロキシ設定等の通信まわりの初期化が済んでから処理する
839 ThumbnailGenerator.InitializeGenerator();
841 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
842 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
843 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
845 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
848 ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
851 AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
852 HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
853 HashMgr = new HashtagManage(HashSupl,
854 _cfgCommon.HashTags.ToArray(),
855 _cfgCommon.HashSelected,
856 _cfgCommon.HashIsPermanent,
857 _cfgCommon.HashIsHead,
858 _cfgCommon.HashIsNotAddToAtReply);
859 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
862 this.IconCache = new ImageCache();
863 this.tweetDetailsView.IconCache = this.IconCache;
866 _fntUnread = this._cfgLocal.FontUnread;
867 _clUnread = this._cfgLocal.ColorUnread;
868 _fntReaded = this._cfgLocal.FontRead;
869 _clReaded = this._cfgLocal.ColorRead;
870 _clFav = this._cfgLocal.ColorFav;
871 _clOWL = this._cfgLocal.ColorOWL;
872 _clRetweet = this._cfgLocal.ColorRetweet;
873 _fntDetail = this._cfgLocal.FontDetail;
874 _clDetail = this._cfgLocal.ColorDetail;
875 _clDetailLink = this._cfgLocal.ColorDetailLink;
876 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
877 _clSelf = this._cfgLocal.ColorSelf;
878 _clAtSelf = this._cfgLocal.ColorAtSelf;
879 _clTarget = this._cfgLocal.ColorTarget;
880 _clAtTarget = this._cfgLocal.ColorAtTarget;
881 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
882 _clAtTo = this._cfgLocal.ColorAtTo;
883 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
884 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
885 _clInputFont = this._cfgLocal.ColorInputFont;
886 _fntInputFont = this._cfgLocal.FontInputFont;
888 _brsBackColorMine = new SolidBrush(_clSelf);
889 _brsBackColorAt = new SolidBrush(_clAtSelf);
890 _brsBackColorYou = new SolidBrush(_clTarget);
891 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
892 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
893 _brsBackColorAtTo = new SolidBrush(_clAtTo);
894 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
895 _brsBackColorNone = new SolidBrush(_clListBackcolor);
897 // StringFormatオブジェクトへの事前設定
898 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
899 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
900 //sf.FormatFlags = StringFormatFlags.LineLimit; //
901 sfTab.Alignment = StringAlignment.Center;
902 sfTab.LineAlignment = StringAlignment.Center;
904 InitDetailHtmlFormat();
906 //Regex statregex = new Regex("^0*");
907 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
909 _history.Add(new PostingStatus());
911 this.inReplyTo = null;
914 SearchDialog.Owner = this;
915 UrlDialog.Owner = this;
918 NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
919 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
921 //新着取得時のリストスクロールをするか。trueならスクロールしない
922 ListLockMenuItem.Checked = _cfgCommon.ListLock;
923 this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
925 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
926 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
928 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
929 this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
932 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
933 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
934 _myLoc = _cfgLocal.FormLocation;
936 if (this.WindowState != FormWindowState.Minimized)
938 this.DesktopLocation = _cfgLocal.FormLocation;
939 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
940 bool outOfScreen = true;
941 if (Screen.AllScreens.Length == 1) //ハングするとの報告
943 foreach (Screen scr in Screen.AllScreens)
945 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
953 this.DesktopLocation = new Point(0, 0);
954 _myLoc = this.DesktopLocation;
958 this.TopMost = this._cfgCommon.AlwaysTop;
959 _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
960 _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
961 if (_cfgLocal.PreviewDistance == -1)
963 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965 _cfgLocal.PreviewDistance = _mySpDis3;
969 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
971 MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
972 //this.Tween_ClientSizeChanged(this, null);
973 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
974 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
976 StatusText.Font = _fntInputFont;
977 StatusText.ForeColor = _clInputFont;
979 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
980 this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
981 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
983 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
984 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
986 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
987 if (this._cfgCommon.UnreadManage == false)
989 ReadedStripMenuItem.Enabled = false;
990 UnreadStripMenuItem.Enabled = false;
993 //リンク先URL表示部の初期化(画面左下)
994 StatusLabelUrl.Text = "";
996 StatusLabel.Text = "";
997 StatusLabel.AutoToolTip = false;
998 StatusLabel.ToolTipText = "";
1000 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1002 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1003 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1004 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1005 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1007 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1008 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1009 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1010 this.SplitContainer2.Panel2.AccessibleName = "";
1012 ////////////////////////////////////////////////////////////////////////////////
1013 var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1014 var mode = ComparerMode.Id;
1015 switch (_cfgCommon.SortColumn)
1017 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1021 mode = ComparerMode.Id; //Idソートに読み替え
1024 mode = ComparerMode.Nickname;
1027 mode = ComparerMode.Data;
1030 mode = ComparerMode.Id;
1033 mode = ComparerMode.Name;
1036 mode = ComparerMode.Source;
1039 _statuses.SetSortMode(mode, sortOrder);
1040 ////////////////////////////////////////////////////////////////////////////////
1042 ApplyListViewIconSize(this._cfgCommon.IconSize);
1044 //<<<<<<<<タブ関連>>>>>>>
1048 //デフォルトタブの存在チェック、ない場合には追加
1049 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1050 this._statuses.AddTab(new HomeTabModel());
1052 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1053 this._statuses.AddTab(new MentionsTabModel());
1055 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1056 this._statuses.AddTab(new DirectMessagesTabModel());
1058 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1059 this._statuses.AddTab(new FavoritesTabModel());
1061 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1062 this._statuses.AddTab(new MuteTabModel());
1064 foreach (var tab in _statuses.Tabs.Values)
1067 if (tab.TabType == MyCommon.TabUsageType.Mute)
1070 if (!AddNewTab(tab, startup: true))
1071 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1074 _curTab = ListTab.SelectedTab;
1076 _curList = (DetailsListView)_curTab.Tag;
1078 if (this._cfgCommon.TabIconDisp)
1080 ListTab.DrawMode = TabDrawMode.Normal;
1084 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1085 ListTab.DrawItem += ListTab_DrawItem;
1086 ListTab.ImageList = null;
1089 if (this._cfgCommon.HotkeyEnabled)
1092 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1093 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1094 modKey |= HookGlobalHotkey.ModKeys.Alt;
1095 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1096 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1097 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1098 modKey |= HookGlobalHotkey.ModKeys.Shift;
1099 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1100 modKey |= HookGlobalHotkey.ModKeys.Win;
1102 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1105 if (this._cfgCommon.IsUseNotifyGrowl)
1108 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1110 SetMainWindowTitle();
1111 SetNotifyIconText();
1113 if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1115 this.Visible = true;
1119 TimerTimeline.AutoReset = true;
1120 TimerTimeline.SynchronizingObject = this;
1122 TimerTimeline.Interval = 1000;
1123 TimerTimeline.Enabled = true;
1125 TimerRefreshIcon.Interval = 200;
1126 TimerRefreshIcon.Enabled = true;
1128 _ignoreConfigSave = false;
1129 this.TweenMain_Resize(null, null);
1130 if (saveRequired) SaveConfigsAll(false);
1132 foreach (var ua in this._cfgCommon.UserAccounts)
1134 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1136 ua.UserId = tw.UserId;
1143 // 初回起動時だけ右下のメニューを目立たせる
1144 HashStripSplitButton.ShowDropDown();
1148 private void InitDetailHtmlFormat()
1150 if (this._cfgCommon.IsMonospace)
1152 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1153 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1157 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1158 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1161 detailHtmlFormatHeader = detailHtmlFormatHeader
1162 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1163 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1164 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1165 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1166 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1167 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1170 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1175 txt = ListTab.TabPages[e.Index].Text;
1182 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1183 if (e.State == DrawItemState.Selected)
1185 e.DrawFocusRectangle();
1190 if (_statuses.Tabs[txt].UnreadCount > 0)
1193 fore = System.Drawing.SystemBrushes.ControlText;
1197 fore = System.Drawing.SystemBrushes.ControlText;
1199 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1202 private void LoadConfig()
1204 _cfgCommon = SettingCommon.Load();
1205 SettingCommon.Instance = this._cfgCommon;
1206 if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1208 _cfgCommon.UserAccounts = new List<UserAccount>();
1209 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1211 UserAccount account = new UserAccount();
1212 account.Username = _cfgCommon.UserName;
1213 account.UserId = _cfgCommon.UserId;
1214 account.Token = _cfgCommon.Token;
1215 account.TokenSecret = _cfgCommon.TokenSecret;
1217 _cfgCommon.UserAccounts.Add(account);
1221 _cfgLocal = SettingLocal.Load();
1223 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1224 if (_cfgLocal.ScaleDimension.IsEmpty)
1225 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1227 var tabsSetting = SettingTabs.Load().Tabs;
1228 foreach (var tabSetting in tabsSetting)
1231 switch (tabSetting.TabType)
1233 case MyCommon.TabUsageType.Home:
1234 tab = new HomeTabModel(tabSetting.TabName);
1236 case MyCommon.TabUsageType.Mentions:
1237 tab = new MentionsTabModel(tabSetting.TabName);
1239 case MyCommon.TabUsageType.DirectMessage:
1240 tab = new DirectMessagesTabModel(tabSetting.TabName);
1242 case MyCommon.TabUsageType.Favorites:
1243 tab = new FavoritesTabModel(tabSetting.TabName);
1245 case MyCommon.TabUsageType.UserDefined:
1246 tab = new FilterTabModel(tabSetting.TabName);
1248 case MyCommon.TabUsageType.UserTimeline:
1249 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1251 case MyCommon.TabUsageType.PublicSearch:
1252 tab = new PublicSearchTabModel(tabSetting.TabName)
1254 SearchWords = tabSetting.SearchWords,
1255 SearchLang = tabSetting.SearchLang,
1258 case MyCommon.TabUsageType.Lists:
1259 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1261 case MyCommon.TabUsageType.Mute:
1262 tab = new MuteTabModel(tabSetting.TabName);
1268 tab.UnreadManage = tabSetting.UnreadManage;
1269 tab.Protected = tabSetting.Protected;
1270 tab.Notify = tabSetting.Notify;
1271 tab.SoundFile = tabSetting.SoundFile;
1273 if (tab.IsDistributableTabType)
1275 var filterTab = (FilterTabModel)tab;
1276 filterTab.FilterArray = tabSetting.FilterArray;
1277 filterTab.FilterModified = false;
1280 if (this._statuses.ContainsTab(tab.TabName))
1281 tab.TabName = this._statuses.MakeTabName("MyTab");
1283 this._statuses.AddTab(tab);
1285 if (_statuses.Tabs.Count == 0)
1287 _statuses.AddTab(new HomeTabModel());
1288 _statuses.AddTab(new MentionsTabModel());
1289 _statuses.AddTab(new DirectMessagesTabModel());
1290 _statuses.AddTab(new FavoritesTabModel());
1294 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1296 if (!TimerTimeline.Enabled) return;
1300 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1302 private static int homeCounter = 0;
1303 private static int mentionCounter = 0;
1304 private static int dmCounter = 0;
1305 private static int pubSearchCounter = 0;
1306 private static int userTimelineCounter = 0;
1307 private static int listsCounter = 0;
1308 private static int usCounter = 0;
1309 private static int ResumeWait = 0;
1310 private static int refreshFollowers = 0;
1312 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1314 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1315 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1316 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1317 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1318 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1319 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1320 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1321 Interlocked.Increment(ref refreshFollowers);
1323 var refreshTasks = new List<Task>();
1326 if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1328 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1329 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1330 refreshTasks.Add(this.GetHomeTimelineAsync());
1331 ResetTimers.Timeline = false;
1333 if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1335 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1336 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1337 refreshTasks.Add(this.GetReplyAsync());
1338 ResetTimers.Reply = false;
1340 if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1342 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1343 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1344 refreshTasks.Add(this.GetDirectMessagesAsync());
1345 ResetTimers.DirectMessage = false;
1347 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1349 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1350 if (!ResetTimers.PublicSearch)
1351 refreshTasks.Add(this.GetPublicSearchAllAsync());
1352 ResetTimers.PublicSearch = false;
1354 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1356 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1357 if (!ResetTimers.UserTimeline)
1358 refreshTasks.Add(this.GetUserTimelineAllAsync());
1359 ResetTimers.UserTimeline = false;
1361 if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1363 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1364 if (!ResetTimers.Lists)
1365 refreshTasks.Add(this.GetListTimelineAllAsync());
1366 ResetTimers.Lists = false;
1368 if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1370 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1371 if (this.tw.UserStreamActive)
1372 this.RefreshTimeline();
1373 ResetTimers.UserStream = false;
1375 if (refreshFollowers > 6 * 3600)
1377 Interlocked.Exchange(ref refreshFollowers, 0);
1378 refreshTasks.AddRange(new[]
1380 this.doGetFollowersMenu(),
1381 this.RefreshNoRetweetIdsAsync(),
1382 this.RefreshTwitterConfigurationAsync(),
1387 Interlocked.Increment(ref ResumeWait);
1388 if (ResumeWait > 30)
1391 Interlocked.Exchange(ref ResumeWait, 0);
1392 refreshTasks.AddRange(new[]
1394 this.GetHomeTimelineAsync(),
1395 this.GetReplyAsync(),
1396 this.GetDirectMessagesAsync(),
1397 this.GetPublicSearchAllAsync(),
1398 this.GetUserTimelineAllAsync(),
1399 this.GetListTimelineAllAsync(),
1400 this.doGetFollowersMenu(),
1401 this.RefreshTwitterConfigurationAsync(),
1406 await Task.WhenAll(refreshTasks);
1409 private void RefreshTimeline()
1411 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1413 // 現在表示中のタブのスクロール位置を退避
1414 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1416 // 現在表示中のタブのリスト上の選択位置などを退避
1417 var curListSelection = this.SaveListViewSelection(this._curList, curTabModel);
1420 PostClass[] notifyPosts;
1423 bool newMentionOrDm;
1425 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1427 if (MyCommon._endingFlag) return;
1431 if (this._cfgCommon.TabIconDisp)
1433 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1435 var tabModel = this._statuses.Tabs[tabPage.Text];
1436 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1437 tabPage.ImageIndex = 0; // 未読アイコン
1442 this.ListTab.Refresh();
1447 if (this._curList.VirtualListSize != curTabModel.AllCount || isDelete)
1449 using (ControlTransaction.Update(this._curList))
1451 this.PurgeListViewItemCache();
1454 this._curList.VirtualListSize = curTabModel.AllCount;
1457 this.RestoreListViewSelection(this._curList, curTabModel, curListSelection);
1460 // スクロール位置の復元は Begin/EndUpdate の外で行う
1461 // 参照: https://github.com/opentween/OpenTween/commit/7dbf6491
1462 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1466 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1468 SetMainWindowTitle();
1469 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1471 HashSupl.AddRangeItem(tw.GetHashList());
1475 internal struct ListViewScroll
1477 public ScrollLockMode ScrollLockMode { get; set; }
1478 public long? TopItemStatusId { get; set; }
1481 internal enum ScrollLockMode
1483 /// <summary>固定しない</summary>
1486 /// <summary>最上部に固定する</summary>
1489 /// <summary>最下部に固定する</summary>
1492 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1497 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1499 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1501 var listScroll = new ListViewScroll
1503 ScrollLockMode = this.GetScrollLockMode(listView),
1506 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1508 var topItem = listView.TopItem;
1509 if (topItem != null)
1510 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1516 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1518 if (this._statuses.SortMode == ComparerMode.Id)
1520 if (this._statuses.SortOrder == SortOrder.Ascending)
1523 if (this.ListLockMenuItem.Checked)
1524 return ScrollLockMode.None;
1526 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1529 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1530 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1531 return ScrollLockMode.FixedToBottom;
1533 return ScrollLockMode.None;
1538 if (this.ListLockMenuItem.Checked)
1539 return ScrollLockMode.FixedToItem;
1541 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1542 var topItem = listView.TopItem;
1543 if (topItem == null || topItem.Index == 0)
1544 return ScrollLockMode.FixedToTop;
1546 return ScrollLockMode.FixedToItem;
1551 return ScrollLockMode.FixedToItem;
1555 internal struct ListViewSelection
1557 public long[] SelectedStatusIds { get; set; }
1558 public long? SelectionMarkStatusId { get; set; }
1559 public long? FocusedStatusId { get; set; }
1563 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1565 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1567 var listsDict = new Dictionary<string, ListViewSelection>();
1569 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1571 var listView = (DetailsListView)tabPage.Tag;
1572 var tab = _statuses.Tabs[tabPage.Text];
1574 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1581 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1583 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1585 if (listView.VirtualListSize == 0)
1587 return new ListViewSelection
1589 SelectedStatusIds = new long[0],
1590 SelectionMarkStatusId = null,
1591 FocusedStatusId = null,
1595 return new ListViewSelection
1597 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1598 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1599 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1603 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1605 var selectedIndices = listView.SelectedIndices;
1606 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1607 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1612 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1614 var focusedItem = listView.FocusedItem;
1616 return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1619 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1621 var selectionMarkIndex = listView.SelectionMark;
1623 return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1627 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1629 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1631 if (listView.VirtualListSize == 0)
1634 switch (listScroll.ScrollLockMode)
1636 case ScrollLockMode.FixedToTop:
1637 listView.EnsureVisible(0);
1639 case ScrollLockMode.FixedToBottom:
1640 listView.EnsureVisible(listView.VirtualListSize - 1);
1642 case ScrollLockMode.FixedToItem:
1643 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1645 listView.TopItem = listView.Items[topIndex];
1647 case ScrollLockMode.None:
1654 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1656 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1658 // status_id から ListView 上のインデックスに変換
1659 int[] selectedIndices = null;
1660 if (listSelection.SelectedStatusIds != null)
1661 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1663 var focusedIndex = -1;
1664 if (listSelection.FocusedStatusId != null)
1665 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1667 var selectionMarkIndex = -1;
1668 if (listSelection.SelectionMarkStatusId != null)
1669 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1671 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1674 private bool BalloonRequired()
1676 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1677 ev.Eventtype = MyCommon.EVENTTYPE.None;
1679 return BalloonRequired(ev);
1682 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1684 if (type == MyCommon.EVENTTYPE.None)
1687 if (!this._cfgCommon.EventNotifyEnabled)
1690 return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1693 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1698 return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1701 private bool BalloonRequired(Twitter.FormattedEvent ev)
1706 if (NativeMethods.IsScreenSaverRunning())
1710 if (!this.NewPostPopMenuItem.Checked)
1712 // 「新着通知が無効でもイベントを通知する」にも該当しない
1713 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1717 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1718 if (this._cfgCommon.LimitBalloon)
1720 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1724 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1727 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1729 if (this._cfgCommon.ReadOwnPost)
1731 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1736 if (BalloonRequired())
1738 if (notifyPosts != null && notifyPosts.Length > 0)
1740 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1741 if (this._cfgCommon.IsUseNotifyGrowl)
1743 StringBuilder sb = new StringBuilder();
1747 foreach (PostClass post in notifyPosts)
1749 if (!(notifyPosts.Length > 3))
1755 if (post.IsReply && !post.IsExcludeReply) reply = true;
1756 if (post.IsDm) dm = true;
1757 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1758 switch (this._cfgCommon.NameBalloon)
1760 case MyCommon.NameBalloonEnum.UserID:
1761 sb.Append(post.ScreenName).Append(" : ");
1763 case MyCommon.NameBalloonEnum.NickName:
1764 sb.Append(post.Nickname).Append(" : ");
1767 sb.Append(post.TextFromApi);
1768 if (notifyPosts.Length > 3)
1770 if (notifyPosts.Last() != post) continue;
1773 StringBuilder title = new StringBuilder();
1774 GrowlHelper.NotifyType nt;
1775 if (this._cfgCommon.DispUsername)
1777 title.Append(tw.Username);
1778 title.Append(" - ");
1786 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1787 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1788 title.Append(Application.ProductName);
1789 title.Append(" [DM] ");
1790 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1791 nt = GrowlHelper.NotifyType.DirectMessage;
1795 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1796 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1797 title.Append(Application.ProductName);
1798 title.Append(" [Reply!] ");
1799 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1800 nt = GrowlHelper.NotifyType.Reply;
1804 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1805 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1806 title.Append(Application.ProductName);
1808 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1809 nt = GrowlHelper.NotifyType.Notify;
1811 string bText = sb.ToString();
1812 if (string.IsNullOrEmpty(bText)) return;
1814 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1815 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1820 StringBuilder sb = new StringBuilder();
1823 foreach (PostClass post in notifyPosts)
1825 if (post.IsReply && !post.IsExcludeReply) reply = true;
1826 if (post.IsDm) dm = true;
1827 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1828 switch (this._cfgCommon.NameBalloon)
1830 case MyCommon.NameBalloonEnum.UserID:
1831 sb.Append(post.ScreenName).Append(" : ");
1833 case MyCommon.NameBalloonEnum.NickName:
1834 sb.Append(post.Nickname).Append(" : ");
1837 sb.Append(post.TextFromApi);
1840 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1841 StringBuilder title = new StringBuilder();
1843 if (this._cfgCommon.DispUsername)
1845 title.Append(tw.Username);
1846 title.Append(" - ");
1854 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1855 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1856 ntIcon = ToolTipIcon.Warning;
1857 title.Append(Application.ProductName);
1858 title.Append(" [DM] ");
1859 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1863 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1864 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1865 ntIcon = ToolTipIcon.Warning;
1866 title.Append(Application.ProductName);
1867 title.Append(" [Reply!] ");
1868 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1872 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1873 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1874 ntIcon = ToolTipIcon.Info;
1875 title.Append(Application.ProductName);
1877 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1879 string bText = sb.ToString();
1880 if (string.IsNullOrEmpty(bText)) return;
1881 //NotifyIcon1.BalloonTipText = sb.ToString();
1882 //NotifyIcon1.ShowBalloonTip(500);
1883 NotifyIcon1.BalloonTipTitle = title.ToString();
1884 NotifyIcon1.BalloonTipText = bText;
1885 NotifyIcon1.BalloonTipIcon = ntIcon;
1886 NotifyIcon1.ShowBalloonTip(500);
1892 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1896 string dir = Application.StartupPath;
1897 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1899 dir = Path.Combine(dir, "Sounds");
1901 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1911 //mentions新着時に画面ブリンク
1912 if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1914 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1918 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1920 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1922 _curItemIndex = _curList.SelectedIndices[0];
1923 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1927 this._curPost = GetCurTabPost(_curItemIndex);
1929 catch (ArgumentException)
1934 this.PushSelectPostChain();
1936 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1938 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1944 private void ChangeCacheStyleRead(bool Read, int Index)
1946 var tabInfo = _statuses.Tabs[_curTab.Text];
1947 //Read:true=既読 false=未読
1948 //未読管理していなかったら既読として扱う
1949 if (!tabInfo.UnreadManage ||
1950 !this._cfgCommon.UnreadManage) Read = true;
1952 var listCache = this._listItemCache;
1953 if (listCache == null)
1956 // キャッシュに含まれていないアイテムは対象外
1959 if (!listCache.TryGetValue(Index, out itm, out post))
1962 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1965 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1972 Item.SubItems[5].Text = "";
1977 Item.SubItems[5].Text = "★";
1983 else if (Post.RetweetedId != null)
1985 else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1987 else if (Read || !this._cfgCommon.UseUnreadStyle)
1992 if (DList == null || Item.Index == -1)
1994 Item.ForeColor = cl;
1995 if (this._cfgCommon.UseUnreadStyle)
2001 if (this._cfgCommon.UseUnreadStyle)
2002 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2004 DList.ChangeItemForeColor(Item.Index, cl);
2005 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2009 private void ColorizeList()
2011 //Index:更新対象のListviewItem.Index。Colorを返す。
2012 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2015 _post = _anchorPost;
2019 if (_post == null) return;
2021 var listCache = this._listItemCache;
2022 if (listCache == null)
2025 var index = listCache.StartIndex;
2026 foreach (var cachedPost in listCache.Post)
2028 var backColor = this.JudgeColor(_post, cachedPost);
2029 this._curList.ChangeItemBackColor(index++, backColor);
2033 private void ColorizeList(ListViewItem Item, int Index)
2035 //Index:更新対象のListviewItem.Index。Colorを返す。
2036 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2039 _post = _anchorPost;
2043 PostClass tPost = GetCurTabPost(Index);
2045 if (_post == null) return;
2047 if (Item.Index == -1)
2048 Item.BackColor = JudgeColor(_post, tPost);
2050 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2053 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2056 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2059 else if (TargetPost.IsMe)
2062 else if (TargetPost.IsReply)
2065 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2067 cl = _clAtFromTarget;
2068 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2071 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2076 cl = _clListBackcolor;
2081 private async void PostButton_Click(object sender, EventArgs e)
2083 if (StatusText.Text.Trim().Length == 0)
2085 if (!ImageSelector.Enabled)
2087 await this.DoRefresh();
2092 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2094 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2096 MessageBoxButtons.YesNoCancel,
2097 MessageBoxIcon.Question);
2100 case DialogResult.Yes:
2101 StatusText.Text = "";
2102 await this.doReTweetOfficial(false);
2104 case DialogResult.Cancel:
2109 var inReplyToStatusId = this.inReplyTo?.Item1;
2110 var inReplyToScreenName = this.inReplyTo?.Item2;
2111 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2113 if (this._cfgCommon.Nicoms)
2115 StatusText.SelectionStart = StatusText.Text.Length;
2116 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2118 //if (SettingDialog.UrlConvertAuto)
2120 // StatusText.SelectionStart = StatusText.Text.Length;
2121 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2123 //else if (SettingDialog.Nicoms)
2125 // StatusText.SelectionStart = StatusText.Text.Length;
2126 // UrlConvert(UrlConverter.Nicoms);
2128 StatusText.SelectionStart = StatusText.Text.Length;
2129 CheckReplyTo(StatusText.Text);
2131 var statusText = this.FormatStatusText(this.StatusText.Text);
2133 if (this.GetRestStatusCount(statusText) < 0)
2135 // 文字数制限を超えているが強制的に投稿するか
2136 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2137 if (ret != DialogResult.OK)
2141 var status = new PostingStatus();
2142 status.status = statusText;
2144 status.inReplyToId = this.inReplyTo?.Item1;
2145 status.inReplyToName = this.inReplyTo?.Item2;
2146 if (ImageSelector.Visible)
2149 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2153 this.inReplyTo = null;
2154 StatusText.Text = "";
2155 _history.Add(new PostingStatus());
2156 _hisIdx = _history.Count - 1;
2157 if (!ToolStripFocusLockMenuItem.Checked)
2158 ((Control)ListTab.SelectedTab.Tag).Focus();
2159 urlUndoBuffer = null;
2160 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2163 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2165 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2166 await this.OpenUriInBrowserAsync(tmp);
2169 await this.PostMessageAsync(status);
2172 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2174 MyCommon._endingFlag = true;
2178 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2180 if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2182 //_endingFlag=false:フォームの×ボタン
2184 this.Visible = false;
2188 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2189 _ignoreConfigSave = true;
2190 MyCommon._endingFlag = true;
2191 TimerTimeline.Enabled = false;
2192 TimerRefreshIcon.Enabled = false;
2196 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2198 this.Visible = true;
2199 if (this.WindowState == FormWindowState.Minimized)
2201 this.WindowState = FormWindowState.Normal;
2204 this.BringToFront();
2207 private static int errorCount = 0;
2209 private static bool CheckAccountValid()
2211 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2217 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2226 private Task GetHomeTimelineAsync()
2228 return this.GetHomeTimelineAsync(loadMore: false);
2231 private async Task GetHomeTimelineAsync(bool loadMore)
2233 await this.workerSemaphore.WaitAsync();
2237 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2238 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2240 this.RefreshTimeline();
2242 catch (WebApiException ex)
2244 this._myStatusError = true;
2245 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2249 this.workerSemaphore.Release();
2253 private Task GetReplyAsync()
2255 return this.GetReplyAsync(loadMore: false);
2258 private async Task GetReplyAsync(bool loadMore)
2260 await this.workerSemaphore.WaitAsync();
2264 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2265 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2267 this.RefreshTimeline();
2269 catch (WebApiException ex)
2271 this._myStatusError = true;
2272 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2276 this.workerSemaphore.Release();
2280 private Task GetDirectMessagesAsync()
2282 return this.GetDirectMessagesAsync(loadMore: false);
2285 private async Task GetDirectMessagesAsync(bool loadMore)
2287 await this.workerSemaphore.WaitAsync();
2291 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2292 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2294 this.RefreshTimeline();
2296 catch (WebApiException ex)
2298 this._myStatusError = true;
2299 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2303 this.workerSemaphore.Release();
2307 private Task GetFavoritesAsync()
2309 return this.GetFavoritesAsync(loadMore: false);
2312 private async Task GetFavoritesAsync(bool loadMore)
2314 await this.workerSemaphore.WaitAsync();
2318 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2319 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2321 this.RefreshTimeline();
2323 catch (WebApiException ex)
2325 this._myStatusError = true;
2326 this.StatusLabel.Text = ex.Message;
2330 this.workerSemaphore.Release();
2334 private Task GetPublicSearchAllAsync()
2336 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2338 return this.GetPublicSearchAsync(tabs, loadMore: false);
2341 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2343 return this.GetPublicSearchAsync(tab, loadMore: false);
2346 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2348 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2351 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2353 await this.workerSemaphore.WaitAsync();
2357 foreach (var tab in tabs)
2361 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2363 catch (WebApiException ex)
2365 this._myStatusError = true;
2366 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2370 this.RefreshTimeline();
2374 this.workerSemaphore.Release();
2378 private Task GetUserTimelineAllAsync()
2380 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2382 return this.GetUserTimelineAsync(tabs, loadMore: false);
2385 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2387 return this.GetUserTimelineAsync(tab, loadMore: false);
2390 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2392 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2395 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2397 await this.workerSemaphore.WaitAsync();
2401 foreach (var tab in tabs)
2405 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2407 catch (WebApiException ex)
2409 this._myStatusError = true;
2410 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2414 this.RefreshTimeline();
2418 this.workerSemaphore.Release();
2422 private Task GetListTimelineAllAsync()
2424 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2426 return this.GetListTimelineAsync(tabs, loadMore: false);
2429 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2431 return this.GetListTimelineAsync(tab, loadMore: false);
2434 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2436 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2439 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2441 await this.workerSemaphore.WaitAsync();
2445 foreach (var tab in tabs)
2449 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2451 catch (WebApiException ex)
2453 this._myStatusError = true;
2454 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2458 this.RefreshTimeline();
2462 this.workerSemaphore.Release();
2466 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2468 await this.workerSemaphore.WaitAsync();
2472 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2474 this.RefreshTimeline();
2476 catch (WebApiException ex)
2478 this._myStatusError = true;
2479 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2483 this.workerSemaphore.Release();
2487 private async Task FavAddAsync(long statusId, TabModel tab)
2489 await this.workerSemaphore.WaitAsync();
2493 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2495 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2497 catch (WebApiException ex)
2499 this._myStatusError = true;
2500 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2504 this.workerSemaphore.Release();
2508 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2510 if (ct.IsCancellationRequested)
2513 if (!CheckAccountValid())
2514 throw new WebApiException("Auth error. Check your account");
2517 if (!tab.Posts.TryGetValue(statusId, out post))
2523 await Task.Run(async () =>
2525 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2529 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2531 .ConfigureAwait(false);
2533 if (this._cfgCommon.RestrictFavCheck)
2535 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2536 .ConfigureAwait(false);
2538 if (status.Favorited != true)
2539 throw new WebApiException("NG(Restricted?)");
2542 this._favTimestamps.Add(DateTime.Now);
2545 if (this._statuses.ContainsKey(statusId))
2547 var postTl = this._statuses[statusId];
2548 postTl.IsFav = true;
2550 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2551 favTab.AddPostQueue(postTl);
2554 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2555 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2557 if (tb.Contains(statusId))
2558 tb.Posts[statusId].IsFav = true;
2561 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2563 catch (WebApiException)
2565 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2570 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2571 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2573 if (this._favTimestamps[i] < oneHour)
2574 this._favTimestamps.RemoveAt(i);
2577 this._statuses.DistributePosts();
2580 if (ct.IsCancellationRequested)
2583 this.RefreshTimeline();
2585 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2587 using (ControlTransaction.Update(this._curList))
2589 var idx = tab.IndexOf(statusId);
2591 this.ChangeCacheStyleRead(post.IsRead, idx);
2594 if (statusId == this._curPost.StatusId)
2595 await this.DispSelectedPost(true); // 選択アイテム再表示
2599 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2601 await this.workerSemaphore.WaitAsync();
2605 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2607 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2609 catch (WebApiException ex)
2611 this._myStatusError = true;
2612 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2616 this.workerSemaphore.Release();
2620 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2622 if (ct.IsCancellationRequested)
2625 if (!CheckAccountValid())
2626 throw new WebApiException("Auth error. Check your account");
2628 var successIds = new List<long>();
2630 await Task.Run(async () =>
2634 var failedCount = 0;
2635 foreach (var statusId in statusIds)
2639 var post = tab.Posts[statusId];
2641 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2648 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2650 .ConfigureAwait(false);
2652 catch (WebApiException)
2658 successIds.Add(statusId);
2659 post.IsFav = false; // リスト再描画必要
2661 if (this._statuses.ContainsKey(statusId))
2663 this._statuses[statusId].IsFav = false;
2666 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2667 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2669 if (tb.Contains(statusId))
2670 tb.Posts[statusId].IsFav = false;
2675 if (ct.IsCancellationRequested)
2678 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2679 foreach (var statusId in successIds)
2681 // ツイートが削除された訳ではないので IsDeleted はセットしない
2682 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2685 this.RefreshTimeline();
2687 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2689 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2695 using (ControlTransaction.Update(this._curList))
2697 foreach (var statusId in successIds)
2699 var idx = tab.IndexOf(statusId);
2703 var post = tab.Posts[statusId];
2704 this.ChangeCacheStyleRead(post.IsRead, idx);
2708 if (successIds.Contains(this._curPost.StatusId))
2709 await this.DispSelectedPost(true); // 選択アイテム再表示
2714 private async Task PostMessageAsync(PostingStatus status)
2716 await this.workerSemaphore.WaitAsync();
2720 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2722 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2724 catch (WebApiException ex)
2726 this._myStatusError = true;
2727 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2731 this.workerSemaphore.Release();
2735 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2737 if (ct.IsCancellationRequested)
2740 if (!CheckAccountValid())
2741 throw new WebApiException("Auth error. Check your account");
2743 p.Report("Posting...");
2749 await Task.Run(async () =>
2751 if (status.mediaItems == null || status.mediaItems.Length == 0)
2753 await this.tw.PostStatus(status.status, status.inReplyToId)
2754 .ConfigureAwait(false);
2758 var service = ImageSelector.GetService(status.imageService);
2759 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2760 .ConfigureAwait(false);
2764 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2766 catch (WebApiException ex)
2768 // 処理は中断せずエラーの表示のみ行う
2769 errMsg = $"Err:{ex.Message}(PostMessage)";
2771 this._myStatusError = true;
2773 catch (UnauthorizedAccessException ex)
2775 // アップロード対象のファイルが開けなかった場合など
2776 errMsg = $"Err:{ex.Message}(PostMessage)";
2778 this._myStatusError = true;
2782 // 使い終わった MediaItem は破棄する
2783 if (status.mediaItems != null)
2785 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2787 disposableItem.Dispose();
2792 if (ct.IsCancellationRequested)
2795 if (!string.IsNullOrEmpty(errMsg) &&
2796 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2797 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2799 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2801 var ret = MessageBox.Show(
2803 "Failed to update status",
2804 MessageBoxButtons.RetryCancel,
2805 MessageBoxIcon.Question);
2807 if (ret == DialogResult.Retry)
2809 await this.PostMessageAsync(status);
2813 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2814 if (this.ToolStripFocusLockMenuItem.Checked)
2815 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2820 this._postTimestamps.Add(DateTime.Now);
2822 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2823 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2825 if (this._postTimestamps[i] < oneHour)
2826 this._postTimestamps.RemoveAt(i);
2829 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2831 this.HashMgr.ClearHashtag();
2832 this.HashStripSplitButton.Text = "#[-]";
2833 this.HashToggleMenuItem.Checked = false;
2834 this.HashToggleToolStripMenuItem.Checked = false;
2837 this.SetMainWindowTitle();
2839 if (this._cfgCommon.PostAndGet)
2841 if (this.tw.UserStreamActive)
2842 this.RefreshTimeline();
2844 await this.GetHomeTimelineAsync();
2848 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2850 await this.workerSemaphore.WaitAsync();
2854 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2856 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2858 if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
2859 await this.GetHomeTimelineAsync();
2861 catch (WebApiException ex)
2863 this._myStatusError = true;
2864 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2868 this.workerSemaphore.Release();
2872 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2874 if (ct.IsCancellationRequested)
2877 if (!CheckAccountValid())
2878 throw new WebApiException("Auth error. Check your account");
2881 if (!this._cfgCommon.UnreadManage)
2884 read = this._initial && this._cfgCommon.Read;
2886 p.Report("Posting...");
2888 foreach (var statusId in statusIds)
2890 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2893 if (ct.IsCancellationRequested)
2896 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2898 this._postTimestamps.Add(DateTime.Now);
2900 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2901 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2903 if (this._postTimestamps[i] < oneHour)
2904 this._postTimestamps.RemoveAt(i);
2908 private async Task RefreshFollowerIdsAsync()
2910 await this.workerSemaphore.WaitAsync();
2913 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2915 await this.tw.RefreshFollowerIds();
2917 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2919 this.RefreshTimeline();
2920 this.PurgeListViewItemCache();
2921 this._curList?.Refresh();
2923 catch (WebApiException ex)
2925 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2929 this.workerSemaphore.Release();
2933 private async Task RefreshNoRetweetIdsAsync()
2935 await this.workerSemaphore.WaitAsync();
2938 await this.tw.RefreshNoRetweetIds();
2940 this.StatusLabel.Text = "NoRetweetIds refreshed";
2942 catch (WebApiException ex)
2944 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2948 this.workerSemaphore.Release();
2952 private async Task RefreshBlockIdsAsync()
2954 await this.workerSemaphore.WaitAsync();
2957 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2959 await this.tw.RefreshBlockIds();
2961 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2963 catch (WebApiException ex)
2965 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2969 this.workerSemaphore.Release();
2973 private async Task RefreshTwitterConfigurationAsync()
2975 await this.workerSemaphore.WaitAsync();
2978 await this.tw.RefreshConfiguration();
2980 if (this.tw.Configuration.PhotoSizeLimit != 0)
2982 foreach (var service in this.ImageSelector.GetServices())
2984 service.UpdateTwitterConfiguration(this.tw.Configuration);
2988 this.PurgeListViewItemCache();
2990 this._curList?.Refresh();
2992 catch (WebApiException ex)
2994 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2998 this.workerSemaphore.Release();
3002 private async Task RefreshMuteUserIdsAsync()
3004 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3008 await tw.RefreshMuteUserIdsAsync();
3010 catch (WebApiException ex)
3012 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3016 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3019 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3021 if (e.Button == MouseButtons.Left)
3023 this.Visible = true;
3024 if (this.WindowState == FormWindowState.Minimized)
3026 this.WindowState = _formWindowState;
3029 this.BringToFront();
3033 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3035 switch (this._cfgCommon.ListDoubleClickAction)
3038 MakeReplyOrDirectStatus();
3041 await this.FavoriteChange(true);
3044 if (_curPost != null)
3045 await this.ShowUserStatus(_curPost.ScreenName, false);
3051 ShowRelatedStatusesMenuItem_Click(null, null);
3054 MoveToHomeToolStripMenuItem_Click(null, null);
3057 StatusOpenMenuItem_Click(null, null);
3065 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3067 await this.FavoriteChange(true);
3070 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3072 await this.FavoriteChange(false);
3076 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3078 await this.FavoritesRetweetOfficial();
3081 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3083 await this.FavoritesRetweetUnofficial();
3086 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3089 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3092 //trueでFavAdd,falseでFavRemove
3093 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3094 || !this.ExistCurrentPost) return;
3096 if (this._curList.SelectedIndices.Count > 1)
3101 // https://support.twitter.com/articles/76915#favoriting
3102 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3103 _DoFavRetweetFlags = false;
3108 if (multiFavoriteChangeDialogEnable)
3110 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3111 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3112 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3114 if (confirm == DialogResult.Cancel)
3122 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3123 if (selectedPost.IsFav)
3125 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3129 await this.FavAddAsync(selectedPost.StatusId, tab);
3133 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3134 .Select(x => this.GetCurTabPost(x))
3135 .Where(x => x.IsFav);
3137 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3138 if (statusIds.Length == 0)
3140 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3144 await this.FavRemoveAsync(statusIds, tab);
3148 private PostClass GetCurTabPost(int Index)
3150 var listCache = this._listItemCache;
3151 if (listCache != null)
3155 if (listCache.TryGetValue(Index, out item, out post))
3159 return _statuses.Tabs[_curTab.Text][Index];
3162 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3164 if (_curList.SelectedIndices.Count > 0)
3165 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3166 else if (_curList.SelectedIndices.Count == 0)
3167 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3170 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3172 if (_curList.SelectedIndices.Count > 0)
3173 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3176 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3178 if ((!_initialLayout) && this.Visible)
3180 if (this.WindowState == FormWindowState.Normal)
3182 _mySize = this.ClientSize;
3183 _mySpDis = this.SplitContainer1.SplitterDistance;
3184 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3185 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3186 ModifySettingLocal = true;
3191 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3193 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3194 if (comparerMode == null)
3197 this.SetSortColumn(comparerMode.Value);
3201 /// 列インデックスからソートを行う ComparerMode を求める
3203 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3204 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3205 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3208 return ComparerMode.Id;
3210 switch (columnIndex)
3213 return ComparerMode.Nickname;
3215 return ComparerMode.Data;
3217 return ComparerMode.Id;
3219 return ComparerMode.Name;
3221 return ComparerMode.Source;
3223 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3229 /// 発言一覧の指定した位置の列でソートする
3231 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3232 private void SetSortColumnByDisplayIndex(int columnIndex)
3234 // 表示上の列の位置から ColumnHeader を求める
3235 var col = this._curList.Columns.Cast<ColumnHeader>()
3236 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3241 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3242 if (comparerMode == null)
3245 this.SetSortColumn(comparerMode.Value);
3249 /// 発言一覧の最後列の項目でソートする
3251 private void SetSortLastColumn()
3253 // 表示上の最後列にある ColumnHeader を求める
3254 var col = this._curList.Columns.Cast<ColumnHeader>()
3255 .OrderByDescending(x => x.DisplayIndex)
3258 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3259 if (comparerMode == null)
3262 this.SetSortColumn(comparerMode.Value);
3266 /// 発言一覧を指定された ComparerMode に基づいてソートする
3268 private void SetSortColumn(ComparerMode sortColumn)
3270 if (this._cfgCommon.SortOrderLock)
3273 this._statuses.ToggleSortOrder(sortColumn);
3274 this.InitColumnText();
3276 var list = this._curList;
3279 list.Columns[0].Text = this.ColumnText[0];
3280 list.Columns[1].Text = this.ColumnText[2];
3284 for (var i = 0; i <= 7; i++)
3286 list.Columns[i].Text = this.ColumnText[i];
3290 this.PurgeListViewItemCache();
3292 var tab = this._statuses.Tabs[this._curTab.Text];
3293 if (tab.AllCount > 0 && this._curPost != null)
3295 var idx = tab.IndexOf(this._curPost.StatusId);
3298 this.SelectListItem(list, idx);
3299 list.EnsureVisible(idx);
3304 this.ModifySettingCommon = true;
3307 private void TweenMain_LocationChanged(object sender, EventArgs e)
3309 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3311 _myLoc = this.DesktopLocation;
3312 ModifySettingLocal = true;
3316 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3318 if (ListTab.SelectedTab == null) return;
3319 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3320 if (!this.ExistCurrentPost)
3322 ReplyStripMenuItem.Enabled = false;
3323 ReplyAllStripMenuItem.Enabled = false;
3324 DMStripMenuItem.Enabled = false;
3325 ShowProfileMenuItem.Enabled = false;
3326 ShowUserTimelineContextMenuItem.Enabled = false;
3327 ListManageUserContextToolStripMenuItem2.Enabled = false;
3328 MoveToFavToolStripMenuItem.Enabled = false;
3329 TabMenuItem.Enabled = false;
3330 IDRuleMenuItem.Enabled = false;
3331 SourceRuleMenuItem.Enabled = false;
3332 ReadedStripMenuItem.Enabled = false;
3333 UnreadStripMenuItem.Enabled = false;
3337 ShowProfileMenuItem.Enabled = true;
3338 ListManageUserContextToolStripMenuItem2.Enabled = true;
3339 ReplyStripMenuItem.Enabled = true;
3340 ReplyAllStripMenuItem.Enabled = true;
3341 DMStripMenuItem.Enabled = true;
3342 ShowUserTimelineContextMenuItem.Enabled = true;
3343 MoveToFavToolStripMenuItem.Enabled = true;
3344 TabMenuItem.Enabled = true;
3345 IDRuleMenuItem.Enabled = true;
3346 SourceRuleMenuItem.Enabled = true;
3347 ReadedStripMenuItem.Enabled = true;
3348 UnreadStripMenuItem.Enabled = true;
3350 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3352 FavAddToolStripMenuItem.Enabled = false;
3353 FavRemoveToolStripMenuItem.Enabled = false;
3354 StatusOpenMenuItem.Enabled = false;
3355 FavorareMenuItem.Enabled = false;
3356 ShowRelatedStatusesMenuItem.Enabled = false;
3358 ReTweetStripMenuItem.Enabled = false;
3359 ReTweetUnofficialStripMenuItem.Enabled = false;
3360 QuoteStripMenuItem.Enabled = false;
3361 FavoriteRetweetContextMenu.Enabled = false;
3362 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3366 FavAddToolStripMenuItem.Enabled = true;
3367 FavRemoveToolStripMenuItem.Enabled = true;
3368 StatusOpenMenuItem.Enabled = true;
3369 FavorareMenuItem.Enabled = true;
3370 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3372 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3374 ReTweetStripMenuItem.Enabled = false;
3375 ReTweetUnofficialStripMenuItem.Enabled = false;
3376 QuoteStripMenuItem.Enabled = false;
3377 FavoriteRetweetContextMenu.Enabled = false;
3378 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3382 ReTweetStripMenuItem.Enabled = true;
3383 ReTweetUnofficialStripMenuItem.Enabled = true;
3384 QuoteStripMenuItem.Enabled = true;
3385 FavoriteRetweetContextMenu.Enabled = true;
3386 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3389 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3391 // RefreshMoreStripMenuItem.Enabled = true;
3395 // RefreshMoreStripMenuItem.Enabled = false;
3397 if (!this.ExistCurrentPost
3398 || _curPost.InReplyToStatusId == null)
3400 RepliedStatusOpenMenuItem.Enabled = false;
3404 RepliedStatusOpenMenuItem.Enabled = true;
3406 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3408 MoveToRTHomeMenuItem.Enabled = false;
3412 MoveToRTHomeMenuItem.Enabled = true;
3415 if (this.ExistCurrentPost)
3417 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3418 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3419 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3421 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3425 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3427 MakeReplyOrDirectStatus(false, true);
3430 private void DMStripMenuItem_Click(object sender, EventArgs e)
3432 MakeReplyOrDirectStatus(false, false);
3435 private async Task doStatusDelete()
3437 if (this._curTab == null || this._curList == null)
3440 if (this._curList.SelectedIndices.Count == 0)
3443 var posts = this._curList.SelectedIndices.Cast<int>()
3444 .Select(x => this.GetCurTabPost(x))
3447 // 選択されたツイートの中に削除可能なものが一つでもあるか
3448 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3451 var ret = MessageBox.Show(this,
3452 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3453 Properties.Resources.DeleteStripMenuItem_ClickText2,
3454 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3456 if (ret != DialogResult.OK)
3459 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3461 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3463 Exception lastException = null;
3464 foreach (var post in posts)
3466 if (!post.CanDeleteBy(this.tw.UserId))
3473 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3478 if (post.RetweetedByUserId == this.tw.UserId)
3480 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3482 await this.twitterApi.StatusesDestroy(post.StatusId)
3487 if (post.UserId == this.tw.UserId)
3489 if (post.RetweetedId != null)
3490 // 他人に RT された自分のツイート
3491 // => RT 元の自分のツイートを削除
3492 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3497 await this.twitterApi.StatusesDestroy(post.StatusId)
3503 catch (WebApiException ex)
3509 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3512 if (lastException == null)
3513 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3515 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3517 this.PurgeListViewItemCache();
3518 this._curPost = null;
3519 this._curItemIndex = -1;
3521 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3523 var listView = (DetailsListView)tabPage.Tag;
3524 var tab = this._statuses.Tabs[tabPage.Text];
3526 using (ControlTransaction.Update(listView))
3528 listView.VirtualListSize = tab.AllCount;
3530 if (tabPage == this._curTab)
3532 listView.SelectedIndices.Clear();
3534 if (tab.AllCount != 0)
3537 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3538 selectedIndex = focusedIndex;
3540 selectedIndex = tab.AllCount - 1;
3542 listView.SelectedIndices.Add(selectedIndex);
3543 listView.EnsureVisible(selectedIndex);
3544 listView.FocusedItem = listView.Items[selectedIndex];
3549 if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3551 if (tabPage.ImageIndex == 0)
3552 tabPage.ImageIndex = -1; // タブアイコン
3556 if (!this._cfgCommon.TabIconDisp)
3557 this.ListTab.Refresh();
3561 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3563 await this.doStatusDelete();
3566 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3568 using (ControlTransaction.Update(this._curList))
3570 foreach (int idx in _curList.SelectedIndices)
3572 var post = this._statuses.Tabs[this._curTab.Text][idx];
3573 this._statuses.SetReadAllTab(post.StatusId, read: true);
3574 ChangeCacheStyleRead(true, idx);
3578 foreach (TabPage tb in ListTab.TabPages)
3580 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3582 if (this._cfgCommon.TabIconDisp)
3584 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3588 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3591 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3593 using (ControlTransaction.Update(this._curList))
3595 foreach (int idx in _curList.SelectedIndices)
3597 var post = this._statuses.Tabs[this._curTab.Text][idx];
3598 this._statuses.SetReadAllTab(post.StatusId, read: false);
3599 ChangeCacheStyleRead(false, idx);
3603 foreach (TabPage tb in ListTab.TabPages)
3605 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3607 if (this._cfgCommon.TabIconDisp)
3609 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3613 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3616 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3618 await this.DoRefresh();
3621 private async Task DoRefresh()
3623 if (_curTab != null)
3626 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3629 switch (_statuses.Tabs[_curTab.Text].TabType)
3631 case MyCommon.TabUsageType.Mentions:
3632 await this.GetReplyAsync();
3634 case MyCommon.TabUsageType.DirectMessage:
3635 await this.GetDirectMessagesAsync();
3637 case MyCommon.TabUsageType.Favorites:
3638 await this.GetFavoritesAsync();
3640 //case MyCommon.TabUsageType.Profile:
3642 case MyCommon.TabUsageType.PublicSearch:
3643 var searchTab = (PublicSearchTabModel)tab;
3644 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3645 await this.GetPublicSearchAsync(searchTab);
3647 case MyCommon.TabUsageType.UserTimeline:
3648 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3650 case MyCommon.TabUsageType.Lists:
3651 var listTab = (ListTimelineTabModel)tab;
3652 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3653 await this.GetListTimelineAsync(listTab);
3656 await this.GetHomeTimelineAsync();
3662 await this.GetHomeTimelineAsync();
3666 private async Task DoRefreshMore()
3669 if (_curTab != null)
3672 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3675 switch (_statuses.Tabs[_curTab.Text].TabType)
3677 case MyCommon.TabUsageType.Mentions:
3678 await this.GetReplyAsync(loadMore: true);
3680 case MyCommon.TabUsageType.DirectMessage:
3681 await this.GetDirectMessagesAsync(loadMore: true);
3683 case MyCommon.TabUsageType.Favorites:
3684 await this.GetFavoritesAsync(loadMore: true);
3686 case MyCommon.TabUsageType.Profile:
3689 case MyCommon.TabUsageType.PublicSearch:
3690 var searchTab = (PublicSearchTabModel)tab;
3691 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3692 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3694 case MyCommon.TabUsageType.UserTimeline:
3695 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3697 case MyCommon.TabUsageType.Lists:
3698 var listTab = (ListTimelineTabModel)tab;
3699 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3700 await this.GetListTimelineAsync(listTab, loadMore: true);
3703 await this.GetHomeTimelineAsync(loadMore: true);
3709 await this.GetHomeTimelineAsync(loadMore: true);
3713 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3715 DialogResult result = DialogResult.Abort;
3717 using (var settingDialog = new AppendSettingDialog())
3719 settingDialog.Icon = this.MainIcon;
3720 settingDialog.Owner = this;
3721 settingDialog.ShowInTaskbar = showTaskbarIcon;
3722 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3724 settingDialog.tw = this.tw;
3725 settingDialog.twitterApi = this.twitterApi;
3727 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
3731 result = settingDialog.ShowDialog(this);
3735 return DialogResult.Abort;
3738 if (result == DialogResult.OK)
3742 settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
3750 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3753 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3755 var oldIconSz = this._cfgCommon.IconSize;
3757 if (ShowSettingDialog() == DialogResult.OK)
3761 tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
3762 tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
3763 ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
3764 ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
3765 ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
3766 TwitterApiConnection.RestApiHost = this._cfgCommon.TwitterApiHost;
3768 Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
3769 Networking.UploadImageTimeout = TimeSpan.FromSeconds(this._cfgCommon.UploadImageTimeout);
3770 Networking.SetWebProxy(this._cfgLocal.ProxyType,
3771 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
3772 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
3773 Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
3775 ImageSelector.Reset(tw, this.tw.Configuration);
3779 if (this._cfgCommon.TabIconDisp)
3781 ListTab.DrawItem -= ListTab_DrawItem;
3782 ListTab.DrawMode = TabDrawMode.Normal;
3783 ListTab.ImageList = this.TabImage;
3787 ListTab.DrawItem -= ListTab_DrawItem;
3788 ListTab.DrawItem += ListTab_DrawItem;
3789 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3790 ListTab.ImageList = null;
3793 catch (Exception ex)
3795 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3796 ex.Data["IsTerminatePermission"] = false;
3802 if (!this._cfgCommon.UnreadManage)
3804 ReadedStripMenuItem.Enabled = false;
3805 UnreadStripMenuItem.Enabled = false;
3806 if (this._cfgCommon.TabIconDisp)
3808 foreach (TabPage myTab in ListTab.TabPages)
3810 myTab.ImageIndex = -1;
3816 ReadedStripMenuItem.Enabled = true;
3817 UnreadStripMenuItem.Enabled = true;
3820 catch (Exception ex)
3822 ex.Data["Instance"] = "ListTab(UnreadManage)";
3823 ex.Data["IsTerminatePermission"] = false;
3830 SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
3832 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3833 imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
3834 imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
3836 this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
3837 this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
3838 _fntUnread = this._cfgLocal.FontUnread;
3839 _clUnread = this._cfgLocal.ColorUnread;
3840 _fntReaded = this._cfgLocal.FontRead;
3841 _clReaded = this._cfgLocal.ColorRead;
3842 _clFav = this._cfgLocal.ColorFav;
3843 _clOWL = this._cfgLocal.ColorOWL;
3844 _clRetweet = this._cfgLocal.ColorRetweet;
3845 _fntDetail = this._cfgLocal.FontDetail;
3846 _clDetail = this._cfgLocal.ColorDetail;
3847 _clDetailLink = this._cfgLocal.ColorDetailLink;
3848 _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
3849 _clSelf = this._cfgLocal.ColorSelf;
3850 _clAtSelf = this._cfgLocal.ColorAtSelf;
3851 _clTarget = this._cfgLocal.ColorTarget;
3852 _clAtTarget = this._cfgLocal.ColorAtTarget;
3853 _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
3854 _clAtTo = this._cfgLocal.ColorAtTo;
3855 _clListBackcolor = this._cfgLocal.ColorListBackcolor;
3856 _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
3857 _clInputFont = this._cfgLocal.ColorInputFont;
3858 _fntInputFont = this._cfgLocal.FontInputFont;
3859 _brsBackColorMine.Dispose();
3860 _brsBackColorAt.Dispose();
3861 _brsBackColorYou.Dispose();
3862 _brsBackColorAtYou.Dispose();
3863 _brsBackColorAtFromTarget.Dispose();
3864 _brsBackColorAtTo.Dispose();
3865 _brsBackColorNone.Dispose();
3866 _brsBackColorMine = new SolidBrush(_clSelf);
3867 _brsBackColorAt = new SolidBrush(_clAtSelf);
3868 _brsBackColorYou = new SolidBrush(_clTarget);
3869 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3870 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3871 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3872 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3876 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3877 StatusText.Font = _fntInputFont;
3878 StatusText.ForeColor = _clInputFont;
3880 catch (Exception ex)
3882 MessageBox.Show(ex.Message);
3887 InitDetailHtmlFormat();
3889 catch (Exception ex)
3891 ex.Data["Instance"] = "Font";
3892 ex.Data["IsTerminatePermission"] = false;
3898 foreach (TabPage tb in ListTab.TabPages)
3900 if (this._cfgCommon.TabIconDisp)
3902 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3909 catch (Exception ex)
3911 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3912 ex.Data["IsTerminatePermission"] = false;
3918 var oldIconCol = _iconCol;
3920 if (this._cfgCommon.IconSize != oldIconSz)
3921 ApplyListViewIconSize(this._cfgCommon.IconSize);
3923 foreach (TabPage tp in ListTab.TabPages)
3925 DetailsListView lst = (DetailsListView)tp.Tag;
3927 using (ControlTransaction.Update(lst))
3929 lst.GridLines = this._cfgCommon.ShowGrid;
3930 lst.Font = _fntReaded;
3931 lst.BackColor = _clListBackcolor;
3933 if (_iconCol != oldIconCol)
3938 catch (Exception ex)
3940 ex.Data["Instance"] = "ListView(IconSize)";
3941 ex.Data["IsTerminatePermission"] = false;
3945 SetMainWindowTitle();
3946 SetNotifyIconText();
3948 this.PurgeListViewItemCache();
3949 _curList?.Refresh();
3952 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3953 if (this._cfgCommon.HotkeyEnabled)
3955 ///グローバルホットキーの登録。設定で変更可能にするかも
3956 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3957 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
3958 modKey |= HookGlobalHotkey.ModKeys.Alt;
3959 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
3960 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3961 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
3962 modKey |= HookGlobalHotkey.ModKeys.Shift;
3963 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
3964 modKey |= HookGlobalHotkey.ModKeys.Win;
3966 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
3969 if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
3972 StatusText_TextChanged(null, null);
3981 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3982 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3985 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3987 this.TopMost = this._cfgCommon.AlwaysTop;
3988 SaveConfigsAll(false);
3990 if (tw.Username != oldUser.Username)
3991 await this.doGetFollowersMenu();
3997 private void SetTabAlignment()
3999 var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4000 if (ListTab.Alignment == newAlignment) return;
4002 // 各タブのリスト上の選択位置などを退避
4003 var listSelections = this.SaveListViewSelection();
4005 ListTab.Alignment = newAlignment;
4007 foreach (TabPage tab in ListTab.TabPages)
4009 DetailsListView lst = (DetailsListView)tab.Tag;
4010 TabModel tabInfo = _statuses.Tabs[tab.Text];
4011 using (ControlTransaction.Update(lst))
4014 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4019 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4025 case MyCommon.IconSizes.IconNone:
4028 case MyCommon.IconSizes.Icon16:
4031 case MyCommon.IconSizes.Icon24:
4034 case MyCommon.IconSizes.Icon48:
4037 case MyCommon.IconSizes.Icon48_2:
4045 // ディスプレイの DPI 設定を考慮したサイズを設定する
4046 _listViewImageList.ImageSize = new Size(
4048 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4052 _listViewImageList.ImageSize = new Size(1, 1);
4056 private void ResetColumns(DetailsListView list)
4058 using (ControlTransaction.Update(list))
4059 using (ControlTransaction.Layout(list, false))
4062 list.ColumnClick -= MyList_ColumnClick;
4063 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4064 list.ColumnReordered -= MyList_ColumnReordered;
4065 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4067 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4068 list.Columns.Clear();
4069 cols.ForEach(col => col.Dispose());
4072 InitColumns(list, true);
4074 list.ColumnClick += MyList_ColumnClick;
4075 list.DrawColumnHeader += MyList_DrawColumnHeader;
4076 list.ColumnReordered += MyList_ColumnReordered;
4077 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4081 public void AddNewTabForSearch(string searchWord)
4083 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4084 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4086 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4088 foreach (TabPage tp in ListTab.TabPages)
4090 if (tb.TabName == tp.Text)
4092 ListTab.SelectedTab = tp;
4099 string tabName = searchWord;
4100 for (int i = 0; i <= 100; i++)
4102 if (_statuses.ContainsTab(tabName))
4108 var tab = new PublicSearchTabModel(tabName);
4109 _statuses.AddTab(tab);
4110 AddNewTab(tab, startup: false);
4112 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4114 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4115 cmb.Items.Add(searchWord);
4116 cmb.Text = searchWord;
4119 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4122 private void ShowUserTimeline()
4124 if (!this.ExistCurrentPost) return;
4125 AddNewTabForUserTimeline(_curPost.ScreenName);
4128 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4130 if (e.KeyCode == Keys.Escape)
4132 TabPage relTp = ListTab.SelectedTab;
4133 RemoveSpecifiedTab(relTp.Text, false);
4135 e.SuppressKeyPress = true;
4139 public void AddNewTabForUserTimeline(string user)
4141 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4142 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4144 if (tb.ScreenName == user)
4146 foreach (TabPage tp in ListTab.TabPages)
4148 if (tb.TabName == tp.Text)
4150 ListTab.SelectedTab = tp;
4157 string tabName = "user:" + user;
4158 while (_statuses.ContainsTab(tabName))
4163 var tab = new UserTimelineTabModel(tabName, user);
4164 this._statuses.AddTab(tab);
4165 this.AddNewTab(tab, startup: false);
4167 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4170 this.GetUserTimelineAsync(tab);
4173 public bool AddNewTab(TabModel tab, bool startup)
4176 foreach (TabPage tb in ListTab.TabPages)
4178 if (tb.Text == tab.TabName) return false;
4182 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4184 var _tabPage = new TabPage();
4185 var _listCustom = new DetailsListView();
4187 int cnt = ListTab.TabPages.Count;
4189 ///ToDo:Create and set controls follow tabtypes
4191 using (ControlTransaction.Update(_listCustom))
4192 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4193 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4194 using (ControlTransaction.Layout(this.SplitContainer1, false))
4195 using (ControlTransaction.Layout(this.ListTab, false))
4196 using (ControlTransaction.Layout(this))
4197 using (ControlTransaction.Layout(_tabPage, false))
4199 _tabPage.Controls.Add(_listCustom);
4202 var userTab = tab as UserTimelineTabModel;
4203 var listTab = tab as ListTimelineTabModel;
4204 var searchTab = tab as PublicSearchTabModel;
4206 if (userTab != null || listTab != null)
4208 var label = new Label();
4209 label.Dock = DockStyle.Top;
4210 label.Name = "labelUser";
4213 if (listTab != null)
4215 label.Text = listTab.ListInfo.ToString();
4217 else if (userTab != null)
4219 label.Text = userTab.ScreenName + "'s Timeline";
4221 label.TextAlign = ContentAlignment.MiddleLeft;
4222 using (ComboBox tmpComboBox = new ComboBox())
4224 label.Height = tmpComboBox.Height;
4226 _tabPage.Controls.Add(label);
4229 else if (searchTab != null)
4231 var pnl = new Panel();
4233 var lbl = new Label();
4234 var cmb = new ComboBox();
4235 var btn = new Button();
4236 var cmbLang = new ComboBox();
4238 using (ControlTransaction.Layout(pnl, false))
4240 pnl.Controls.Add(cmb);
4241 pnl.Controls.Add(cmbLang);
4242 pnl.Controls.Add(btn);
4243 pnl.Controls.Add(lbl);
4244 pnl.Name = "panelSearch";
4246 pnl.Dock = DockStyle.Top;
4247 pnl.Height = cmb.Height;
4248 pnl.Enter += SearchControls_Enter;
4249 pnl.Leave += SearchControls_Leave;
4252 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4253 cmb.Dock = DockStyle.Fill;
4254 cmb.Name = "comboSearch";
4255 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4256 cmb.ImeMode = ImeMode.NoControl;
4257 cmb.TabStop = false;
4259 cmb.AutoCompleteMode = AutoCompleteMode.None;
4260 cmb.KeyDown += SearchComboBox_KeyDown;
4263 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4264 cmbLang.Dock = DockStyle.Right;
4266 cmbLang.Name = "comboLang";
4267 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4268 cmbLang.TabStop = false;
4269 cmbLang.TabIndex = 2;
4270 cmbLang.Items.Add("");
4271 cmbLang.Items.Add("ja");
4272 cmbLang.Items.Add("en");
4273 cmbLang.Items.Add("ar");
4274 cmbLang.Items.Add("da");
4275 cmbLang.Items.Add("nl");
4276 cmbLang.Items.Add("fa");
4277 cmbLang.Items.Add("fi");
4278 cmbLang.Items.Add("fr");
4279 cmbLang.Items.Add("de");
4280 cmbLang.Items.Add("hu");
4281 cmbLang.Items.Add("is");
4282 cmbLang.Items.Add("it");
4283 cmbLang.Items.Add("no");
4284 cmbLang.Items.Add("pl");
4285 cmbLang.Items.Add("pt");
4286 cmbLang.Items.Add("ru");
4287 cmbLang.Items.Add("es");
4288 cmbLang.Items.Add("sv");
4289 cmbLang.Items.Add("th");
4291 lbl.Text = "Search(C-S-f)";
4292 lbl.Name = "label1";
4293 lbl.Dock = DockStyle.Left;
4295 lbl.Height = cmb.Height;
4296 lbl.TextAlign = ContentAlignment.MiddleLeft;
4299 btn.Text = "Search";
4300 btn.Name = "buttonSearch";
4301 btn.UseVisualStyleBackColor = true;
4302 btn.Dock = DockStyle.Right;
4303 btn.TabStop = false;
4305 btn.Click += SearchButton_Click;
4307 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4309 cmb.Items.Add(searchTab.SearchWords);
4310 cmb.Text = searchTab.SearchWords;
4313 cmbLang.Text = searchTab.SearchLang;
4315 _tabPage.Controls.Add(pnl);
4319 _tabPage.Tag = _listCustom;
4320 this.ListTab.Controls.Add(_tabPage);
4322 _tabPage.Location = new Point(4, 4);
4323 _tabPage.Name = "CTab" + cnt;
4324 _tabPage.Size = new Size(380, 260);
4325 _tabPage.TabIndex = 2 + cnt;
4326 _tabPage.Text = tab.TabName;
4327 _tabPage.UseVisualStyleBackColor = true;
4328 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4330 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4331 _listCustom.TabIndex = 1;
4332 _listCustom.AllowColumnReorder = true;
4333 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4334 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4335 _listCustom.Dock = DockStyle.Fill;
4336 _listCustom.FullRowSelect = true;
4337 _listCustom.HideSelection = false;
4338 _listCustom.Location = new Point(0, 0);
4339 _listCustom.Margin = new Padding(0);
4340 _listCustom.Name = "CList" + Environment.TickCount;
4341 _listCustom.ShowItemToolTips = true;
4342 _listCustom.Size = new Size(380, 260);
4343 _listCustom.UseCompatibleStateImageBehavior = false;
4344 _listCustom.View = View.Details;
4345 _listCustom.OwnerDraw = true;
4346 _listCustom.VirtualMode = true;
4347 _listCustom.Font = _fntReaded;
4348 _listCustom.BackColor = _clListBackcolor;
4350 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4351 _listCustom.AllowDrop = true;
4353 _listCustom.SmallImageList = _listViewImageList;
4355 InitColumns(_listCustom, startup);
4357 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4358 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4359 _listCustom.ColumnClick += MyList_ColumnClick;
4360 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4361 _listCustom.DragDrop += TweenMain_DragDrop;
4362 _listCustom.DragEnter += TweenMain_DragEnter;
4363 _listCustom.DragOver += TweenMain_DragOver;
4364 _listCustom.DrawItem += MyList_DrawItem;
4365 _listCustom.MouseClick += MyList_MouseClick;
4366 _listCustom.ColumnReordered += MyList_ColumnReordered;
4367 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4368 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4369 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4370 _listCustom.DrawSubItem += MyList_DrawSubItem;
4371 _listCustom.HScrolled += MyList_HScrolled;
4377 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4379 var tabInfo = _statuses.GetTabByName(TabName);
4380 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4384 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4385 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4386 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4392 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4393 if (_tabPage == null) return false;
4395 SetListProperty(); //他のタブに列幅等を反映
4398 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4399 _tabPage.Tag = null;
4401 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4402 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4403 using (ControlTransaction.Layout(this.SplitContainer1, false))
4404 using (ControlTransaction.Layout(this.ListTab, false))
4405 using (ControlTransaction.Layout(this))
4406 using (ControlTransaction.Layout(_tabPage, false))
4408 if (this.ListTab.SelectedTab == _tabPage)
4410 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4411 this._beforeSelectedTab = null;
4413 this.ListTab.Controls.Remove(_tabPage);
4416 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4418 using (Control label = _tabPage.Controls["labelUser"])
4420 _tabPage.Controls.Remove(label);
4423 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4425 using (Control pnl = _tabPage.Controls["panelSearch"])
4427 pnl.Enter -= SearchControls_Enter;
4428 pnl.Leave -= SearchControls_Leave;
4429 _tabPage.Controls.Remove(pnl);
4431 foreach (Control ctrl in pnl.Controls)
4433 if (ctrl.Name == "buttonSearch")
4435 ctrl.Click -= SearchButton_Click;
4437 else if (ctrl.Name == "comboSearch")
4439 ctrl.KeyDown -= SearchComboBox_KeyDown;
4441 pnl.Controls.Remove(ctrl);
4447 _tabPage.Controls.Remove(_listCustom);
4449 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4450 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4451 _listCustom.ColumnClick -= MyList_ColumnClick;
4452 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4453 _listCustom.DragDrop -= TweenMain_DragDrop;
4454 _listCustom.DragEnter -= TweenMain_DragEnter;
4455 _listCustom.DragOver -= TweenMain_DragOver;
4456 _listCustom.DrawItem -= MyList_DrawItem;
4457 _listCustom.MouseClick -= MyList_MouseClick;
4458 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4459 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4460 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4461 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4462 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4463 _listCustom.HScrolled -= MyList_HScrolled;
4465 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4466 _listCustom.Columns.Clear();
4467 cols.ForEach(col => col.Dispose());
4470 _listCustom.ContextMenuStrip = null;
4471 _listCustom.ColumnHeaderContextMenuStrip = null;
4472 _listCustom.Font = null;
4474 _listCustom.SmallImageList = null;
4475 _listCustom.ListViewItemSorter = null;
4478 if (_curTab.Equals(_tabPage))
4485 this.PurgeListViewItemCache();
4489 _listCustom.Dispose();
4490 _statuses.RemoveTab(TabName);
4492 foreach (TabPage tp in ListTab.TabPages)
4494 DetailsListView lst = (DetailsListView)tp.Tag;
4495 var count = _statuses.Tabs[tp.Text].AllCount;
4496 lst.VirtualListSize = count;
4502 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4504 this.PurgeListViewItemCache();
4505 _beforeSelectedTab = e.TabPage;
4508 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4512 if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4515 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4516 if (!dragEnableRectangle.Contains(e.Location))
4518 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4519 tn = ListTab.SelectedTab.Text;
4522 if (string.IsNullOrEmpty(tn)) return;
4524 foreach (TabPage tb in ListTab.TabPages)
4528 ListTab.DoDragDrop(tb, DragDropEffects.All);
4538 Point cpos = new Point(e.X, e.Y);
4539 for (int i = 0; i < ListTab.TabPages.Count; i++)
4541 Rectangle rect = ListTab.GetTabRect(i);
4542 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4543 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4545 _rclickTabName = ListTab.TabPages[i].Text;
4551 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4553 //_curList.Refresh();
4554 SetMainWindowTitle();
4555 SetStatusLabelUrl();
4556 SetApiStatusLabel();
4557 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4558 TabMenuControl(ListTab.SelectedTab.Text);
4559 this.PushSelectPostChain();
4560 await DispSelectedPost();
4563 private void SetListProperty()
4565 //削除などで見つからない場合は処理せず
4566 if (_curList == null) return;
4567 if (!_isColumnChanged) return;
4569 int[] dispOrder = new int[_curList.Columns.Count];
4570 for (int i = 0; i < _curList.Columns.Count; i++)
4572 for (int j = 0; j < _curList.Columns.Count; j++)
4574 if (_curList.Columns[j].DisplayIndex == i)
4583 foreach (TabPage tb in ListTab.TabPages)
4585 if (!tb.Equals(_curTab))
4587 if (tb.Tag != null && tb.Controls.Count > 0)
4589 DetailsListView lst = (DetailsListView)tb.Tag;
4590 for (int i = 0; i < lst.Columns.Count; i++)
4592 lst.Columns[dispOrder[i]].DisplayIndex = i;
4593 lst.Columns[i].Width = _curList.Columns[i].Width;
4599 _isColumnChanged = false;
4602 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4604 if (e.KeyChar == '@')
4606 if (!this._cfgCommon.UseAtIdSupplement) return;
4608 int cnt = AtIdSupl.ItemCount;
4609 ShowSuplDialog(StatusText, AtIdSupl);
4610 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4613 else if (e.KeyChar == '#')
4615 if (!this._cfgCommon.UseHashSupplement) return;
4616 ShowSuplDialog(StatusText, HashSupl);
4621 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4623 ShowSuplDialog(owner, dialog, 0, "");
4626 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4628 ShowSuplDialog(owner, dialog, offset, "");
4631 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4633 dialog.StartsWith = startswith;
4640 dialog.ShowDialog();
4642 this.TopMost = this._cfgCommon.AlwaysTop;
4643 int selStart = owner.SelectionStart;
4646 if (dialog.DialogResult == DialogResult.OK)
4648 if (!string.IsNullOrEmpty(dialog.inputText))
4652 fHalf = owner.Text.Substring(0, selStart - offset);
4654 if (selStart < owner.Text.Length)
4656 eHalf = owner.Text.Substring(selStart);
4658 owner.Text = fHalf + dialog.inputText + eHalf;
4659 owner.SelectionStart = selStart + dialog.inputText.Length;
4666 fHalf = owner.Text.Substring(0, selStart);
4668 if (selStart < owner.Text.Length)
4670 eHalf = owner.Text.Substring(selStart);
4672 owner.Text = fHalf + eHalf;
4675 owner.SelectionStart = selStart;
4681 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4684 if (!e.Alt && !e.Control && !e.Shift)
4686 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4688 bool isSpace = false;
4689 foreach (char c in StatusText.Text)
4691 if (c == ' ' || c == ' ')
4704 StatusText.Text = "";
4705 JumpUnreadMenuItem_Click(null, null);
4709 this.StatusText_TextChanged(null, null);
4712 private void StatusText_TextChanged(object sender, EventArgs e)
4715 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4716 lblLen.Text = pLen.ToString();
4719 StatusText.ForeColor = Color.Red;
4723 StatusText.ForeColor = _clInputFont;
4726 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4728 if (string.IsNullOrEmpty(StatusText.Text))
4730 this.inReplyTo = null;
4735 /// ツイート投稿前のフッター付与などの前処理を行います
4737 private string FormatStatusText(string statusText)
4739 statusText = statusText.Replace("\r\n", "\n");
4741 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4744 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4747 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4749 // 文中の全角スペースを半角スペース1個にする
4750 statusText = statusText.Replace(" ", " ");
4753 // DM の場合はこれ以降の処理を行わない
4754 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4758 if (this._cfgCommon.PostShiftEnter)
4760 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4764 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
4765 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4767 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4770 if (statusText.Contains("RT @"))
4771 disableFooter = true;
4776 var hashtag = this.HashMgr.UseHash;
4777 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4780 header = HashMgr.UseHash + " ";
4782 footer = " " + HashMgr.UseHash;
4787 if (this._cfgLocal.UseRecommendStatus)
4790 footer += this.recommendedStatusFooter;
4792 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
4794 // テキストボックスに入力されている文字列を使用する
4795 footer += " " + this._cfgLocal.StatusText.Trim();
4799 statusText = header + statusText + footer;
4801 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4803 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4804 // 参照: https://support.twitter.com/articles/14020
4806 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4807 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4809 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4810 statusText = '\u200b' + statusText;
4818 /// 投稿欄に表示する入力可能な文字数を計算します
4820 private int GetRestStatusCount(string statusText)
4823 var remainCount = this.tw.GetTextLengthRemain(statusText);
4825 var uploadService = this.ImageSelector.SelectedService;
4826 if (this.ImageSelector.Visible && uploadService != null)
4828 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4829 remainCount -= uploadService.GetReservedTextLength(1);
4835 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4837 if (sender != this._curList)
4840 var listCache = this._listItemCache;
4841 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4843 // If the newly requested cache is a subset of the old cache,
4844 // no need to rebuild everything, so do nothing.
4848 // Now we need to rebuild the cache.
4849 this.CreateCache(e.StartIndex, e.EndIndex);
4852 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4854 var listCache = this._listItemCache;
4855 if (listCache?.TargetList == sender)
4858 PostClass cacheItemPost;
4859 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4866 // A cache miss, so create a new ListViewItem and pass it back.
4867 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4870 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4874 // 不正な要求に対する間に合わせの応答
4875 string[] sitem = {"", "", "", "", "", "", "", ""};
4876 e.Item = new ImageListViewItem(sitem);
4880 private void CreateCache(int startIndex, int endIndex)
4882 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4884 if (tabInfo.AllCount == 0)
4887 // キャッシュ要求(要求範囲±30を作成)
4888 startIndex = Math.Max(startIndex - 30, 0);
4889 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4891 var cacheLength = endIndex - startIndex + 1;
4893 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4894 var listItems = Enumerable.Range(0, cacheLength)
4895 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4898 var listCache = new ListViewItemCache
4900 TargetList = this._curList,
4901 StartIndex = startIndex,
4902 EndIndex = endIndex,
4904 ListItem = listItems,
4907 Interlocked.Exchange(ref this._listItemCache, listCache);
4911 /// DetailsListView のための ListViewItem のキャッシュを消去する
4913 private void PurgeListViewItemCache()
4915 Interlocked.Exchange(ref this._listItemCache, null);
4918 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4920 StringBuilder mk = new StringBuilder();
4921 //if (Post.IsDeleted) mk.Append("×");
4922 //if (Post.IsMark) mk.Append("♪");
4923 //if (Post.IsProtect) mk.Append("Ю");
4924 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4925 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4926 ImageListViewItem itm;
4927 if (Post.RetweetedId == null)
4929 string[] sitem= {"",
4931 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4932 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4937 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4941 string[] sitem = {"",
4943 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4944 Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
4945 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4949 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4951 itm.StateIndex = Post.StateIndex;
4954 bool read = Post.IsRead;
4955 //未読管理していなかったら既読として扱う
4956 if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
4957 ChangeItemStyleRead(read, itm, Post, null);
4958 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4963 /// 全てのタブの振り分けルールを反映し直します
4965 private void ApplyPostFilters()
4967 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4969 this.PurgeListViewItemCache();
4970 this._curPost = null;
4971 this._curItemIndex = -1;
4972 this._statuses.FilterAll();
4974 foreach (TabPage tabPage in this.ListTab.TabPages)
4976 var tab = this._statuses.Tabs[tabPage.Text];
4978 var listview = (DetailsListView)tabPage.Tag;
4979 using (ControlTransaction.Update(listview))
4981 listview.VirtualListSize = tab.AllCount;
4984 if (this._cfgCommon.TabIconDisp)
4986 if (tab.UnreadCount > 0)
4987 tabPage.ImageIndex = 0;
4989 tabPage.ImageIndex = -1;
4993 if (!this._cfgCommon.TabIconDisp)
4994 this.ListTab.Refresh();
4996 SetMainWindowTitle();
4997 SetStatusLabelUrl();
5001 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5003 e.DrawDefault = true;
5006 private void MyList_HScrolled(object sender, EventArgs e)
5008 DetailsListView listView = (DetailsListView)sender;
5012 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5014 if (e.State == 0) return;
5015 e.DrawDefault = false;
5017 SolidBrush brs2 = null;
5018 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5020 if (e.Item.BackColor == _clSelf)
5021 brs2 = _brsBackColorMine;
5022 else if (e.Item.BackColor == _clAtSelf)
5023 brs2 = _brsBackColorAt;
5024 else if (e.Item.BackColor == _clTarget)
5025 brs2 = _brsBackColorYou;
5026 else if (e.Item.BackColor == _clAtTarget)
5027 brs2 = _brsBackColorAtYou;
5028 else if (e.Item.BackColor == _clAtFromTarget)
5029 brs2 = _brsBackColorAtFromTarget;
5030 else if (e.Item.BackColor == _clAtTo)
5031 brs2 = _brsBackColorAtTo;
5033 brs2 = _brsBackColorNone;
5038 if (((Control)sender).Focused)
5039 brs2 = _brsHighLight;
5041 brs2 = _brsDeactiveSelection;
5043 e.Graphics.FillRectangle(brs2, e.Bounds);
5044 e.DrawFocusRectangle();
5045 this.DrawListViewItemIcon(e);
5048 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5050 if (e.ItemState == 0) return;
5052 if (e.ColumnIndex > 0)
5055 var post = (PostClass)e.Item.Tag;
5057 RectangleF rct = e.Bounds;
5058 rct.Width = e.Header.Width;
5059 int fontHeight = e.Item.Font.Height;
5062 rct.Y += fontHeight;
5063 rct.Height -= fontHeight;
5067 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5069 //if (heightDiff > fontHeight * 0.7)
5071 // rct.Height += fontHeight;
5072 // drawLineCount += 1;
5075 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5076 if (!_iconCol && drawLineCount <= 1)
5078 //rct.Inflate(0, heightDiff / -2);
5079 //rct.Height += fontHeight / 2;
5081 else if (heightDiff < fontHeight * 0.7)
5083 //最終行が70%以上欠けていたら、最終行は表示しない
5084 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5085 rct.Height = (fontHeight * drawLineCount) - 1;
5092 //if (!_iconCol && drawLineCount > 1)
5094 // rct.Y += fontHeight * 0.2;
5095 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5100 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5101 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5106 Rectangle rctB = e.Bounds;
5107 rctB.Width = e.Header.Width;
5108 rctB.Height = fontHeight;
5110 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5112 TextRenderer.DrawText(e.Graphics,
5113 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5115 Rectangle.Round(rct),
5117 TextFormatFlags.WordBreak |
5118 TextFormatFlags.EndEllipsis |
5119 TextFormatFlags.GlyphOverhangPadding |
5120 TextFormatFlags.NoPrefix);
5121 TextRenderer.DrawText(e.Graphics,
5122 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 + "]",
5126 TextFormatFlags.SingleLine |
5127 TextFormatFlags.EndEllipsis |
5128 TextFormatFlags.GlyphOverhangPadding |
5129 TextFormatFlags.NoPrefix);
5135 if (e.ColumnIndex != 2)
5136 text = e.SubItem.Text;
5138 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5140 if (drawLineCount == 1)
5142 TextRenderer.DrawText(e.Graphics,
5145 Rectangle.Round(rct),
5147 TextFormatFlags.SingleLine |
5148 TextFormatFlags.EndEllipsis |
5149 TextFormatFlags.GlyphOverhangPadding |
5150 TextFormatFlags.NoPrefix |
5151 TextFormatFlags.VerticalCenter);
5155 TextRenderer.DrawText(e.Graphics,
5158 Rectangle.Round(rct),
5160 TextFormatFlags.WordBreak |
5161 TextFormatFlags.EndEllipsis |
5162 TextFormatFlags.GlyphOverhangPadding |
5163 TextFormatFlags.NoPrefix);
5166 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5171 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5173 if (_iconSz == 0) return;
5175 ImageListViewItem item = (ImageListViewItem)e.Item;
5177 //e.Bounds.Leftが常に0を指すから自前で計算
5178 Rectangle itemRect = item.Bounds;
5179 var col0 = e.Item.ListView.Columns[0];
5180 itemRect.Width = col0.Width;
5182 if (col0.DisplayIndex > 0)
5184 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5186 if (clm.DisplayIndex < col0.DisplayIndex)
5187 itemRect.X += clm.Width;
5191 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5192 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5193 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5196 var img = item.Image;
5199 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5200 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5202 if (iconRect.Width > 0)
5204 e.Graphics.FillRectangle(Brushes.White, iconRect);
5205 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5208 e.Graphics.DrawImage(img.Image, iconRect);
5210 catch (ArgumentException)
5212 item.RefreshImageAsync();
5218 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5219 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5221 item.GetImageAsync();
5224 if (item.StateIndex > -1)
5226 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5227 if (stateRect.Width > 0)
5229 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5230 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5231 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5236 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5238 base.ScaleControl(factor, specified);
5240 ScaleChildControl(this.TabImage, factor);
5242 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5243 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5245 foreach (var listview in listviews)
5247 ScaleChildControl(listview, factor);
5251 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5253 // ImageListViewItem item = (ImageListViewItem)e.Item;
5254 // if (item.StateImageIndex > -1)
5256 // ////e.Bounds.Leftが常に0を指すから自前で計算
5257 // //Rectangle itemRect = item.Bounds;
5258 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5260 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5262 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5264 // // itemRect.X += clm.Width;
5268 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5269 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5271 // if (rct.Width > 0)
5273 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5274 // //e.Graphics.FillRectangle(Brushes.White, rct);
5275 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5276 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5281 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5283 var tab = this._statuses.Tabs[this._curTab.Text];
5285 if (tab.AllCount == 0)
5287 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5291 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5296 case SEARCHTYPE.NextSearch: // 次を検索
5297 if (selectedIndex != -1)
5298 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5302 case SEARCHTYPE.PrevSearch: // 前を検索
5303 if (selectedIndex != -1)
5304 startIndex = Math.Max(selectedIndex - 1, 0);
5306 startIndex = tab.AllCount - 1;
5308 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5310 if (selectedIndex != -1)
5311 startIndex = selectedIndex;
5317 Func<string, bool> stringComparer;
5320 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5322 catch (ArgumentException)
5324 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5328 var reverse = searchType == SEARCHTYPE.PrevSearch;
5329 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5330 .DefaultIfEmpty(-1).First();
5332 if (foundIndex == -1)
5334 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5338 this.SelectListItem(this._curList, foundIndex);
5339 this._curList.EnsureVisible(foundIndex);
5342 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5345 this.ShowSearchDialog();
5348 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5350 var previousSearch = this.SearchDialog.ResultOptions;
5351 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5353 this.SearchDialog.Reset();
5354 this.ShowSearchDialog();
5360 previousSearch.Query,
5361 previousSearch.CaseSensitive,
5362 previousSearch.UseRegex,
5363 SEARCHTYPE.NextSearch);
5366 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5368 var previousSearch = this.SearchDialog.ResultOptions;
5369 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5371 this.SearchDialog.Reset();
5372 this.ShowSearchDialog();
5378 previousSearch.Query,
5379 previousSearch.CaseSensitive,
5380 previousSearch.UseRegex,
5381 SEARCHTYPE.PrevSearch);
5385 /// 検索ダイアログを表示し、検索を実行します
5387 private void ShowSearchDialog()
5389 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5391 this.TopMost = this._cfgCommon.AlwaysTop;
5394 this.TopMost = this._cfgCommon.AlwaysTop;
5396 var searchOptions = this.SearchDialog.ResultOptions;
5397 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5399 if (searchOptions.NewTab)
5401 var tabName = Properties.Resources.SearchResults_TabName;
5405 tabName = this._statuses.MakeTabName(tabName);
5407 catch (TabException ex)
5409 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5412 var resultTab = new LocalSearchTabModel(tabName);
5413 this.AddNewTab(resultTab, startup: false);
5414 this._statuses.AddTab(resultTab);
5416 var targetTab = this._statuses.Tabs[this._curTab.Text];
5418 Func<string, bool> stringComparer;
5421 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5423 catch (ArgumentException)
5425 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5429 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5430 if (foundIndices.Length == 0)
5432 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5436 var foundPosts = foundIndices.Select(x => targetTab[x]);
5437 foreach (var post in foundPosts)
5439 resultTab.AddPostQueue(post);
5442 this._statuses.DistributePosts();
5443 this.RefreshTimeline();
5445 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5446 .First(x => x.Text == tabName);
5448 this.ListTab.SelectedTab = tabPage;
5453 searchOptions.Query,
5454 searchOptions.CaseSensitive,
5455 searchOptions.UseRegex,
5456 SEARCHTYPE.DialogSearch);
5459 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5461 this.AddNewTabForSearch(searchOptions.Query);
5465 /// <summary>発言検索に使用するメソッドを生成します</summary>
5466 /// <exception cref="ArgumentException">
5467 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5469 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5473 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5474 var regex = new Regex(query, regexOption);
5476 return x => regex.IsMatch(x);
5480 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5482 return x => x.IndexOf(query, comparisonType) != -1;
5486 private void AboutMenuItem_Click(object sender, EventArgs e)
5488 using (TweenAboutBox about = new TweenAboutBox())
5490 about.ShowDialog(this);
5492 this.TopMost = this._cfgCommon.AlwaysTop;
5495 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5497 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5499 if (ImageSelector.Enabled)
5502 TabModel foundTab = null;
5505 DetailsListView lst = null;
5508 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5510 var tabPage = this.ListTab.TabPages[i];
5511 var tab = this._statuses.Tabs[tabPage.Text];
5512 var unreadIndex = tab.NextUnreadIndex;
5514 if (unreadIndex != -1)
5516 ListTab.SelectedIndex = i;
5518 foundIndex = unreadIndex;
5519 lst = (DetailsListView)tabPage.Tag;
5524 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5525 if (foundTab == null && bgnIdx > 0)
5527 for (int i = 0; i < bgnIdx; i++)
5529 var tabPage = this.ListTab.TabPages[i];
5530 var tab = this._statuses.Tabs[tabPage.Text];
5531 var unreadIndex = tab.NextUnreadIndex;
5533 if (unreadIndex != -1)
5535 ListTab.SelectedIndex = i;
5537 foundIndex = unreadIndex;
5538 lst = (DetailsListView)tabPage.Tag;
5544 if (foundTab == null)
5546 //全部調べたが未読見つからず→先頭タブの最新発言へ
5547 ListTab.SelectedIndex = 0;
5548 var tabPage = this.ListTab.TabPages[0];
5549 var tab = this._statuses.Tabs[tabPage.Text];
5551 if (tab.AllCount == 0)
5554 if (_statuses.SortOrder == SortOrder.Ascending)
5555 foundIndex = tab.AllCount - 1;
5559 lst = (DetailsListView)tabPage.Tag;
5562 SelectListItem(lst, foundIndex);
5564 if (_statuses.SortMode == ComparerMode.Id)
5566 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5567 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5573 lst.EnsureVisible(foundIndex);
5578 lst.EnsureVisible(foundIndex);
5584 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5586 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5588 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5589 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5593 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5595 if (_curList.SelectedIndices.Count > 0)
5597 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5598 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5602 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5604 await this.CheckNewVersion(false);
5607 private void RunTweenUp()
5609 ProcessStartInfo pinfo = new ProcessStartInfo();
5610 pinfo.UseShellExecute = true;
5611 pinfo.WorkingDirectory = MyCommon.settingPath;
5612 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5613 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5616 Process.Start(pinfo);
5620 MessageBox.Show("Failed to execute TweenUp3.exe.");
5624 public class VersionInfo
5626 public Version Version { get; set; }
5627 public Uri DownloadUri { get; set; }
5628 public string ReleaseNote { get; set; }
5632 /// OpenTween の最新バージョンの情報を取得します
5634 public async Task<VersionInfo> GetVersionInfoAsync()
5636 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5637 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5639 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5640 .ConfigureAwait(false);
5642 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5643 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5645 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5646 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5648 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5650 return new VersionInfo
5652 Version = Version.Parse(msgHeader[0]),
5653 DownloadUri = new Uri(msgHeader[1]),
5654 ReleaseNote = msgBody,
5658 private async Task CheckNewVersion(bool startup = false)
5660 if (ApplicationSettings.VersionInfoUrl == null)
5661 return; // 更新チェック無効化
5665 var versionInfo = await this.GetVersionInfoAsync();
5667 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5672 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5673 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5674 msgtext = MyCommon.ReplaceAppName(msgtext);
5676 MessageBox.Show(msgtext,
5677 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5678 MessageBoxButtons.OK, MessageBoxIcon.Information);
5683 using (var dialog = new UpdateDialog())
5685 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5686 MyCommon.GetReadableVersion(versionInfo.Version));
5687 dialog.DetailsText = versionInfo.ReleaseNote;
5689 if (dialog.ShowDialog(this) == DialogResult.Yes)
5691 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5697 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5700 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5701 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5702 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5707 private async Task Colorize()
5710 await this.DispSelectedPost();
5711 //件数関連の場合、タイトル即時書き換え
5712 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
5713 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5714 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5715 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5717 SetMainWindowTitle();
5719 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5720 SetStatusLabelUrl();
5721 foreach (TabPage tb in ListTab.TabPages)
5723 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5725 if (this._cfgCommon.TabIconDisp)
5727 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5731 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
5734 public string createDetailHtml(string orgdata)
5736 if (this._cfgLocal.UseTwemoji)
5737 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5739 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5742 private Task DispSelectedPost()
5744 return this.DispSelectedPost(false);
5747 private PostClass displayPost = new PostClass();
5750 /// サムネイル表示に使用する CancellationToken の生成元
5752 private CancellationTokenSource thumbnailTokenSource = null;
5754 private async Task DispSelectedPost(bool forceupdate)
5756 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5759 var oldDisplayPost = this.displayPost;
5760 this.displayPost = this._curPost;
5762 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5765 var loadTasks = new List<Task>
5767 this.tweetDetailsView.ShowPostDetails(this._curPost),
5770 this.SplitContainer3.Panel2Collapsed = true;
5772 if (this._cfgCommon.PreviewEnable)
5774 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5775 oldTokenSource?.Cancel();
5777 var token = this.thumbnailTokenSource.Token;
5778 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5783 await Task.WhenAll(loadTasks);
5785 catch (OperationCanceledException) { }
5788 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5790 await this.OpenApplicationWebsite();
5793 private async Task OpenApplicationWebsite()
5795 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5798 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5800 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5803 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5805 if (ListTab.SelectedTab != null)
5807 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5809 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5810 if (pnl.Controls["comboSearch"].Focused ||
5811 pnl.Controls["comboLang"].Focused ||
5812 pnl.Controls["buttonSearch"].Focused) return;
5815 if (e.Control || e.Shift || e.Alt)
5816 this._anchorFlag = false;
5819 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5822 e.SuppressKeyPress = true;
5825 if (asyncTask != null)
5830 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5832 private void InitializeShortcuts()
5834 this.shortcutCommands = new[]
5836 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5837 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5838 .FocusedOn(FocusedControl.ListTab)
5839 .Do(() => SendKeys.Send("{DOWN}")),
5841 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5842 .FocusedOn(FocusedControl.ListTab)
5843 .Do(() => SendKeys.Send("{UP}")),
5845 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5846 .FocusedOn(FocusedControl.ListTab)
5847 .Do(() => SendKeys.Send("{PGDN}")),
5849 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5850 .FocusedOn(FocusedControl.ListTab)
5851 .Do(() => SendKeys.Send("{PGUP}")),
5853 ShortcutCommand.Create(Keys.F1)
5854 .Do(() => this.OpenApplicationWebsite()),
5856 ShortcutCommand.Create(Keys.F3)
5857 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5859 ShortcutCommand.Create(Keys.F5)
5860 .Do(() => this.DoRefresh()),
5862 ShortcutCommand.Create(Keys.F6)
5863 .Do(() => this.GetReplyAsync()),
5865 ShortcutCommand.Create(Keys.F7)
5866 .Do(() => this.GetDirectMessagesAsync()),
5868 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5869 .NotFocusedOn(FocusedControl.StatusText)
5870 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5872 ShortcutCommand.Create(Keys.G)
5873 .NotFocusedOn(FocusedControl.StatusText)
5874 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5876 ShortcutCommand.Create(Keys.Right, Keys.N)
5877 .FocusedOn(FocusedControl.ListTab)
5878 .Do(() => this.GoRelPost(forward: true)),
5880 ShortcutCommand.Create(Keys.Left, Keys.P)
5881 .FocusedOn(FocusedControl.ListTab)
5882 .Do(() => this.GoRelPost(forward: false)),
5884 ShortcutCommand.Create(Keys.OemPeriod)
5885 .FocusedOn(FocusedControl.ListTab)
5886 .Do(() => this.GoAnchor()),
5888 ShortcutCommand.Create(Keys.I)
5889 .FocusedOn(FocusedControl.ListTab)
5890 .OnlyWhen(() => this.StatusText.Enabled)
5891 .Do(() => this.StatusText.Focus()),
5893 ShortcutCommand.Create(Keys.Enter)
5894 .FocusedOn(FocusedControl.ListTab)
5895 .Do(() => this.MakeReplyOrDirectStatus()),
5897 ShortcutCommand.Create(Keys.R)
5898 .FocusedOn(FocusedControl.ListTab)
5899 .Do(() => this.DoRefresh()),
5901 ShortcutCommand.Create(Keys.L)
5902 .FocusedOn(FocusedControl.ListTab)
5903 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5905 ShortcutCommand.Create(Keys.H)
5906 .FocusedOn(FocusedControl.ListTab)
5907 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5909 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5910 .FocusedOn(FocusedControl.ListTab)
5911 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5913 ShortcutCommand.Create(Keys.S)
5914 .FocusedOn(FocusedControl.ListTab)
5915 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5917 ShortcutCommand.Create(Keys.A)
5918 .FocusedOn(FocusedControl.ListTab)
5919 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5921 // ] in_reply_to参照元へ戻る
5922 ShortcutCommand.Create(Keys.Oem4)
5923 .FocusedOn(FocusedControl.ListTab)
5924 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5926 // [ in_reply_toへジャンプ
5927 ShortcutCommand.Create(Keys.Oem6)
5928 .FocusedOn(FocusedControl.ListTab)
5929 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5931 ShortcutCommand.Create(Keys.Escape)
5932 .FocusedOn(FocusedControl.ListTab)
5934 this._anchorFlag = false;
5935 if (ListTab.SelectedTab != null)
5937 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5938 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5940 var relTp = ListTab.SelectedTab;
5941 RemoveSpecifiedTab(relTp.Text, false);
5947 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5948 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5949 .FocusedOn(FocusedControl.ListTab)
5950 .Do(() => this._anchorFlag = false, preventDefault: false),
5952 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5953 ShortcutCommand.Create(Keys.Up, Keys.Down)
5954 .FocusedOn(FocusedControl.PostBrowser)
5957 ShortcutCommand.Create(Keys.Control | Keys.R)
5958 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5960 ShortcutCommand.Create(Keys.Control | Keys.D)
5961 .Do(() => this.doStatusDelete()),
5963 ShortcutCommand.Create(Keys.Control | Keys.M)
5964 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5966 ShortcutCommand.Create(Keys.Control | Keys.S)
5967 .Do(() => this.FavoriteChange(FavAdd: true)),
5969 ShortcutCommand.Create(Keys.Control | Keys.I)
5970 .Do(() => this.doRepliedStatusOpen()),
5972 ShortcutCommand.Create(Keys.Control | Keys.Q)
5973 .Do(() => this.doQuoteOfficial()),
5975 ShortcutCommand.Create(Keys.Control | Keys.B)
5976 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5978 ShortcutCommand.Create(Keys.Control | Keys.T)
5979 .Do(() => this.HashManageMenuItem_Click(null, null)),
5981 ShortcutCommand.Create(Keys.Control | Keys.L)
5982 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5984 ShortcutCommand.Create(Keys.Control | Keys.Y)
5985 .NotFocusedOn(FocusedControl.PostBrowser)
5986 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5988 ShortcutCommand.Create(Keys.Control | Keys.F)
5989 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5991 ShortcutCommand.Create(Keys.Control | Keys.U)
5992 .Do(() => this.ShowUserTimeline()),
5994 ShortcutCommand.Create(Keys.Control | Keys.H)
5995 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5997 ShortcutCommand.Create(Keys.Control | Keys.G)
5998 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6000 ShortcutCommand.Create(Keys.Control | Keys.O)
6001 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6003 ShortcutCommand.Create(Keys.Control | Keys.E)
6004 .Do(() => this.OpenURLMenuItem_Click(null, null)),
6006 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6007 .FocusedOn(FocusedControl.ListTab)
6008 .Do(() => this._colorize = true, preventDefault: false),
6010 ShortcutCommand.Create(Keys.Control | Keys.N)
6011 .FocusedOn(FocusedControl.ListTab)
6012 .Do(() => this.GoNextTab(forward: true)),
6014 ShortcutCommand.Create(Keys.Control | Keys.P)
6015 .FocusedOn(FocusedControl.ListTab)
6016 .Do(() => this.GoNextTab(forward: false)),
6018 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6019 .FocusedOn(FocusedControl.ListTab)
6020 .Do(() => this.CopyStot()),
6022 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6023 ShortcutCommand.Create(Keys.Control | Keys.D1)
6024 .FocusedOn(FocusedControl.ListTab)
6025 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6026 .Do(() => this.ListTab.SelectedIndex = 0),
6028 ShortcutCommand.Create(Keys.Control | Keys.D2)
6029 .FocusedOn(FocusedControl.ListTab)
6030 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6031 .Do(() => this.ListTab.SelectedIndex = 1),
6033 ShortcutCommand.Create(Keys.Control | Keys.D3)
6034 .FocusedOn(FocusedControl.ListTab)
6035 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6036 .Do(() => this.ListTab.SelectedIndex = 2),
6038 ShortcutCommand.Create(Keys.Control | Keys.D4)
6039 .FocusedOn(FocusedControl.ListTab)
6040 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6041 .Do(() => this.ListTab.SelectedIndex = 3),
6043 ShortcutCommand.Create(Keys.Control | Keys.D5)
6044 .FocusedOn(FocusedControl.ListTab)
6045 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6046 .Do(() => this.ListTab.SelectedIndex = 4),
6048 ShortcutCommand.Create(Keys.Control | Keys.D6)
6049 .FocusedOn(FocusedControl.ListTab)
6050 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6051 .Do(() => this.ListTab.SelectedIndex = 5),
6053 ShortcutCommand.Create(Keys.Control | Keys.D7)
6054 .FocusedOn(FocusedControl.ListTab)
6055 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6056 .Do(() => this.ListTab.SelectedIndex = 6),
6058 ShortcutCommand.Create(Keys.Control | Keys.D8)
6059 .FocusedOn(FocusedControl.ListTab)
6060 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6061 .Do(() => this.ListTab.SelectedIndex = 7),
6063 ShortcutCommand.Create(Keys.Control | Keys.D9)
6064 .FocusedOn(FocusedControl.ListTab)
6065 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6067 ShortcutCommand.Create(Keys.Control | Keys.A)
6068 .FocusedOn(FocusedControl.StatusText)
6069 .Do(() => this.StatusText.SelectAll()),
6071 ShortcutCommand.Create(Keys.Control | Keys.V)
6072 .FocusedOn(FocusedControl.StatusText)
6073 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6075 ShortcutCommand.Create(Keys.Control | Keys.Up)
6076 .FocusedOn(FocusedControl.StatusText)
6078 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6080 var inReplyToStatusId = this.inReplyTo?.Item1;
6081 var inReplyToScreenName = this.inReplyTo?.Item2;
6082 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6085 if (_hisIdx < 0) _hisIdx = 0;
6087 var historyItem = this._history[this._hisIdx];
6088 StatusText.Text = historyItem.status;
6089 StatusText.SelectionStart = StatusText.Text.Length;
6090 if (historyItem.inReplyToId != null)
6091 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6093 this.inReplyTo = null;
6096 ShortcutCommand.Create(Keys.Control | Keys.Down)
6097 .FocusedOn(FocusedControl.StatusText)
6099 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6101 var inReplyToStatusId = this.inReplyTo?.Item1;
6102 var inReplyToScreenName = this.inReplyTo?.Item2;
6103 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6106 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6108 var historyItem = this._history[this._hisIdx];
6109 StatusText.Text = historyItem.status;
6110 StatusText.SelectionStart = StatusText.Text.Length;
6111 if (historyItem.inReplyToId != null)
6112 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6114 this.inReplyTo = null;
6117 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6118 .FocusedOn(FocusedControl.StatusText)
6120 if (ListTab.SelectedIndex == 0)
6122 ListTab.SelectedIndex = ListTab.TabCount - 1;
6126 ListTab.SelectedIndex -= 1;
6131 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6132 .FocusedOn(FocusedControl.StatusText)
6134 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6136 ListTab.SelectedIndex = 0;
6140 ListTab.SelectedIndex += 1;
6145 ShortcutCommand.Create(Keys.Control | Keys.Y)
6146 .FocusedOn(FocusedControl.PostBrowser)
6148 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6149 MultiLineMenuItem_Click(null, null);
6152 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6153 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6155 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6156 .Do(() => this.DoRefreshMore()),
6158 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6159 .Do(() => this.GetReplyAsync(loadMore: true)),
6161 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6162 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6164 ShortcutCommand.Create(Keys.Shift | Keys.R)
6165 .NotFocusedOn(FocusedControl.StatusText)
6166 .Do(() => this.DoRefreshMore()),
6168 ShortcutCommand.Create(Keys.Shift | Keys.H)
6169 .FocusedOn(FocusedControl.ListTab)
6170 .Do(() => this.GoTopEnd(GoTop: true)),
6172 ShortcutCommand.Create(Keys.Shift | Keys.L)
6173 .FocusedOn(FocusedControl.ListTab)
6174 .Do(() => this.GoTopEnd(GoTop: false)),
6176 ShortcutCommand.Create(Keys.Shift | Keys.M)
6177 .FocusedOn(FocusedControl.ListTab)
6178 .Do(() => this.GoMiddle()),
6180 ShortcutCommand.Create(Keys.Shift | Keys.G)
6181 .FocusedOn(FocusedControl.ListTab)
6182 .Do(() => this.GoLast()),
6184 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6185 .FocusedOn(FocusedControl.ListTab)
6186 .Do(() => this.MoveMiddle()),
6188 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6189 .FocusedOn(FocusedControl.ListTab)
6190 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6192 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6193 .FocusedOn(FocusedControl.ListTab)
6194 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6196 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6197 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6198 .FocusedOn(FocusedControl.ListTab)
6199 .Do(() => this.GoFav(forward: true)),
6201 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6202 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6203 .FocusedOn(FocusedControl.ListTab)
6204 .Do(() => this.GoFav(forward: false)),
6206 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6207 .FocusedOn(FocusedControl.ListTab)
6208 .Do(() => this.GoBackSelectPostChain()),
6210 ShortcutCommand.Create(Keys.Alt | Keys.R)
6211 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6213 ShortcutCommand.Create(Keys.Alt | Keys.P)
6214 .OnlyWhen(() => this._curPost != null)
6215 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6217 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6218 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6220 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6221 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6223 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6224 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6226 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6227 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6229 // 別タブの同じ書き込みへ(ALT+←/→)
6230 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6231 .FocusedOn(FocusedControl.ListTab)
6232 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6234 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6235 .FocusedOn(FocusedControl.ListTab)
6236 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6238 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6239 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6241 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6242 .Do(() => this.CopyIdUri()),
6244 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6245 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6246 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6247 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6249 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6250 .Do(() => this.FavoriteChange(FavAdd: false)),
6252 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6253 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6255 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6256 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6258 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6259 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6261 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6262 .Do(() => this.doMoveToRTHome()),
6264 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6265 .Do(() => this.FavorareMenuItem_Click(null, null)),
6267 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6268 .FocusedOn(FocusedControl.StatusText)
6270 if (_curList != null && _curList.VirtualListSize != 0 &&
6271 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6273 var idx = _curList.SelectedIndices[0] - 1;
6274 SelectListItem(_curList, idx);
6275 _curList.EnsureVisible(idx);
6279 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6280 .FocusedOn(FocusedControl.StatusText)
6282 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6283 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6285 var idx = _curList.SelectedIndices[0] + 1;
6286 SelectListItem(_curList, idx);
6287 _curList.EnsureVisible(idx);
6291 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6292 .FocusedOn(FocusedControl.StatusText)
6294 if (StatusText.SelectionStart > 0)
6296 int endidx = StatusText.SelectionStart - 1;
6297 string startstr = "";
6298 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6300 char c = StatusText.Text[i];
6301 if (Char.IsLetterOrDigit(c) || c == '_')
6307 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6308 int cnt = AtIdSupl.ItemCount;
6309 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6310 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6314 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6315 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6325 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6326 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6327 .FocusedOn(FocusedControl.ListTab)
6328 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6330 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6331 .FocusedOn(FocusedControl.ListTab)
6332 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6334 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6335 .FocusedOn(FocusedControl.ListTab)
6336 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6338 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6339 .FocusedOn(FocusedControl.ListTab)
6340 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6342 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6343 .FocusedOn(FocusedControl.ListTab)
6344 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6346 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6347 .FocusedOn(FocusedControl.ListTab)
6348 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6350 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6351 .FocusedOn(FocusedControl.ListTab)
6352 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6354 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6355 .FocusedOn(FocusedControl.ListTab)
6356 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6358 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6359 .FocusedOn(FocusedControl.ListTab)
6360 .Do(() => this.SetSortLastColumn()),
6362 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6363 .Do(() => this.FavoritesRetweetOfficial()),
6365 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6366 .Do(() => this.FavoritesRetweetUnofficial()),
6368 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6369 .Do(() => this.OpenUserAppointUrl()),
6371 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6372 .FocusedOn(FocusedControl.PostBrowser)
6373 .Do(() => this.doReTweetUnofficial()),
6375 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6376 .OnlyWhen(() => this.ExistCurrentPost)
6377 .Do(() => this.tweetDetailsView.DoTranslation()),
6379 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6380 .Do(() => this.doReTweetUnofficial()),
6382 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6383 .Do(() => this.CopyUserId()),
6385 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6386 .Do(() => this.tweetThumbnail1.ScrollUp()),
6388 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6389 .Do(() => this.tweetThumbnail1.ScrollDown()),
6391 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6392 .FocusedOn(FocusedControl.ListTab)
6393 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6394 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6398 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6400 // Task を返す非同期処理があれば asyncTask に代入する
6403 // ShortcutCommand に対応しているコマンドはここで処理される
6404 foreach (var command in this.shortcutCommands)
6406 if (command.IsMatch(keyData, focusedOn))
6408 asyncTask = command.RunCommand();
6409 return command.PreventDefault;
6416 private void GoNextTab(bool forward)
6418 int idx = ListTab.SelectedIndex;
6422 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6427 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6429 ListTab.SelectedIndex = idx;
6432 private void CopyStot()
6435 StringBuilder sb = new StringBuilder();
6436 bool IsProtected = false;
6438 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6439 foreach (int idx in _curList.SelectedIndices)
6441 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6442 if (post.IsDeleted) continue;
6445 if (post.RetweetedId != null)
6446 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6448 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6452 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6457 MessageBox.Show(Properties.Resources.CopyStotText1);
6461 clstr = sb.ToString();
6464 Clipboard.SetDataObject(clstr, false, 5, 100);
6466 catch (Exception ex)
6468 MessageBox.Show(ex.Message);
6473 private void CopyIdUri()
6475 if (this._curTab == null)
6478 var tab = this._statuses.GetTabByName(this._curTab.Text);
6479 if (tab == null || tab is DirectMessagesTabModel)
6482 var copyUrls = new List<string>();
6483 foreach (int idx in _curList.SelectedIndices)
6485 var post = tab[idx];
6486 copyUrls.Add(MyCommon.GetStatusUrl(post));
6489 if (copyUrls.Count == 0)
6494 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6496 catch (ExternalException ex)
6498 MessageBox.Show(ex.Message);
6502 private void GoFav(bool forward)
6504 if (_curList.VirtualListSize == 0) return;
6511 if (_curList.SelectedIndices.Count == 0)
6517 fIdx = _curList.SelectedIndices[0] + 1;
6518 if (fIdx > _curList.VirtualListSize - 1) return;
6520 toIdx = _curList.VirtualListSize;
6525 if (_curList.SelectedIndices.Count == 0)
6527 fIdx = _curList.VirtualListSize - 1;
6531 fIdx = _curList.SelectedIndices[0] - 1;
6532 if (fIdx < 0) return;
6538 for (int idx = fIdx; idx != toIdx; idx += stp)
6540 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6542 SelectListItem(_curList, idx);
6543 _curList.EnsureVisible(idx);
6549 private void GoSamePostToAnotherTab(bool left)
6551 if (this._curList.SelectedIndices.Count == 0)
6554 var tab = this._statuses.Tabs[this._curTab.Text];
6556 // Directタブは対象外(見つかるはずがない)
6557 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6560 var selectedIndex = this._curList.SelectedIndices[0];
6561 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6563 int fIdx, toIdx, stp;
6568 if (ListTab.SelectedIndex == 0)
6574 fIdx = ListTab.SelectedIndex - 1;
6582 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6588 fIdx = ListTab.SelectedIndex + 1;
6590 toIdx = ListTab.TabCount;
6594 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6596 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6599 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6602 var foundIndex = targetTab.IndexOf(selectedStatusId);
6603 if (foundIndex != -1)
6605 ListTab.SelectedIndex = tabidx;
6606 SelectListItem(_curList, foundIndex);
6607 _curList.EnsureVisible(foundIndex);
6613 private void GoPost(bool forward)
6615 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6618 var tab = this._statuses.Tabs[this._curTab.Text];
6619 var selectedIndex = this._curList.SelectedIndices[0];
6621 int fIdx, toIdx, stp;
6625 fIdx = selectedIndex + 1;
6626 if (fIdx > tab.AllCount - 1) return;
6627 toIdx = tab.AllCount;
6632 fIdx = selectedIndex - 1;
6633 if (fIdx < 0) return;
6639 if (_curPost.RetweetedId == null)
6641 name = _curPost.ScreenName;
6645 name = _curPost.RetweetedBy;
6647 for (int idx = fIdx; idx != toIdx; idx += stp)
6649 var post = tab[idx];
6650 if (post.RetweetedId == null)
6652 if (post.ScreenName == name)
6654 SelectListItem(_curList, idx);
6655 _curList.EnsureVisible(idx);
6661 if (post.RetweetedBy == name)
6663 SelectListItem(_curList, idx);
6664 _curList.EnsureVisible(idx);
6671 private void GoRelPost(bool forward)
6673 if (this._curList.SelectedIndices.Count == 0)
6676 var tab = this._statuses.Tabs[this._curTab.Text];
6677 var selectedIndex = this._curList.SelectedIndices[0];
6679 int fIdx, toIdx, stp;
6683 fIdx = selectedIndex + 1;
6684 if (fIdx > tab.AllCount - 1) return;
6685 toIdx = tab.AllCount;
6690 fIdx = selectedIndex - 1;
6691 if (fIdx < 0) return;
6698 if (_curPost == null) return;
6699 _anchorPost = _curPost;
6704 if (_anchorPost == null) return;
6707 for (int idx = fIdx; idx != toIdx; idx += stp)
6709 var post = tab[idx];
6710 if (post.ScreenName == _anchorPost.ScreenName ||
6711 post.RetweetedBy == _anchorPost.ScreenName ||
6712 post.ScreenName == _anchorPost.RetweetedBy ||
6713 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6714 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6715 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6716 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6717 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6719 SelectListItem(_curList, idx);
6720 _curList.EnsureVisible(idx);
6726 private void GoAnchor()
6728 if (_anchorPost == null) return;
6729 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6730 if (idx == -1) return;
6732 SelectListItem(_curList, idx);
6733 _curList.EnsureVisible(idx);
6736 private void GoTopEnd(bool GoTop)
6738 if (_curList.VirtualListSize == 0)
6746 _item = _curList.GetItemAt(0, 25);
6754 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6756 idx = _curList.VirtualListSize - 1;
6760 SelectListItem(_curList, idx);
6763 private void GoMiddle()
6765 if (_curList.VirtualListSize == 0)
6773 _item = _curList.GetItemAt(0, 0);
6783 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6786 idx2 = _curList.VirtualListSize - 1;
6792 idx3 = (idx1 + idx2) / 2;
6794 SelectListItem(_curList, idx3);
6797 private void GoLast()
6799 if (_curList.VirtualListSize == 0) return;
6801 if (_statuses.SortOrder == SortOrder.Ascending)
6803 SelectListItem(_curList, _curList.VirtualListSize - 1);
6804 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6808 SelectListItem(_curList, 0);
6809 _curList.EnsureVisible(0);
6813 private void MoveTop()
6815 if (_curList.SelectedIndices.Count == 0) return;
6816 int idx = _curList.SelectedIndices[0];
6817 if (_statuses.SortOrder == SortOrder.Ascending)
6819 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6823 _curList.EnsureVisible(0);
6825 _curList.EnsureVisible(idx);
6828 private async Task GoInReplyToPostTree()
6830 if (_curPost == null) return;
6832 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6834 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6838 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6840 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6841 _curPost.InReplyToUser = post.InReplyToUser;
6842 _curPost.IsReply = post.IsReply;
6843 this.PurgeListViewItemCache();
6844 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6846 catch (WebApiException ex)
6848 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6852 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6854 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6856 replyChains = new Stack<ReplyChain>();
6858 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6861 string inReplyToTabName;
6862 long inReplyToId = _curPost.InReplyToStatusId.Value;
6863 string inReplyToUser = _curPost.InReplyToUser;
6864 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6866 var inReplyToPosts = from tab in _statuses.Tabs.Values
6867 orderby tab != curTabClass
6868 from post in tab.Posts.Values
6869 where post.StatusId == inReplyToId
6870 let index = tab.IndexOf(post.StatusId)
6872 select new {Tab = tab, Index = index};
6874 var inReplyPost = inReplyToPosts.FirstOrDefault();
6875 if (inReplyPost == null)
6879 await Task.Run(async () =>
6881 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6882 .ConfigureAwait(false);
6885 _statuses.AddPost(post);
6886 _statuses.DistributePosts();
6889 catch (WebApiException ex)
6891 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6892 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6896 this.RefreshTimeline();
6898 inReplyPost = inReplyToPosts.FirstOrDefault();
6899 if (inReplyPost == null)
6901 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6905 inReplyToTabName = inReplyPost.Tab.TabName;
6906 inReplyToIndex = inReplyPost.Index;
6908 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6909 DetailsListView listView = (DetailsListView)tabPage.Tag;
6911 if (_curTab != tabPage)
6913 this.ListTab.SelectTab(tabPage);
6916 this.SelectListItem(listView, inReplyToIndex);
6917 listView.EnsureVisible(inReplyToIndex);
6920 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6922 if (_curPost == null) return;
6924 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6925 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6929 if (_curPost.InReplyToStatusId != null)
6931 var posts = from t in _statuses.Tabs
6932 from p in t.Value.Posts
6933 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6934 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6936 orderby isForward ? indexOf : indexOf * -1
6937 orderby t.Value != curTabClass
6938 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6941 var postList = posts.ToList();
6942 for (int i = postList.Count - 1; i >= 0; i--)
6945 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6947 postList.RemoveAt(index);
6950 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6951 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6952 if (post == null) post = postList.First();
6953 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6954 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6955 SelectListItem(listView, post.Index);
6956 listView.EnsureVisible(post.Index);
6958 catch (InvalidOperationException)
6966 if (replyChains == null || replyChains.Count < 1)
6968 var posts = from t in _statuses.Tabs
6969 from p in t.Value.Posts
6970 where p.Value.InReplyToStatusId == _curPost.StatusId
6971 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6974 orderby t.Value != curTabClass
6975 select new {Tab = t.Value, Index = indexOf};
6978 var post = posts.First();
6979 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6980 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6981 SelectListItem(listView, post.Index);
6982 listView.EnsureVisible(post.Index);
6984 catch (InvalidOperationException)
6991 ReplyChain chainHead = replyChains.Pop();
6992 if (chainHead.InReplyToId == _curPost.StatusId)
6994 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7003 ListTab.SelectTab(chainHead.OriginalTab);
7009 SelectListItem(_curList, idx);
7010 _curList.EnsureVisible(idx);
7016 this.GoBackInReplyToPostTree(parallel);
7022 private void GoBackSelectPostChain()
7024 if (this.selectPostChains.Count > 1)
7033 this.selectPostChains.Pop();
7034 var tabPostPair = this.selectPostChains.Peek();
7036 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7038 if (tabPostPair.Item2 != null)
7040 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7041 if (idx == -1) continue; //該当ポストが存在しないので無視
7044 tp = tabPostPair.Item1;
7046 this.selectPostChains.Pop();
7048 catch (InvalidOperationException)
7054 while (this.selectPostChains.Count > 1);
7059 //履歴が残り1つであればクリアしておく
7060 if (this.selectPostChains.Count == 1)
7061 this.selectPostChains.Clear();
7065 DetailsListView lst = (DetailsListView)tp.Tag;
7066 this.ListTab.SelectedTab = tp;
7069 SelectListItem(lst, idx);
7070 lst.EnsureVisible(idx);
7076 private void PushSelectPostChain()
7078 int count = this.selectPostChains.Count;
7081 var p = this.selectPostChains.Peek();
7082 if (p.Item1 == this._curTab)
7084 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7085 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7088 if (count >= 2500) TrimPostChain();
7089 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7092 private void TrimPostChain()
7094 if (this.selectPostChains.Count <= 2000) return;
7095 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7096 for (int i = 0; i < 2000; i++)
7098 p.Push(this.selectPostChains.Pop());
7100 this.selectPostChains.Clear();
7101 for (int i = 0; i < 2000; i++)
7103 this.selectPostChains.Push(p.Pop());
7107 private bool GoStatus(long statusId)
7109 if (statusId == 0) return false;
7110 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7112 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7114 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7115 ListTab.SelectedIndex = tabidx;
7116 SelectListItem(_curList, idx);
7117 _curList.EnsureVisible(idx);
7124 private bool GoDirectMessage(long statusId)
7126 if (statusId == 0) return false;
7127 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7129 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7131 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7132 ListTab.SelectedIndex = tabidx;
7133 SelectListItem(_curList, idx);
7134 _curList.EnsureVisible(idx);
7141 private void MyList_MouseClick(object sender, MouseEventArgs e)
7143 _anchorFlag = false;
7146 private void StatusText_Enter(object sender, EventArgs e)
7148 // フォーカスの戻り先を StatusText に設定
7149 this.Tag = StatusText;
7150 StatusText.BackColor = _clInputBackcolor;
7153 public Color InputBackColor
7155 get { return _clInputBackcolor; }
7156 set { _clInputBackcolor = value; }
7159 private void StatusText_Leave(object sender, EventArgs e)
7161 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7162 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7163 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7166 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7169 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7172 e.SuppressKeyPress = true;
7175 this.StatusText_TextChanged(null, null);
7177 if (asyncTask != null)
7181 private void SaveConfigsAll(bool ifModified)
7185 SaveConfigsCommon();
7192 if (ModifySettingCommon) SaveConfigsCommon();
7193 if (ModifySettingLocal) SaveConfigsLocal();
7194 if (ModifySettingAtId) SaveConfigsAtId();
7198 private void SaveConfigsAtId()
7200 if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7202 ModifySettingAtId = false;
7203 SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7207 private void SaveConfigsCommon()
7209 if (_ignoreConfigSave) return;
7211 ModifySettingCommon = false;
7214 _cfgCommon.UserName = tw.Username;
7215 _cfgCommon.UserId = tw.UserId;
7216 _cfgCommon.Token = tw.AccessToken;
7217 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7219 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7220 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7222 _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7225 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7226 switch (_statuses.SortMode)
7228 case ComparerMode.Nickname: //ニックネーム
7229 _cfgCommon.SortColumn = 1;
7231 case ComparerMode.Data: //本文
7232 _cfgCommon.SortColumn = 2;
7234 case ComparerMode.Id: //時刻=発言Id
7235 _cfgCommon.SortColumn = 3;
7237 case ComparerMode.Name: //名前
7238 _cfgCommon.SortColumn = 4;
7240 case ComparerMode.Source: //Source
7241 _cfgCommon.SortColumn = 7;
7245 _cfgCommon.HashTags = HashMgr.HashHistories;
7246 if (HashMgr.IsPermanent)
7248 _cfgCommon.HashSelected = HashMgr.UseHash;
7252 _cfgCommon.HashSelected = "";
7254 _cfgCommon.HashIsHead = HashMgr.IsHead;
7255 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7256 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7257 if (ToolStripFocusLockMenuItem != null &&
7258 ToolStripFocusLockMenuItem.IsDisposed == false)
7260 _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7262 _cfgCommon.TrackWord = tw.TrackWord;
7263 _cfgCommon.AllAtReply = tw.AllAtReply;
7264 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7265 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7271 private void SaveConfigsLocal()
7273 if (_ignoreConfigSave) return;
7276 ModifySettingLocal = false;
7277 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7278 _cfgLocal.FormSize = _mySize;
7279 _cfgLocal.FormLocation = _myLoc;
7280 _cfgLocal.SplitterDistance = _mySpDis;
7281 _cfgLocal.PreviewDistance = _mySpDis3;
7282 _cfgLocal.StatusMultiline = StatusText.Multiline;
7283 _cfgLocal.StatusTextHeight = _mySpDis2;
7285 _cfgLocal.FontUnread = _fntUnread;
7286 _cfgLocal.ColorUnread = _clUnread;
7287 _cfgLocal.FontRead = _fntReaded;
7288 _cfgLocal.ColorRead = _clReaded;
7289 _cfgLocal.FontDetail = _fntDetail;
7290 _cfgLocal.ColorDetail = _clDetail;
7291 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7292 _cfgLocal.ColorDetailLink = _clDetailLink;
7293 _cfgLocal.ColorFav = _clFav;
7294 _cfgLocal.ColorOWL = _clOWL;
7295 _cfgLocal.ColorRetweet = _clRetweet;
7296 _cfgLocal.ColorSelf = _clSelf;
7297 _cfgLocal.ColorAtSelf = _clAtSelf;
7298 _cfgLocal.ColorTarget = _clTarget;
7299 _cfgLocal.ColorAtTarget = _clAtTarget;
7300 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7301 _cfgLocal.ColorAtTo = _clAtTo;
7302 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7303 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7304 _cfgLocal.ColorInputFont = _clInputFont;
7305 _cfgLocal.FontInputFont = _fntInputFont;
7307 if (_ignoreConfigSave) return;
7312 private void SaveConfigsTabs()
7314 var tabsSetting = new SettingTabs();
7316 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7317 .Select(x => this._statuses.Tabs[x.Text])
7318 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7320 foreach (var tab in tabs)
7322 if (!tab.IsPermanentTabType)
7325 var tabSetting = new SettingTabs.SettingTabItem
7327 TabName = tab.TabName,
7328 TabType = tab.TabType,
7329 UnreadManage = tab.UnreadManage,
7330 Protected = tab.Protected,
7331 Notify = tab.Notify,
7332 SoundFile = tab.SoundFile,
7335 var filterTab = tab as FilterTabModel;
7336 if (filterTab != null)
7337 tabSetting.FilterArray = filterTab.FilterArray;
7339 var userTab = tab as UserTimelineTabModel;
7340 if (userTab != null)
7341 tabSetting.User = userTab.ScreenName;
7343 var searchTab = tab as PublicSearchTabModel;
7344 if (searchTab != null)
7346 tabSetting.SearchWords = searchTab.SearchWords;
7347 tabSetting.SearchLang = searchTab.SearchLang;
7350 var listTab = tab as ListTimelineTabModel;
7351 if (listTab != null)
7352 tabSetting.ListInfo = listTab.ListInfo;
7354 tabsSetting.Tabs.Add(tabSetting);
7360 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7363 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7364 if (ret != DialogResult.OK)
7367 var match = Twitter.StatusUrlRegex.Match(inputText);
7370 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7371 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7377 var statusId = long.Parse(match.Groups["StatusId"].Value);
7378 await this.OpenRelatedTab(statusId);
7380 catch (TabException ex)
7382 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7386 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7388 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7389 Properties.Resources.SaveLogMenuItem_ClickText2,
7390 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7391 if (rslt == DialogResult.Cancel) return;
7393 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7394 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7395 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7396 SaveFileDialog1.FilterIndex = 0;
7397 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7398 SaveFileDialog1.RestoreDirectory = true;
7400 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7402 if (!SaveFileDialog1.ValidateNames) return;
7403 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7405 if (rslt == DialogResult.Yes)
7408 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7410 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7411 string protect = "";
7412 if (post.IsProtect) protect = "Protect";
7413 sw.WriteLine(post.Nickname + "\t" +
7414 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7415 post.CreatedAt + "\t" +
7416 post.ScreenName + "\t" +
7417 post.StatusId + "\t" +
7418 post.ImageUrl + "\t" +
7419 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7425 foreach (int idx in _curList.SelectedIndices)
7427 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7428 string protect = "";
7429 if (post.IsProtect) protect = "Protect";
7430 sw.WriteLine(post.Nickname + "\t" +
7431 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7432 post.CreatedAt + "\t" +
7433 post.ScreenName + "\t" +
7434 post.StatusId + "\t" +
7435 post.ImageUrl + "\t" +
7436 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7442 this.TopMost = this._cfgCommon.AlwaysTop;
7445 public bool TabRename(string origTabName, out string newTabName)
7449 using (InputTabName inputName = new InputTabName())
7451 inputName.TabName = origTabName;
7452 inputName.ShowDialog();
7453 if (inputName.DialogResult == DialogResult.Cancel) return false;
7454 newTabName = inputName.TabName;
7456 this.TopMost = this._cfgCommon.AlwaysTop;
7457 if (!string.IsNullOrEmpty(newTabName))
7460 for (int i = 0; i < ListTab.TabCount; i++)
7462 if (ListTab.TabPages[i].Text == newTabName)
7464 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7465 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7470 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7471 .First(x => x.Text == origTabName);
7473 ListViewScroll scrollInfo;
7474 if (this.listViewScroll.TryGetValue(origTabName, out scrollInfo))
7476 this.listViewScroll.Remove(origTabName);
7477 this.listViewScroll[newTabName] = scrollInfo;
7480 ListViewSelection selectionInfo;
7481 if (this.listViewSelection.TryGetValue(origTabName, out selectionInfo))
7483 this.listViewSelection.Remove(origTabName);
7484 this.listViewSelection[newTabName] = selectionInfo;
7488 tabPage.Text = newTabName;
7489 _statuses.RenameTab(origTabName, newTabName);
7491 SaveConfigsCommon();
7493 _rclickTabName = newTabName;
7502 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7504 if (e.Button == MouseButtons.Middle)
7506 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7508 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7510 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7511 this.SaveConfigsTabs();
7518 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7521 TabRename(this.ListTab.SelectedTab.Text, out _);
7524 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7526 if (this._cfgCommon.TabMouseLock) return;
7527 if (e.Button == MouseButtons.Left)
7529 for (int i = 0; i < ListTab.TabPages.Count; i++)
7531 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7534 _tabMouseDownPoint = e.Location;
7545 private void ListTab_DragEnter(object sender, DragEventArgs e)
7547 if (e.Data.GetDataPresent(typeof(TabPage)))
7548 e.Effect = DragDropEffects.Move;
7550 e.Effect = DragDropEffects.None;
7553 private void ListTab_DragDrop(object sender, DragEventArgs e)
7555 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7560 Point cpos = new Point(e.X, e.Y);
7561 Point spos = ListTab.PointToClient(cpos);
7563 for (i = 0; i < ListTab.TabPages.Count; i++)
7565 Rectangle rect = ListTab.GetTabRect(i);
7566 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7567 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7569 tn = ListTab.TabPages[i].Text;
7570 if (spos.X <= (rect.Left + rect.Right) / 2)
7579 //タブのないところにドロップ->最後尾へ移動
7580 if (string.IsNullOrEmpty(tn))
7582 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7584 i = ListTab.TabPages.Count - 1;
7587 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7588 if (tp.Text == tn) return;
7590 ReOrderTab(tp.Text, tn, bef);
7593 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7595 var baseIndex = this.GetTabPageIndex(baseTabText);
7596 if (baseIndex == -1)
7599 var targetIndex = this.GetTabPageIndex(targetTabText);
7600 if (targetIndex == -1)
7603 using (ControlTransaction.Layout(this.ListTab))
7605 var mTp = this.ListTab.TabPages[targetIndex];
7606 this.ListTab.TabPages.Remove(mTp);
7608 if (targetIndex < baseIndex)
7611 if (isBeforeBaseTab)
7612 ListTab.TabPages.Insert(baseIndex, mTp);
7614 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7620 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7622 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7623 //isReply:true=@,false=DM
7624 if (!StatusText.Enabled) return;
7625 if (_curList == null) return;
7626 if (_curTab == null) return;
7627 if (!this.ExistCurrentPost) return;
7629 // 複数あてリプライはReplyではなく通常ポスト
7630 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7631 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7632 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7634 if (_curList.SelectedIndices.Count > 0)
7637 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7640 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7643 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7644 StatusText.SelectionStart = StatusText.Text.Length;
7646 this.inReplyTo = null;
7649 if (string.IsNullOrEmpty(StatusText.Text))
7653 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7654 StatusText.Text = "@" + _curPost.ScreenName + " ";
7656 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7657 var inReplyToScreenName = this._curPost.ScreenName;
7658 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7666 //1件選んでEnter or DoubleClick
7667 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7669 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7672 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7673 var inReplyToScreenName = this._curPost.ScreenName;
7674 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7678 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7681 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7684 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7685 this.inReplyTo = null;
7690 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7691 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7692 var inReplyToScreenName = this._curPost.ScreenName;
7693 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7700 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7701 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7702 this.inReplyTo = null;
7707 //1件選んでCtrl-Rの場合(返信先操作せず)
7708 int sidx = StatusText.SelectionStart;
7709 string id = "@" + _curPost.ScreenName + " ";
7712 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7717 StatusText.Text = StatusText.Text.Insert(sidx, id);
7719 //if (StatusText.Text.StartsWith("@"))
7722 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7723 // sidx += 5 + _curPost.ScreenName.Length;
7728 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7729 // sidx += 3 + _curPost.ScreenName.Length;
7731 StatusText.SelectionStart = sidx;
7734 //_reply_to_name = null;
7742 if (!isAuto && !isReply) return;
7744 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7748 //Enter or DoubleClick
7750 string sTxt = StatusText.Text;
7751 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7754 this.inReplyTo = null;
7756 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7758 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7759 if (!sTxt.Contains("@" + post.ScreenName + " "))
7761 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7762 //sTxt = "@" + post.ScreenName + " " + sTxt;
7765 StatusText.Text = sTxt;
7770 if (_curList.SelectedIndices.Count > 1)
7775 int sidx = StatusText.SelectionStart;
7776 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7778 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7779 if (!ids.Contains("@" + post.ScreenName + " ") &&
7780 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7782 ids += "@" + post.ScreenName + " ";
7786 foreach (string nm in post.ReplyToList)
7788 if (!ids.Contains("@" + nm + " ") &&
7789 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7791 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7793 ids += "@" + m.Result("${id}") + " ";
7795 ids += "@" + nm + " ";
7800 if (ids.Length == 0) return;
7801 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7803 StatusText.Text = ". " + StatusText.Text;
7805 this.inReplyTo = null;
7809 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7814 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7816 //if (StatusText.Text.StartsWith("@"))
7818 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7819 // sidx += 2 + ids.Length;
7823 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7824 // sidx += 1 + ids.Length;
7826 StatusText.SelectionStart = sidx;
7832 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7835 int sidx = StatusText.SelectionStart;
7836 PostClass post = _curPost;
7837 if (!ids.Contains("@" + post.ScreenName + " ") &&
7838 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7840 ids += "@" + post.ScreenName + " ";
7842 foreach (string nm in post.ReplyToList)
7844 if (!ids.Contains("@" + nm + " ") &&
7845 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7847 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7849 ids += "@" + m.Result("${id}") + " ";
7851 ids += "@" + nm + " ";
7854 if (!string.IsNullOrEmpty(post.RetweetedBy))
7856 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7857 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7859 ids += "@" + post.RetweetedBy + " ";
7862 if (ids.Length == 0) return;
7863 if (string.IsNullOrEmpty(StatusText.Text))
7866 StatusText.Text = ids;
7867 StatusText.SelectionStart = ids.Length;
7870 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7871 var inReplyToScreenName = this._curPost.ScreenName;
7872 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7878 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7883 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7885 StatusText.SelectionStart = sidx;
7891 StatusText.SelectionStart = StatusText.Text.Length;
7896 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7901 private static int iconCnt = 0;
7902 private static int blinkCnt = 0;
7903 private static bool blink = false;
7904 private static bool idle = false;
7906 private async Task RefreshTasktrayIcon()
7909 await this.Colorize();
7911 if (!TimerRefreshIcon.Enabled) return;
7912 //Static usCheckCnt As int = 0
7914 //Static iconDlListTopItem As ListViewItem = null
7916 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7917 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7919 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7921 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7927 //if (usCheckCnt > 300) //1min
7930 // if (!this.IsReceivedUserStream)
7932 // TraceOut("ReconnectUserStream");
7933 // tw.ReconnectUserStream();
7937 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7939 if (iconCnt >= this.NIconRefresh.Length)
7947 SaveConfigsAll(true);
7952 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7954 _myStatusError = false;
7958 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7959 if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7961 if (blinkCnt > 0) return;
7963 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7965 NotifyIcon1.Icon = ReplyIcon;
7969 NotifyIcon1.Icon = ReplyIconBlink;
7977 //優先度:エラー→オフライン→アイドル
7981 NotifyIcon1.Icon = NIconAtRed;
7984 if (_myStatusOnline)
7986 NotifyIcon1.Icon = NIconAt;
7990 NotifyIcon1.Icon = NIconAtSmoke;
7994 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7997 await this.RefreshTasktrayIcon();
8000 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8002 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8003 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8005 if (ListTab != null && ListTab.SelectedTab != null)
8006 _rclickTabName = ListTab.SelectedTab.Text;
8011 if (_statuses == null) return;
8012 if (_statuses.Tabs == null) return;
8015 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
8018 NotifyDispMenuItem.Checked = tb.Notify;
8019 this.NotifyTbMenuItem.Checked = tb.Notify;
8021 soundfileListup = true;
8022 SoundFileComboBox.Items.Clear();
8023 this.SoundFileTbComboBox.Items.Clear();
8024 SoundFileComboBox.Items.Add("");
8025 this.SoundFileTbComboBox.Items.Add("");
8026 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8027 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8029 oDir = oDir.GetDirectories("Sounds")[0];
8031 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8033 SoundFileComboBox.Items.Add(oFile.Name);
8034 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8036 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8037 if (idx == -1) idx = 0;
8038 SoundFileComboBox.SelectedIndex = idx;
8039 this.SoundFileTbComboBox.SelectedIndex = idx;
8040 soundfileListup = false;
8041 UreadManageMenuItem.Checked = tb.UnreadManage;
8042 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8044 TabMenuControl(_rclickTabName);
8047 private void TabMenuControl(string tabName)
8049 var tabInfo = _statuses.GetTabByName(tabName);
8051 this.FilterEditMenuItem.Enabled = true;
8052 this.EditRuleTbMenuItem.Enabled = true;
8054 if (tabInfo.IsDefaultTabType)
8056 this.ProtectTabMenuItem.Enabled = false;
8057 this.ProtectTbMenuItem.Enabled = false;
8061 this.ProtectTabMenuItem.Enabled = true;
8062 this.ProtectTbMenuItem.Enabled = true;
8065 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8067 this.ProtectTabMenuItem.Checked = true;
8068 this.ProtectTbMenuItem.Checked = true;
8069 this.DeleteTabMenuItem.Enabled = false;
8070 this.DeleteTbMenuItem.Enabled = false;
8074 this.ProtectTabMenuItem.Checked = false;
8075 this.ProtectTbMenuItem.Checked = false;
8076 this.DeleteTabMenuItem.Enabled = true;
8077 this.DeleteTbMenuItem.Enabled = true;
8081 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8083 var checkState = ((ToolStripMenuItem)sender).Checked;
8086 this.ProtectTbMenuItem.Checked = checkState;
8087 this.ProtectTabMenuItem.Checked = checkState;
8090 this.DeleteTabMenuItem.Enabled = !checkState;
8091 this.DeleteTbMenuItem.Enabled = !checkState;
8093 if (string.IsNullOrEmpty(_rclickTabName)) return;
8094 _statuses.Tabs[_rclickTabName].Protected = checkState;
8099 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8101 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8102 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8104 if (string.IsNullOrEmpty(_rclickTabName)) return;
8105 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8110 public void ChangeTabUnreadManage(string tabName, bool isManage)
8112 var idx = this.GetTabPageIndex(tabName);
8116 _statuses.Tabs[tabName].UnreadManage = isManage;
8117 if (this._cfgCommon.TabIconDisp)
8119 if (_statuses.Tabs[tabName].UnreadCount > 0)
8120 ListTab.TabPages[idx].ImageIndex = 0;
8122 ListTab.TabPages[idx].ImageIndex = -1;
8125 if (_curTab.Text == tabName)
8127 this.PurgeListViewItemCache();
8131 SetMainWindowTitle();
8132 SetStatusLabelUrl();
8133 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8136 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8138 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8139 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8141 if (string.IsNullOrEmpty(_rclickTabName)) return;
8143 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8148 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8150 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8152 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8157 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8159 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8161 RemoveSpecifiedTab(_rclickTabName, true);
8165 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8167 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8169 using (var fltDialog = new FilterDialog())
8171 fltDialog.Owner = this;
8172 fltDialog.SetCurrent(_rclickTabName);
8173 fltDialog.ShowDialog(this);
8175 this.TopMost = this._cfgCommon.AlwaysTop;
8177 this.ApplyPostFilters();
8181 private void AddTabMenuItem_Click(object sender, EventArgs e)
8183 string tabName = null;
8184 MyCommon.TabUsageType tabUsage;
8185 using (InputTabName inputName = new InputTabName())
8187 inputName.TabName = _statuses.MakeTabName("MyTab");
8188 inputName.IsShowUsage = true;
8189 inputName.ShowDialog();
8190 if (inputName.DialogResult == DialogResult.Cancel) return;
8191 tabName = inputName.TabName;
8192 tabUsage = inputName.Usage;
8194 this.TopMost = this._cfgCommon.AlwaysTop;
8195 if (!string.IsNullOrEmpty(tabName))
8198 ListElement list = null;
8199 if (tabUsage == MyCommon.TabUsageType.Lists)
8201 using (ListAvailable listAvail = new ListAvailable())
8203 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8204 if (listAvail.SelectedList == null) return;
8205 list = listAvail.SelectedList;
8212 case MyCommon.TabUsageType.UserDefined:
8213 tab = new FilterTabModel(tabName);
8215 case MyCommon.TabUsageType.PublicSearch:
8216 tab = new PublicSearchTabModel(tabName);
8218 case MyCommon.TabUsageType.Lists:
8219 tab = new ListTimelineTabModel(tabName, list);
8225 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8227 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8228 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8234 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8236 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8237 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8239 if (tabUsage == MyCommon.TabUsageType.Lists)
8241 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8242 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8243 this.GetListTimelineAsync(listTab);
8249 private void TabMenuItem_Click(object sender, EventArgs e)
8251 using (var fltDialog = new FilterDialog())
8253 fltDialog.Owner = this;
8256 foreach (int idx in _curList.SelectedIndices)
8260 if (!SelectTab(out tabName)) return;
8262 fltDialog.SetCurrent(tabName);
8263 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8265 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8269 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8271 fltDialog.ShowDialog(this);
8272 this.TopMost = this._cfgCommon.AlwaysTop;
8276 this.ApplyPostFilters();
8278 if (this.ListTab.SelectedTab != null &&
8279 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8281 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8285 protected override bool ProcessDialogKey(Keys keyData)
8287 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8288 if ((keyData & Keys.KeyCode) == Keys.Enter)
8290 if (StatusText.Focused)
8292 bool _NewLine = false;
8295 if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8297 if (StatusText.Multiline)
8299 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8301 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8305 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8309 else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8311 if (StatusText.Multiline)
8313 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8315 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8319 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8325 if (StatusText.Multiline)
8327 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8329 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8330 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8334 if (((keyData & Keys.Shift) == Keys.Shift) ||
8335 (((keyData & Keys.Control) != Keys.Control) &&
8336 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8342 int pos1 = StatusText.SelectionStart;
8343 if (StatusText.SelectionLength > 0)
8345 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8347 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8348 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8353 PostButton_Click(null, null);
8357 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8358 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8359 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8361 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8366 return base.ProcessDialogKey(keyData);
8369 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8371 MakeReplyOrDirectStatus(false, true, true);
8374 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8377 if (_curList.SelectedIndices.Count == 0) return;
8379 var tab = this._statuses.Tabs[this._curTab.Text];
8380 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8381 .Select(x => tab[x])
8382 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8385 this.AddFilterRuleByScreenName(screenNameArray);
8387 if (screenNameArray.Length != 0)
8389 List<string> atids = new List<string>();
8390 foreach (var screenName in screenNameArray)
8392 atids.Add("@" + screenName);
8394 int cnt = AtIdSupl.ItemCount;
8395 AtIdSupl.AddRangeItem(atids.ToArray());
8396 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8400 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8402 if (this._curList.SelectedIndices.Count == 0)
8405 var tab = this._statuses.Tabs[this._curTab.Text];
8406 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8407 .Select(x => tab[x].Source).ToArray();
8409 this.AddFilterRuleBySource(sourceArray);
8412 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8416 if (!SelectTab(out tabName)) return;
8418 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8422 if (tab.TabType != MyCommon.TabUsageType.Mute)
8424 this.MoveOrCopy(out mv, out mk);
8428 // ミュートタブでは常に MoveMatches を true にする
8433 foreach (var screenName in screenNameArray)
8435 tab.AddFilter(new PostFilterRule
8437 FilterName = screenName,
8438 UseNameField = true,
8442 FilterByUrl = false,
8446 this.ApplyPostFilters();
8450 public void AddFilterRuleBySource(params string[] sourceArray)
8452 // タブ選択ダイアログを表示(or追加)
8454 if (!this.SelectTab(out tabName))
8457 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8461 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8463 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8464 this.MoveOrCopy(out mv, out mk);
8468 // ミュートタブでは常に MoveMatches を true にする
8473 // 振り分けルールに追加するSource
8474 foreach (var source in sourceArray)
8476 filterTab.AddFilter(new PostFilterRule
8478 FilterSource = source,
8482 FilterByUrl = false,
8486 this.ApplyPostFilters();
8487 this.SaveConfigsTabs();
8490 private bool SelectTab(out string tabName)
8497 using (var dialog = new TabsDialog(_statuses))
8499 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8501 var selectedTab = dialog.SelectedTab;
8502 tabName = selectedTab == null ? null : selectedTab.TabName;
8505 ListTab.SelectedTab.Focus();
8507 if (tabName == null)
8509 using (InputTabName inputName = new InputTabName())
8511 inputName.TabName = _statuses.MakeTabName("MyTab");
8512 inputName.ShowDialog();
8513 if (inputName.DialogResult == DialogResult.Cancel) return false;
8514 tabName = inputName.TabName;
8516 this.TopMost = this._cfgCommon.AlwaysTop;
8517 if (!string.IsNullOrEmpty(tabName))
8519 var tab = new FilterTabModel(tabName);
8520 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8522 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8523 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8541 private void MoveOrCopy(out bool move, out bool mark)
8545 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8546 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8554 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8555 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8565 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8570 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8575 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8577 if (StatusText.Focused)
8580 StatusText.SelectAll();
8584 // ListView上でのCtrl+A
8585 NativeMethods.SelectAllItems(this._curList);
8589 private void MoveMiddle()
8595 if (_curList.SelectedIndices.Count == 0) return;
8597 int idx = _curList.SelectedIndices[0];
8599 _item = _curList.GetItemAt(0, 25);
8605 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8607 idx2 = _curList.VirtualListSize - 1;
8611 idx -= Math.Abs(idx1 - idx2) / 2;
8612 if (idx < 0) idx = 0;
8614 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8615 _curList.EnsureVisible(idx);
8618 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8620 var linkElements = this.tweetDetailsView.GetLinkElements();
8622 if (linkElements.Length > 0)
8624 UrlDialog.ClearUrl();
8626 string openUrlStr = "";
8628 if (linkElements.Length == 1)
8630 // ツイートに含まれる URL が 1 つのみの場合
8631 // => OpenURL ダイアログを表示せずにリンクを開く
8636 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8638 catch (ArgumentException)
8647 if (string.IsNullOrEmpty(urlStr)) return;
8648 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8650 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8651 await this.OpenUriAsync(new Uri(openUrlStr));
8655 // ツイートに含まれる URL が複数ある場合
8656 // => OpenURL を表示しユーザーが選択したリンクを開く
8658 foreach (var linkElm in linkElements)
8661 string linkText = "";
8665 urlStr = linkElm.GetAttribute("title");
8666 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8667 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8668 linkText = linkElm.InnerText;
8670 catch (ArgumentException)
8679 if (string.IsNullOrEmpty(urlStr)) continue;
8680 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8684 if (UrlDialog.ShowDialog() == DialogResult.OK)
8686 openUrlStr = UrlDialog.SelectedUrl;
8688 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8689 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8696 this.TopMost = this._cfgCommon.AlwaysTop;
8701 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8703 if (string.IsNullOrEmpty(_rclickTabName)) return;
8704 ClearTab(_rclickTabName, true);
8707 private void ClearTab(string tabName, bool showWarning)
8711 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8712 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8718 _statuses.ClearTabIds(tabName);
8719 if (ListTab.SelectedTab.Text == tabName)
8722 _anchorFlag = false;
8723 this.PurgeListViewItemCache();
8727 foreach (TabPage tb in ListTab.TabPages)
8729 if (tb.Text == tabName)
8731 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8736 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8738 SetMainWindowTitle();
8739 SetStatusLabelUrl();
8742 private static long followers = 0;
8744 private void SetMainWindowTitle()
8747 StringBuilder ttl = new StringBuilder(256);
8750 if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
8751 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8752 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8753 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8755 foreach (var tab in _statuses.Tabs.Values)
8757 ur += tab.UnreadCount;
8762 if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
8763 ttl.Append(Application.ProductName);
8765 switch (this._cfgCommon.DispLatestPost)
8767 case MyCommon.DispTitleEnum.Ver:
8768 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8770 case MyCommon.DispTitleEnum.Post:
8771 if (_history != null && _history.Count > 1)
8772 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8774 case MyCommon.DispTitleEnum.UnreadRepCount:
8775 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8777 case MyCommon.DispTitleEnum.UnreadAllCount:
8778 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8780 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8781 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8783 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8784 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8786 case MyCommon.DispTitleEnum.OwnStatus:
8787 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8788 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8794 this.Text = ttl.ToString();
8796 catch (AccessViolationException)
8798 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8802 private string GetStatusLabelText()
8805 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8806 if (_statuses == null) return "";
8807 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8808 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8809 if (tbRep == null || tbDm == null) return "";
8810 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8815 StringBuilder slbl = new StringBuilder(256);
8818 foreach (var tab in _statuses.Tabs.Values)
8820 ur += tab.UnreadCount;
8822 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8824 tur = tab.UnreadCount;
8835 UnreadAtCounter = urat;
8837 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8839 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8840 if (this._cfgCommon.TimelinePeriod == 0)
8842 slbl.Append(Properties.Resources.SetStatusLabelText2);
8846 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8848 return slbl.ToString();
8851 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8855 if (this.InvokeRequired && !this.IsDisposed)
8857 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8861 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8862 SetApiStatusLabel(endpointName);
8865 catch (ObjectDisposedException)
8869 catch (InvalidOperationException)
8875 private void SetApiStatusLabel(string endpointName = null)
8877 if (_curTab == null)
8879 this.toolStripApiGauge.ApiEndpoint = null;
8883 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8885 if (endpointName == null)
8890 case MyCommon.TabUsageType.Home:
8891 case MyCommon.TabUsageType.UserDefined:
8892 endpointName = "/statuses/home_timeline";
8895 case MyCommon.TabUsageType.Mentions:
8896 endpointName = "/statuses/mentions_timeline";
8899 case MyCommon.TabUsageType.Favorites:
8900 endpointName = "/favorites/list";
8903 case MyCommon.TabUsageType.DirectMessage:
8904 endpointName = "/direct_messages";
8907 case MyCommon.TabUsageType.UserTimeline:
8908 endpointName = "/statuses/user_timeline";
8911 case MyCommon.TabUsageType.Lists:
8912 endpointName = "/lists/statuses";
8915 case MyCommon.TabUsageType.PublicSearch:
8916 endpointName = "/search/tweets";
8919 case MyCommon.TabUsageType.Related:
8920 endpointName = "/statuses/show/:id";
8927 this.toolStripApiGauge.ApiEndpoint = endpointName;
8931 // 表示中のタブに関連する endpoint であれば更新
8934 switch (endpointName)
8936 case "/statuses/home_timeline":
8937 update = tabType == MyCommon.TabUsageType.Home ||
8938 tabType == MyCommon.TabUsageType.UserDefined;
8941 case "/statuses/mentions_timeline":
8942 update = tabType == MyCommon.TabUsageType.Mentions;
8945 case "/favorites/list":
8946 update = tabType == MyCommon.TabUsageType.Favorites;
8949 case "/direct_messages:":
8950 update = tabType == MyCommon.TabUsageType.DirectMessage;
8953 case "/statuses/user_timeline":
8954 update = tabType == MyCommon.TabUsageType.UserTimeline;
8957 case "/lists/statuses":
8958 update = tabType == MyCommon.TabUsageType.Lists;
8961 case "/search/tweets":
8962 update = tabType == MyCommon.TabUsageType.PublicSearch;
8965 case "/statuses/show/:id":
8966 update = tabType == MyCommon.TabUsageType.Related;
8975 this.toolStripApiGauge.ApiEndpoint = endpointName;
8981 private void SetStatusLabelUrl()
8983 StatusLabelUrl.Text = GetStatusLabelText();
8986 public void SetStatusLabel(string text)
8988 StatusLabel.Text = text;
8991 private void SetNotifyIconText()
8993 var ur = new StringBuilder(64);
8995 // タスクトレイアイコンのツールチップテキスト書き換え
8997 ur.Remove(0, ur.Length);
8998 if (this._cfgCommon.DispUsername)
9000 ur.Append(tw.Username);
9003 ur.Append(Application.ProductName);
9005 ur.Append("(Debug Build)");
9007 if (UnreadCounter != -1 && UnreadAtCounter != -1)
9010 ur.Append(UnreadCounter);
9012 ur.Append(UnreadAtCounter);
9015 NotifyIcon1.Text = ur.ToString();
9018 internal void CheckReplyTo(string StatusText)
9022 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9024 foreach (Match hm in m)
9026 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9028 hstr += "#" + hm.Result("$3") + " ";
9029 HashSupl.AddItem("#" + hm.Result("$3"));
9032 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9034 hstr += HashMgr.UseHash;
9036 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9038 // 本当にリプライ先指定すべきかどうかの判定
9039 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9041 if (this._cfgCommon.UseAtIdSupplement)
9043 int bCnt = AtIdSupl.ItemCount;
9044 foreach (Match mid in m)
9046 AtIdSupl.AddItem(mid.Result("${id}"));
9048 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9051 // リプライ先ステータスIDの指定がない場合は指定しない
9052 if (this.inReplyTo == null)
9056 // 次の条件を満たす場合に in_reply_to_status_id 指定
9057 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9058 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9059 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9063 var inReplyToScreenName = this.inReplyTo.Item2;
9064 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9066 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9070 foreach (Match mid in m)
9072 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9077 this.inReplyTo = null;
9080 private void TweenMain_Resize(object sender, EventArgs e)
9082 if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9084 this.Visible = false;
9086 if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9088 // 現在の DPI と設定保存時の DPI との比を取得する
9089 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9091 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9092 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9093 this.DesktopLocation = _cfgLocal.FormLocation;
9094 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9097 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9098 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9099 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9101 this.SplitContainer1.SplitterDistance = splitterDistance;
9105 StatusText.Multiline = _cfgLocal.StatusMultiline;
9106 if (StatusText.Multiline)
9108 var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9109 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9110 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9112 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9114 StatusText.Height = statusTextHeight;
9118 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9120 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9124 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9125 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9127 this.SplitContainer3.SplitterDistance = previewDistance;
9130 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9131 this.SplitContainer3.Panel2Collapsed = true;
9133 _initialLayout = false;
9135 if (this.WindowState != FormWindowState.Minimized)
9137 _formWindowState = this.WindowState;
9141 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9143 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9144 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9145 if (PlaySoundMenuItem.Checked)
9147 this._cfgCommon.PlaySound = true;
9151 this._cfgCommon.PlaySound = false;
9153 ModifySettingCommon = true;
9156 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9158 if (this._initialLayout)
9161 int splitterDistance;
9162 switch (this.WindowState)
9164 case FormWindowState.Normal:
9165 splitterDistance = this.SplitContainer1.SplitterDistance;
9167 case FormWindowState.Maximized:
9168 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9169 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9170 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9171 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9177 this._mySpDis = splitterDistance;
9178 this.ModifySettingLocal = true;
9181 private async Task doRepliedStatusOpen()
9183 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9185 if (MyCommon.IsKeyDown(Keys.Shift))
9187 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9190 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9192 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9193 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9197 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9199 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9200 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9201 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9204 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9209 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9211 await this.doRepliedStatusOpen();
9214 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9216 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9217 if (multiline != this.StatusText.Multiline)
9219 this.StatusText.Multiline = multiline;
9220 MultiLineMenuItem.Checked = multiline;
9221 ModifySettingLocal = true;
9225 private void StatusText_MultilineChanged(object sender, EventArgs e)
9227 if (this.StatusText.Multiline)
9228 this.StatusText.ScrollBars = ScrollBars.Vertical;
9230 this.StatusText.ScrollBars = ScrollBars.None;
9232 ModifySettingLocal = true;
9235 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9238 StatusText.Multiline = MultiLineMenuItem.Checked;
9239 _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
9240 if (MultiLineMenuItem.Checked)
9242 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9243 SplitContainer2.SplitterDistance = 0;
9245 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9249 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9251 ModifySettingLocal = true;
9254 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9256 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9257 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9259 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9260 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9261 //Appendix A. Collected ABNF for URI
9262 //http://www.ietf.org/rfc/rfc3986.txt
9266 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9268 if (StatusText.SelectionLength > 0)
9270 string tmp = StatusText.SelectedText;
9271 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9272 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9274 // 文字列が選択されている場合はその文字列について処理
9276 //nico.ms使用、nicovideoにマッチしたら変換
9277 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9279 result = nicoms.Shorten(tmp);
9281 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9283 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9286 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9287 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9288 result = resultUri.AbsoluteUri;
9290 catch (WebApiException e)
9292 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9295 catch (UriFormatException e)
9297 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9306 if (!string.IsNullOrEmpty(result))
9308 urlUndo undotmp = new urlUndo();
9310 StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
9311 StatusText.SelectedText = result;
9314 undotmp.Before = tmp;
9315 undotmp.After = result;
9317 if (urlUndoBuffer == null)
9319 urlUndoBuffer = new List<urlUndo>();
9320 UrlUndoToolStripMenuItem.Enabled = true;
9323 urlUndoBuffer.Add(undotmp);
9329 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9330 @"(?<url>(?<protocol>https?://)" +
9331 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9332 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9333 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9334 // 正規表現にマッチしたURL文字列をtinyurl化
9335 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9337 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9338 string tmp = mt.Result("${url}");
9339 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9340 urlUndo undotmp = new urlUndo();
9343 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9345 //nico.ms使用、nicovideoにマッチしたら変換
9346 if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
9348 result = nicoms.Shorten(tmp);
9350 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9352 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9355 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9356 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9357 result = resultUri.AbsoluteUri;
9359 catch (HttpRequestException e)
9361 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9362 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9363 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9365 this.StatusLabel.Text = Converter_Type + ":" + message;
9368 catch (WebApiException e)
9370 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9373 catch (UriFormatException e)
9375 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9384 if (!string.IsNullOrEmpty(result))
9386 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9387 StatusText.SelectedText = result;
9389 undotmp.Before = mt.Result("${url}");
9390 undotmp.After = result;
9392 if (urlUndoBuffer == null)
9394 urlUndoBuffer = new List<urlUndo>();
9395 UrlUndoToolStripMenuItem.Enabled = true;
9398 urlUndoBuffer.Add(undotmp);
9406 private void doUrlUndo()
9408 if (urlUndoBuffer != null)
9410 string tmp = StatusText.Text;
9411 foreach (urlUndo data in urlUndoBuffer)
9413 tmp = tmp.Replace(data.After, data.Before);
9415 StatusText.Text = tmp;
9416 urlUndoBuffer = null;
9417 UrlUndoToolStripMenuItem.Enabled = false;
9418 StatusText.SelectionStart = 0;
9419 StatusText.SelectionLength = 0;
9423 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9425 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9428 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9430 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9433 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9435 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9438 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9440 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9443 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9445 if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
9447 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
9448 Random rnd = new Random();
9449 // 前回使用した短縮URLサービス以外を選択する
9452 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9454 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9455 await UrlConvertAsync(svc);
9459 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9464 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9466 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9467 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9468 _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
9469 ModifySettingCommon = true;
9472 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9474 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9475 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9476 _cfgCommon.ListLock = ListLockMenuItem.Checked;
9477 ModifySettingCommon = true;
9480 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9482 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9483 MenuStrip1.Tag = new Object();
9484 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9487 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9489 if (this.Tag != null) // 設定された戻り先へ遷移
9491 if (this.Tag == this.ListTab.SelectedTab)
9492 ((Control)this.ListTab.SelectedTab.Tag).Select();
9494 ((Control)this.Tag).Select();
9496 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9498 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9500 this.Tag = ListTab.SelectedTab.Tag;
9501 ((Control)this.Tag).Select();
9504 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9505 MenuStrip1.Tag = null;
9508 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9510 DetailsListView lst = (DetailsListView)sender;
9511 if (_cfgLocal == null) return;
9515 _cfgLocal.Width1 = lst.Columns[0].Width;
9516 _cfgLocal.Width3 = lst.Columns[1].Width;
9520 int[] darr = new int[lst.Columns.Count];
9521 for (int i = 0; i < lst.Columns.Count; i++)
9523 darr[lst.Columns[i].DisplayIndex] = i;
9525 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9527 for (int i = 0; i < lst.Columns.Count; i++)
9532 _cfgLocal.DisplayIndex1 = i;
9535 _cfgLocal.DisplayIndex2 = i;
9538 _cfgLocal.DisplayIndex3 = i;
9541 _cfgLocal.DisplayIndex4 = i;
9544 _cfgLocal.DisplayIndex5 = i;
9547 _cfgLocal.DisplayIndex6 = i;
9550 _cfgLocal.DisplayIndex7 = i;
9553 _cfgLocal.DisplayIndex8 = i;
9557 _cfgLocal.Width1 = lst.Columns[0].Width;
9558 _cfgLocal.Width2 = lst.Columns[1].Width;
9559 _cfgLocal.Width3 = lst.Columns[2].Width;
9560 _cfgLocal.Width4 = lst.Columns[3].Width;
9561 _cfgLocal.Width5 = lst.Columns[4].Width;
9562 _cfgLocal.Width6 = lst.Columns[5].Width;
9563 _cfgLocal.Width7 = lst.Columns[6].Width;
9564 _cfgLocal.Width8 = lst.Columns[7].Width;
9566 ModifySettingLocal = true;
9567 _isColumnChanged = true;
9570 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9572 DetailsListView lst = (DetailsListView)sender;
9573 if (_cfgLocal == null) return;
9576 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9578 _cfgLocal.Width1 = lst.Columns[0].Width;
9579 ModifySettingLocal = true;
9580 _isColumnChanged = true;
9582 if (_cfgLocal.Width3 != lst.Columns[1].Width)
9584 _cfgLocal.Width3 = lst.Columns[1].Width;
9585 ModifySettingLocal = true;
9586 _isColumnChanged = true;
9591 if (_cfgLocal.Width1 != lst.Columns[0].Width)
9593 _cfgLocal.Width1 = lst.Columns[0].Width;
9594 ModifySettingLocal = true;
9595 _isColumnChanged = true;
9597 if (_cfgLocal.Width2 != lst.Columns[1].Width)
9599 _cfgLocal.Width2 = lst.Columns[1].Width;
9600 ModifySettingLocal = true;
9601 _isColumnChanged = true;
9603 if (_cfgLocal.Width3 != lst.Columns[2].Width)
9605 _cfgLocal.Width3 = lst.Columns[2].Width;
9606 ModifySettingLocal = true;
9607 _isColumnChanged = true;
9609 if (_cfgLocal.Width4 != lst.Columns[3].Width)
9611 _cfgLocal.Width4 = lst.Columns[3].Width;
9612 ModifySettingLocal = true;
9613 _isColumnChanged = true;
9615 if (_cfgLocal.Width5 != lst.Columns[4].Width)
9617 _cfgLocal.Width5 = lst.Columns[4].Width;
9618 ModifySettingLocal = true;
9619 _isColumnChanged = true;
9621 if (_cfgLocal.Width6 != lst.Columns[5].Width)
9623 _cfgLocal.Width6 = lst.Columns[5].Width;
9624 ModifySettingLocal = true;
9625 _isColumnChanged = true;
9627 if (_cfgLocal.Width7 != lst.Columns[6].Width)
9629 _cfgLocal.Width7 = lst.Columns[6].Width;
9630 ModifySettingLocal = true;
9631 _isColumnChanged = true;
9633 if (_cfgLocal.Width8 != lst.Columns[7].Width)
9635 _cfgLocal.Width8 = lst.Columns[7].Width;
9636 ModifySettingLocal = true;
9637 _isColumnChanged = true;
9640 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9643 // SaveConfigsLocal();
9647 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9649 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9650 ModifySettingLocal = true;
9653 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9655 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9657 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9659 SelectMedia_DragDrop(e);
9662 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9664 var url = GetUrlFromDataObject(e.Data);
9667 if (url.Item2 == null)
9668 appendText = url.Item1;
9670 appendText = url.Item2 + " " + url.Item1;
9672 if (this.StatusText.TextLength == 0)
9673 this.StatusText.Text = appendText;
9675 this.StatusText.Text += " " + appendText;
9677 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9679 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9681 this.StatusText.Text += text;
9683 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9685 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9686 if (data != null) StatusText.Text += data;
9691 /// IDataObject から URL とタイトルの対を取得します
9694 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9696 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9697 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9698 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9700 if (data.GetDataPresent("text/x-moz-url"))
9702 // Firefox, Google Chrome で利用可能
9703 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9705 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9707 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9708 if (lines.Length < 2)
9709 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9711 return new Tuple<string, string>(lines[0], lines[1]);
9714 else if (data.GetDataPresent("IESiteModeToUrl"))
9716 // Internet Exproler 用
9717 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9719 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9721 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9722 if (lines.Length < 2)
9723 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9725 return new Tuple<string, string>(lines[0], lines[1]);
9728 else if (data.GetDataPresent("UniformResourceLocatorW"))
9732 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9734 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9735 return new Tuple<string, string>(url, null);
9739 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9742 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9744 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9746 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9748 SelectMedia_DragEnter(e);
9752 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9754 e.Effect = DragDropEffects.Copy;
9757 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9759 e.Effect = DragDropEffects.Copy;
9762 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9764 e.Effect = DragDropEffects.Copy;
9768 e.Effect = DragDropEffects.None;
9771 private void TweenMain_DragOver(object sender, DragEventArgs e)
9775 public bool IsNetworkAvailable()
9778 nw = MyCommon.IsNetworkAvailable();
9779 _myStatusOnline = nw;
9783 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9785 var uriStr = uri.AbsoluteUri;
9787 // OpenTween 内部で使用する URL
9788 if (uri.Authority == "opentween")
9790 await this.OpenInternalUriAsync(uri);
9794 // ハッシュタグを含む Twitter 検索
9795 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9798 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9799 var pos = unescapedQuery.IndexOf('#');
9800 if (pos == -1) return;
9802 var hash = unescapedQuery.Substring(pos);
9803 this.HashSupl.AddItem(hash);
9804 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9805 this.AddNewTabForSearch(hash);
9810 // フラグが立っている場合は設定と逆の動作をする
9811 if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
9812 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
9814 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9815 if (userUriMatch.Success)
9817 var screenName = userUriMatch.Groups["ScreenName"].Value;
9818 if (this.IsTwitterId(screenName))
9820 this.AddNewTabForUserTimeline(screenName);
9827 await this.OpenUriInBrowserAsync(uriStr);
9831 /// OpenTween 内部の機能を呼び出すための URL を開きます
9833 private async Task OpenInternalUriAsync(Uri uri)
9835 // ツイートを開く (//opentween/status/:status_id)
9836 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9839 var statusId = long.Parse(match.Groups[1].Value);
9840 await this.OpenRelatedTab(statusId);
9845 public Task OpenUriInBrowserAsync(string UriString)
9847 return Task.Run(() =>
9849 string myPath = UriString;
9853 var configBrowserPath = this._cfgLocal.BrowserPath;
9854 if (!string.IsNullOrEmpty(configBrowserPath))
9856 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9858 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9859 string browserPath = configBrowserPath.Substring(1, sep - 1);
9861 if (sep < configBrowserPath.Length - 1)
9863 arg = configBrowserPath.Substring(sep + 1);
9865 myPath = arg + " " + myPath;
9866 System.Diagnostics.Process.Start(browserPath, myPath);
9870 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9875 System.Diagnostics.Process.Start(myPath);
9880 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9885 private void ListTabSelect(TabPage _tab)
9889 if (this._curList != null)
9891 var beforeSelectedList = this._curList;
9892 var beforeSelectedTabModel = this._statuses.Tabs[this._curTab.Text];
9894 // 発言一覧のスクロール位置・選択状態を退避
9895 this.listViewScroll[beforeSelectedTabModel.TabName] = this.SaveListViewScroll(beforeSelectedList, beforeSelectedTabModel);
9896 this.listViewSelection[beforeSelectedTabModel.TabName] = this.SaveListViewSelection(beforeSelectedList, beforeSelectedTabModel);
9899 this.PurgeListViewItemCache();
9902 _curList = (DetailsListView)_tab.Tag;
9904 var curTabModel = this._statuses.Tabs[this._curTab.Text];
9906 this._curList.VirtualListSize = curTabModel.AllCount;
9909 ListViewScroll scrollInfo;
9910 if (this.listViewScroll.TryGetValue(curTabModel.TabName, out scrollInfo))
9911 this.RestoreListViewScroll(this._curList, curTabModel, scrollInfo);
9914 ListViewSelection selectionInfo;
9915 if (this.listViewSelection.TryGetValue(curTabModel.TabName, out selectionInfo))
9916 this.RestoreListViewSelection(this._curList, curTabModel, selectionInfo);
9918 if (_curList.SelectedIndices.Count > 0)
9920 _curItemIndex = _curList.SelectedIndices[0];
9921 _curPost = GetCurTabPost(_curItemIndex);
9930 _anchorFlag = false;
9934 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9938 for (int i = 0; i < _curList.Columns.Count; i++)
9940 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9945 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9947 ListTabSelect(e.TabPage);
9950 private void SelectListItem(DetailsListView LView, int Index)
9953 Rectangle bnd = new Rectangle();
9955 var item = LView.FocusedItem;
9964 LView.SelectedIndices.Clear();
9966 while (LView.SelectedIndices.Count > 0);
9967 item = LView.Items[Index];
9968 item.Selected = true;
9969 item.Focused = true;
9971 if (flg) LView.Invalidate(bnd);
9974 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9977 Rectangle bnd = new Rectangle();
9979 var item = LView.FocusedItem;
9990 LView.SelectedIndices.Clear();
9992 while (LView.SelectedIndices.Count > 0);
9993 LView.SelectItems(Index);
9995 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9997 LView.SelectionMark = selectionMarkIndex;
9999 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10001 LView.Items[focusedIndex].Focused = true;
10003 else if (Index != null && Index.Length != 0)
10005 LView.Items[Index.Last()].Focused = true;
10008 if (flg) LView.Invalidate(bnd);
10011 private void StartUserStream()
10013 tw.NewPostFromStream += tw_NewPostFromStream;
10014 tw.UserStreamStarted += tw_UserStreamStarted;
10015 tw.UserStreamStopped += tw_UserStreamStopped;
10016 tw.PostDeleted += tw_PostDeleted;
10017 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10019 this.RefreshUserStreamsMenu();
10021 if (this._cfgCommon.UserstreamStartup)
10022 tw.StartUserStream();
10025 private async void TweenMain_Shown(object sender, EventArgs e)
10027 NotifyIcon1.Visible = true;
10029 if (this.IsNetworkAvailable())
10033 var loadTasks = new List<Task>
10035 this.RefreshMuteUserIdsAsync(),
10036 this.RefreshBlockIdsAsync(),
10037 this.RefreshNoRetweetIdsAsync(),
10038 this.RefreshTwitterConfigurationAsync(),
10039 this.GetHomeTimelineAsync(),
10040 this.GetReplyAsync(),
10041 this.GetDirectMessagesAsync(),
10042 this.GetPublicSearchAllAsync(),
10043 this.GetUserTimelineAllAsync(),
10044 this.GetListTimelineAllAsync(),
10047 if (this._cfgCommon.StartupFollowers)
10048 loadTasks.Add(this.RefreshFollowerIdsAsync());
10050 if (this._cfgCommon.GetFav)
10051 loadTasks.Add(this.GetFavoritesAsync());
10053 var allTasks = Task.WhenAll(loadTasks);
10058 var timeout = Task.Delay(5000);
10059 if (await Task.WhenAny(allTasks, timeout) != timeout)
10063 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10065 if (MyCommon._endingFlag)
10069 if (MyCommon._endingFlag) return;
10071 if (ApplicationSettings.VersionInfoUrl != null)
10073 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10074 if (this._cfgCommon.StartupVersion)
10075 await this.CheckNewVersion(true);
10079 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10080 this.VerUpMenuItem.Enabled = false;
10081 this.VerUpMenuItem.Available = false;
10082 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10085 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10086 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10088 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10089 SettingStripMenuItem_Click(null, null);
10093 var reloadTasks = new List<Task>();
10095 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
10096 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10098 if (!tw.GetNoRetweetSuccess)
10099 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10101 if (this.tw.Configuration.PhotoSizeLimit == 0)
10102 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10104 await Task.WhenAll(reloadTasks);
10109 TimerTimeline.Enabled = true;
10112 private async Task doGetFollowersMenu()
10114 await this.RefreshFollowerIdsAsync();
10115 await this.DispSelectedPost(true);
10118 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10120 await this.doGetFollowersMenu();
10123 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10125 doReTweetUnofficial();
10128 private async Task doReTweetOfficial(bool isConfirm)
10131 if (this.ExistCurrentPost)
10133 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10135 if (this._curPost.IsProtect)
10136 MessageBox.Show("Protected.");
10138 _DoFavRetweetFlags = false;
10141 if (_curList.SelectedIndices.Count > 15)
10143 MessageBox.Show(Properties.Resources.RetweetLimitText);
10144 _DoFavRetweetFlags = false;
10147 else if (_curList.SelectedIndices.Count > 1)
10149 string QuestionText = Properties.Resources.RetweetQuestion2;
10150 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10151 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10153 case DialogResult.Cancel:
10154 case DialogResult.No:
10155 _DoFavRetweetFlags = false;
10161 if (!this._cfgCommon.RetweetNoConfirm)
10163 string Questiontext = Properties.Resources.RetweetQuestion1;
10164 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10165 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10167 _DoFavRetweetFlags = false;
10173 var statusIds = new List<long>();
10174 foreach (int idx in _curList.SelectedIndices)
10176 PostClass post = GetCurTabPost(idx);
10177 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10178 statusIds.Add(post.StatusId);
10181 await this.RetweetAsync(statusIds);
10185 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10187 await this.doReTweetOfficial(true);
10190 private async Task FavoritesRetweetOfficial()
10192 if (!this.ExistCurrentPost) return;
10193 _DoFavRetweetFlags = true;
10194 var retweetTask = this.doReTweetOfficial(true);
10195 if (_DoFavRetweetFlags)
10197 _DoFavRetweetFlags = false;
10198 var favoriteTask = this.FavoriteChange(true, false);
10200 await Task.WhenAll(retweetTask, favoriteTask);
10208 private async Task FavoritesRetweetUnofficial()
10210 if (this.ExistCurrentPost && !_curPost.IsDm)
10212 _DoFavRetweetFlags = true;
10213 var favoriteTask = this.FavoriteChange(true);
10214 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10216 _DoFavRetweetFlags = false;
10217 doReTweetUnofficial();
10220 await favoriteTask;
10225 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10227 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10228 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10229 /// <returns>復元されたツイート本文</returns>
10230 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10232 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10235 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10237 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10239 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10243 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10245 statusHtml = statusHtml.Replace("<br>", " ");
10247 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10248 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10249 statusHtml = statusHtml.Replace(" ", " ");
10251 return WebUtility.HtmlDecode(statusHtml);
10254 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10256 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10258 if (_curPost != null)
10259 await this.DispSelectedPost(true);
10262 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10264 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10265 DebugModeToolStripMenuItem.Visible = true;
10267 DebugModeToolStripMenuItem.Visible = false;
10270 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10272 this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10275 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10277 ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
10280 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10282 if (TraceOutToolStripMenuItem.Checked)
10283 MyCommon.TraceFlag = true;
10285 MyCommon.TraceFlag = false;
10288 private void TweenMain_Deactivate(object sender, EventArgs e)
10290 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10291 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10294 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10296 if (string.IsNullOrEmpty(_rclickTabName)) return;
10299 TabRename(_rclickTabName, out _);
10302 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10304 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10307 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10309 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10312 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10314 TwitterApiStatus apiStatus;
10316 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10318 var cancellationToken = dialog.EnableCancellation();
10322 var task = this.tw.GetInfoApi();
10323 apiStatus = await dialog.WaitForAsync(this, task);
10325 catch (WebApiException)
10330 if (cancellationToken.IsCancellationRequested)
10333 if (apiStatus == null)
10335 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10340 using (var apiDlg = new ApiInfoDialog())
10342 apiDlg.ShowDialog(this);
10346 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10348 var id = _curPost?.ScreenName ?? "";
10350 await this.FollowCommand(id);
10353 internal async Task FollowCommand(string id)
10355 using (var inputName = new InputTabName())
10357 inputName.FormTitle = "Follow";
10358 inputName.FormDescription = Properties.Resources.FRMessage1;
10359 inputName.TabName = id;
10361 if (inputName.ShowDialog(this) != DialogResult.OK)
10363 if (string.IsNullOrWhiteSpace(inputName.TabName))
10366 id = inputName.TabName.Trim();
10369 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10373 var task = this.twitterApi.FriendshipsCreate(id);
10374 await dialog.WaitForAsync(this, task);
10376 catch (WebApiException ex)
10378 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10383 MessageBox.Show(Properties.Resources.FRMessage3);
10386 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10388 var id = _curPost?.ScreenName ?? "";
10390 await this.RemoveCommand(id, false);
10393 internal async Task RemoveCommand(string id, bool skipInput)
10397 using (var inputName = new InputTabName())
10399 inputName.FormTitle = "Unfollow";
10400 inputName.FormDescription = Properties.Resources.FRMessage1;
10401 inputName.TabName = id;
10403 if (inputName.ShowDialog(this) != DialogResult.OK)
10405 if (string.IsNullOrWhiteSpace(inputName.TabName))
10408 id = inputName.TabName.Trim();
10412 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10416 var task = this.twitterApi.FriendshipsDestroy(id);
10417 await dialog.WaitForAsync(this, task);
10419 catch (WebApiException ex)
10421 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10426 MessageBox.Show(Properties.Resources.FRMessage3);
10429 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10431 var id = _curPost?.ScreenName ?? "";
10433 await this.ShowFriendship(id);
10436 internal async Task ShowFriendship(string id)
10438 using (var inputName = new InputTabName())
10440 inputName.FormTitle = "Show Friendships";
10441 inputName.FormDescription = Properties.Resources.FRMessage1;
10442 inputName.TabName = id;
10444 if (inputName.ShowDialog(this) != DialogResult.OK)
10446 if (string.IsNullOrWhiteSpace(inputName.TabName))
10449 id = inputName.TabName.Trim();
10452 bool isFollowing, isFollowed;
10454 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10456 var cancellationToken = dialog.EnableCancellation();
10460 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10461 var friendship = await dialog.WaitForAsync(this, task);
10463 isFollowing = friendship.Relationship.Source.Following;
10464 isFollowed = friendship.Relationship.Source.FollowedBy;
10466 catch (WebApiException ex)
10468 if (!cancellationToken.IsCancellationRequested)
10469 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10473 if (cancellationToken.IsCancellationRequested)
10477 string result = "";
10480 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10484 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10488 result += Properties.Resources.GetFriendshipInfo3;
10492 result += Properties.Resources.GetFriendshipInfo4;
10494 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10495 MessageBox.Show(result);
10498 internal async Task ShowFriendship(string[] ids)
10500 foreach (string id in ids)
10502 bool isFollowing, isFollowed;
10504 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10506 var cancellationToken = dialog.EnableCancellation();
10510 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10511 var friendship = await dialog.WaitForAsync(this, task);
10513 isFollowing = friendship.Relationship.Source.Following;
10514 isFollowed = friendship.Relationship.Source.FollowedBy;
10516 catch (WebApiException ex)
10518 if (!cancellationToken.IsCancellationRequested)
10519 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10523 if (cancellationToken.IsCancellationRequested)
10527 string result = "";
10533 ff += Properties.Resources.GetFriendshipInfo1;
10537 ff += Properties.Resources.GetFriendshipInfo2;
10540 ff += System.Environment.NewLine + " ";
10543 ff += Properties.Resources.GetFriendshipInfo3;
10547 ff += Properties.Resources.GetFriendshipInfo4;
10549 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10552 if (MessageBox.Show(
10553 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10554 MessageBoxButtons.YesNo,
10555 MessageBoxIcon.Question,
10556 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10558 await this.RemoveCommand(id, true);
10563 MessageBox.Show(result);
10568 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10570 await this.doShowUserStatus(tw.Username, false);
10571 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10573 // doShowUserStatus(tw.Username, false);
10577 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10582 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10583 // URLから切り出した文字列を渡す
10585 public bool IsTwitterId(string name)
10587 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10588 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10590 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10593 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10595 ModifySettingCommon = true;
10598 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10600 ModifySettingCommon = true;
10603 private void doQuoteOfficial()
10605 if (this.ExistCurrentPost)
10607 if (_curPost.IsDm ||
10608 !StatusText.Enabled) return;
10610 if (_curPost.IsProtect)
10612 MessageBox.Show("Protected.");
10616 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10618 this.inReplyTo = null;
10620 StatusText.SelectionStart = 0;
10621 StatusText.Focus();
10625 private void doReTweetUnofficial()
10628 if (this.ExistCurrentPost)
10630 if (_curPost.IsDm || !StatusText.Enabled)
10633 if (_curPost.IsProtect)
10635 MessageBox.Show("Protected.");
10638 string rtdata = _curPost.Text;
10639 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10641 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10643 // 投稿時に in_reply_to_status_id を付加する
10644 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10645 var inReplyToScreenName = this._curPost.ScreenName;
10646 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10648 StatusText.SelectionStart = 0;
10649 StatusText.Focus();
10653 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10658 private void SearchButton_Click(object sender, EventArgs e)
10661 Control pnl = ((Control)sender).Parent;
10662 if (pnl == null) return;
10663 string tbName = pnl.Parent.Text;
10664 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10665 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10666 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10667 cmb.Text = cmb.Text.Trim();
10668 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10669 bool Quote = false;
10670 StringBuilder buf = new StringBuilder();
10671 char[] c = cmb.Text.ToCharArray();
10672 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10674 if (cnt > cmb.Text.Length - 4)
10676 buf.Append(cmb.Text.Substring(cnt));
10685 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10687 buf.Append(" OR ");
10692 buf.Append(c[cnt]);
10694 cmb.Text = buf.ToString();
10696 var listView = (DetailsListView)pnl.Parent.Tag;
10698 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10700 tb.SearchWords = cmb.Text;
10701 tb.SearchLang = cmbLang.Text;
10702 if (string.IsNullOrEmpty(cmb.Text))
10710 int idx = cmb.Items.IndexOf(tb.SearchWords);
10711 if (idx > -1) cmb.Items.RemoveAt(idx);
10712 cmb.Items.Insert(0, tb.SearchWords);
10713 cmb.Text = tb.SearchWords;
10715 this.PurgeListViewItemCache();
10716 listView.VirtualListSize = 0;
10717 _statuses.ClearTabIds(tbName);
10718 SaveConfigsTabs(); //検索条件の保存
10721 this.GetPublicSearchAsync(tb);
10725 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10728 await this.DoRefreshMore();
10732 /// 指定されたタブのListTabにおける位置を返します
10735 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10737 public int GetTabPageIndex(string tabName)
10740 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10742 if (tabPage.Text == tabName)
10751 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10753 if (_statuses.RemovedTab.Count == 0)
10755 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10760 DetailsListView listView = null;
10762 TabModel tb = _statuses.RemovedTab.Pop();
10763 if (tb.TabType == MyCommon.TabUsageType.Related)
10765 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10766 if (relatedTab != null)
10768 // 関連発言なら既存のタブを置き換える
10769 tb.TabName = relatedTab.TabName;
10770 this.ClearTab(tb.TabName, false);
10771 _statuses.Tabs[tb.TabName] = tb;
10773 for (int i = 0; i < ListTab.TabPages.Count; i++)
10775 var tabPage = ListTab.TabPages[i];
10776 if (tb.TabName == tabPage.Text)
10778 listView = (DetailsListView)tabPage.Tag;
10779 ListTab.SelectedIndex = i;
10786 const string TabName = "Related Tweets";
10787 string renamed = TabName;
10788 for (int i = 2; i <= 100; i++)
10790 if (!_statuses.ContainsTab(renamed)) break;
10791 renamed = TabName + i;
10793 tb.TabName = renamed;
10795 _statuses.AddTab(tb);
10796 AddNewTab(tb, startup: false);
10798 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10799 listView = (DetailsListView)tabPage.Tag;
10800 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10805 string renamed = tb.TabName;
10806 for (int i = 1; i < int.MaxValue; i++)
10808 if (!_statuses.ContainsTab(renamed)) break;
10809 renamed = tb.TabName + "(" + i + ")";
10811 tb.TabName = renamed;
10813 _statuses.AddTab(tb);
10814 AddNewTab(tb, startup: false);
10816 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10817 listView = (DetailsListView)tabPage.Tag;
10818 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10822 if (listView != null)
10824 using (ControlTransaction.Update(listView))
10826 listView.VirtualListSize = tb.AllCount;
10832 private async Task doMoveToRTHome()
10834 if (_curList.SelectedIndices.Count > 0)
10836 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10837 if (post.RetweetedId != null)
10839 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10844 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10846 await this.doMoveToRTHome();
10849 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10851 var screenName = this._curPost?.ScreenName;
10852 if (screenName != null)
10853 this.ListManageUserContext(screenName);
10856 public void ListManageUserContext(string screenName)
10858 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10860 listSelectForm.ShowDialog(this);
10864 private void SearchControls_Enter(object sender, EventArgs e)
10866 Control pnl = (Control)sender;
10867 foreach (Control ctl in pnl.Controls)
10869 ctl.TabStop = true;
10873 private void SearchControls_Leave(object sender, EventArgs e)
10875 Control pnl = (Control)sender;
10876 foreach (Control ctl in pnl.Controls)
10878 ctl.TabStop = false;
10882 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10884 if (ListTab.SelectedTab != null)
10886 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10887 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10891 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10893 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10896 private void HashManageMenuItem_Click(object sender, EventArgs e)
10898 DialogResult rslt = DialogResult.Cancel;
10901 rslt = HashMgr.ShowDialog();
10907 this.TopMost = this._cfgCommon.AlwaysTop;
10908 if (rslt == DialogResult.Cancel) return;
10909 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10911 HashStripSplitButton.Text = HashMgr.UseHash;
10912 HashToggleMenuItem.Checked = true;
10913 HashToggleToolStripMenuItem.Checked = true;
10917 HashStripSplitButton.Text = "#[-]";
10918 HashToggleMenuItem.Checked = false;
10919 HashToggleToolStripMenuItem.Checked = false;
10921 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10923 // int sidx = StatusText.SelectionStart;
10924 // string hash = HashMgr.UseHash + " ";
10927 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10928 // hash = " " + hash;
10930 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10931 // sidx += hash.Length;
10932 // StatusText.SelectionStart = sidx;
10933 // StatusText.Focus();
10935 ModifySettingCommon = true;
10936 this.StatusText_TextChanged(null, null);
10939 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10941 HashMgr.ToggleHash();
10942 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10944 HashStripSplitButton.Text = HashMgr.UseHash;
10945 HashToggleMenuItem.Checked = true;
10946 HashToggleToolStripMenuItem.Checked = true;
10950 HashStripSplitButton.Text = "#[-]";
10951 HashToggleMenuItem.Checked = false;
10952 HashToggleToolStripMenuItem.Checked = false;
10954 ModifySettingCommon = true;
10955 this.StatusText_TextChanged(null, null);
10958 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10960 HashToggleMenuItem_Click(null, null);
10963 public void SetPermanentHashtag(string hashtag)
10965 HashMgr.SetPermanentHash("#" + hashtag);
10966 HashStripSplitButton.Text = HashMgr.UseHash;
10967 HashToggleMenuItem.Checked = true;
10968 HashToggleToolStripMenuItem.Checked = true;
10970 ModifySettingCommon = true;
10973 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10975 if (ListTab.SelectedTab == null) return;
10976 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10977 if (!this.ExistCurrentPost)
10979 this.ReplyOpMenuItem.Enabled = false;
10980 this.ReplyAllOpMenuItem.Enabled = false;
10981 this.DmOpMenuItem.Enabled = false;
10982 this.ShowProfMenuItem.Enabled = false;
10983 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10984 this.ListManageMenuItem.Enabled = false;
10985 this.OpenFavOpMenuItem.Enabled = false;
10986 this.CreateTabRuleOpMenuItem.Enabled = false;
10987 this.CreateIdRuleOpMenuItem.Enabled = false;
10988 this.CreateSourceRuleOpMenuItem.Enabled = false;
10989 this.ReadOpMenuItem.Enabled = false;
10990 this.UnreadOpMenuItem.Enabled = false;
10994 this.ReplyOpMenuItem.Enabled = true;
10995 this.ReplyAllOpMenuItem.Enabled = true;
10996 this.DmOpMenuItem.Enabled = true;
10997 this.ShowProfMenuItem.Enabled = true;
10998 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10999 this.ListManageMenuItem.Enabled = true;
11000 this.OpenFavOpMenuItem.Enabled = true;
11001 this.CreateTabRuleOpMenuItem.Enabled = true;
11002 this.CreateIdRuleOpMenuItem.Enabled = true;
11003 this.CreateSourceRuleOpMenuItem.Enabled = true;
11004 this.ReadOpMenuItem.Enabled = true;
11005 this.UnreadOpMenuItem.Enabled = true;
11008 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
11010 this.FavOpMenuItem.Enabled = false;
11011 this.UnFavOpMenuItem.Enabled = false;
11012 this.OpenStatusOpMenuItem.Enabled = false;
11013 this.OpenFavotterOpMenuItem.Enabled = false;
11014 this.ShowRelatedStatusesMenuItem2.Enabled = false;
11015 this.RtOpMenuItem.Enabled = false;
11016 this.RtUnOpMenuItem.Enabled = false;
11017 this.QtOpMenuItem.Enabled = false;
11018 this.FavoriteRetweetMenuItem.Enabled = false;
11019 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11023 this.FavOpMenuItem.Enabled = true;
11024 this.UnFavOpMenuItem.Enabled = true;
11025 this.OpenStatusOpMenuItem.Enabled = true;
11026 this.OpenFavotterOpMenuItem.Enabled = true;
11027 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
11029 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11031 this.RtOpMenuItem.Enabled = false;
11032 this.RtUnOpMenuItem.Enabled = false;
11033 this.QtOpMenuItem.Enabled = false;
11034 this.FavoriteRetweetMenuItem.Enabled = false;
11035 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11039 this.RtOpMenuItem.Enabled = true;
11040 this.RtUnOpMenuItem.Enabled = true;
11041 this.QtOpMenuItem.Enabled = true;
11042 this.FavoriteRetweetMenuItem.Enabled = true;
11043 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11047 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11049 this.RefreshPrevOpMenuItem.Enabled = true;
11053 this.RefreshPrevOpMenuItem.Enabled = false;
11055 if (!this.ExistCurrentPost
11056 || _curPost.InReplyToStatusId == null)
11058 OpenRepSourceOpMenuItem.Enabled = false;
11062 OpenRepSourceOpMenuItem.Enabled = true;
11064 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11066 OpenRterHomeMenuItem.Enabled = false;
11070 OpenRterHomeMenuItem.Enabled = true;
11073 if (this.ExistCurrentPost)
11075 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11079 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11081 ContextMenuTabProperty_Opening(sender, null);
11084 public Twitter TwitterInstance
11089 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11091 if (this._initialLayout)
11094 int splitterDistance;
11095 switch (this.WindowState)
11097 case FormWindowState.Normal:
11098 splitterDistance = this.SplitContainer3.SplitterDistance;
11100 case FormWindowState.Maximized:
11101 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11102 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11103 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11104 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11110 this._mySpDis3 = splitterDistance;
11111 this.ModifySettingLocal = true;
11114 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11116 if (_statuses.RemovedTab.Count == 0)
11118 UndoRemoveTabMenuItem.Enabled = false;
11122 UndoRemoveTabMenuItem.Enabled = true;
11124 if (ListTab.SelectedTab != null)
11126 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11127 PublicSearchQueryMenuItem.Enabled = true;
11129 PublicSearchQueryMenuItem.Enabled = false;
11133 PublicSearchQueryMenuItem.Enabled = false;
11135 if (!this.ExistCurrentPost)
11137 this.CopySTOTMenuItem.Enabled = false;
11138 this.CopyURLMenuItem.Enabled = false;
11139 this.CopyUserIdStripMenuItem.Enabled = false;
11143 this.CopySTOTMenuItem.Enabled = true;
11144 this.CopyURLMenuItem.Enabled = true;
11145 this.CopyUserIdStripMenuItem.Enabled = true;
11146 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11147 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11151 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11153 SetNotifyIconText();
11156 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11158 var id = _curPost?.ScreenName ?? "";
11160 await this.ShowUserStatus(id);
11163 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11165 TwitterUser user = null;
11167 if (ShowInputDialog)
11169 using (var inputName = new InputTabName())
11171 inputName.FormTitle = "Show UserStatus";
11172 inputName.FormDescription = Properties.Resources.FRMessage1;
11173 inputName.TabName = id;
11175 if (inputName.ShowDialog(this) != DialogResult.OK)
11177 if (string.IsNullOrWhiteSpace(inputName.TabName))
11180 id = inputName.TabName.Trim();
11184 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11186 var cancellationToken = dialog.EnableCancellation();
11190 var task = this.twitterApi.UsersShow(id);
11191 user = await dialog.WaitForAsync(this, task);
11193 catch (WebApiException ex)
11195 if (!cancellationToken.IsCancellationRequested)
11196 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11200 if (cancellationToken.IsCancellationRequested)
11204 await this.doShowUserStatus(user);
11207 private async Task doShowUserStatus(TwitterUser user)
11209 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11211 var showUserTask = userDialog.ShowUserAsync(user);
11212 userDialog.ShowDialog(this);
11215 this.BringToFront();
11217 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11218 await showUserTask;
11222 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11224 return this.doShowUserStatus(id, ShowInputDialog);
11227 internal Task ShowUserStatus(string id)
11229 return this.doShowUserStatus(id, true);
11232 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11234 if (_curPost != null)
11236 await this.ShowUserStatus(_curPost.ScreenName, false);
11240 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11242 if (!this.ExistCurrentPost)
11245 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11246 TwitterStatus status;
11248 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11250 var cancellationToken = dialog.EnableCancellation();
11254 var task = this.twitterApi.StatusesShow(statusId);
11255 status = await dialog.WaitForAsync(this, task);
11257 catch (WebApiException ex)
11259 if (!cancellationToken.IsCancellationRequested)
11260 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11264 if (cancellationToken.IsCancellationRequested)
11268 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11271 private HookGlobalHotkey _hookGlobalHotkey;
11274 _hookGlobalHotkey = new HookGlobalHotkey(this);
11276 // この呼び出しは、Windows フォーム デザイナで必要です。
11277 InitializeComponent();
11279 // InitializeComponent() 呼び出しの後で初期化を追加します。
11281 if (!this.DesignMode)
11283 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11284 this.StatusText.Dock = DockStyle.Fill;
11287 this.tweetDetailsView.Owner = this;
11289 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11290 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11291 this.gh.NotifyClicked += GrowlHelper_Callback;
11293 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11294 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11296 this.ImageSelector.Visible = false;
11297 this.ImageSelector.Enabled = false;
11298 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11300 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11302 this.ReplaceAppName();
11303 this.InitializeShortcuts();
11306 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11308 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11311 this.Visible = false;
11313 else if (Form.ActiveForm == null)
11315 this.Visible = true;
11316 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11318 this.BringToFront();
11319 this.StatusText.Focus();
11323 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11325 this.MultiLineMenuItem.PerformClick();
11328 public PostClass CurPost
11330 get { return _curPost; }
11334 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11336 if (ImageSelector.Visible)
11337 ImageSelector.EndSelection();
11339 ImageSelector.BeginSelection();
11342 private void SelectMedia_DragEnter(DragEventArgs e)
11344 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11346 e.Effect = DragDropEffects.Copy;
11349 e.Effect = DragDropEffects.None;
11352 private void SelectMedia_DragDrop(DragEventArgs e)
11355 this.BringToFront();
11356 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11357 StatusText.Focus();
11360 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11362 TimelinePanel.Visible = false;
11363 TimelinePanel.Enabled = false;
11366 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11368 TimelinePanel.Visible = true;
11369 TimelinePanel.Enabled = true;
11370 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11373 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11375 this.AllowDrop = false;
11378 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11380 this.AllowDrop = true;
11383 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11385 if (ImageSelector.Visible)
11387 ModifySettingCommon = true;
11388 SaveConfigsAll(true);
11390 this.StatusText_TextChanged(null, null);
11394 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11396 this.StatusText_TextChanged(null, null);
11400 /// StatusTextでCtrl+Vが押下された時の処理
11402 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11406 if (Clipboard.ContainsText())
11408 // clipboardにテキストがある場合は貼り付け処理
11409 this.StatusText.Paste(Clipboard.GetText());
11411 else if (Clipboard.ContainsImage())
11414 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11415 Properties.Resources.PostPictureWarn4,
11416 MessageBoxButtons.OKCancel,
11417 MessageBoxIcon.Question,
11418 MessageBoxDefaultButton.Button2)
11419 == DialogResult.OK)
11421 // clipboardから画像を取得
11422 using (var image = Clipboard.GetImage())
11424 this.ImageSelector.BeginSelection(image);
11429 catch (ExternalException ex)
11431 MessageBox.Show(ex.Message);
11436 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11438 using (ListManage form = new ListManage(tw))
11440 form.ShowDialog(this);
11444 public bool ModifySettingCommon { get; set; }
11445 public bool ModifySettingLocal { get; set; }
11446 public bool ModifySettingAtId { get; set; }
11448 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11450 if (this.ExistCurrentPost && !_curPost.IsDm)
11451 RtCountMenuItem.Enabled = true;
11453 RtCountMenuItem.Enabled = false;
11455 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11456 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11458 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11461 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11466 private void CopyUserId()
11468 if (_curPost == null) return;
11469 string clstr = _curPost.ScreenName;
11472 Clipboard.SetDataObject(clstr, false, 5, 100);
11474 catch (Exception ex)
11476 MessageBox.Show(ex.Message);
11480 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11482 if (this.ExistCurrentPost && !_curPost.IsDm)
11486 await this.OpenRelatedTab(this._curPost);
11488 catch (TabException ex)
11490 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11496 /// 指定されたツイートに対する関連発言タブを開きます
11498 /// <param name="statusId">表示するツイートのID</param>
11499 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11500 private async Task OpenRelatedTab(long statusId)
11502 var post = this._statuses[statusId];
11507 post = await this.tw.GetStatusApi(false, statusId);
11509 catch (WebApiException ex)
11511 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11516 await this.OpenRelatedTab(post);
11520 /// 指定されたツイートに対する関連発言タブを開きます
11522 /// <param name="post">表示する対象となるツイート</param>
11523 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11524 private async Task OpenRelatedTab(PostClass post)
11526 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11527 if (tabRelated != null)
11529 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11532 var tabName = this._statuses.MakeTabName("Related Tweets");
11534 tabRelated = new RelatedPostsTabModel(tabName, post);
11535 tabRelated.UnreadManage = false;
11536 tabRelated.Notify = false;
11538 this._statuses.AddTab(tabRelated);
11539 this.AddNewTab(tabRelated, startup: false);
11542 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11544 tabPage = this.ListTab.TabPages[i];
11545 if (tabName == tabPage.Text)
11547 this.ListTab.SelectedIndex = i;
11552 await this.GetRelatedTweetsAsync(tabRelated);
11554 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11555 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11557 if (tabPage != null)
11559 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11561 var listView = (DetailsListView)tabPage.Tag;
11562 var targetPost = tabRelated.TargetPost;
11563 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11565 if (index != -1 && index < listView.Items.Count)
11567 listView.SelectedIndices.Add(index);
11568 listView.Items[index].Focused = true;
11573 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11575 StringBuilder buf = new StringBuilder();
11576 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11577 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11578 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11579 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11580 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11583 private void tw_UserIdChanged()
11585 this.ModifySettingCommon = true;
11588 #region "Userstream"
11589 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11593 if (InvokeRequired && !IsDisposed)
11595 await this.InvokeAsync(async () =>
11597 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11598 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11600 this.PurgeListViewItemCache();
11601 ((DetailsListView)_curTab.Tag).Update();
11602 if (_curPost != null && _curPost.StatusId == e.StatusId)
11603 await this.DispSelectedPost(true);
11609 catch (ObjectDisposedException)
11613 catch (InvalidOperationException)
11619 private int userStreamsRefreshing = 0;
11621 private async void tw_NewPostFromStream(object sender, EventArgs e)
11623 if (this._cfgCommon.ReadOldPosts)
11625 _statuses.SetReadHomeTab(); //新着時未読クリア
11628 this._statuses.DistributePosts();
11630 if (this._cfgCommon.UserstreamPeriod > 0) return;
11632 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11633 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11637 await this.InvokeAsync(() => this.RefreshTimeline())
11638 .ConfigureAwait(false);
11642 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11647 private async void tw_UserStreamStarted(object sender, EventArgs e)
11651 if (InvokeRequired && !IsDisposed)
11653 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11657 catch (ObjectDisposedException)
11661 catch (InvalidOperationException)
11666 this.RefreshUserStreamsMenu();
11667 this.MenuItemUserStream.Enabled = true;
11669 StatusLabel.Text = "UserStream Started.";
11672 private async void tw_UserStreamStopped(object sender, EventArgs e)
11676 if (InvokeRequired && !IsDisposed)
11678 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11682 catch (ObjectDisposedException)
11686 catch (InvalidOperationException)
11691 this.RefreshUserStreamsMenu();
11692 this.MenuItemUserStream.Enabled = true;
11694 StatusLabel.Text = "UserStream Stopped.";
11697 private void RefreshUserStreamsMenu()
11699 if (this.tw.UserStreamActive)
11701 this.MenuItemUserStream.Text = "&UserStream ▶";
11702 this.StopToolStripMenuItem.Text = "&Stop";
11706 this.MenuItemUserStream.Text = "&UserStream ■";
11707 this.StopToolStripMenuItem.Text = "&Start";
11711 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11715 if (InvokeRequired && !IsDisposed)
11717 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11721 catch (ObjectDisposedException)
11725 catch (InvalidOperationException)
11729 var ev = e.EventData;
11730 StatusLabel.Text = "Event: " + ev.Event;
11731 //if (ev.Event == "favorite")
11733 // NotifyFavorite(ev);
11736 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11738 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11740 this.PurgeListViewItemCache();
11741 ((DetailsListView)_curTab.Tag).Update();
11743 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11745 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11746 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11751 private void NotifyEvent(Twitter.FormattedEvent ev)
11754 if (BalloonRequired(ev))
11756 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11757 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11758 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11759 StringBuilder title = new StringBuilder();
11760 if (this._cfgCommon.DispUsername)
11762 title.Append(tw.Username);
11763 title.Append(" - ");
11769 title.Append(Application.ProductName);
11770 title.Append(" [");
11771 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11772 title.Append("] by ");
11773 if (!string.IsNullOrEmpty(ev.Username))
11775 title.Append(ev.Username);
11779 //title.Append("");
11782 if (!string.IsNullOrEmpty(ev.Target))
11784 //NotifyIcon1.BalloonTipText = ev.Target;
11789 //NotifyIcon1.BalloonTipText = " ";
11792 //NotifyIcon1.ShowBalloonTip(500);
11793 if (this._cfgCommon.IsUseNotifyGrowl)
11795 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11796 ev.Id.ToString(), title.ToString(), text);
11800 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11801 NotifyIcon1.BalloonTipTitle = title.ToString();
11802 NotifyIcon1.BalloonTipText = text;
11803 NotifyIcon1.ShowBalloonTip(500);
11808 string snd = this._cfgCommon.EventSoundFile;
11809 if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
11811 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11815 string dir = Application.StartupPath;
11816 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11818 dir = Path.Combine(dir, "Sounds");
11820 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11832 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11834 MenuItemUserStream.Enabled = false;
11835 if (StopRefreshAllMenuItem.Checked)
11837 StopRefreshAllMenuItem.Checked = false;
11840 if (this.tw.UserStreamActive)
11842 tw.StopUserStream();
11846 tw.StartUserStream();
11850 private static string inputTrack = "";
11852 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11854 if (TrackToolStripMenuItem.Checked)
11856 using (InputTabName inputForm = new InputTabName())
11858 inputForm.TabName = inputTrack;
11859 inputForm.FormTitle = "Input track word";
11860 inputForm.FormDescription = "Track word";
11861 if (inputForm.ShowDialog() != DialogResult.OK)
11863 TrackToolStripMenuItem.Checked = false;
11866 inputTrack = inputForm.TabName.Trim();
11868 if (!inputTrack.Equals(tw.TrackWord))
11870 tw.TrackWord = inputTrack;
11871 this.ModifySettingCommon = true;
11872 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11873 tw.ReconnectUserStream();
11879 tw.ReconnectUserStream();
11881 this.ModifySettingCommon = true;
11884 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11886 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11887 this.ModifySettingCommon = true;
11888 tw.ReconnectUserStream();
11891 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11893 if (evtDialog == null || evtDialog.IsDisposed)
11896 evtDialog = new EventViewerDialog();
11897 evtDialog.Owner = this;
11899 Point pos = evtDialog.Location;
11900 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11901 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11902 evtDialog.Location = pos;
11904 evtDialog.EventSource = tw.StoredEvent;
11905 if (!evtDialog.Visible)
11907 evtDialog.Show(this);
11911 evtDialog.Activate();
11913 this.TopMost = this._cfgCommon.AlwaysTop;
11917 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11919 MyCommon._endingFlag = true;
11923 Application.Restart();
11927 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11931 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11933 if (!string.IsNullOrEmpty(tw.Username))
11934 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11937 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11939 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11942 private bool ExistCurrentPost
11946 if (_curPost == null) return false;
11947 if (_curPost.IsDeleted) return false;
11952 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11954 ShowUserTimeline();
11957 private string GetUserIdFromCurPostOrInput(string caption)
11959 var id = _curPost?.ScreenName ?? "";
11961 using (InputTabName inputName = new InputTabName())
11963 inputName.FormTitle = caption;
11964 inputName.FormDescription = Properties.Resources.FRMessage1;
11965 inputName.TabName = id;
11966 if (inputName.ShowDialog() == DialogResult.OK &&
11967 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11969 id = inputName.TabName.Trim();
11979 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11981 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11982 if (!string.IsNullOrEmpty(id))
11984 AddNewTabForUserTimeline(id);
11988 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11990 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11991 if (!string.IsNullOrEmpty(id))
11993 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11997 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11999 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
12002 private void TimelineRefreshEnableChange(bool isEnable)
12006 tw.StartUserStream();
12010 tw.StopUserStream();
12012 TimerTimeline.Enabled = isEnable;
12015 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
12017 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12020 private async Task OpenUserAppointUrl()
12022 if (this._cfgCommon.UserAppointUrl != null)
12024 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
12026 if (_curPost != null)
12028 string xUrl = this._cfgCommon.UserAppointUrl;
12029 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12031 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12032 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12034 await this.OpenUriInBrowserAsync(xUrl);
12039 await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
12044 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12046 await this.OpenUserAppointUrl();
12049 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12051 if (Form.ActiveForm == null)
12053 await this.InvokeAsync(() =>
12055 this.Visible = true;
12056 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12058 this.BringToFront();
12059 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12061 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12065 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12071 private void ReplaceAppName()
12073 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12074 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12077 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12079 this.SplitContainer3.Panel2Collapsed = false;
12082 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12084 await this.OpenThumbnailPicture(e.Thumbnail);
12087 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12089 await this.OpenUriInBrowserAsync(e.ImageUrl);
12092 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12094 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12096 await this.OpenUriInBrowserAsync(url);
12099 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12101 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12104 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12106 if (e.KeyCode == Keys.Space)
12108 this.JumpUnreadMenuItem_Click(null, null);
12110 e.SuppressKeyPress = true;
12114 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12116 this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
12117 this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
12118 this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
12119 this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
12120 this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
12122 this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
12125 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12127 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12130 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12132 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12135 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12137 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12140 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12142 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12145 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12147 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12150 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12152 if (this._cfgCommon.IconSize == iconSize) return;
12154 var oldIconCol = _iconCol;
12156 this._cfgCommon.IconSize = iconSize;
12157 ApplyListViewIconSize(iconSize);
12159 if (_iconCol != oldIconCol)
12161 foreach (TabPage tp in ListTab.TabPages)
12163 ResetColumns((DetailsListView)tp.Tag);
12167 _curList?.Refresh();
12169 ModifySettingCommon = true;
12172 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12174 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12175 if (this._cfgCommon.SortOrderLock == state) return;
12177 this._cfgCommon.SortOrderLock = state;
12179 ModifySettingCommon = true;
12182 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12184 if (!string.IsNullOrEmpty(e.StatusText))
12186 this.StatusLabelUrl.Text = e.StatusText;
12190 this.SetStatusLabelUrl();