1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
10 // This file is part of OpenTween.
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
37 using System.Globalization;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Runtime.InteropServices;
46 using System.Text.RegularExpressions;
47 using System.Threading;
48 using System.Threading.Tasks;
49 using System.Windows.Forms;
51 using OpenTween.Api.DataModel;
52 using OpenTween.Connection;
53 using OpenTween.Models;
54 using OpenTween.OpenTweenCustomControl;
55 using OpenTween.Setting;
56 using OpenTween.Thumbnail;
60 public partial class TweenMain : OTBaseForm
63 private Size _mySize; //画面サイズ
64 private Point _myLoc; //画面位置
65 private int _mySpDis; //区切り位置
66 private int _mySpDis2; //発言欄区切り位置
67 private int _mySpDis3; //プレビュー区切り位置
68 private int _iconSz; //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
69 private bool _iconCol; //1列表示の時true(48サイズのとき)
72 private bool _initial; //true:起動時処理中
73 private bool _initialLayout = true;
74 private bool _ignoreConfigSave; //true:起動時処理中
75 private bool _tabDrag; //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
76 private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
77 private Point _tabMouseDownPoint;
78 private string _rclickTabName; //右クリックしたタブの名前(Tabコントロール機能不足対応)
79 private readonly object _syncObject = new object(); //ロック用
81 private const string detailHtmlFormatHeaderMono =
82 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
83 + "<style type=\"text/css\"><!-- "
84 + "body, p, pre {margin: 0;} "
85 + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
86 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
87 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
88 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
89 + ".quote-tweet.reply {border-color: #f33;} "
90 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
92 + "</head><body><pre>";
93 private const string detailHtmlFormatFooterMono = "</pre></body></html>";
94 private const string detailHtmlFormatHeaderColor =
95 "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
96 + "<style type=\"text/css\"><!-- "
97 + "body, p, pre {margin: 0;} "
98 + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
99 + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
100 + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
101 + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
102 + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
103 + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
105 + "</head><body><p>";
106 private const string detailHtmlFormatFooterColor = "</p></body></html>";
107 private string detailHtmlFormatHeader;
108 private string detailHtmlFormatFooter;
110 private bool _myStatusError = false;
111 private bool _myStatusOnline = false;
112 private bool soundfileListup = false;
113 private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
116 private TwitterApi twitterApi = new TwitterApi();
120 private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123 internal SearchWordDialog SearchDialog = new SearchWordDialog(); //検索画面インスタンス
124 private OpenURL UrlDialog = new OpenURL();
125 public AtIdSupplement AtIdSupl; //@id補助
126 public AtIdSupplement HashSupl; //Hashtag補助
127 public HashtagManage HashMgr;
128 private EventViewerDialog evtDialog;
131 private Font _fntUnread; //未読用フォント
132 private Color _clUnread; //未読用文字色
133 private Font _fntReaded; //既読用フォント
134 private Color _clReaded; //既読用文字色
135 private Color _clFav; //Fav用文字色
136 private Color _clOWL; //片思い用文字色
137 private Color _clRetweet; //Retweet用文字色
138 private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText); //選択中の行用文字色
139 private Font _fntDetail; //発言詳細部用フォント
140 private Color _clDetail; //発言詳細部用色
141 private Color _clDetailLink; //発言詳細部用リンク文字色
142 private Color _clDetailBackcolor; //発言詳細部用背景色
143 private Color _clSelf; //自分の発言用背景色
144 private Color _clAtSelf; //自分宛返信用背景色
145 private Color _clTarget; //選択発言者の他の発言用背景色
146 private Color _clAtTarget; //選択発言中の返信先用背景色
147 private Color _clAtFromTarget; //選択発言者への返信発言用背景色
148 private Color _clAtTo; //選択発言の唯一@先
149 private Color _clListBackcolor; //リスト部通常発言背景色
150 private Color _clInputBackcolor; //入力欄背景色
151 private Color _clInputFont; //入力欄文字色
152 private Font _fntInputFont; //入力欄フォント
153 private ImageCache IconCache; //アイコン画像リスト
154 private Icon NIconAt; //At.ico タスクトレイアイコン:通常時
155 private Icon NIconAtRed; //AtRed.ico タスクトレイアイコン:通信エラー時
156 private Icon NIconAtSmoke; //AtSmoke.ico タスクトレイアイコン:オフライン時
157 private Icon[] NIconRefresh = new Icon[4]; //Refresh.ico タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
158 private Icon TabIcon; //Tab.ico 未読のあるタブ用アイコン
159 private Icon MainIcon; //Main.ico 画面左上のアイコン
160 private Icon ReplyIcon; //5g
161 private Icon ReplyIconBlink; //6g
163 private ImageList _listViewImageList = new ImageList(); //ListViewItemの高さ変更用
165 private PostClass _anchorPost;
166 private bool _anchorFlag; //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
168 private List<PostingStatus> _history = new List<PostingStatus>(); //発言履歴
169 private int _hisIdx; //発言履歴カレントインデックス
171 //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
172 private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175 private List<DateTime> _postTimestamps = new List<DateTime>();
176 private List<DateTime> _favTimestamps = new List<DateTime>();
179 private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
180 private SolidBrush _brsBackColorMine;
181 private SolidBrush _brsBackColorAt;
182 private SolidBrush _brsBackColorYou;
183 private SolidBrush _brsBackColorAtYou;
184 private SolidBrush _brsBackColorAtFromTarget;
185 private SolidBrush _brsBackColorAtTo;
186 private SolidBrush _brsBackColorNone;
187 private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
188 private StringFormat sfTab = new StringFormat();
190 //////////////////////////////////////////////////////////////////////////////////////////////////////////
191 private TabInformations _statuses;
194 /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
197 /// キャッシュクリアのために null が代入されることがあるため、
198 /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
199 /// 一旦ローカル変数に代入してから参照すること。
201 private ListViewItemCache _listItemCache = null;
203 internal class ListViewItemCache
205 /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
206 public ListView TargetList { get; set; }
208 /// <summary>キャッシュする範囲の開始インデックス</summary>
209 public int StartIndex { get; set; }
211 /// <summary>キャッシュする範囲の終了インデックス</summary>
212 public int EndIndex { get; set; }
214 /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
215 public ListViewItem[] ListItem { get; set; }
217 /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
218 public PostClass[] Post { get; set; }
220 /// <summary>キャッシュされたアイテムの件数</summary>
222 => this.EndIndex - this.StartIndex + 1;
224 /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
225 /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
226 public bool Contains(int index)
227 => index >= this.StartIndex && index <= this.EndIndex;
229 /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
230 /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
231 public bool IsSupersetOf(int rangeStart, int rangeEnd)
232 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
234 /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
235 /// <returns>取得に成功すれば true、それ以外は false</returns>
236 public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
238 if (this.Contains(index))
240 item = this.ListItem[index - this.StartIndex];
241 post = this.Post[index - this.StartIndex];
253 private TabPage _curTab;
254 private int _curItemIndex;
255 private DetailsListView _curList;
256 private PostClass _curPost;
257 private bool _isColumnChanged = false;
259 private const int MAX_WORKER_THREADS = 20;
260 private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
261 private CancellationTokenSource workerCts = new CancellationTokenSource();
262 private IProgress<string> workerProgress;
264 private int UnreadCounter = -1;
265 private int UnreadAtCounter = -1;
267 private string[] ColumnOrgText = new string[9];
268 private string[] ColumnText = new string[9];
270 private bool _DoFavRetweetFlags = false;
271 private bool osResumed = false;
273 //////////////////////////////////////////////////////////////////////////////////////////////////////////
274 private bool _colorize = false;
276 private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
278 private string recommendedStatusFooter;
281 private struct urlUndo
283 public string Before;
287 private List<urlUndo> urlUndoBuffer = null;
289 private struct ReplyChain
291 public long OriginalId;
292 public long InReplyToId;
293 public TabPage OriginalTab;
295 public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
297 this.OriginalId = originalId;
298 this.InReplyToId = inReplyToId;
299 this.OriginalTab = originalTab;
303 private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
304 private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
307 internal enum SEARCHTYPE
314 private class PostingStatus
316 public string status = "";
317 public long? inReplyToId = null;
318 public string inReplyToName = null;
319 public string imageService = ""; //画像投稿サービス名
320 public IMediaItem[] mediaItems = null;
321 public PostingStatus()
324 public PostingStatus(string status, long? replyToId, string replyToName)
326 this.status = status;
327 this.inReplyToId = replyToId;
328 this.inReplyToName = replyToName;
332 private void TweenMain_Activated(object sender, EventArgs e)
334 //画面がアクティブになったら、発言欄の背景色戻す
335 if (StatusText.Focused)
337 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
341 private bool disposed = false;
344 /// 使用中のリソースをすべてクリーンアップします。
346 /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
347 protected override void Dispose(bool disposing)
349 base.Dispose(disposing);
356 this.components?.Dispose();
359 SearchDialog.Dispose();
362 NIconAtRed?.Dispose();
363 NIconAtSmoke?.Dispose();
364 foreach (var iconRefresh in this.NIconRefresh)
366 iconRefresh?.Dispose();
370 ReplyIcon?.Dispose();
371 ReplyIconBlink?.Dispose();
372 _listViewImageList.Dispose();
373 _brsHighLight.Dispose();
374 _brsBackColorMine?.Dispose();
375 _brsBackColorAt?.Dispose();
376 _brsBackColorYou?.Dispose();
377 _brsBackColorAtYou?.Dispose();
378 _brsBackColorAtFromTarget?.Dispose();
379 _brsBackColorAtTo?.Dispose();
380 _brsBackColorNone?.Dispose();
381 _brsDeactiveSelection?.Dispose();
385 this.workerCts.Cancel();
387 if (IconCache != null)
389 this.IconCache.CancelAsync();
390 this.IconCache.Dispose();
393 this.thumbnailTokenSource?.Dispose();
396 this.twitterApi.Dispose();
397 this._hookGlobalHotkey.Dispose();
400 // 終了時にRemoveHandlerしておかないとメモリリークする
401 // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
402 Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
404 this.disposed = true;
407 private void LoadIcons()
409 // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
410 var iconsDir = Path.Combine(Application.StartupPath, "Icons");
413 var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
416 var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
419 var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
422 var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
424 // タスクトレイ: オフライン時アイコン
425 var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
427 // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
428 var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
429 var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
431 // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
432 var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
433 var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
434 var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
435 var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
437 // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
439 this.MainIcon = iconMain ?? Properties.Resources.MIcon;
440 this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
441 this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
442 this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
443 this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
445 if (iconReply != null && iconReplyBlink != null)
447 this.ReplyIcon = iconReply;
448 this.ReplyIconBlink = iconReplyBlink;
452 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
453 this.ReplyIconBlink = this.NIconAt;
456 if (iconRefresh1 == null)
458 this.NIconRefresh = new[] {
459 Properties.Resources.Refresh, Properties.Resources.Refresh2,
460 Properties.Resources.Refresh3, Properties.Resources.Refresh4,
463 else if (iconRefresh2 == null)
465 this.NIconRefresh = new[] { iconRefresh1 };
467 else if (iconRefresh3 == null)
469 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
471 else if (iconRefresh4 == null)
473 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
475 else // iconRefresh1 から iconRefresh4 まで全て揃っている
477 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
481 private Icon LoadIcon(string filePath)
483 if (!File.Exists(filePath))
488 return new Icon(filePath);
496 private void InitColumns(ListView list, bool startup)
498 this.InitColumnText();
500 ColumnHeader[] columns = null;
507 new ColumnHeader(), // アイコン
508 new ColumnHeader(), // 本文
511 columns[0].Text = this.ColumnText[0];
512 columns[1].Text = this.ColumnText[2];
516 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
518 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
519 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
520 columns[0].DisplayIndex = 0;
521 columns[1].DisplayIndex = 1;
526 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
528 columns[idx].Width = curListColumn.Width;
529 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
538 new ColumnHeader(), // アイコン
539 new ColumnHeader(), // ニックネーム
540 new ColumnHeader(), // 本文
541 new ColumnHeader(), // 日付
542 new ColumnHeader(), // ユーザID
543 new ColumnHeader(), // 未読
544 new ColumnHeader(), // マーク&プロテクト
545 new ColumnHeader(), // ソース
548 foreach (var i in Enumerable.Range(0, columns.Length))
549 columns[i].Text = this.ColumnText[i];
553 var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / SettingManager.Local.ScaleDimension.Width;
555 columns[0].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width1);
556 columns[1].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width2);
557 columns[2].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width3);
558 columns[3].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width4);
559 columns[4].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width5);
560 columns[5].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width6);
561 columns[6].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width7);
562 columns[7].Width = ScaleBy(widthScaleFactor, SettingManager.Local.Width8);
564 var displayIndex = new[] {
565 SettingManager.Local.DisplayIndex1, SettingManager.Local.DisplayIndex2,
566 SettingManager.Local.DisplayIndex3, SettingManager.Local.DisplayIndex4,
567 SettingManager.Local.DisplayIndex5, SettingManager.Local.DisplayIndex6,
568 SettingManager.Local.DisplayIndex7, SettingManager.Local.DisplayIndex8
571 foreach (var i in Enumerable.Range(0, displayIndex.Length))
573 columns[i].DisplayIndex = displayIndex[i];
579 foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
581 columns[idx].Width = curListColumn.Width;
582 columns[idx].DisplayIndex = curListColumn.DisplayIndex;
588 list.Columns.AddRange(columns);
596 foreach (var column in columns)
602 private void InitColumnText()
605 ColumnText[1] = Properties.Resources.AddNewTabText2;
606 ColumnText[2] = Properties.Resources.AddNewTabText3;
607 ColumnText[3] = Properties.Resources.AddNewTabText4_2;
608 ColumnText[4] = Properties.Resources.AddNewTabText5;
611 ColumnText[7] = "Source";
613 ColumnOrgText[0] = "";
614 ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
615 ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
616 ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
617 ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
618 ColumnOrgText[5] = "";
619 ColumnOrgText[6] = "";
620 ColumnOrgText[7] = "Source";
623 switch (_statuses.SortMode)
625 case ComparerMode.Nickname: //ニックネーム
628 case ComparerMode.Data: //本文
631 case ComparerMode.Id: //時刻=発言Id
634 case ComparerMode.Name: //名前
637 case ComparerMode.Source: //Source
644 if (_statuses.SortOrder == SortOrder.Descending)
646 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
647 ColumnText[2] = ColumnOrgText[2] + "▾";
651 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
652 ColumnText[2] = ColumnOrgText[2] + "▴";
657 if (_statuses.SortOrder == SortOrder.Descending)
659 // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
660 ColumnText[c] = ColumnOrgText[c] + "▾";
664 // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
665 ColumnText[c] = ColumnOrgText[c] + "▴";
670 private void InitializeTraceFrag()
673 TraceOutToolStripMenuItem.Checked = true;
674 MyCommon.TraceFlag = true;
676 if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
678 TraceOutToolStripMenuItem.Checked = true;
679 MyCommon.TraceFlag = true;
683 private void TweenMain_Load(object sender, EventArgs e)
685 _ignoreConfigSave = true;
686 this.Visible = false;
688 if (MyApplication.StartupOptions.ContainsKey("d"))
689 MyCommon.TraceFlag = true;
691 InitializeTraceFrag();
693 //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
695 MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
696 Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
698 Regex.CacheSize = 100;
701 _statuses = TabInformations.GetInstance();
705 this.Icon = MainIcon; //メインフォーム(TweenMain)
706 NotifyIcon1.Icon = NIconAt; //タスクトレイ
707 TabImage.Images.Add(TabIcon); //タブ見出し
709 //<<<<<<<<<設定関連>>>>>>>>>
713 // 現在の DPI と設定保存時の DPI との比を取得する
714 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
717 var fontUIGlobal = SettingManager.Local.FontUIGlobal;
718 if (fontUIGlobal != null)
720 OTBaseForm.GlobalFont = fontUIGlobal;
721 this.Font = fontUIGlobal;
725 if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
727 if (SettingManager.Common.TimelinePeriod < 15 && SettingManager.Common.TimelinePeriod > 0)
728 SettingManager.Common.TimelinePeriod = 15;
730 if (SettingManager.Common.ReplyPeriod < 15 && SettingManager.Common.ReplyPeriod > 0)
731 SettingManager.Common.ReplyPeriod = 15;
733 if (SettingManager.Common.DMPeriod < 15 && SettingManager.Common.DMPeriod > 0)
734 SettingManager.Common.DMPeriod = 15;
736 if (SettingManager.Common.PubSearchPeriod < 30 && SettingManager.Common.PubSearchPeriod > 0)
737 SettingManager.Common.PubSearchPeriod = 30;
739 if (SettingManager.Common.UserTimelinePeriod < 15 && SettingManager.Common.UserTimelinePeriod > 0)
740 SettingManager.Common.UserTimelinePeriod = 15;
742 if (SettingManager.Common.ListsPeriod < 15 && SettingManager.Common.ListsPeriod > 0)
743 SettingManager.Common.ListsPeriod = 15;
746 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, SettingManager.Common.CountApi))
747 SettingManager.Common.CountApi = 60;
748 if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, SettingManager.Common.CountApiReply))
749 SettingManager.Common.CountApiReply = 40;
751 if (SettingManager.Common.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(SettingManager.Common.MoreCountApi))
752 SettingManager.Common.MoreCountApi = 200;
753 if (SettingManager.Common.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(SettingManager.Common.FirstCountApi))
754 SettingManager.Common.FirstCountApi = 100;
756 if (SettingManager.Common.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, SettingManager.Common.FavoritesCountApi))
757 SettingManager.Common.FavoritesCountApi = 40;
758 if (SettingManager.Common.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, SettingManager.Common.ListCountApi))
759 SettingManager.Common.ListCountApi = 100;
760 if (SettingManager.Common.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, SettingManager.Common.SearchCountApi))
761 SettingManager.Common.SearchCountApi = 100;
762 if (SettingManager.Common.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, SettingManager.Common.UserTimelineCountApi))
763 SettingManager.Common.UserTimelineCountApi = 20;
765 //廃止サービスが選択されていた場合ux.nuへ読み替え
766 if (SettingManager.Common.AutoShortUrlFirst < 0)
767 SettingManager.Common.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
769 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
770 this.tw = new Twitter(this.twitterApi);
773 if (string.IsNullOrEmpty(SettingManager.Common.Token)) SettingManager.Common.UserName = "";
774 tw.Initialize(SettingManager.Common.Token, SettingManager.Common.TokenSecret, SettingManager.Common.UserName, SettingManager.Common.UserId);
778 Networking.Initialize();
780 bool saveRequired = false;
781 bool firstRun = false;
783 //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
784 if (string.IsNullOrEmpty(tw.Username))
789 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
790 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
791 string.IsNullOrEmpty(tw.Username))
793 Application.Exit(); //強制終了
799 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
800 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
801 Networking.SetWebProxy(SettingManager.Local.ProxyType,
802 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
803 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
804 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
806 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
807 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
808 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
809 tw.TrackWord = SettingManager.Common.TrackWord;
810 TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
811 tw.AllAtReply = SettingManager.Common.AllAtReply;
812 AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
813 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
814 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
815 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
817 // アクセストークンが有効であるか確認する
818 // ここが Twitter API への最初のアクセスになるようにすること
821 this.tw.VerifyCredentials();
823 catch (WebApiException ex)
825 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
826 Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
830 //プロキシ設定等の通信まわりの初期化が済んでから処理する
831 ThumbnailGenerator.InitializeGenerator();
833 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
834 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
835 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
837 Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
840 ImageSelector.Initialize(tw, this.tw.Configuration, SettingManager.Common.UseImageServiceName, SettingManager.Common.UseImageService);
843 AtIdSupl = new AtIdSupplement(SettingManager.AtIdList.AtIdList, "@");
844 HashSupl = new AtIdSupplement(SettingManager.Common.HashTags, "#");
845 HashMgr = new HashtagManage(HashSupl,
846 SettingManager.Common.HashTags.ToArray(),
847 SettingManager.Common.HashSelected,
848 SettingManager.Common.HashIsPermanent,
849 SettingManager.Common.HashIsHead,
850 SettingManager.Common.HashIsNotAddToAtReply);
851 if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
854 this.IconCache = new ImageCache();
855 this.tweetDetailsView.IconCache = this.IconCache;
858 _fntUnread = SettingManager.Local.FontUnread;
859 _clUnread = SettingManager.Local.ColorUnread;
860 _fntReaded = SettingManager.Local.FontRead;
861 _clReaded = SettingManager.Local.ColorRead;
862 _clFav = SettingManager.Local.ColorFav;
863 _clOWL = SettingManager.Local.ColorOWL;
864 _clRetweet = SettingManager.Local.ColorRetweet;
865 _fntDetail = SettingManager.Local.FontDetail;
866 _clDetail = SettingManager.Local.ColorDetail;
867 _clDetailLink = SettingManager.Local.ColorDetailLink;
868 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
869 _clSelf = SettingManager.Local.ColorSelf;
870 _clAtSelf = SettingManager.Local.ColorAtSelf;
871 _clTarget = SettingManager.Local.ColorTarget;
872 _clAtTarget = SettingManager.Local.ColorAtTarget;
873 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
874 _clAtTo = SettingManager.Local.ColorAtTo;
875 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
876 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
877 _clInputFont = SettingManager.Local.ColorInputFont;
878 _fntInputFont = SettingManager.Local.FontInputFont;
880 _brsBackColorMine = new SolidBrush(_clSelf);
881 _brsBackColorAt = new SolidBrush(_clAtSelf);
882 _brsBackColorYou = new SolidBrush(_clTarget);
883 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
884 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
885 _brsBackColorAtTo = new SolidBrush(_clAtTo);
886 //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
887 _brsBackColorNone = new SolidBrush(_clListBackcolor);
889 // StringFormatオブジェクトへの事前設定
890 //sf.Alignment = StringAlignment.Near; // Textを近くへ配置(左から右の場合は左寄せ)
891 //sf.LineAlignment = StringAlignment.Near; // Textを近くへ配置(上寄せ)
892 //sf.FormatFlags = StringFormatFlags.LineLimit; //
893 sfTab.Alignment = StringAlignment.Center;
894 sfTab.LineAlignment = StringAlignment.Center;
896 InitDetailHtmlFormat();
898 //Regex statregex = new Regex("^0*");
899 this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
901 _history.Add(new PostingStatus());
903 this.inReplyTo = null;
906 SearchDialog.Owner = this;
907 UrlDialog.Owner = this;
910 NewPostPopMenuItem.Checked = SettingManager.Common.NewAllPop;
911 this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
913 //新着取得時のリストスクロールをするか。trueならスクロールしない
914 ListLockMenuItem.Checked = SettingManager.Common.ListLock;
915 this.LockListFileMenuItem.Checked = SettingManager.Common.ListLock;
917 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
918 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
920 this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
921 this.ToolStripFocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
924 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
925 _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
926 _myLoc = SettingManager.Local.FormLocation;
928 if (this.WindowState != FormWindowState.Minimized)
930 this.DesktopLocation = SettingManager.Local.FormLocation;
931 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
932 bool outOfScreen = true;
933 if (Screen.AllScreens.Length == 1) //ハングするとの報告
935 foreach (Screen scr in Screen.AllScreens)
937 if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
945 this.DesktopLocation = new Point(0, 0);
946 _myLoc = this.DesktopLocation;
950 this.TopMost = SettingManager.Common.AlwaysTop;
951 _mySpDis = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
952 _mySpDis2 = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
953 if (SettingManager.Local.PreviewDistance == -1)
955 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
956 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
957 SettingManager.Local.PreviewDistance = _mySpDis3;
961 _mySpDis3 = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
963 MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
964 //this.Tween_ClientSizeChanged(this, null);
965 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
966 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
968 StatusText.Font = _fntInputFont;
969 StatusText.ForeColor = _clInputFont;
971 // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
972 this.StatusText.Multiline = false; // SettingManager.Local.StatusMultiline の設定は後で反映される
973 this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
975 // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
976 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
978 //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
979 if (SettingManager.Common.UnreadManage == false)
981 ReadedStripMenuItem.Enabled = false;
982 UnreadStripMenuItem.Enabled = false;
985 //リンク先URL表示部の初期化(画面左下)
986 StatusLabelUrl.Text = "";
988 StatusLabel.Text = "";
989 StatusLabel.AutoToolTip = false;
990 StatusLabel.ToolTipText = "";
992 lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
994 this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
995 CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
996 CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
997 CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
999 // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1000 // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1001 // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1002 this.SplitContainer2.Panel2.AccessibleName = "";
1004 ////////////////////////////////////////////////////////////////////////////////
1005 var sortOrder = (SortOrder)SettingManager.Common.SortOrder;
1006 var mode = ComparerMode.Id;
1007 switch (SettingManager.Common.SortColumn)
1009 case 0: //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1013 mode = ComparerMode.Id; //Idソートに読み替え
1016 mode = ComparerMode.Nickname;
1019 mode = ComparerMode.Data;
1022 mode = ComparerMode.Id;
1025 mode = ComparerMode.Name;
1028 mode = ComparerMode.Source;
1031 _statuses.SetSortMode(mode, sortOrder);
1032 ////////////////////////////////////////////////////////////////////////////////
1034 ApplyListViewIconSize(SettingManager.Common.IconSize);
1036 //<<<<<<<<タブ関連>>>>>>>
1040 //デフォルトタブの存在チェック、ない場合には追加
1041 if (this._statuses.GetTabByType<HomeTabModel>() == null)
1042 this._statuses.AddTab(new HomeTabModel());
1044 if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1045 this._statuses.AddTab(new MentionsTabModel());
1047 if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1048 this._statuses.AddTab(new DirectMessagesTabModel());
1050 if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1051 this._statuses.AddTab(new FavoritesTabModel());
1053 if (this._statuses.GetTabByType<MuteTabModel>() == null)
1054 this._statuses.AddTab(new MuteTabModel());
1056 foreach (var tab in _statuses.Tabs.Values)
1059 if (tab.TabType == MyCommon.TabUsageType.Mute)
1062 if (!AddNewTab(tab, startup: true))
1063 throw new TabException(Properties.Resources.TweenMain_LoadText1);
1066 _curTab = ListTab.SelectedTab;
1068 _curList = (DetailsListView)_curTab.Tag;
1070 if (SettingManager.Common.TabIconDisp)
1072 ListTab.DrawMode = TabDrawMode.Normal;
1076 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1077 ListTab.DrawItem += ListTab_DrawItem;
1078 ListTab.ImageList = null;
1081 if (SettingManager.Common.HotkeyEnabled)
1084 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1085 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
1086 modKey |= HookGlobalHotkey.ModKeys.Alt;
1087 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
1088 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1089 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
1090 modKey |= HookGlobalHotkey.ModKeys.Shift;
1091 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
1092 modKey |= HookGlobalHotkey.ModKeys.Win;
1094 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
1097 if (SettingManager.Common.IsUseNotifyGrowl)
1100 StatusLabel.Text = Properties.Resources.Form1_LoadText1; //画面右下の状態表示を変更
1102 SetMainWindowTitle();
1103 SetNotifyIconText();
1105 if (!SettingManager.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1107 this.Visible = true;
1111 TimerTimeline.AutoReset = true;
1112 TimerTimeline.SynchronizingObject = this;
1114 TimerTimeline.Interval = 1000;
1115 TimerTimeline.Enabled = true;
1117 TimerRefreshIcon.Interval = 200;
1118 TimerRefreshIcon.Enabled = true;
1120 _ignoreConfigSave = false;
1121 this.TweenMain_Resize(null, null);
1122 if (saveRequired) SaveConfigsAll(false);
1124 foreach (var ua in SettingManager.Common.UserAccounts)
1126 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1128 ua.UserId = tw.UserId;
1135 // 初回起動時だけ右下のメニューを目立たせる
1136 HashStripSplitButton.ShowDropDown();
1140 private void InitDetailHtmlFormat()
1142 if (SettingManager.Common.IsMonospace)
1144 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1145 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1149 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1150 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1153 detailHtmlFormatHeader = detailHtmlFormatHeader
1154 .Replace("%FONT_FAMILY%", _fntDetail.Name)
1155 .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1156 .Replace("%FONT_COLOR%", $"{_clDetail.R},{_clDetail.G},{_clDetail.B}")
1157 .Replace("%LINK_COLOR%", $"{_clDetailLink.R},{_clDetailLink.G},{_clDetailLink.B}")
1158 .Replace("%BG_COLOR%", $"{_clDetailBackcolor.R},{_clDetailBackcolor.G},{_clDetailBackcolor.B}")
1159 .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1162 private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1167 txt = ListTab.TabPages[e.Index].Text;
1174 e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1175 if (e.State == DrawItemState.Selected)
1177 e.DrawFocusRectangle();
1182 if (_statuses.Tabs[txt].UnreadCount > 0)
1185 fore = System.Drawing.SystemBrushes.ControlText;
1189 fore = System.Drawing.SystemBrushes.ControlText;
1191 e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1194 private void LoadConfig()
1196 SettingManager.Local = SettingManager.Local;
1198 // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1199 if (SettingManager.Local.ScaleDimension.IsEmpty)
1200 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
1202 var tabSettings = SettingManager.Tabs;
1203 foreach (var tabSetting in tabSettings.Tabs)
1206 switch (tabSetting.TabType)
1208 case MyCommon.TabUsageType.Home:
1209 tab = new HomeTabModel(tabSetting.TabName);
1211 case MyCommon.TabUsageType.Mentions:
1212 tab = new MentionsTabModel(tabSetting.TabName);
1214 case MyCommon.TabUsageType.DirectMessage:
1215 tab = new DirectMessagesTabModel(tabSetting.TabName);
1217 case MyCommon.TabUsageType.Favorites:
1218 tab = new FavoritesTabModel(tabSetting.TabName);
1220 case MyCommon.TabUsageType.UserDefined:
1221 tab = new FilterTabModel(tabSetting.TabName);
1223 case MyCommon.TabUsageType.UserTimeline:
1224 tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1226 case MyCommon.TabUsageType.PublicSearch:
1227 tab = new PublicSearchTabModel(tabSetting.TabName)
1229 SearchWords = tabSetting.SearchWords,
1230 SearchLang = tabSetting.SearchLang,
1233 case MyCommon.TabUsageType.Lists:
1234 tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1236 case MyCommon.TabUsageType.Mute:
1237 tab = new MuteTabModel(tabSetting.TabName);
1243 tab.UnreadManage = tabSetting.UnreadManage;
1244 tab.Protected = tabSetting.Protected;
1245 tab.Notify = tabSetting.Notify;
1246 tab.SoundFile = tabSetting.SoundFile;
1248 if (tab.IsDistributableTabType)
1250 var filterTab = (FilterTabModel)tab;
1251 filterTab.FilterArray = tabSetting.FilterArray;
1252 filterTab.FilterModified = false;
1255 if (this._statuses.ContainsTab(tab.TabName))
1256 tab.TabName = this._statuses.MakeTabName("MyTab");
1258 this._statuses.AddTab(tab);
1260 if (_statuses.Tabs.Count == 0)
1262 _statuses.AddTab(new HomeTabModel());
1263 _statuses.AddTab(new MentionsTabModel());
1264 _statuses.AddTab(new DirectMessagesTabModel());
1265 _statuses.AddTab(new FavoritesTabModel());
1269 private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1271 if (!TimerTimeline.Enabled) return;
1275 private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1277 private static int homeCounter = 0;
1278 private static int mentionCounter = 0;
1279 private static int dmCounter = 0;
1280 private static int pubSearchCounter = 0;
1281 private static int userTimelineCounter = 0;
1282 private static int listsCounter = 0;
1283 private static int usCounter = 0;
1284 private static int ResumeWait = 0;
1285 private static int refreshFollowers = 0;
1287 private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1289 if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1290 if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1291 if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1292 if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1293 if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1294 if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1295 if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1296 Interlocked.Increment(ref refreshFollowers);
1298 var refreshTasks = new List<Task>();
1301 if (ResetTimers.Timeline || homeCounter <= 0 && SettingManager.Common.TimelinePeriod > 0)
1303 Interlocked.Exchange(ref homeCounter, SettingManager.Common.TimelinePeriod);
1304 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1305 refreshTasks.Add(this.GetHomeTimelineAsync());
1306 ResetTimers.Timeline = false;
1308 if (ResetTimers.Reply || mentionCounter <= 0 && SettingManager.Common.ReplyPeriod > 0)
1310 Interlocked.Exchange(ref mentionCounter, SettingManager.Common.ReplyPeriod);
1311 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1312 refreshTasks.Add(this.GetReplyAsync());
1313 ResetTimers.Reply = false;
1315 if (ResetTimers.DirectMessage || dmCounter <= 0 && SettingManager.Common.DMPeriod > 0)
1317 Interlocked.Exchange(ref dmCounter, SettingManager.Common.DMPeriod);
1318 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1319 refreshTasks.Add(this.GetDirectMessagesAsync());
1320 ResetTimers.DirectMessage = false;
1322 if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && SettingManager.Common.PubSearchPeriod > 0)
1324 Interlocked.Exchange(ref pubSearchCounter, SettingManager.Common.PubSearchPeriod);
1325 if (!ResetTimers.PublicSearch)
1326 refreshTasks.Add(this.GetPublicSearchAllAsync());
1327 ResetTimers.PublicSearch = false;
1329 if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && SettingManager.Common.UserTimelinePeriod > 0)
1331 Interlocked.Exchange(ref userTimelineCounter, SettingManager.Common.UserTimelinePeriod);
1332 if (!ResetTimers.UserTimeline)
1333 refreshTasks.Add(this.GetUserTimelineAllAsync());
1334 ResetTimers.UserTimeline = false;
1336 if (ResetTimers.Lists || listsCounter <= 0 && SettingManager.Common.ListsPeriod > 0)
1338 Interlocked.Exchange(ref listsCounter, SettingManager.Common.ListsPeriod);
1339 if (!ResetTimers.Lists)
1340 refreshTasks.Add(this.GetListTimelineAllAsync());
1341 ResetTimers.Lists = false;
1343 if (ResetTimers.UserStream || usCounter <= 0 && SettingManager.Common.UserstreamPeriod > 0)
1345 Interlocked.Exchange(ref usCounter, SettingManager.Common.UserstreamPeriod);
1346 if (this.tw.UserStreamActive)
1347 this.RefreshTimeline();
1348 ResetTimers.UserStream = false;
1350 if (refreshFollowers > 6 * 3600)
1352 Interlocked.Exchange(ref refreshFollowers, 0);
1353 refreshTasks.AddRange(new[]
1355 this.doGetFollowersMenu(),
1356 this.RefreshNoRetweetIdsAsync(),
1357 this.RefreshTwitterConfigurationAsync(),
1362 Interlocked.Increment(ref ResumeWait);
1363 if (ResumeWait > 30)
1366 Interlocked.Exchange(ref ResumeWait, 0);
1367 refreshTasks.AddRange(new[]
1369 this.GetHomeTimelineAsync(),
1370 this.GetReplyAsync(),
1371 this.GetDirectMessagesAsync(),
1372 this.GetPublicSearchAllAsync(),
1373 this.GetUserTimelineAllAsync(),
1374 this.GetListTimelineAllAsync(),
1375 this.doGetFollowersMenu(),
1376 this.RefreshTwitterConfigurationAsync(),
1381 await Task.WhenAll(refreshTasks);
1384 private void RefreshTimeline()
1386 var curTabModel = this._statuses.Tabs[this._curTab.Text];
1388 // 現在表示中のタブのスクロール位置を退避
1389 var curListScroll = this.SaveListViewScroll(this._curList, curTabModel);
1391 // 各タブのリスト上の選択位置などを退避
1392 var listSelections = this.SaveListViewSelection();
1395 PostClass[] notifyPosts;
1398 bool newMentionOrDm;
1400 addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1402 if (MyCommon._endingFlag) return;
1405 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1407 var listView = (DetailsListView)tabPage.Tag;
1408 var tabModel = this._statuses.Tabs[tabPage.Text];
1410 if (listView.VirtualListSize != tabModel.AllCount || isDelete)
1412 using (ControlTransaction.Update(listView))
1414 if (listView == this._curList)
1415 this.PurgeListViewItemCache();
1420 listView.VirtualListSize = tabModel.AllCount;
1422 catch (NullReferenceException ex)
1424 // WinForms 内部で ListView.set_TopItem が発生させている例外
1425 // https://ja.osdn.net/ticket/browse.php?group_id=6526&tid=36588
1426 MyCommon.TraceOut(ex, $"TabType: {tabModel.TabType}, Count: {tabModel.AllCount}, ListSize: {listView.VirtualListSize}");
1430 this.RestoreListViewSelection(listView, tabModel, listSelections[tabModel.TabName]);
1437 if (SettingManager.Common.TabIconDisp)
1439 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1441 var tabModel = this._statuses.Tabs[tabPage.Text];
1442 if (tabModel.UnreadCount > 0 && tabPage.ImageIndex != 0)
1443 tabPage.ImageIndex = 0; // 未読アイコン
1448 this.ListTab.Refresh();
1453 this.RestoreListViewScroll(this._curList, curTabModel, curListScroll);
1456 NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1458 SetMainWindowTitle();
1459 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1461 HashSupl.AddRangeItem(tw.GetHashList());
1465 internal struct ListViewScroll
1467 public ScrollLockMode ScrollLockMode { get; set; }
1468 public long? TopItemStatusId { get; set; }
1471 internal enum ScrollLockMode
1473 /// <summary>固定しない</summary>
1476 /// <summary>最上部に固定する</summary>
1479 /// <summary>最下部に固定する</summary>
1482 /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1487 /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1489 private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1491 var listScroll = new ListViewScroll
1493 ScrollLockMode = this.GetScrollLockMode(listView),
1496 if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1498 var topItemIndex = listView.TopItem?.Index ?? -1;
1499 if (topItemIndex != -1 && topItemIndex < tab.AllCount)
1500 listScroll.TopItemStatusId = tab.GetStatusIdAt(topItemIndex);
1506 private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1508 if (this._statuses.SortMode == ComparerMode.Id)
1510 if (this._statuses.SortOrder == SortOrder.Ascending)
1513 if (this.ListLockMenuItem.Checked)
1514 return ScrollLockMode.None;
1516 // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1519 var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1520 if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1521 return ScrollLockMode.FixedToBottom;
1523 return ScrollLockMode.None;
1528 if (this.ListLockMenuItem.Checked)
1529 return ScrollLockMode.FixedToItem;
1531 // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1532 var topItem = listView.TopItem;
1533 if (topItem == null || topItem.Index == 0)
1534 return ScrollLockMode.FixedToTop;
1536 return ScrollLockMode.FixedToItem;
1541 return ScrollLockMode.FixedToItem;
1545 internal struct ListViewSelection
1547 public long[] SelectedStatusIds { get; set; }
1548 public long? SelectionMarkStatusId { get; set; }
1549 public long? FocusedStatusId { get; set; }
1553 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1555 private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1557 var listsDict = new Dictionary<string, ListViewSelection>();
1559 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1561 var listView = (DetailsListView)tabPage.Tag;
1562 var tab = _statuses.Tabs[tabPage.Text];
1564 listsDict[tab.TabName] = this.SaveListViewSelection(listView, tab);
1571 /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1573 private ListViewSelection SaveListViewSelection(DetailsListView listView, TabModel tab)
1575 if (listView.VirtualListSize == 0)
1577 return new ListViewSelection
1579 SelectedStatusIds = new long[0],
1580 SelectionMarkStatusId = null,
1581 FocusedStatusId = null,
1585 return new ListViewSelection
1587 SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1588 FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1589 SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1593 private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1595 var selectedIndices = listView.SelectedIndices;
1596 if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1597 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1602 private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1604 var index = listView.FocusedItem?.Index ?? -1;
1606 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1609 private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1611 var index = listView.SelectionMark;
1613 return index != -1 && index < tab.AllCount ? tab.GetStatusIdAt(index) : (long?)null;
1617 /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1619 private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1621 if (listView.VirtualListSize == 0)
1624 switch (listScroll.ScrollLockMode)
1626 case ScrollLockMode.FixedToTop:
1627 listView.EnsureVisible(0);
1629 case ScrollLockMode.FixedToBottom:
1630 listView.EnsureVisible(listView.VirtualListSize - 1);
1632 case ScrollLockMode.FixedToItem:
1633 var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1635 listView.TopItem = listView.Items[topIndex];
1637 case ScrollLockMode.None:
1644 /// <see cref="SaveListViewSelection"/> によって保存された選択状態を復元します
1646 private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1648 // status_id から ListView 上のインデックスに変換
1649 int[] selectedIndices = null;
1650 if (listSelection.SelectedStatusIds != null)
1651 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1653 var focusedIndex = -1;
1654 if (listSelection.FocusedStatusId != null)
1655 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1657 var selectionMarkIndex = -1;
1658 if (listSelection.SelectionMarkStatusId != null)
1659 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1661 this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1664 private bool BalloonRequired()
1666 Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1667 ev.Eventtype = MyCommon.EVENTTYPE.None;
1669 return BalloonRequired(ev);
1672 private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1674 if (type == MyCommon.EVENTTYPE.None)
1677 if (!SettingManager.Common.EventNotifyEnabled)
1680 return SettingManager.Common.EventNotifyFlag.HasFlag(type);
1683 private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1688 return SettingManager.Common.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1691 private bool BalloonRequired(Twitter.FormattedEvent ev)
1696 if (NativeMethods.IsScreenSaverRunning())
1700 if (!this.NewPostPopMenuItem.Checked)
1702 // 「新着通知が無効でもイベントを通知する」にも該当しない
1703 if (!SettingManager.Common.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1707 // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1708 if (SettingManager.Common.LimitBalloon)
1710 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1714 return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1717 private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1719 if (SettingManager.Common.ReadOwnPost)
1721 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1726 if (BalloonRequired())
1728 if (notifyPosts != null && notifyPosts.Length > 0)
1730 //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1731 if (SettingManager.Common.IsUseNotifyGrowl)
1733 StringBuilder sb = new StringBuilder();
1737 foreach (PostClass post in notifyPosts)
1739 if (!(notifyPosts.Length > 3))
1745 if (post.IsReply && !post.IsExcludeReply) reply = true;
1746 if (post.IsDm) dm = true;
1747 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1748 switch (SettingManager.Common.NameBalloon)
1750 case MyCommon.NameBalloonEnum.UserID:
1751 sb.Append(post.ScreenName).Append(" : ");
1753 case MyCommon.NameBalloonEnum.NickName:
1754 sb.Append(post.Nickname).Append(" : ");
1757 sb.Append(post.TextFromApi);
1758 if (notifyPosts.Length > 3)
1760 if (notifyPosts.Last() != post) continue;
1763 StringBuilder title = new StringBuilder();
1764 GrowlHelper.NotifyType nt;
1765 if (SettingManager.Common.DispUsername)
1767 title.Append(tw.Username);
1768 title.Append(" - ");
1776 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1777 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1778 title.Append(Application.ProductName);
1779 title.Append(" [DM] ");
1780 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1781 nt = GrowlHelper.NotifyType.DirectMessage;
1785 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1786 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1787 title.Append(Application.ProductName);
1788 title.Append(" [Reply!] ");
1789 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1790 nt = GrowlHelper.NotifyType.Reply;
1794 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1795 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1796 title.Append(Application.ProductName);
1798 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1799 nt = GrowlHelper.NotifyType.Notify;
1801 string bText = sb.ToString();
1802 if (string.IsNullOrEmpty(bText)) return;
1804 var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1805 gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1810 StringBuilder sb = new StringBuilder();
1813 foreach (PostClass post in notifyPosts)
1815 if (post.IsReply && !post.IsExcludeReply) reply = true;
1816 if (post.IsDm) dm = true;
1817 if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1818 switch (SettingManager.Common.NameBalloon)
1820 case MyCommon.NameBalloonEnum.UserID:
1821 sb.Append(post.ScreenName).Append(" : ");
1823 case MyCommon.NameBalloonEnum.NickName:
1824 sb.Append(post.Nickname).Append(" : ");
1827 sb.Append(post.TextFromApi);
1830 //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1831 StringBuilder title = new StringBuilder();
1833 if (SettingManager.Common.DispUsername)
1835 title.Append(tw.Username);
1836 title.Append(" - ");
1844 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1845 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1846 ntIcon = ToolTipIcon.Warning;
1847 title.Append(Application.ProductName);
1848 title.Append(" [DM] ");
1849 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1853 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1854 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1855 ntIcon = ToolTipIcon.Warning;
1856 title.Append(Application.ProductName);
1857 title.Append(" [Reply!] ");
1858 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1862 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1863 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1864 ntIcon = ToolTipIcon.Info;
1865 title.Append(Application.ProductName);
1867 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1869 string bText = sb.ToString();
1870 if (string.IsNullOrEmpty(bText)) return;
1871 //NotifyIcon1.BalloonTipText = sb.ToString();
1872 //NotifyIcon1.ShowBalloonTip(500);
1873 NotifyIcon1.BalloonTipTitle = title.ToString();
1874 NotifyIcon1.BalloonTipText = bText;
1875 NotifyIcon1.BalloonTipIcon = ntIcon;
1876 NotifyIcon1.ShowBalloonTip(500);
1882 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(soundFile))
1886 string dir = Application.StartupPath;
1887 if (Directory.Exists(Path.Combine(dir, "Sounds")))
1889 dir = Path.Combine(dir, "Sounds");
1891 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1901 //mentions新着時に画面ブリンク
1902 if (!_initial && SettingManager.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1904 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1908 private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1910 if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1912 _curItemIndex = _curList.SelectedIndices[0];
1913 if (_curItemIndex > _curList.VirtualListSize - 1) return;
1917 this._curPost = GetCurTabPost(_curItemIndex);
1919 catch (ArgumentException)
1924 this.PushSelectPostChain();
1926 this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1928 ChangeCacheStyleRead(true, _curItemIndex); //既読へ(フォント、文字色)
1934 private void ChangeCacheStyleRead(bool Read, int Index)
1936 var tabInfo = _statuses.Tabs[_curTab.Text];
1937 //Read:true=既読 false=未読
1938 //未読管理していなかったら既読として扱う
1939 if (!tabInfo.UnreadManage ||
1940 !SettingManager.Common.UnreadManage) Read = true;
1942 var listCache = this._listItemCache;
1943 if (listCache == null)
1946 // キャッシュに含まれていないアイテムは対象外
1949 if (!listCache.TryGetValue(Index, out itm, out post))
1952 ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1955 private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1962 Item.SubItems[5].Text = "";
1967 Item.SubItems[5].Text = "★";
1973 else if (Post.RetweetedId != null)
1975 else if (Post.IsOwl && (Post.IsDm || SettingManager.Common.OneWayLove))
1977 else if (Read || !SettingManager.Common.UseUnreadStyle)
1982 if (DList == null || Item.Index == -1)
1984 Item.ForeColor = cl;
1985 if (SettingManager.Common.UseUnreadStyle)
1991 if (SettingManager.Common.UseUnreadStyle)
1992 DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1994 DList.ChangeItemForeColor(Item.Index, cl);
1995 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1999 private void ColorizeList()
2001 //Index:更新対象のListviewItem.Index。Colorを返す。
2002 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2005 _post = _anchorPost;
2009 if (_post == null) return;
2011 var listCache = this._listItemCache;
2012 if (listCache == null)
2015 var index = listCache.StartIndex;
2016 foreach (var cachedPost in listCache.Post)
2018 var backColor = this.JudgeColor(_post, cachedPost);
2019 this._curList.ChangeItemBackColor(index++, backColor);
2023 private void ColorizeList(ListViewItem Item, int Index)
2025 //Index:更新対象のListviewItem.Index。Colorを返す。
2026 //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2029 _post = _anchorPost;
2033 PostClass tPost = GetCurTabPost(Index);
2035 if (_post == null) return;
2037 if (Item.Index == -1)
2038 Item.BackColor = JudgeColor(_post, tPost);
2040 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2043 private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2046 if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2049 else if (TargetPost.IsMe)
2052 else if (TargetPost.IsReply)
2055 else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2057 cl = _clAtFromTarget;
2058 else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2061 else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2066 cl = _clListBackcolor;
2071 private async void PostButton_Click(object sender, EventArgs e)
2073 if (StatusText.Text.Trim().Length == 0)
2075 if (!ImageSelector.Enabled)
2077 await this.DoRefresh();
2082 if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2084 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2086 MessageBoxButtons.YesNoCancel,
2087 MessageBoxIcon.Question);
2090 case DialogResult.Yes:
2091 StatusText.Text = "";
2092 await this.doReTweetOfficial(false);
2094 case DialogResult.Cancel:
2099 var inReplyToStatusId = this.inReplyTo?.Item1;
2100 var inReplyToScreenName = this.inReplyTo?.Item2;
2101 _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2103 if (SettingManager.Common.Nicoms)
2105 StatusText.SelectionStart = StatusText.Text.Length;
2106 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2108 //if (SettingDialog.UrlConvertAuto)
2110 // StatusText.SelectionStart = StatusText.Text.Length;
2111 // UrlConvertAutoToolStripMenuItem_Click(null, null);
2113 //else if (SettingDialog.Nicoms)
2115 // StatusText.SelectionStart = StatusText.Text.Length;
2116 // UrlConvert(UrlConverter.Nicoms);
2118 StatusText.SelectionStart = StatusText.Text.Length;
2119 CheckReplyTo(StatusText.Text);
2121 var statusText = this.FormatStatusText(this.StatusText.Text);
2123 if (this.GetRestStatusCount(statusText) < 0)
2125 // 文字数制限を超えているが強制的に投稿するか
2126 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2127 if (ret != DialogResult.OK)
2131 var status = new PostingStatus();
2132 status.status = statusText;
2134 status.inReplyToId = this.inReplyTo?.Item1;
2135 status.inReplyToName = this.inReplyTo?.Item2;
2136 if (ImageSelector.Visible)
2139 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2143 this.inReplyTo = null;
2144 StatusText.Text = "";
2145 _history.Add(new PostingStatus());
2146 _hisIdx = _history.Count - 1;
2147 if (!ToolStripFocusLockMenuItem.Checked)
2148 ((Control)ListTab.SelectedTab.Tag).Focus();
2149 urlUndoBuffer = null;
2150 UrlUndoToolStripMenuItem.Enabled = false; //Undoをできないように設定
2153 if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2155 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2156 await this.OpenUriInBrowserAsync(tmp);
2159 await this.PostMessageAsync(status);
2162 private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2164 MyCommon._endingFlag = true;
2168 private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2170 if (!SettingManager.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2172 //_endingFlag=false:フォームの×ボタン
2174 this.Visible = false;
2178 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2179 _ignoreConfigSave = true;
2180 MyCommon._endingFlag = true;
2181 TimerTimeline.Enabled = false;
2182 TimerRefreshIcon.Enabled = false;
2186 private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2188 this.Visible = true;
2189 if (this.WindowState == FormWindowState.Minimized)
2191 this.WindowState = FormWindowState.Normal;
2194 this.BringToFront();
2197 private static int errorCount = 0;
2199 private static bool CheckAccountValid()
2201 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2207 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2216 private Task GetHomeTimelineAsync()
2218 return this.GetHomeTimelineAsync(loadMore: false);
2221 private async Task GetHomeTimelineAsync(bool loadMore)
2223 await this.workerSemaphore.WaitAsync();
2227 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
2228 await homeTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2230 this.RefreshTimeline();
2232 catch (WebApiException ex)
2234 this._myStatusError = true;
2235 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2239 this.workerSemaphore.Release();
2243 private Task GetReplyAsync()
2245 return this.GetReplyAsync(loadMore: false);
2248 private async Task GetReplyAsync(bool loadMore)
2250 await this.workerSemaphore.WaitAsync();
2254 var replyTab = this._statuses.GetTabByType<MentionsTabModel>();
2255 await replyTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2257 this.RefreshTimeline();
2259 catch (WebApiException ex)
2261 this._myStatusError = true;
2262 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2266 this.workerSemaphore.Release();
2270 private Task GetDirectMessagesAsync()
2272 return this.GetDirectMessagesAsync(loadMore: false);
2275 private async Task GetDirectMessagesAsync(bool loadMore)
2277 await this.workerSemaphore.WaitAsync();
2281 var dmTab = this._statuses.GetTabByType<DirectMessagesTabModel>();
2282 await dmTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2284 this.RefreshTimeline();
2286 catch (WebApiException ex)
2288 this._myStatusError = true;
2289 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2293 this.workerSemaphore.Release();
2297 private Task GetFavoritesAsync()
2299 return this.GetFavoritesAsync(loadMore: false);
2302 private async Task GetFavoritesAsync(bool loadMore)
2304 await this.workerSemaphore.WaitAsync();
2308 var favTab = this._statuses.GetTabByType<FavoritesTabModel>();
2309 await favTab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2311 this.RefreshTimeline();
2313 catch (WebApiException ex)
2315 this._myStatusError = true;
2316 this.StatusLabel.Text = ex.Message;
2320 this.workerSemaphore.Release();
2324 private Task GetPublicSearchAllAsync()
2326 var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2328 return this.GetPublicSearchAsync(tabs, loadMore: false);
2331 private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2333 return this.GetPublicSearchAsync(tab, loadMore: false);
2336 private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2338 return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2341 private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2343 await this.workerSemaphore.WaitAsync();
2347 foreach (var tab in tabs)
2351 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2353 catch (WebApiException ex)
2355 this._myStatusError = true;
2356 this.StatusLabel.Text = $"Err:{ex.Message}(GetSearch)";
2360 this.RefreshTimeline();
2364 this.workerSemaphore.Release();
2368 private Task GetUserTimelineAllAsync()
2370 var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2372 return this.GetUserTimelineAsync(tabs, loadMore: false);
2375 private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2377 return this.GetUserTimelineAsync(tab, loadMore: false);
2380 private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2382 return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2385 private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2387 await this.workerSemaphore.WaitAsync();
2391 foreach (var tab in tabs)
2395 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2397 catch (WebApiException ex)
2399 this._myStatusError = true;
2400 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2404 this.RefreshTimeline();
2408 this.workerSemaphore.Release();
2412 private Task GetListTimelineAllAsync()
2414 var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2416 return this.GetListTimelineAsync(tabs, loadMore: false);
2419 private Task GetListTimelineAsync(ListTimelineTabModel tab)
2421 return this.GetListTimelineAsync(tab, loadMore: false);
2424 private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2426 return this.GetListTimelineAsync(new[] { tab }, loadMore);
2429 private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2431 await this.workerSemaphore.WaitAsync();
2435 foreach (var tab in tabs)
2439 await tab.RefreshAsync(this.tw, loadMore, this._initial, this.workerProgress);
2441 catch (WebApiException ex)
2443 this._myStatusError = true;
2444 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2448 this.RefreshTimeline();
2452 this.workerSemaphore.Release();
2456 private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2458 await this.workerSemaphore.WaitAsync();
2462 await tab.RefreshAsync(this.tw, this._initial, this.workerProgress);
2464 this.RefreshTimeline();
2466 catch (WebApiException ex)
2468 this._myStatusError = true;
2469 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2473 this.workerSemaphore.Release();
2477 private async Task FavAddAsync(long statusId, TabModel tab)
2479 await this.workerSemaphore.WaitAsync();
2483 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2485 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2487 catch (WebApiException ex)
2489 this._myStatusError = true;
2490 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2494 this.workerSemaphore.Release();
2498 private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2500 if (ct.IsCancellationRequested)
2503 if (!CheckAccountValid())
2504 throw new WebApiException("Auth error. Check your account");
2507 if (!tab.Posts.TryGetValue(statusId, out post))
2513 await Task.Run(async () =>
2515 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2519 await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2521 .ConfigureAwait(false);
2523 if (SettingManager.Common.RestrictFavCheck)
2525 var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2526 .ConfigureAwait(false);
2528 if (status.Favorited != true)
2529 throw new WebApiException("NG(Restricted?)");
2532 this._favTimestamps.Add(DateTime.Now);
2535 if (this._statuses.ContainsKey(statusId))
2537 var postTl = this._statuses[statusId];
2538 postTl.IsFav = true;
2540 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2541 favTab.AddPostQueue(postTl);
2544 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2545 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2547 if (tb.Contains(statusId))
2548 tb.Posts[statusId].IsFav = true;
2551 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2553 catch (WebApiException)
2555 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2560 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2561 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2563 if (this._favTimestamps[i] < oneHour)
2564 this._favTimestamps.RemoveAt(i);
2567 this._statuses.DistributePosts();
2570 if (ct.IsCancellationRequested)
2573 this.RefreshTimeline();
2575 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2577 using (ControlTransaction.Update(this._curList))
2579 var idx = tab.IndexOf(statusId);
2581 this.ChangeCacheStyleRead(post.IsRead, idx);
2584 if (statusId == this._curPost.StatusId)
2585 await this.DispSelectedPost(true); // 選択アイテム再表示
2589 private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2591 await this.workerSemaphore.WaitAsync();
2595 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2597 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2599 catch (WebApiException ex)
2601 this._myStatusError = true;
2602 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2606 this.workerSemaphore.Release();
2610 private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2612 if (ct.IsCancellationRequested)
2615 if (!CheckAccountValid())
2616 throw new WebApiException("Auth error. Check your account");
2618 var successIds = new List<long>();
2620 await Task.Run(async () =>
2624 var failedCount = 0;
2625 foreach (var statusId in statusIds)
2629 var post = tab.Posts[statusId];
2631 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2638 await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
2640 .ConfigureAwait(false);
2642 catch (WebApiException)
2648 successIds.Add(statusId);
2649 post.IsFav = false; // リスト再描画必要
2651 if (this._statuses.ContainsKey(statusId))
2653 this._statuses[statusId].IsFav = false;
2656 // 検索,リスト,UserTimeline,Relatedの各タブに反映
2657 foreach (var tb in this._statuses.GetTabsInnerStorageType())
2659 if (tb.Contains(statusId))
2660 tb.Posts[statusId].IsFav = false;
2665 if (ct.IsCancellationRequested)
2668 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2669 foreach (var statusId in successIds)
2671 // ツイートが削除された訳ではないので IsDeleted はセットしない
2672 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
2675 this.RefreshTimeline();
2677 if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2679 if (tab.TabType == MyCommon.TabUsageType.Favorites)
2685 using (ControlTransaction.Update(this._curList))
2687 foreach (var statusId in successIds)
2689 var idx = tab.IndexOf(statusId);
2693 var post = tab.Posts[statusId];
2694 this.ChangeCacheStyleRead(post.IsRead, idx);
2698 if (successIds.Contains(this._curPost.StatusId))
2699 await this.DispSelectedPost(true); // 選択アイテム再表示
2704 private async Task PostMessageAsync(PostingStatus status)
2706 await this.workerSemaphore.WaitAsync();
2710 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2712 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
2714 catch (WebApiException ex)
2716 this._myStatusError = true;
2717 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
2721 this.workerSemaphore.Release();
2725 private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
2727 if (ct.IsCancellationRequested)
2730 if (!CheckAccountValid())
2731 throw new WebApiException("Auth error. Check your account");
2733 p.Report("Posting...");
2739 await Task.Run(async () =>
2741 if (status.mediaItems == null || status.mediaItems.Length == 0)
2743 await this.tw.PostStatus(status.status, status.inReplyToId)
2744 .ConfigureAwait(false);
2748 var service = ImageSelector.GetService(status.imageService);
2749 await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
2750 .ConfigureAwait(false);
2754 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2756 catch (WebApiException ex)
2758 // 処理は中断せずエラーの表示のみ行う
2759 errMsg = $"Err:{ex.Message}(PostMessage)";
2761 this._myStatusError = true;
2763 catch (UnauthorizedAccessException ex)
2765 // アップロード対象のファイルが開けなかった場合など
2766 errMsg = $"Err:{ex.Message}(PostMessage)";
2768 this._myStatusError = true;
2772 // 使い終わった MediaItem は破棄する
2773 if (status.mediaItems != null)
2775 foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
2777 disposableItem.Dispose();
2782 if (ct.IsCancellationRequested)
2785 if (!string.IsNullOrEmpty(errMsg) &&
2786 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
2787 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
2789 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, status.status);
2791 var ret = MessageBox.Show(
2793 "Failed to update status",
2794 MessageBoxButtons.RetryCancel,
2795 MessageBoxIcon.Question);
2797 if (ret == DialogResult.Retry)
2799 await this.PostMessageAsync(status);
2803 // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
2804 if (this.ToolStripFocusLockMenuItem.Checked)
2805 this.StatusText_Enter(this.StatusText, EventArgs.Empty);
2810 this._postTimestamps.Add(DateTime.Now);
2812 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2813 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2815 if (this._postTimestamps[i] < oneHour)
2816 this._postTimestamps.RemoveAt(i);
2819 if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
2821 this.HashMgr.ClearHashtag();
2822 this.HashStripSplitButton.Text = "#[-]";
2823 this.HashToggleMenuItem.Checked = false;
2824 this.HashToggleToolStripMenuItem.Checked = false;
2827 this.SetMainWindowTitle();
2829 if (SettingManager.Common.PostAndGet)
2831 if (this.tw.UserStreamActive)
2832 this.RefreshTimeline();
2834 await this.GetHomeTimelineAsync();
2838 private async Task RetweetAsync(IReadOnlyList<long> statusIds)
2840 await this.workerSemaphore.WaitAsync();
2844 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2846 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
2848 if (SettingManager.Common.PostAndGet && !this.tw.UserStreamActive)
2849 await this.GetHomeTimelineAsync();
2851 catch (WebApiException ex)
2853 this._myStatusError = true;
2854 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
2858 this.workerSemaphore.Release();
2862 private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
2864 if (ct.IsCancellationRequested)
2867 if (!CheckAccountValid())
2868 throw new WebApiException("Auth error. Check your account");
2871 if (!SettingManager.Common.UnreadManage)
2874 read = this._initial && SettingManager.Common.Read;
2876 p.Report("Posting...");
2878 foreach (var statusId in statusIds)
2880 await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
2883 if (ct.IsCancellationRequested)
2886 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
2888 this._postTimestamps.Add(DateTime.Now);
2890 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2891 foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
2893 if (this._postTimestamps[i] < oneHour)
2894 this._postTimestamps.RemoveAt(i);
2898 private async Task RefreshFollowerIdsAsync()
2900 await this.workerSemaphore.WaitAsync();
2903 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
2905 await this.tw.RefreshFollowerIds();
2907 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
2909 this.RefreshTimeline();
2910 this.PurgeListViewItemCache();
2911 this._curList?.Refresh();
2913 catch (WebApiException ex)
2915 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
2919 this.workerSemaphore.Release();
2923 private async Task RefreshNoRetweetIdsAsync()
2925 await this.workerSemaphore.WaitAsync();
2928 await this.tw.RefreshNoRetweetIds();
2930 this.StatusLabel.Text = "NoRetweetIds refreshed";
2932 catch (WebApiException ex)
2934 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
2938 this.workerSemaphore.Release();
2942 private async Task RefreshBlockIdsAsync()
2944 await this.workerSemaphore.WaitAsync();
2947 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
2949 await this.tw.RefreshBlockIds();
2951 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
2953 catch (WebApiException ex)
2955 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
2959 this.workerSemaphore.Release();
2963 private async Task RefreshTwitterConfigurationAsync()
2965 await this.workerSemaphore.WaitAsync();
2968 await this.tw.RefreshConfiguration();
2970 if (this.tw.Configuration.PhotoSizeLimit != 0)
2972 foreach (var service in this.ImageSelector.GetServices())
2974 service.UpdateTwitterConfiguration(this.tw.Configuration);
2978 this.PurgeListViewItemCache();
2980 this._curList?.Refresh();
2982 catch (WebApiException ex)
2984 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
2988 this.workerSemaphore.Release();
2992 private async Task RefreshMuteUserIdsAsync()
2994 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
2998 await tw.RefreshMuteUserIdsAsync();
3000 catch (WebApiException ex)
3002 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3006 this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3009 private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3011 if (e.Button == MouseButtons.Left)
3013 this.Visible = true;
3014 if (this.WindowState == FormWindowState.Minimized)
3016 this.WindowState = _formWindowState;
3019 this.BringToFront();
3023 private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3025 switch (SettingManager.Common.ListDoubleClickAction)
3028 MakeReplyOrDirectStatus();
3031 await this.FavoriteChange(true);
3034 if (_curPost != null)
3035 await this.ShowUserStatus(_curPost.ScreenName, false);
3041 ShowRelatedStatusesMenuItem_Click(null, null);
3044 MoveToHomeToolStripMenuItem_Click(null, null);
3047 StatusOpenMenuItem_Click(null, null);
3055 private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3057 await this.FavoriteChange(true);
3060 private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3062 await this.FavoriteChange(false);
3066 private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3068 await this.FavoritesRetweetOfficial();
3071 private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3073 await this.FavoritesRetweetUnofficial();
3076 private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3079 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3082 //trueでFavAdd,falseでFavRemove
3083 if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3084 || !this.ExistCurrentPost) return;
3086 if (this._curList.SelectedIndices.Count > 1)
3091 // https://support.twitter.com/articles/76915#favoriting
3092 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3093 _DoFavRetweetFlags = false;
3098 if (multiFavoriteChangeDialogEnable)
3100 var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3101 Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3102 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3104 if (confirm == DialogResult.Cancel)
3112 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3113 if (selectedPost.IsFav)
3115 this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3119 await this.FavAddAsync(selectedPost.StatusId, tab);
3123 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3124 .Select(x => this.GetCurTabPost(x))
3125 .Where(x => x.IsFav);
3127 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3128 if (statusIds.Length == 0)
3130 this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3134 await this.FavRemoveAsync(statusIds, tab);
3138 private PostClass GetCurTabPost(int Index)
3140 var listCache = this._listItemCache;
3141 if (listCache != null)
3145 if (listCache.TryGetValue(Index, out item, out post))
3149 return _statuses.Tabs[_curTab.Text][Index];
3152 private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3154 if (_curList.SelectedIndices.Count > 0)
3155 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3156 else if (_curList.SelectedIndices.Count == 0)
3157 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3160 private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3162 if (_curList.SelectedIndices.Count > 0)
3163 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3166 private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3168 if ((!_initialLayout) && this.Visible)
3170 if (this.WindowState == FormWindowState.Normal)
3172 _mySize = this.ClientSize;
3173 _mySpDis = this.SplitContainer1.SplitterDistance;
3174 _mySpDis3 = this.SplitContainer3.SplitterDistance;
3175 if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3176 ModifySettingLocal = true;
3181 private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3183 var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3184 if (comparerMode == null)
3187 this.SetSortColumn(comparerMode.Value);
3191 /// 列インデックスからソートを行う ComparerMode を求める
3193 /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3194 /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3195 private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3198 return ComparerMode.Id;
3200 switch (columnIndex)
3203 return ComparerMode.Nickname;
3205 return ComparerMode.Data;
3207 return ComparerMode.Id;
3209 return ComparerMode.Name;
3211 return ComparerMode.Source;
3213 // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3219 /// 発言一覧の指定した位置の列でソートする
3221 /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3222 private void SetSortColumnByDisplayIndex(int columnIndex)
3224 // 表示上の列の位置から ColumnHeader を求める
3225 var col = this._curList.Columns.Cast<ColumnHeader>()
3226 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
3231 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3232 if (comparerMode == null)
3235 this.SetSortColumn(comparerMode.Value);
3239 /// 発言一覧の最後列の項目でソートする
3241 private void SetSortLastColumn()
3243 // 表示上の最後列にある ColumnHeader を求める
3244 var col = this._curList.Columns.Cast<ColumnHeader>()
3245 .OrderByDescending(x => x.DisplayIndex)
3248 var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3249 if (comparerMode == null)
3252 this.SetSortColumn(comparerMode.Value);
3256 /// 発言一覧を指定された ComparerMode に基づいてソートする
3258 private void SetSortColumn(ComparerMode sortColumn)
3260 if (SettingManager.Common.SortOrderLock)
3263 this._statuses.ToggleSortOrder(sortColumn);
3264 this.InitColumnText();
3266 var list = this._curList;
3269 list.Columns[0].Text = this.ColumnText[0];
3270 list.Columns[1].Text = this.ColumnText[2];
3274 for (var i = 0; i <= 7; i++)
3276 list.Columns[i].Text = this.ColumnText[i];
3280 this.PurgeListViewItemCache();
3282 var tab = this._statuses.Tabs[this._curTab.Text];
3283 if (tab.AllCount > 0 && this._curPost != null)
3285 var idx = tab.IndexOf(this._curPost.StatusId);
3288 this.SelectListItem(list, idx);
3289 list.EnsureVisible(idx);
3294 this.ModifySettingCommon = true;
3297 private void TweenMain_LocationChanged(object sender, EventArgs e)
3299 if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3301 _myLoc = this.DesktopLocation;
3302 ModifySettingLocal = true;
3306 private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3308 if (ListTab.SelectedTab == null) return;
3309 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3310 if (!this.ExistCurrentPost)
3312 ReplyStripMenuItem.Enabled = false;
3313 ReplyAllStripMenuItem.Enabled = false;
3314 DMStripMenuItem.Enabled = false;
3315 ShowProfileMenuItem.Enabled = false;
3316 ShowUserTimelineContextMenuItem.Enabled = false;
3317 ListManageUserContextToolStripMenuItem2.Enabled = false;
3318 MoveToFavToolStripMenuItem.Enabled = false;
3319 TabMenuItem.Enabled = false;
3320 IDRuleMenuItem.Enabled = false;
3321 SourceRuleMenuItem.Enabled = false;
3322 ReadedStripMenuItem.Enabled = false;
3323 UnreadStripMenuItem.Enabled = false;
3327 ShowProfileMenuItem.Enabled = true;
3328 ListManageUserContextToolStripMenuItem2.Enabled = true;
3329 ReplyStripMenuItem.Enabled = true;
3330 ReplyAllStripMenuItem.Enabled = true;
3331 DMStripMenuItem.Enabled = true;
3332 ShowUserTimelineContextMenuItem.Enabled = true;
3333 MoveToFavToolStripMenuItem.Enabled = true;
3334 TabMenuItem.Enabled = true;
3335 IDRuleMenuItem.Enabled = true;
3336 SourceRuleMenuItem.Enabled = true;
3337 ReadedStripMenuItem.Enabled = true;
3338 UnreadStripMenuItem.Enabled = true;
3340 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3342 FavAddToolStripMenuItem.Enabled = false;
3343 FavRemoveToolStripMenuItem.Enabled = false;
3344 StatusOpenMenuItem.Enabled = false;
3345 FavorareMenuItem.Enabled = false;
3346 ShowRelatedStatusesMenuItem.Enabled = false;
3348 ReTweetStripMenuItem.Enabled = false;
3349 ReTweetUnofficialStripMenuItem.Enabled = false;
3350 QuoteStripMenuItem.Enabled = false;
3351 FavoriteRetweetContextMenu.Enabled = false;
3352 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3356 FavAddToolStripMenuItem.Enabled = true;
3357 FavRemoveToolStripMenuItem.Enabled = true;
3358 StatusOpenMenuItem.Enabled = true;
3359 FavorareMenuItem.Enabled = true;
3360 ShowRelatedStatusesMenuItem.Enabled = true; //PublicSearchの時問題出るかも
3362 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
3364 ReTweetStripMenuItem.Enabled = false;
3365 ReTweetUnofficialStripMenuItem.Enabled = false;
3366 QuoteStripMenuItem.Enabled = false;
3367 FavoriteRetweetContextMenu.Enabled = false;
3368 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3372 ReTweetStripMenuItem.Enabled = true;
3373 ReTweetUnofficialStripMenuItem.Enabled = true;
3374 QuoteStripMenuItem.Enabled = true;
3375 FavoriteRetweetContextMenu.Enabled = true;
3376 FavoriteRetweetUnofficialContextMenu.Enabled = true;
3379 //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3381 // RefreshMoreStripMenuItem.Enabled = true;
3385 // RefreshMoreStripMenuItem.Enabled = false;
3387 if (!this.ExistCurrentPost
3388 || _curPost.InReplyToStatusId == null)
3390 RepliedStatusOpenMenuItem.Enabled = false;
3394 RepliedStatusOpenMenuItem.Enabled = true;
3396 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3398 MoveToRTHomeMenuItem.Enabled = false;
3402 MoveToRTHomeMenuItem.Enabled = true;
3405 if (this.ExistCurrentPost)
3407 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3408 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3409 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3411 this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3415 private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3417 MakeReplyOrDirectStatus(false, true);
3420 private void DMStripMenuItem_Click(object sender, EventArgs e)
3422 MakeReplyOrDirectStatus(false, false);
3425 private async Task doStatusDelete()
3427 if (this._curTab == null || this._curList == null)
3430 if (this._curList.SelectedIndices.Count == 0)
3433 var posts = this._curList.SelectedIndices.Cast<int>()
3434 .Select(x => this.GetCurTabPost(x))
3437 // 選択されたツイートの中に削除可能なものが一つでもあるか
3438 if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3441 var ret = MessageBox.Show(this,
3442 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3443 Properties.Resources.DeleteStripMenuItem_ClickText2,
3444 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3446 if (ret != DialogResult.OK)
3449 var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3451 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3453 Exception lastException = null;
3454 foreach (var post in posts)
3456 if (!post.CanDeleteBy(this.tw.UserId))
3463 await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3468 if (post.RetweetedByUserId == this.tw.UserId)
3470 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
3472 await this.twitterApi.StatusesDestroy(post.StatusId)
3477 if (post.UserId == this.tw.UserId)
3479 if (post.RetweetedId != null)
3480 // 他人に RT された自分のツイート
3481 // => RT 元の自分のツイートを削除
3482 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3487 await this.twitterApi.StatusesDestroy(post.StatusId)
3493 catch (WebApiException ex)
3499 this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3502 if (lastException == null)
3503 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3505 this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3507 this.PurgeListViewItemCache();
3508 this._curPost = null;
3509 this._curItemIndex = -1;
3511 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3513 var listView = (DetailsListView)tabPage.Tag;
3514 var tab = this._statuses.Tabs[tabPage.Text];
3516 using (ControlTransaction.Update(listView))
3518 listView.VirtualListSize = tab.AllCount;
3520 if (tabPage == this._curTab)
3522 listView.SelectedIndices.Clear();
3524 if (tab.AllCount != 0)
3527 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3528 selectedIndex = focusedIndex;
3530 selectedIndex = tab.AllCount - 1;
3532 listView.SelectedIndices.Add(selectedIndex);
3533 listView.EnsureVisible(selectedIndex);
3534 listView.FocusedItem = listView.Items[selectedIndex];
3539 if (SettingManager.Common.TabIconDisp && tab.UnreadCount == 0)
3541 if (tabPage.ImageIndex == 0)
3542 tabPage.ImageIndex = -1; // タブアイコン
3546 if (!SettingManager.Common.TabIconDisp)
3547 this.ListTab.Refresh();
3551 private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3553 await this.doStatusDelete();
3556 private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3558 using (ControlTransaction.Update(this._curList))
3560 foreach (int idx in _curList.SelectedIndices)
3562 var post = this._statuses.Tabs[this._curTab.Text][idx];
3563 this._statuses.SetReadAllTab(post.StatusId, read: true);
3564 ChangeCacheStyleRead(true, idx);
3568 foreach (TabPage tb in ListTab.TabPages)
3570 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3572 if (SettingManager.Common.TabIconDisp)
3574 if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3578 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3581 private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3583 using (ControlTransaction.Update(this._curList))
3585 foreach (int idx in _curList.SelectedIndices)
3587 var post = this._statuses.Tabs[this._curTab.Text][idx];
3588 this._statuses.SetReadAllTab(post.StatusId, read: false);
3589 ChangeCacheStyleRead(false, idx);
3593 foreach (TabPage tb in ListTab.TabPages)
3595 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3597 if (SettingManager.Common.TabIconDisp)
3599 if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3603 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
3606 private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3608 await this.DoRefresh();
3611 private async Task DoRefresh()
3613 if (_curTab != null)
3616 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3619 switch (_statuses.Tabs[_curTab.Text].TabType)
3621 case MyCommon.TabUsageType.Mentions:
3622 await this.GetReplyAsync();
3624 case MyCommon.TabUsageType.DirectMessage:
3625 await this.GetDirectMessagesAsync();
3627 case MyCommon.TabUsageType.Favorites:
3628 await this.GetFavoritesAsync();
3630 //case MyCommon.TabUsageType.Profile:
3632 case MyCommon.TabUsageType.PublicSearch:
3633 var searchTab = (PublicSearchTabModel)tab;
3634 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3635 await this.GetPublicSearchAsync(searchTab);
3637 case MyCommon.TabUsageType.UserTimeline:
3638 await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3640 case MyCommon.TabUsageType.Lists:
3641 var listTab = (ListTimelineTabModel)tab;
3642 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3643 await this.GetListTimelineAsync(listTab);
3646 await this.GetHomeTimelineAsync();
3652 await this.GetHomeTimelineAsync();
3656 private async Task DoRefreshMore()
3659 if (_curTab != null)
3662 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3665 switch (_statuses.Tabs[_curTab.Text].TabType)
3667 case MyCommon.TabUsageType.Mentions:
3668 await this.GetReplyAsync(loadMore: true);
3670 case MyCommon.TabUsageType.DirectMessage:
3671 await this.GetDirectMessagesAsync(loadMore: true);
3673 case MyCommon.TabUsageType.Favorites:
3674 await this.GetFavoritesAsync(loadMore: true);
3676 case MyCommon.TabUsageType.Profile:
3679 case MyCommon.TabUsageType.PublicSearch:
3680 var searchTab = (PublicSearchTabModel)tab;
3681 if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3682 await this.GetPublicSearchAsync(searchTab, loadMore: true);
3684 case MyCommon.TabUsageType.UserTimeline:
3685 await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
3687 case MyCommon.TabUsageType.Lists:
3688 var listTab = (ListTimelineTabModel)tab;
3689 if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
3690 await this.GetListTimelineAsync(listTab, loadMore: true);
3693 await this.GetHomeTimelineAsync(loadMore: true);
3699 await this.GetHomeTimelineAsync(loadMore: true);
3703 private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
3705 DialogResult result = DialogResult.Abort;
3707 using (var settingDialog = new AppendSettingDialog())
3709 settingDialog.Icon = this.MainIcon;
3710 settingDialog.Owner = this;
3711 settingDialog.ShowInTaskbar = showTaskbarIcon;
3712 settingDialog.IntervalChanged += this.TimerInterval_Changed;
3714 settingDialog.tw = this.tw;
3715 settingDialog.twitterApi = this.twitterApi;
3717 settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
3721 result = settingDialog.ShowDialog(this);
3725 return DialogResult.Abort;
3728 if (result == DialogResult.OK)
3732 settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
3740 private async void SettingStripMenuItem_Click(object sender, EventArgs e)
3743 var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
3745 var oldIconSz = SettingManager.Common.IconSize;
3747 if (ShowSettingDialog() == DialogResult.OK)
3751 tw.RestrictFavCheck = SettingManager.Common.RestrictFavCheck;
3752 tw.ReadOwnPost = SettingManager.Common.ReadOwnPost;
3753 ShortUrl.Instance.DisableExpanding = !SettingManager.Common.TinyUrlResolve;
3754 ShortUrl.Instance.BitlyId = SettingManager.Common.BilyUser;
3755 ShortUrl.Instance.BitlyKey = SettingManager.Common.BitlyPwd;
3756 TwitterApiConnection.RestApiHost = SettingManager.Common.TwitterApiHost;
3758 Networking.DefaultTimeout = TimeSpan.FromSeconds(SettingManager.Common.DefaultTimeOut);
3759 Networking.UploadImageTimeout = TimeSpan.FromSeconds(SettingManager.Common.UploadImageTimeout);
3760 Networking.SetWebProxy(SettingManager.Local.ProxyType,
3761 SettingManager.Local.ProxyAddress, SettingManager.Local.ProxyPort,
3762 SettingManager.Local.ProxyUser, SettingManager.Local.ProxyPassword);
3763 Networking.ForceIPv4 = SettingManager.Common.ForceIPv4;
3765 ImageSelector.Reset(tw, this.tw.Configuration);
3769 if (SettingManager.Common.TabIconDisp)
3771 ListTab.DrawItem -= ListTab_DrawItem;
3772 ListTab.DrawMode = TabDrawMode.Normal;
3773 ListTab.ImageList = this.TabImage;
3777 ListTab.DrawItem -= ListTab_DrawItem;
3778 ListTab.DrawItem += ListTab_DrawItem;
3779 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
3780 ListTab.ImageList = null;
3783 catch (Exception ex)
3785 ex.Data["Instance"] = "ListTab(TabIconDisp)";
3786 ex.Data["IsTerminatePermission"] = false;
3792 if (!SettingManager.Common.UnreadManage)
3794 ReadedStripMenuItem.Enabled = false;
3795 UnreadStripMenuItem.Enabled = false;
3796 if (SettingManager.Common.TabIconDisp)
3798 foreach (TabPage myTab in ListTab.TabPages)
3800 myTab.ImageIndex = -1;
3806 ReadedStripMenuItem.Enabled = true;
3807 UnreadStripMenuItem.Enabled = true;
3810 catch (Exception ex)
3812 ex.Data["Instance"] = "ListTab(UnreadManage)";
3813 ex.Data["IsTerminatePermission"] = false;
3820 SplitContainer1.IsPanelInverted = !SettingManager.Common.StatusAreaAtBottom;
3822 var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
3823 imgazyobizinet.Enabled = SettingManager.Common.EnableImgAzyobuziNet;
3824 imgazyobizinet.DisabledInDM = SettingManager.Common.ImgAzyobuziNetDisabledInDM;
3826 this.PlaySoundMenuItem.Checked = SettingManager.Common.PlaySound;
3827 this.PlaySoundFileMenuItem.Checked = SettingManager.Common.PlaySound;
3828 _fntUnread = SettingManager.Local.FontUnread;
3829 _clUnread = SettingManager.Local.ColorUnread;
3830 _fntReaded = SettingManager.Local.FontRead;
3831 _clReaded = SettingManager.Local.ColorRead;
3832 _clFav = SettingManager.Local.ColorFav;
3833 _clOWL = SettingManager.Local.ColorOWL;
3834 _clRetweet = SettingManager.Local.ColorRetweet;
3835 _fntDetail = SettingManager.Local.FontDetail;
3836 _clDetail = SettingManager.Local.ColorDetail;
3837 _clDetailLink = SettingManager.Local.ColorDetailLink;
3838 _clDetailBackcolor = SettingManager.Local.ColorDetailBackcolor;
3839 _clSelf = SettingManager.Local.ColorSelf;
3840 _clAtSelf = SettingManager.Local.ColorAtSelf;
3841 _clTarget = SettingManager.Local.ColorTarget;
3842 _clAtTarget = SettingManager.Local.ColorAtTarget;
3843 _clAtFromTarget = SettingManager.Local.ColorAtFromTarget;
3844 _clAtTo = SettingManager.Local.ColorAtTo;
3845 _clListBackcolor = SettingManager.Local.ColorListBackcolor;
3846 _clInputBackcolor = SettingManager.Local.ColorInputBackcolor;
3847 _clInputFont = SettingManager.Local.ColorInputFont;
3848 _fntInputFont = SettingManager.Local.FontInputFont;
3849 _brsBackColorMine.Dispose();
3850 _brsBackColorAt.Dispose();
3851 _brsBackColorYou.Dispose();
3852 _brsBackColorAtYou.Dispose();
3853 _brsBackColorAtFromTarget.Dispose();
3854 _brsBackColorAtTo.Dispose();
3855 _brsBackColorNone.Dispose();
3856 _brsBackColorMine = new SolidBrush(_clSelf);
3857 _brsBackColorAt = new SolidBrush(_clAtSelf);
3858 _brsBackColorYou = new SolidBrush(_clTarget);
3859 _brsBackColorAtYou = new SolidBrush(_clAtTarget);
3860 _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
3861 _brsBackColorAtTo = new SolidBrush(_clAtTo);
3862 _brsBackColorNone = new SolidBrush(_clListBackcolor);
3866 if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
3867 StatusText.Font = _fntInputFont;
3868 StatusText.ForeColor = _clInputFont;
3870 catch (Exception ex)
3872 MessageBox.Show(ex.Message);
3877 InitDetailHtmlFormat();
3879 catch (Exception ex)
3881 ex.Data["Instance"] = "Font";
3882 ex.Data["IsTerminatePermission"] = false;
3888 foreach (TabPage tb in ListTab.TabPages)
3890 if (SettingManager.Common.TabIconDisp)
3892 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3899 catch (Exception ex)
3901 ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
3902 ex.Data["IsTerminatePermission"] = false;
3908 var oldIconCol = _iconCol;
3910 if (SettingManager.Common.IconSize != oldIconSz)
3911 ApplyListViewIconSize(SettingManager.Common.IconSize);
3913 foreach (TabPage tp in ListTab.TabPages)
3915 DetailsListView lst = (DetailsListView)tp.Tag;
3917 using (ControlTransaction.Update(lst))
3919 lst.GridLines = SettingManager.Common.ShowGrid;
3920 lst.Font = _fntReaded;
3921 lst.BackColor = _clListBackcolor;
3923 if (_iconCol != oldIconCol)
3928 catch (Exception ex)
3930 ex.Data["Instance"] = "ListView(IconSize)";
3931 ex.Data["IsTerminatePermission"] = false;
3935 SetMainWindowTitle();
3936 SetNotifyIconText();
3938 this.PurgeListViewItemCache();
3939 _curList?.Refresh();
3942 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
3943 if (SettingManager.Common.HotkeyEnabled)
3945 ///グローバルホットキーの登録。設定で変更可能にするかも
3946 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
3947 if ((SettingManager.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
3948 modKey |= HookGlobalHotkey.ModKeys.Alt;
3949 if ((SettingManager.Common.HotkeyModifier & Keys.Control) == Keys.Control)
3950 modKey |= HookGlobalHotkey.ModKeys.Ctrl;
3951 if ((SettingManager.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
3952 modKey |= HookGlobalHotkey.ModKeys.Shift;
3953 if ((SettingManager.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
3954 modKey |= HookGlobalHotkey.ModKeys.Win;
3956 _hookGlobalHotkey.RegisterOriginalHotkey(SettingManager.Common.HotkeyKey, SettingManager.Common.HotkeyValue, modKey);
3959 if (SettingManager.Common.IsUseNotifyGrowl) gh.RegisterGrowl();
3962 StatusText_TextChanged(null, null);
3971 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
3972 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
3975 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3977 this.TopMost = SettingManager.Common.AlwaysTop;
3978 SaveConfigsAll(false);
3980 if (tw.Username != oldUser.Username)
3981 await this.doGetFollowersMenu();
3987 private void SetTabAlignment()
3989 var newAlignment = SettingManager.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
3990 if (ListTab.Alignment == newAlignment) return;
3992 // 各タブのリスト上の選択位置などを退避
3993 var listSelections = this.SaveListViewSelection();
3995 ListTab.Alignment = newAlignment;
3997 foreach (TabPage tab in ListTab.TabPages)
3999 DetailsListView lst = (DetailsListView)tab.Tag;
4000 TabModel tabInfo = _statuses.Tabs[tab.Text];
4001 using (ControlTransaction.Update(lst))
4004 this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4009 private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4015 case MyCommon.IconSizes.IconNone:
4018 case MyCommon.IconSizes.Icon16:
4021 case MyCommon.IconSizes.Icon24:
4024 case MyCommon.IconSizes.Icon48:
4027 case MyCommon.IconSizes.Icon48_2:
4035 // ディスプレイの DPI 設定を考慮したサイズを設定する
4036 _listViewImageList.ImageSize = new Size(
4038 (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4042 _listViewImageList.ImageSize = new Size(1, 1);
4046 private void ResetColumns(DetailsListView list)
4048 using (ControlTransaction.Update(list))
4049 using (ControlTransaction.Layout(list, false))
4052 list.ColumnClick -= MyList_ColumnClick;
4053 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4054 list.ColumnReordered -= MyList_ColumnReordered;
4055 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4057 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4058 list.Columns.Clear();
4059 cols.ForEach(col => col.Dispose());
4062 InitColumns(list, true);
4064 list.ColumnClick += MyList_ColumnClick;
4065 list.DrawColumnHeader += MyList_DrawColumnHeader;
4066 list.ColumnReordered += MyList_ColumnReordered;
4067 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4071 public void AddNewTabForSearch(string searchWord)
4073 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4074 foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4076 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4078 foreach (TabPage tp in ListTab.TabPages)
4080 if (tb.TabName == tp.Text)
4082 ListTab.SelectedTab = tp;
4089 string tabName = searchWord;
4090 for (int i = 0; i <= 100; i++)
4092 if (_statuses.ContainsTab(tabName))
4098 var tab = new PublicSearchTabModel(tabName);
4099 _statuses.AddTab(tab);
4100 AddNewTab(tab, startup: false);
4102 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4104 ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4105 cmb.Items.Add(searchWord);
4106 cmb.Text = searchWord;
4109 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4112 private void ShowUserTimeline()
4114 if (!this.ExistCurrentPost) return;
4115 AddNewTabForUserTimeline(_curPost.ScreenName);
4118 private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4120 if (e.KeyCode == Keys.Escape)
4122 TabPage relTp = ListTab.SelectedTab;
4123 RemoveSpecifiedTab(relTp.Text, false);
4125 e.SuppressKeyPress = true;
4129 public void AddNewTabForUserTimeline(string user)
4131 //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4132 foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4134 if (tb.ScreenName == user)
4136 foreach (TabPage tp in ListTab.TabPages)
4138 if (tb.TabName == tp.Text)
4140 ListTab.SelectedTab = tp;
4147 string tabName = "user:" + user;
4148 while (_statuses.ContainsTab(tabName))
4153 var tab = new UserTimelineTabModel(tabName, user);
4154 this._statuses.AddTab(tab);
4155 this.AddNewTab(tab, startup: false);
4157 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4160 this.GetUserTimelineAsync(tab);
4163 public bool AddNewTab(TabModel tab, bool startup)
4166 foreach (TabPage tb in ListTab.TabPages)
4168 if (tb.Text == tab.TabName) return false;
4172 if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4174 var _tabPage = new TabPage();
4175 var _listCustom = new DetailsListView();
4177 int cnt = ListTab.TabPages.Count;
4179 ///ToDo:Create and set controls follow tabtypes
4181 using (ControlTransaction.Update(_listCustom))
4182 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4183 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4184 using (ControlTransaction.Layout(this.SplitContainer1, false))
4185 using (ControlTransaction.Layout(this.ListTab, false))
4186 using (ControlTransaction.Layout(this))
4187 using (ControlTransaction.Layout(_tabPage, false))
4189 _tabPage.Controls.Add(_listCustom);
4192 var userTab = tab as UserTimelineTabModel;
4193 var listTab = tab as ListTimelineTabModel;
4194 var searchTab = tab as PublicSearchTabModel;
4196 if (userTab != null || listTab != null)
4198 var label = new Label();
4199 label.Dock = DockStyle.Top;
4200 label.Name = "labelUser";
4203 if (listTab != null)
4205 label.Text = listTab.ListInfo.ToString();
4207 else if (userTab != null)
4209 label.Text = userTab.ScreenName + "'s Timeline";
4211 label.TextAlign = ContentAlignment.MiddleLeft;
4212 using (ComboBox tmpComboBox = new ComboBox())
4214 label.Height = tmpComboBox.Height;
4216 _tabPage.Controls.Add(label);
4219 else if (searchTab != null)
4221 var pnl = new Panel();
4223 var lbl = new Label();
4224 var cmb = new ComboBox();
4225 var btn = new Button();
4226 var cmbLang = new ComboBox();
4228 using (ControlTransaction.Layout(pnl, false))
4230 pnl.Controls.Add(cmb);
4231 pnl.Controls.Add(cmbLang);
4232 pnl.Controls.Add(btn);
4233 pnl.Controls.Add(lbl);
4234 pnl.Name = "panelSearch";
4236 pnl.Dock = DockStyle.Top;
4237 pnl.Height = cmb.Height;
4238 pnl.Enter += SearchControls_Enter;
4239 pnl.Leave += SearchControls_Leave;
4242 cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4243 cmb.Dock = DockStyle.Fill;
4244 cmb.Name = "comboSearch";
4245 cmb.DropDownStyle = ComboBoxStyle.DropDown;
4246 cmb.ImeMode = ImeMode.NoControl;
4247 cmb.TabStop = false;
4249 cmb.AutoCompleteMode = AutoCompleteMode.None;
4250 cmb.KeyDown += SearchComboBox_KeyDown;
4253 cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4254 cmbLang.Dock = DockStyle.Right;
4256 cmbLang.Name = "comboLang";
4257 cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4258 cmbLang.TabStop = false;
4259 cmbLang.TabIndex = 2;
4260 cmbLang.Items.Add("");
4261 cmbLang.Items.Add("ja");
4262 cmbLang.Items.Add("en");
4263 cmbLang.Items.Add("ar");
4264 cmbLang.Items.Add("da");
4265 cmbLang.Items.Add("nl");
4266 cmbLang.Items.Add("fa");
4267 cmbLang.Items.Add("fi");
4268 cmbLang.Items.Add("fr");
4269 cmbLang.Items.Add("de");
4270 cmbLang.Items.Add("hu");
4271 cmbLang.Items.Add("is");
4272 cmbLang.Items.Add("it");
4273 cmbLang.Items.Add("no");
4274 cmbLang.Items.Add("pl");
4275 cmbLang.Items.Add("pt");
4276 cmbLang.Items.Add("ru");
4277 cmbLang.Items.Add("es");
4278 cmbLang.Items.Add("sv");
4279 cmbLang.Items.Add("th");
4281 lbl.Text = "Search(C-S-f)";
4282 lbl.Name = "label1";
4283 lbl.Dock = DockStyle.Left;
4285 lbl.Height = cmb.Height;
4286 lbl.TextAlign = ContentAlignment.MiddleLeft;
4289 btn.Text = "Search";
4290 btn.Name = "buttonSearch";
4291 btn.UseVisualStyleBackColor = true;
4292 btn.Dock = DockStyle.Right;
4293 btn.TabStop = false;
4295 btn.Click += SearchButton_Click;
4297 if (!string.IsNullOrEmpty(searchTab.SearchWords))
4299 cmb.Items.Add(searchTab.SearchWords);
4300 cmb.Text = searchTab.SearchWords;
4303 cmbLang.Text = searchTab.SearchLang;
4305 _tabPage.Controls.Add(pnl);
4309 _tabPage.Tag = _listCustom;
4310 this.ListTab.Controls.Add(_tabPage);
4312 _tabPage.Location = new Point(4, 4);
4313 _tabPage.Name = "CTab" + cnt;
4314 _tabPage.Size = new Size(380, 260);
4315 _tabPage.TabIndex = 2 + cnt;
4316 _tabPage.Text = tab.TabName;
4317 _tabPage.UseVisualStyleBackColor = true;
4318 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4320 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4321 _listCustom.TabIndex = 1;
4322 _listCustom.AllowColumnReorder = true;
4323 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4324 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4325 _listCustom.Dock = DockStyle.Fill;
4326 _listCustom.FullRowSelect = true;
4327 _listCustom.HideSelection = false;
4328 _listCustom.Location = new Point(0, 0);
4329 _listCustom.Margin = new Padding(0);
4330 _listCustom.Name = "CList" + Environment.TickCount;
4331 _listCustom.ShowItemToolTips = true;
4332 _listCustom.Size = new Size(380, 260);
4333 _listCustom.UseCompatibleStateImageBehavior = false;
4334 _listCustom.View = View.Details;
4335 _listCustom.OwnerDraw = true;
4336 _listCustom.VirtualMode = true;
4337 _listCustom.Font = _fntReaded;
4338 _listCustom.BackColor = _clListBackcolor;
4340 _listCustom.GridLines = SettingManager.Common.ShowGrid;
4341 _listCustom.AllowDrop = true;
4343 _listCustom.SmallImageList = _listViewImageList;
4345 InitColumns(_listCustom, startup);
4347 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4348 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4349 _listCustom.ColumnClick += MyList_ColumnClick;
4350 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4351 _listCustom.DragDrop += TweenMain_DragDrop;
4352 _listCustom.DragEnter += TweenMain_DragEnter;
4353 _listCustom.DragOver += TweenMain_DragOver;
4354 _listCustom.DrawItem += MyList_DrawItem;
4355 _listCustom.MouseClick += MyList_MouseClick;
4356 _listCustom.ColumnReordered += MyList_ColumnReordered;
4357 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4358 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4359 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4360 _listCustom.DrawSubItem += MyList_DrawSubItem;
4361 _listCustom.HScrolled += MyList_HScrolled;
4367 public bool RemoveSpecifiedTab(string TabName, bool confirm)
4369 var tabInfo = _statuses.GetTabByName(TabName);
4370 if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4374 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4375 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4376 MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4382 var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4383 if (_tabPage == null) return false;
4385 SetListProperty(); //他のタブに列幅等を反映
4388 DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4389 _tabPage.Tag = null;
4391 using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4392 using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4393 using (ControlTransaction.Layout(this.SplitContainer1, false))
4394 using (ControlTransaction.Layout(this.ListTab, false))
4395 using (ControlTransaction.Layout(this))
4396 using (ControlTransaction.Layout(_tabPage, false))
4398 if (this.ListTab.SelectedTab == _tabPage)
4400 this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4401 this._beforeSelectedTab = null;
4403 this.ListTab.Controls.Remove(_tabPage);
4406 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4408 using (Control label = _tabPage.Controls["labelUser"])
4410 _tabPage.Controls.Remove(label);
4413 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4415 using (Control pnl = _tabPage.Controls["panelSearch"])
4417 pnl.Enter -= SearchControls_Enter;
4418 pnl.Leave -= SearchControls_Leave;
4419 _tabPage.Controls.Remove(pnl);
4421 foreach (Control ctrl in pnl.Controls)
4423 if (ctrl.Name == "buttonSearch")
4425 ctrl.Click -= SearchButton_Click;
4427 else if (ctrl.Name == "comboSearch")
4429 ctrl.KeyDown -= SearchComboBox_KeyDown;
4431 pnl.Controls.Remove(ctrl);
4437 _tabPage.Controls.Remove(_listCustom);
4439 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4440 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4441 _listCustom.ColumnClick -= MyList_ColumnClick;
4442 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4443 _listCustom.DragDrop -= TweenMain_DragDrop;
4444 _listCustom.DragEnter -= TweenMain_DragEnter;
4445 _listCustom.DragOver -= TweenMain_DragOver;
4446 _listCustom.DrawItem -= MyList_DrawItem;
4447 _listCustom.MouseClick -= MyList_MouseClick;
4448 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4449 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4450 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4451 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4452 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4453 _listCustom.HScrolled -= MyList_HScrolled;
4455 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4456 _listCustom.Columns.Clear();
4457 cols.ForEach(col => col.Dispose());
4460 _listCustom.ContextMenuStrip = null;
4461 _listCustom.ColumnHeaderContextMenuStrip = null;
4462 _listCustom.Font = null;
4464 _listCustom.SmallImageList = null;
4465 _listCustom.ListViewItemSorter = null;
4468 if (_curTab.Equals(_tabPage))
4475 this.PurgeListViewItemCache();
4479 _listCustom.Dispose();
4480 _statuses.RemoveTab(TabName);
4482 foreach (TabPage tp in ListTab.TabPages)
4484 DetailsListView lst = (DetailsListView)tp.Tag;
4485 var count = _statuses.Tabs[tp.Text].AllCount;
4486 lst.VirtualListSize = count;
4492 private void ListTab_Deselected(object sender, TabControlEventArgs e)
4494 this.PurgeListViewItemCache();
4495 _beforeSelectedTab = e.TabPage;
4498 private void ListTab_MouseMove(object sender, MouseEventArgs e)
4502 if (!SettingManager.Common.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4505 Rectangle dragEnableRectangle = new Rectangle(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), _tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4506 if (!dragEnableRectangle.Contains(e.Location))
4508 //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4509 tn = ListTab.SelectedTab.Text;
4512 if (string.IsNullOrEmpty(tn)) return;
4514 foreach (TabPage tb in ListTab.TabPages)
4518 ListTab.DoDragDrop(tb, DragDropEffects.All);
4528 Point cpos = new Point(e.X, e.Y);
4529 for (int i = 0; i < ListTab.TabPages.Count; i++)
4531 Rectangle rect = ListTab.GetTabRect(i);
4532 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4533 rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4535 _rclickTabName = ListTab.TabPages[i].Text;
4541 private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4543 //_curList.Refresh();
4544 SetMainWindowTitle();
4545 SetStatusLabelUrl();
4546 SetApiStatusLabel();
4547 if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4548 TabMenuControl(ListTab.SelectedTab.Text);
4549 this.PushSelectPostChain();
4550 await DispSelectedPost();
4553 private void SetListProperty()
4555 //削除などで見つからない場合は処理せず
4556 if (_curList == null) return;
4557 if (!_isColumnChanged) return;
4559 int[] dispOrder = new int[_curList.Columns.Count];
4560 for (int i = 0; i < _curList.Columns.Count; i++)
4562 for (int j = 0; j < _curList.Columns.Count; j++)
4564 if (_curList.Columns[j].DisplayIndex == i)
4573 foreach (TabPage tb in ListTab.TabPages)
4575 if (!tb.Equals(_curTab))
4577 if (tb.Tag != null && tb.Controls.Count > 0)
4579 DetailsListView lst = (DetailsListView)tb.Tag;
4580 for (int i = 0; i < lst.Columns.Count; i++)
4582 lst.Columns[dispOrder[i]].DisplayIndex = i;
4583 lst.Columns[i].Width = _curList.Columns[i].Width;
4589 _isColumnChanged = false;
4592 private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
4594 if (e.KeyChar == '@')
4596 if (!SettingManager.Common.UseAtIdSupplement) return;
4598 int cnt = AtIdSupl.ItemCount;
4599 ShowSuplDialog(StatusText, AtIdSupl);
4600 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
4603 else if (e.KeyChar == '#')
4605 if (!SettingManager.Common.UseHashSupplement) return;
4606 ShowSuplDialog(StatusText, HashSupl);
4611 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
4613 ShowSuplDialog(owner, dialog, 0, "");
4616 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
4618 ShowSuplDialog(owner, dialog, offset, "");
4621 public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
4623 dialog.StartsWith = startswith;
4630 dialog.ShowDialog();
4632 this.TopMost = SettingManager.Common.AlwaysTop;
4633 int selStart = owner.SelectionStart;
4636 if (dialog.DialogResult == DialogResult.OK)
4638 if (!string.IsNullOrEmpty(dialog.inputText))
4642 fHalf = owner.Text.Substring(0, selStart - offset);
4644 if (selStart < owner.Text.Length)
4646 eHalf = owner.Text.Substring(selStart);
4648 owner.Text = fHalf + dialog.inputText + eHalf;
4649 owner.SelectionStart = selStart + dialog.inputText.Length;
4656 fHalf = owner.Text.Substring(0, selStart);
4658 if (selStart < owner.Text.Length)
4660 eHalf = owner.Text.Substring(selStart);
4662 owner.Text = fHalf + eHalf;
4665 owner.SelectionStart = selStart;
4671 private void StatusText_KeyUp(object sender, KeyEventArgs e)
4674 if (!e.Alt && !e.Control && !e.Shift)
4676 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
4678 bool isSpace = false;
4679 foreach (char c in StatusText.Text)
4681 if (c == ' ' || c == ' ')
4694 StatusText.Text = "";
4695 JumpUnreadMenuItem_Click(null, null);
4699 this.StatusText_TextChanged(null, null);
4702 private void StatusText_TextChanged(object sender, EventArgs e)
4705 int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
4706 lblLen.Text = pLen.ToString();
4709 StatusText.ForeColor = Color.Red;
4713 StatusText.ForeColor = _clInputFont;
4716 this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
4718 if (string.IsNullOrEmpty(StatusText.Text))
4720 this.inReplyTo = null;
4725 /// ツイート投稿前のフッター付与などの前処理を行います
4727 private string FormatStatusText(string statusText)
4729 statusText = statusText.Replace("\r\n", "\n");
4731 if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
4734 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
4737 if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
4739 // 文中の全角スペースを半角スペース1個にする
4740 statusText = statusText.Replace(" ", " ");
4743 // DM の場合はこれ以降の処理を行わない
4744 if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
4748 if (SettingManager.Common.PostShiftEnter)
4750 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4754 if (this.StatusText.Multiline && !SettingManager.Common.PostCtrlEnter)
4755 disableFooter = MyCommon.IsKeyDown(Keys.Control);
4757 disableFooter = MyCommon.IsKeyDown(Keys.Shift);
4760 if (statusText.Contains("RT @"))
4761 disableFooter = true;
4766 var hashtag = this.HashMgr.UseHash;
4767 if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4770 header = HashMgr.UseHash + " ";
4772 footer = " " + HashMgr.UseHash;
4777 if (SettingManager.Local.UseRecommendStatus)
4780 footer += this.recommendedStatusFooter;
4782 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4784 // テキストボックスに入力されている文字列を使用する
4785 footer += " " + SettingManager.Local.StatusText.Trim();
4789 statusText = header + statusText + footer;
4791 if (this.ToolStripMenuItemPreventSmsCommand.Checked)
4793 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4794 // 参照: https://support.twitter.com/articles/14020
4796 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4797 && !Twitter.DMSendTextRegex.IsMatch(statusText))
4799 // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4800 statusText = '\u200b' + statusText;
4808 /// 投稿欄に表示する入力可能な文字数を計算します
4810 private int GetRestStatusCount(string statusText)
4813 var remainCount = this.tw.GetTextLengthRemain(statusText);
4815 var uploadService = this.ImageSelector.SelectedService;
4816 if (this.ImageSelector.Visible && uploadService != null)
4818 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4819 remainCount -= uploadService.GetReservedTextLength(1);
4825 private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4827 if (sender != this._curList)
4830 var listCache = this._listItemCache;
4831 if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4833 // If the newly requested cache is a subset of the old cache,
4834 // no need to rebuild everything, so do nothing.
4838 // Now we need to rebuild the cache.
4839 this.CreateCache(e.StartIndex, e.EndIndex);
4842 private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4844 var listCache = this._listItemCache;
4845 if (listCache?.TargetList == sender)
4848 PostClass cacheItemPost;
4849 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
4856 // A cache miss, so create a new ListViewItem and pass it back.
4857 TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4860 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4864 // 不正な要求に対する間に合わせの応答
4865 string[] sitem = {"", "", "", "", "", "", "", ""};
4866 e.Item = new ImageListViewItem(sitem);
4870 private void CreateCache(int startIndex, int endIndex)
4872 var tabInfo = this._statuses.Tabs[this._curTab.Text];
4874 if (tabInfo.AllCount == 0)
4877 // キャッシュ要求(要求範囲±30を作成)
4878 startIndex = Math.Max(startIndex - 30, 0);
4879 endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
4881 var cacheLength = endIndex - startIndex + 1;
4883 var posts = tabInfo[startIndex, endIndex]; //配列で取得
4884 var listItems = Enumerable.Range(0, cacheLength)
4885 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4888 var listCache = new ListViewItemCache
4890 TargetList = this._curList,
4891 StartIndex = startIndex,
4892 EndIndex = endIndex,
4894 ListItem = listItems,
4897 Interlocked.Exchange(ref this._listItemCache, listCache);
4901 /// DetailsListView のための ListViewItem のキャッシュを消去する
4903 private void PurgeListViewItemCache()
4905 Interlocked.Exchange(ref this._listItemCache, null);
4908 private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4910 StringBuilder mk = new StringBuilder();
4911 //if (Post.IsDeleted) mk.Append("×");
4912 //if (Post.IsMark) mk.Append("♪");
4913 //if (Post.IsProtect) mk.Append("Ю");
4914 //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4915 if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4916 ImageListViewItem itm;
4917 if (Post.RetweetedId == null)
4919 string[] sitem= {"",
4921 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4922 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4927 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4931 string[] sitem = {"",
4933 Post.IsDeleted ? "(DELETED)" : Post.AccessibleText,
4934 Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4935 Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4939 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4941 itm.StateIndex = Post.StateIndex;
4944 bool read = Post.IsRead;
4945 //未読管理していなかったら既読として扱う
4946 if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4947 ChangeItemStyleRead(read, itm, Post, null);
4948 if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4953 /// 全てのタブの振り分けルールを反映し直します
4955 private void ApplyPostFilters()
4957 using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4959 this.PurgeListViewItemCache();
4960 this._curPost = null;
4961 this._curItemIndex = -1;
4962 this._statuses.FilterAll();
4964 foreach (TabPage tabPage in this.ListTab.TabPages)
4966 var tab = this._statuses.Tabs[tabPage.Text];
4968 var listview = (DetailsListView)tabPage.Tag;
4969 using (ControlTransaction.Update(listview))
4971 listview.VirtualListSize = tab.AllCount;
4974 if (SettingManager.Common.TabIconDisp)
4976 if (tab.UnreadCount > 0)
4977 tabPage.ImageIndex = 0;
4979 tabPage.ImageIndex = -1;
4983 if (!SettingManager.Common.TabIconDisp)
4984 this.ListTab.Refresh();
4986 SetMainWindowTitle();
4987 SetStatusLabelUrl();
4991 private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4993 e.DrawDefault = true;
4996 private void MyList_HScrolled(object sender, EventArgs e)
4998 DetailsListView listView = (DetailsListView)sender;
5002 private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5004 if (e.State == 0) return;
5005 e.DrawDefault = false;
5007 SolidBrush brs2 = null;
5008 if (!e.Item.Selected) //e.ItemStateでうまく判定できない???
5010 if (e.Item.BackColor == _clSelf)
5011 brs2 = _brsBackColorMine;
5012 else if (e.Item.BackColor == _clAtSelf)
5013 brs2 = _brsBackColorAt;
5014 else if (e.Item.BackColor == _clTarget)
5015 brs2 = _brsBackColorYou;
5016 else if (e.Item.BackColor == _clAtTarget)
5017 brs2 = _brsBackColorAtYou;
5018 else if (e.Item.BackColor == _clAtFromTarget)
5019 brs2 = _brsBackColorAtFromTarget;
5020 else if (e.Item.BackColor == _clAtTo)
5021 brs2 = _brsBackColorAtTo;
5023 brs2 = _brsBackColorNone;
5028 if (((Control)sender).Focused)
5029 brs2 = _brsHighLight;
5031 brs2 = _brsDeactiveSelection;
5033 e.Graphics.FillRectangle(brs2, e.Bounds);
5034 e.DrawFocusRectangle();
5035 this.DrawListViewItemIcon(e);
5038 private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5040 if (e.ItemState == 0) return;
5042 if (e.ColumnIndex > 0)
5045 var post = (PostClass)e.Item.Tag;
5047 RectangleF rct = e.Bounds;
5048 rct.Width = e.Header.Width;
5049 int fontHeight = e.Item.Font.Height;
5052 rct.Y += fontHeight;
5053 rct.Height -= fontHeight;
5057 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5059 //if (heightDiff > fontHeight * 0.7)
5061 // rct.Height += fontHeight;
5062 // drawLineCount += 1;
5065 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5066 if (!_iconCol && drawLineCount <= 1)
5068 //rct.Inflate(0, heightDiff / -2);
5069 //rct.Height += fontHeight / 2;
5071 else if (heightDiff < fontHeight * 0.7)
5073 //最終行が70%以上欠けていたら、最終行は表示しない
5074 //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5075 rct.Height = (fontHeight * drawLineCount) - 1;
5082 //if (!_iconCol && drawLineCount > 1)
5084 // rct.Y += fontHeight * 0.2;
5085 // if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5090 Color color = (!e.Item.Selected) ? e.Item.ForeColor : //選択されていない行
5091 (((Control)sender).Focused) ? _clHighLight : //選択中の行
5096 Rectangle rctB = e.Bounds;
5097 rctB.Width = e.Header.Width;
5098 rctB.Height = fontHeight;
5100 using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5102 TextRenderer.DrawText(e.Graphics,
5103 post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5105 Rectangle.Round(rct),
5107 TextFormatFlags.WordBreak |
5108 TextFormatFlags.EndEllipsis |
5109 TextFormatFlags.GlyphOverhangPadding |
5110 TextFormatFlags.NoPrefix);
5111 TextRenderer.DrawText(e.Graphics,
5112 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 + "]",
5116 TextFormatFlags.SingleLine |
5117 TextFormatFlags.EndEllipsis |
5118 TextFormatFlags.GlyphOverhangPadding |
5119 TextFormatFlags.NoPrefix);
5125 if (e.ColumnIndex != 2)
5126 text = e.SubItem.Text;
5128 text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5130 if (drawLineCount == 1)
5132 TextRenderer.DrawText(e.Graphics,
5135 Rectangle.Round(rct),
5137 TextFormatFlags.SingleLine |
5138 TextFormatFlags.EndEllipsis |
5139 TextFormatFlags.GlyphOverhangPadding |
5140 TextFormatFlags.NoPrefix |
5141 TextFormatFlags.VerticalCenter);
5145 TextRenderer.DrawText(e.Graphics,
5148 Rectangle.Round(rct),
5150 TextFormatFlags.WordBreak |
5151 TextFormatFlags.EndEllipsis |
5152 TextFormatFlags.GlyphOverhangPadding |
5153 TextFormatFlags.NoPrefix);
5156 //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5161 private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5163 if (_iconSz == 0) return;
5165 ImageListViewItem item = (ImageListViewItem)e.Item;
5167 //e.Bounds.Leftが常に0を指すから自前で計算
5168 Rectangle itemRect = item.Bounds;
5169 var col0 = e.Item.ListView.Columns[0];
5170 itemRect.Width = col0.Width;
5172 if (col0.DisplayIndex > 0)
5174 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5176 if (clm.DisplayIndex < col0.DisplayIndex)
5177 itemRect.X += clm.Width;
5181 // ディスプレイの DPI 設定を考慮したアイコンサイズ
5182 var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5183 var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5186 var img = item.Image;
5189 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5190 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5192 if (iconRect.Width > 0)
5194 e.Graphics.FillRectangle(Brushes.White, iconRect);
5195 e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5198 e.Graphics.DrawImage(img.Image, iconRect);
5200 catch (ArgumentException)
5202 item.RefreshImageAsync();
5208 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5209 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5211 item.GetImageAsync();
5214 if (item.StateIndex > -1)
5216 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5217 if (stateRect.Width > 0)
5219 //e.Graphics.FillRectangle(Brushes.White, stateRect);
5220 //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5221 e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5226 protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5228 base.ScaleControl(factor, specified);
5230 ScaleChildControl(this.TabImage, factor);
5232 var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5233 var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5235 foreach (var listview in listviews)
5237 ScaleChildControl(listview, factor);
5241 //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5243 // ImageListViewItem item = (ImageListViewItem)e.Item;
5244 // if (item.StateImageIndex > -1)
5246 // ////e.Bounds.Leftが常に0を指すから自前で計算
5247 // //Rectangle itemRect = item.Bounds;
5248 // //itemRect.Width = e.Item.ListView.Columns[4].Width;
5250 // //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5252 // // if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5254 // // itemRect.X += clm.Width;
5258 // //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5259 // //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5261 // if (rct.Width > 0)
5263 // RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5264 // //e.Graphics.FillRectangle(Brushes.White, rct);
5265 // //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5266 // e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5271 internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5273 var tab = this._statuses.Tabs[this._curTab.Text];
5275 if (tab.AllCount == 0)
5277 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5281 var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5286 case SEARCHTYPE.NextSearch: // 次を検索
5287 if (selectedIndex != -1)
5288 startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5292 case SEARCHTYPE.PrevSearch: // 前を検索
5293 if (selectedIndex != -1)
5294 startIndex = Math.Max(selectedIndex - 1, 0);
5296 startIndex = tab.AllCount - 1;
5298 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5300 if (selectedIndex != -1)
5301 startIndex = selectedIndex;
5307 Func<string, bool> stringComparer;
5310 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5312 catch (ArgumentException)
5314 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5318 var reverse = searchType == SEARCHTYPE.PrevSearch;
5319 var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5320 .DefaultIfEmpty(-1).First();
5322 if (foundIndex == -1)
5324 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5328 this.SelectListItem(this._curList, foundIndex);
5329 this._curList.EnsureVisible(foundIndex);
5332 private void MenuItemSubSearch_Click(object sender, EventArgs e)
5335 this.ShowSearchDialog();
5338 private void MenuItemSearchNext_Click(object sender, EventArgs e)
5340 var previousSearch = this.SearchDialog.ResultOptions;
5341 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5343 this.SearchDialog.Reset();
5344 this.ShowSearchDialog();
5350 previousSearch.Query,
5351 previousSearch.CaseSensitive,
5352 previousSearch.UseRegex,
5353 SEARCHTYPE.NextSearch);
5356 private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5358 var previousSearch = this.SearchDialog.ResultOptions;
5359 if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5361 this.SearchDialog.Reset();
5362 this.ShowSearchDialog();
5368 previousSearch.Query,
5369 previousSearch.CaseSensitive,
5370 previousSearch.UseRegex,
5371 SEARCHTYPE.PrevSearch);
5375 /// 検索ダイアログを表示し、検索を実行します
5377 private void ShowSearchDialog()
5379 if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5381 this.TopMost = SettingManager.Common.AlwaysTop;
5384 this.TopMost = SettingManager.Common.AlwaysTop;
5386 var searchOptions = this.SearchDialog.ResultOptions;
5387 if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5389 if (searchOptions.NewTab)
5391 var tabName = Properties.Resources.SearchResults_TabName;
5395 tabName = this._statuses.MakeTabName(tabName);
5397 catch (TabException ex)
5399 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5402 var resultTab = new LocalSearchTabModel(tabName);
5403 this.AddNewTab(resultTab, startup: false);
5404 this._statuses.AddTab(resultTab);
5406 var targetTab = this._statuses.Tabs[this._curTab.Text];
5408 Func<string, bool> stringComparer;
5411 stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5413 catch (ArgumentException)
5415 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5419 var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5420 if (foundIndices.Length == 0)
5422 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5426 var foundPosts = foundIndices.Select(x => targetTab[x]);
5427 foreach (var post in foundPosts)
5429 resultTab.AddPostQueue(post);
5432 this._statuses.DistributePosts();
5433 this.RefreshTimeline();
5435 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5436 .First(x => x.Text == tabName);
5438 this.ListTab.SelectedTab = tabPage;
5443 searchOptions.Query,
5444 searchOptions.CaseSensitive,
5445 searchOptions.UseRegex,
5446 SEARCHTYPE.DialogSearch);
5449 else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5451 this.AddNewTabForSearch(searchOptions.Query);
5455 /// <summary>発言検索に使用するメソッドを生成します</summary>
5456 /// <exception cref="ArgumentException">
5457 /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5459 private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5463 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5464 var regex = new Regex(query, regexOption);
5466 return x => regex.IsMatch(x);
5470 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5472 return x => x.IndexOf(query, comparisonType) != -1;
5476 private void AboutMenuItem_Click(object sender, EventArgs e)
5478 using (TweenAboutBox about = new TweenAboutBox())
5480 about.ShowDialog(this);
5482 this.TopMost = SettingManager.Common.AlwaysTop;
5485 private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5487 int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5489 if (ImageSelector.Enabled)
5492 TabModel foundTab = null;
5495 DetailsListView lst = null;
5498 for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5500 var tabPage = this.ListTab.TabPages[i];
5501 var tab = this._statuses.Tabs[tabPage.Text];
5502 var unreadIndex = tab.NextUnreadIndex;
5504 if (unreadIndex != -1)
5506 ListTab.SelectedIndex = i;
5508 foundIndex = unreadIndex;
5509 lst = (DetailsListView)tabPage.Tag;
5514 //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5515 if (foundTab == null && bgnIdx > 0)
5517 for (int i = 0; i < bgnIdx; i++)
5519 var tabPage = this.ListTab.TabPages[i];
5520 var tab = this._statuses.Tabs[tabPage.Text];
5521 var unreadIndex = tab.NextUnreadIndex;
5523 if (unreadIndex != -1)
5525 ListTab.SelectedIndex = i;
5527 foundIndex = unreadIndex;
5528 lst = (DetailsListView)tabPage.Tag;
5534 if (foundTab == null)
5536 //全部調べたが未読見つからず→先頭タブの最新発言へ
5537 ListTab.SelectedIndex = 0;
5538 var tabPage = this.ListTab.TabPages[0];
5539 var tab = this._statuses.Tabs[tabPage.Text];
5541 if (tab.AllCount == 0)
5544 if (_statuses.SortOrder == SortOrder.Ascending)
5545 foundIndex = tab.AllCount - 1;
5549 lst = (DetailsListView)tabPage.Tag;
5552 SelectListItem(lst, foundIndex);
5554 if (_statuses.SortMode == ComparerMode.Id)
5556 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5557 _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5563 lst.EnsureVisible(foundIndex);
5568 lst.EnsureVisible(foundIndex);
5574 private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5576 if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5578 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5579 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5583 private async void FavorareMenuItem_Click(object sender, EventArgs e)
5585 if (_curList.SelectedIndices.Count > 0)
5587 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5588 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5592 private async void VerUpMenuItem_Click(object sender, EventArgs e)
5594 await this.CheckNewVersion(false);
5597 private void RunTweenUp()
5599 ProcessStartInfo pinfo = new ProcessStartInfo();
5600 pinfo.UseShellExecute = true;
5601 pinfo.WorkingDirectory = MyCommon.settingPath;
5602 pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5603 pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5606 Process.Start(pinfo);
5610 MessageBox.Show("Failed to execute TweenUp3.exe.");
5614 public class VersionInfo
5616 public Version Version { get; set; }
5617 public Uri DownloadUri { get; set; }
5618 public string ReleaseNote { get; set; }
5622 /// OpenTween の最新バージョンの情報を取得します
5624 public async Task<VersionInfo> GetVersionInfoAsync()
5626 var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5627 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5629 var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5630 .ConfigureAwait(false);
5632 // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5633 var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5635 var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5636 var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5638 msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5640 return new VersionInfo
5642 Version = Version.Parse(msgHeader[0]),
5643 DownloadUri = new Uri(msgHeader[1]),
5644 ReleaseNote = msgBody,
5648 private async Task CheckNewVersion(bool startup = false)
5650 if (ApplicationSettings.VersionInfoUrl == null)
5651 return; // 更新チェック無効化
5655 var versionInfo = await this.GetVersionInfoAsync();
5657 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5662 var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5663 MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5664 msgtext = MyCommon.ReplaceAppName(msgtext);
5666 MessageBox.Show(msgtext,
5667 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5668 MessageBoxButtons.OK, MessageBoxIcon.Information);
5673 using (var dialog = new UpdateDialog())
5675 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5676 MyCommon.GetReadableVersion(versionInfo.Version));
5677 dialog.DetailsText = versionInfo.ReleaseNote;
5679 if (dialog.ShowDialog(this) == DialogResult.Yes)
5681 await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5687 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5690 MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5691 MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5692 MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5697 private async Task Colorize()
5700 await this.DispSelectedPost();
5701 //件数関連の場合、タイトル即時書き換え
5702 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5703 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5704 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5705 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5707 SetMainWindowTitle();
5709 if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5710 SetStatusLabelUrl();
5711 foreach (TabPage tb in ListTab.TabPages)
5713 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5715 if (SettingManager.Common.TabIconDisp)
5717 if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5721 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5724 public string createDetailHtml(string orgdata)
5726 if (SettingManager.Local.UseTwemoji)
5727 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5729 return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5732 private Task DispSelectedPost()
5734 return this.DispSelectedPost(false);
5737 private PostClass displayPost = new PostClass();
5740 /// サムネイル表示に使用する CancellationToken の生成元
5742 private CancellationTokenSource thumbnailTokenSource = null;
5744 private async Task DispSelectedPost(bool forceupdate)
5746 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5749 var oldDisplayPost = this.displayPost;
5750 this.displayPost = this._curPost;
5752 if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5755 var loadTasks = new List<Task>
5757 this.tweetDetailsView.ShowPostDetails(this._curPost),
5760 this.SplitContainer3.Panel2Collapsed = true;
5762 if (SettingManager.Common.PreviewEnable)
5764 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5765 oldTokenSource?.Cancel();
5767 var token = this.thumbnailTokenSource.Token;
5768 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5773 await Task.WhenAll(loadTasks);
5775 catch (OperationCanceledException) { }
5778 private async void MatomeMenuItem_Click(object sender, EventArgs e)
5780 await this.OpenApplicationWebsite();
5783 private async Task OpenApplicationWebsite()
5785 await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5788 private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5790 await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5793 private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5795 if (ListTab.SelectedTab != null)
5797 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5799 Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5800 if (pnl.Controls["comboSearch"].Focused ||
5801 pnl.Controls["comboLang"].Focused ||
5802 pnl.Controls["buttonSearch"].Focused) return;
5805 if (e.Control || e.Shift || e.Alt)
5806 this._anchorFlag = false;
5809 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
5812 e.SuppressKeyPress = true;
5815 if (asyncTask != null)
5820 private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5822 private void InitializeShortcuts()
5824 this.shortcutCommands = new[]
5826 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5827 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5828 .FocusedOn(FocusedControl.ListTab)
5829 .Do(() => SendKeys.Send("{DOWN}")),
5831 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5832 .FocusedOn(FocusedControl.ListTab)
5833 .Do(() => SendKeys.Send("{UP}")),
5835 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5836 .FocusedOn(FocusedControl.ListTab)
5837 .Do(() => SendKeys.Send("{PGDN}")),
5839 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5840 .FocusedOn(FocusedControl.ListTab)
5841 .Do(() => SendKeys.Send("{PGUP}")),
5843 ShortcutCommand.Create(Keys.F1)
5844 .Do(() => this.OpenApplicationWebsite()),
5846 ShortcutCommand.Create(Keys.F3)
5847 .Do(() => this.MenuItemSearchNext_Click(null, null)),
5849 ShortcutCommand.Create(Keys.F5)
5850 .Do(() => this.DoRefresh()),
5852 ShortcutCommand.Create(Keys.F6)
5853 .Do(() => this.GetReplyAsync()),
5855 ShortcutCommand.Create(Keys.F7)
5856 .Do(() => this.GetDirectMessagesAsync()),
5858 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5859 .NotFocusedOn(FocusedControl.StatusText)
5860 .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5862 ShortcutCommand.Create(Keys.G)
5863 .NotFocusedOn(FocusedControl.StatusText)
5864 .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5866 ShortcutCommand.Create(Keys.Right, Keys.N)
5867 .FocusedOn(FocusedControl.ListTab)
5868 .Do(() => this.GoRelPost(forward: true)),
5870 ShortcutCommand.Create(Keys.Left, Keys.P)
5871 .FocusedOn(FocusedControl.ListTab)
5872 .Do(() => this.GoRelPost(forward: false)),
5874 ShortcutCommand.Create(Keys.OemPeriod)
5875 .FocusedOn(FocusedControl.ListTab)
5876 .Do(() => this.GoAnchor()),
5878 ShortcutCommand.Create(Keys.I)
5879 .FocusedOn(FocusedControl.ListTab)
5880 .OnlyWhen(() => this.StatusText.Enabled)
5881 .Do(() => this.StatusText.Focus()),
5883 ShortcutCommand.Create(Keys.Enter)
5884 .FocusedOn(FocusedControl.ListTab)
5885 .Do(() => this.MakeReplyOrDirectStatus()),
5887 ShortcutCommand.Create(Keys.R)
5888 .FocusedOn(FocusedControl.ListTab)
5889 .Do(() => this.DoRefresh()),
5891 ShortcutCommand.Create(Keys.L)
5892 .FocusedOn(FocusedControl.ListTab)
5893 .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5895 ShortcutCommand.Create(Keys.H)
5896 .FocusedOn(FocusedControl.ListTab)
5897 .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5899 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5900 .FocusedOn(FocusedControl.ListTab)
5901 .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5903 ShortcutCommand.Create(Keys.S)
5904 .FocusedOn(FocusedControl.ListTab)
5905 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5907 ShortcutCommand.Create(Keys.A)
5908 .FocusedOn(FocusedControl.ListTab)
5909 .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5911 // ] in_reply_to参照元へ戻る
5912 ShortcutCommand.Create(Keys.Oem4)
5913 .FocusedOn(FocusedControl.ListTab)
5914 .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5916 // [ in_reply_toへジャンプ
5917 ShortcutCommand.Create(Keys.Oem6)
5918 .FocusedOn(FocusedControl.ListTab)
5919 .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5921 ShortcutCommand.Create(Keys.Escape)
5922 .FocusedOn(FocusedControl.ListTab)
5924 this._anchorFlag = false;
5925 if (ListTab.SelectedTab != null)
5927 var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5928 if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5930 var relTp = ListTab.SelectedTab;
5931 RemoveSpecifiedTab(relTp.Text, false);
5937 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5938 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5939 .FocusedOn(FocusedControl.ListTab)
5940 .Do(() => this._anchorFlag = false, preventDefault: false),
5942 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5943 ShortcutCommand.Create(Keys.Up, Keys.Down)
5944 .FocusedOn(FocusedControl.PostBrowser)
5947 ShortcutCommand.Create(Keys.Control | Keys.R)
5948 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5950 ShortcutCommand.Create(Keys.Control | Keys.D)
5951 .Do(() => this.doStatusDelete()),
5953 ShortcutCommand.Create(Keys.Control | Keys.M)
5954 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5956 ShortcutCommand.Create(Keys.Control | Keys.S)
5957 .Do(() => this.FavoriteChange(FavAdd: true)),
5959 ShortcutCommand.Create(Keys.Control | Keys.I)
5960 .Do(() => this.doRepliedStatusOpen()),
5962 ShortcutCommand.Create(Keys.Control | Keys.Q)
5963 .Do(() => this.doQuoteOfficial()),
5965 ShortcutCommand.Create(Keys.Control | Keys.B)
5966 .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5968 ShortcutCommand.Create(Keys.Control | Keys.T)
5969 .Do(() => this.HashManageMenuItem_Click(null, null)),
5971 ShortcutCommand.Create(Keys.Control | Keys.L)
5972 .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5974 ShortcutCommand.Create(Keys.Control | Keys.Y)
5975 .NotFocusedOn(FocusedControl.PostBrowser)
5976 .Do(() => this.MultiLineMenuItem_Click(null, null)),
5978 ShortcutCommand.Create(Keys.Control | Keys.F)
5979 .Do(() => this.MenuItemSubSearch_Click(null, null)),
5981 ShortcutCommand.Create(Keys.Control | Keys.U)
5982 .Do(() => this.ShowUserTimeline()),
5984 ShortcutCommand.Create(Keys.Control | Keys.H)
5985 .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5987 ShortcutCommand.Create(Keys.Control | Keys.G)
5988 .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5990 ShortcutCommand.Create(Keys.Control | Keys.O)
5991 .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5993 ShortcutCommand.Create(Keys.Control | Keys.E)
5994 .Do(() => this.OpenURLMenuItem_Click(null, null)),
5996 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5997 .FocusedOn(FocusedControl.ListTab)
5998 .Do(() => this._colorize = true, preventDefault: false),
6000 ShortcutCommand.Create(Keys.Control | Keys.N)
6001 .FocusedOn(FocusedControl.ListTab)
6002 .Do(() => this.GoNextTab(forward: true)),
6004 ShortcutCommand.Create(Keys.Control | Keys.P)
6005 .FocusedOn(FocusedControl.ListTab)
6006 .Do(() => this.GoNextTab(forward: false)),
6008 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6009 .FocusedOn(FocusedControl.ListTab)
6010 .Do(() => this.CopyStot()),
6012 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6013 ShortcutCommand.Create(Keys.Control | Keys.D1)
6014 .FocusedOn(FocusedControl.ListTab)
6015 .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6016 .Do(() => this.ListTab.SelectedIndex = 0),
6018 ShortcutCommand.Create(Keys.Control | Keys.D2)
6019 .FocusedOn(FocusedControl.ListTab)
6020 .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6021 .Do(() => this.ListTab.SelectedIndex = 1),
6023 ShortcutCommand.Create(Keys.Control | Keys.D3)
6024 .FocusedOn(FocusedControl.ListTab)
6025 .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6026 .Do(() => this.ListTab.SelectedIndex = 2),
6028 ShortcutCommand.Create(Keys.Control | Keys.D4)
6029 .FocusedOn(FocusedControl.ListTab)
6030 .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6031 .Do(() => this.ListTab.SelectedIndex = 3),
6033 ShortcutCommand.Create(Keys.Control | Keys.D5)
6034 .FocusedOn(FocusedControl.ListTab)
6035 .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6036 .Do(() => this.ListTab.SelectedIndex = 4),
6038 ShortcutCommand.Create(Keys.Control | Keys.D6)
6039 .FocusedOn(FocusedControl.ListTab)
6040 .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6041 .Do(() => this.ListTab.SelectedIndex = 5),
6043 ShortcutCommand.Create(Keys.Control | Keys.D7)
6044 .FocusedOn(FocusedControl.ListTab)
6045 .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6046 .Do(() => this.ListTab.SelectedIndex = 6),
6048 ShortcutCommand.Create(Keys.Control | Keys.D8)
6049 .FocusedOn(FocusedControl.ListTab)
6050 .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6051 .Do(() => this.ListTab.SelectedIndex = 7),
6053 ShortcutCommand.Create(Keys.Control | Keys.D9)
6054 .FocusedOn(FocusedControl.ListTab)
6055 .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6057 ShortcutCommand.Create(Keys.Control | Keys.A)
6058 .FocusedOn(FocusedControl.StatusText)
6059 .Do(() => this.StatusText.SelectAll()),
6061 ShortcutCommand.Create(Keys.Control | Keys.V)
6062 .FocusedOn(FocusedControl.StatusText)
6063 .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6065 ShortcutCommand.Create(Keys.Control | Keys.Up)
6066 .FocusedOn(FocusedControl.StatusText)
6068 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6070 var inReplyToStatusId = this.inReplyTo?.Item1;
6071 var inReplyToScreenName = this.inReplyTo?.Item2;
6072 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6075 if (_hisIdx < 0) _hisIdx = 0;
6077 var historyItem = this._history[this._hisIdx];
6078 StatusText.Text = historyItem.status;
6079 StatusText.SelectionStart = StatusText.Text.Length;
6080 if (historyItem.inReplyToId != null)
6081 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6083 this.inReplyTo = null;
6086 ShortcutCommand.Create(Keys.Control | Keys.Down)
6087 .FocusedOn(FocusedControl.StatusText)
6089 if (!string.IsNullOrWhiteSpace(StatusText.Text))
6091 var inReplyToStatusId = this.inReplyTo?.Item1;
6092 var inReplyToScreenName = this.inReplyTo?.Item2;
6093 _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6096 if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6098 var historyItem = this._history[this._hisIdx];
6099 StatusText.Text = historyItem.status;
6100 StatusText.SelectionStart = StatusText.Text.Length;
6101 if (historyItem.inReplyToId != null)
6102 this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6104 this.inReplyTo = null;
6107 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6108 .FocusedOn(FocusedControl.StatusText)
6110 if (ListTab.SelectedIndex == 0)
6112 ListTab.SelectedIndex = ListTab.TabCount - 1;
6116 ListTab.SelectedIndex -= 1;
6121 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6122 .FocusedOn(FocusedControl.StatusText)
6124 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6126 ListTab.SelectedIndex = 0;
6130 ListTab.SelectedIndex += 1;
6135 ShortcutCommand.Create(Keys.Control | Keys.Y)
6136 .FocusedOn(FocusedControl.PostBrowser)
6138 MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6139 MultiLineMenuItem_Click(null, null);
6142 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6143 .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6145 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6146 .Do(() => this.DoRefreshMore()),
6148 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6149 .Do(() => this.GetReplyAsync(loadMore: true)),
6151 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6152 .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6154 ShortcutCommand.Create(Keys.Shift | Keys.R)
6155 .NotFocusedOn(FocusedControl.StatusText)
6156 .Do(() => this.DoRefreshMore()),
6158 ShortcutCommand.Create(Keys.Shift | Keys.H)
6159 .FocusedOn(FocusedControl.ListTab)
6160 .Do(() => this.GoTopEnd(GoTop: true)),
6162 ShortcutCommand.Create(Keys.Shift | Keys.L)
6163 .FocusedOn(FocusedControl.ListTab)
6164 .Do(() => this.GoTopEnd(GoTop: false)),
6166 ShortcutCommand.Create(Keys.Shift | Keys.M)
6167 .FocusedOn(FocusedControl.ListTab)
6168 .Do(() => this.GoMiddle()),
6170 ShortcutCommand.Create(Keys.Shift | Keys.G)
6171 .FocusedOn(FocusedControl.ListTab)
6172 .Do(() => this.GoLast()),
6174 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6175 .FocusedOn(FocusedControl.ListTab)
6176 .Do(() => this.MoveMiddle()),
6178 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6179 .FocusedOn(FocusedControl.ListTab)
6180 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6182 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6183 .FocusedOn(FocusedControl.ListTab)
6184 .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6186 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6187 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6188 .FocusedOn(FocusedControl.ListTab)
6189 .Do(() => this.GoFav(forward: true)),
6191 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6192 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6193 .FocusedOn(FocusedControl.ListTab)
6194 .Do(() => this.GoFav(forward: false)),
6196 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6197 .FocusedOn(FocusedControl.ListTab)
6198 .Do(() => this.GoBackSelectPostChain()),
6200 ShortcutCommand.Create(Keys.Alt | Keys.R)
6201 .Do(() => this.doReTweetOfficial(isConfirm: true)),
6203 ShortcutCommand.Create(Keys.Alt | Keys.P)
6204 .OnlyWhen(() => this._curPost != null)
6205 .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6207 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6208 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6210 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6211 .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6213 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6214 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6216 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6217 .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6219 // 別タブの同じ書き込みへ(ALT+←/→)
6220 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6221 .FocusedOn(FocusedControl.ListTab)
6222 .Do(() => this.GoSamePostToAnotherTab(left: false)),
6224 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6225 .FocusedOn(FocusedControl.ListTab)
6226 .Do(() => this.GoSamePostToAnotherTab(left: true)),
6228 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6229 .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6231 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6232 .Do(() => this.CopyIdUri()),
6234 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6235 .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6236 this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6237 .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6239 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6240 .Do(() => this.FavoriteChange(FavAdd: false)),
6242 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6243 .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6245 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6246 .Do(() => this.HashToggleMenuItem_Click(null, null)),
6248 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6249 .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6251 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6252 .Do(() => this.doMoveToRTHome()),
6254 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6255 .Do(() => this.FavorareMenuItem_Click(null, null)),
6257 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6258 .FocusedOn(FocusedControl.StatusText)
6260 if (_curList != null && _curList.VirtualListSize != 0 &&
6261 _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6263 var idx = _curList.SelectedIndices[0] - 1;
6264 SelectListItem(_curList, idx);
6265 _curList.EnsureVisible(idx);
6269 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6270 .FocusedOn(FocusedControl.StatusText)
6272 if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6273 && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6275 var idx = _curList.SelectedIndices[0] + 1;
6276 SelectListItem(_curList, idx);
6277 _curList.EnsureVisible(idx);
6281 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6282 .FocusedOn(FocusedControl.StatusText)
6284 if (StatusText.SelectionStart > 0)
6286 int endidx = StatusText.SelectionStart - 1;
6287 string startstr = "";
6288 for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6290 char c = StatusText.Text[i];
6291 if (Char.IsLetterOrDigit(c) || c == '_')
6297 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6298 int cnt = AtIdSupl.ItemCount;
6299 ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6300 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6304 startstr = StatusText.Text.Substring(i + 1, endidx - i);
6305 ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6315 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6316 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6317 .FocusedOn(FocusedControl.ListTab)
6318 .Do(() => this.SetSortColumnByDisplayIndex(0)),
6320 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6321 .FocusedOn(FocusedControl.ListTab)
6322 .Do(() => this.SetSortColumnByDisplayIndex(1)),
6324 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6325 .FocusedOn(FocusedControl.ListTab)
6326 .Do(() => this.SetSortColumnByDisplayIndex(2)),
6328 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6329 .FocusedOn(FocusedControl.ListTab)
6330 .Do(() => this.SetSortColumnByDisplayIndex(3)),
6332 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6333 .FocusedOn(FocusedControl.ListTab)
6334 .Do(() => this.SetSortColumnByDisplayIndex(4)),
6336 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6337 .FocusedOn(FocusedControl.ListTab)
6338 .Do(() => this.SetSortColumnByDisplayIndex(5)),
6340 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6341 .FocusedOn(FocusedControl.ListTab)
6342 .Do(() => this.SetSortColumnByDisplayIndex(6)),
6344 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6345 .FocusedOn(FocusedControl.ListTab)
6346 .Do(() => this.SetSortColumnByDisplayIndex(7)),
6348 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6349 .FocusedOn(FocusedControl.ListTab)
6350 .Do(() => this.SetSortLastColumn()),
6352 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6353 .Do(() => this.FavoritesRetweetOfficial()),
6355 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6356 .Do(() => this.FavoritesRetweetUnofficial()),
6358 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6359 .Do(() => this.OpenUserAppointUrl()),
6361 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6362 .FocusedOn(FocusedControl.PostBrowser)
6363 .Do(() => this.doReTweetUnofficial()),
6365 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6366 .OnlyWhen(() => this.ExistCurrentPost)
6367 .Do(() => this.tweetDetailsView.DoTranslation()),
6369 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6370 .Do(() => this.doReTweetUnofficial()),
6372 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6373 .Do(() => this.CopyUserId()),
6375 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6376 .Do(() => this.tweetThumbnail1.ScrollUp()),
6378 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6379 .Do(() => this.tweetThumbnail1.ScrollDown()),
6381 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6382 .FocusedOn(FocusedControl.ListTab)
6383 .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6384 .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6388 internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6390 // Task を返す非同期処理があれば asyncTask に代入する
6393 // ShortcutCommand に対応しているコマンドはここで処理される
6394 foreach (var command in this.shortcutCommands)
6396 if (command.IsMatch(keyData, focusedOn))
6398 asyncTask = command.RunCommand();
6399 return command.PreventDefault;
6406 private void GoNextTab(bool forward)
6408 int idx = ListTab.SelectedIndex;
6412 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6417 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6419 ListTab.SelectedIndex = idx;
6422 private void CopyStot()
6425 StringBuilder sb = new StringBuilder();
6426 bool IsProtected = false;
6428 if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6429 foreach (int idx in _curList.SelectedIndices)
6431 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6432 if (post.IsDeleted) continue;
6435 if (post.RetweetedId != null)
6436 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6438 sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6442 sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6447 MessageBox.Show(Properties.Resources.CopyStotText1);
6451 clstr = sb.ToString();
6454 Clipboard.SetDataObject(clstr, false, 5, 100);
6456 catch (Exception ex)
6458 MessageBox.Show(ex.Message);
6463 private void CopyIdUri()
6465 if (this._curTab == null)
6468 var tab = this._statuses.GetTabByName(this._curTab.Text);
6469 if (tab == null || tab is DirectMessagesTabModel)
6472 var copyUrls = new List<string>();
6473 foreach (int idx in _curList.SelectedIndices)
6475 var post = tab[idx];
6476 copyUrls.Add(MyCommon.GetStatusUrl(post));
6479 if (copyUrls.Count == 0)
6484 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6486 catch (ExternalException ex)
6488 MessageBox.Show(ex.Message);
6492 private void GoFav(bool forward)
6494 if (_curList.VirtualListSize == 0) return;
6501 if (_curList.SelectedIndices.Count == 0)
6507 fIdx = _curList.SelectedIndices[0] + 1;
6508 if (fIdx > _curList.VirtualListSize - 1) return;
6510 toIdx = _curList.VirtualListSize;
6515 if (_curList.SelectedIndices.Count == 0)
6517 fIdx = _curList.VirtualListSize - 1;
6521 fIdx = _curList.SelectedIndices[0] - 1;
6522 if (fIdx < 0) return;
6528 for (int idx = fIdx; idx != toIdx; idx += stp)
6530 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6532 SelectListItem(_curList, idx);
6533 _curList.EnsureVisible(idx);
6539 private void GoSamePostToAnotherTab(bool left)
6541 if (this._curList.SelectedIndices.Count == 0)
6544 var tab = this._statuses.Tabs[this._curTab.Text];
6546 // Directタブは対象外(見つかるはずがない)
6547 if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6550 var selectedIndex = this._curList.SelectedIndices[0];
6551 var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6553 int fIdx, toIdx, stp;
6558 if (ListTab.SelectedIndex == 0)
6564 fIdx = ListTab.SelectedIndex - 1;
6572 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6578 fIdx = ListTab.SelectedIndex + 1;
6580 toIdx = ListTab.TabCount;
6584 for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6586 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6589 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6592 var foundIndex = targetTab.IndexOf(selectedStatusId);
6593 if (foundIndex != -1)
6595 ListTab.SelectedIndex = tabidx;
6596 SelectListItem(_curList, foundIndex);
6597 _curList.EnsureVisible(foundIndex);
6603 private void GoPost(bool forward)
6605 if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6608 var tab = this._statuses.Tabs[this._curTab.Text];
6609 var selectedIndex = this._curList.SelectedIndices[0];
6611 int fIdx, toIdx, stp;
6615 fIdx = selectedIndex + 1;
6616 if (fIdx > tab.AllCount - 1) return;
6617 toIdx = tab.AllCount;
6622 fIdx = selectedIndex - 1;
6623 if (fIdx < 0) return;
6629 if (_curPost.RetweetedId == null)
6631 name = _curPost.ScreenName;
6635 name = _curPost.RetweetedBy;
6637 for (int idx = fIdx; idx != toIdx; idx += stp)
6639 var post = tab[idx];
6640 if (post.RetweetedId == null)
6642 if (post.ScreenName == name)
6644 SelectListItem(_curList, idx);
6645 _curList.EnsureVisible(idx);
6651 if (post.RetweetedBy == name)
6653 SelectListItem(_curList, idx);
6654 _curList.EnsureVisible(idx);
6661 private void GoRelPost(bool forward)
6663 if (this._curList.SelectedIndices.Count == 0)
6666 var tab = this._statuses.Tabs[this._curTab.Text];
6667 var selectedIndex = this._curList.SelectedIndices[0];
6669 int fIdx, toIdx, stp;
6673 fIdx = selectedIndex + 1;
6674 if (fIdx > tab.AllCount - 1) return;
6675 toIdx = tab.AllCount;
6680 fIdx = selectedIndex - 1;
6681 if (fIdx < 0) return;
6688 if (_curPost == null) return;
6689 _anchorPost = _curPost;
6694 if (_anchorPost == null) return;
6697 for (int idx = fIdx; idx != toIdx; idx += stp)
6699 var post = tab[idx];
6700 if (post.ScreenName == _anchorPost.ScreenName ||
6701 post.RetweetedBy == _anchorPost.ScreenName ||
6702 post.ScreenName == _anchorPost.RetweetedBy ||
6703 (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6704 _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6705 _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6706 post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6707 post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6709 SelectListItem(_curList, idx);
6710 _curList.EnsureVisible(idx);
6716 private void GoAnchor()
6718 if (_anchorPost == null) return;
6719 int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6720 if (idx == -1) return;
6722 SelectListItem(_curList, idx);
6723 _curList.EnsureVisible(idx);
6726 private void GoTopEnd(bool GoTop)
6728 if (_curList.VirtualListSize == 0)
6736 _item = _curList.GetItemAt(0, 25);
6744 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6746 idx = _curList.VirtualListSize - 1;
6750 SelectListItem(_curList, idx);
6753 private void GoMiddle()
6755 if (_curList.VirtualListSize == 0)
6763 _item = _curList.GetItemAt(0, 0);
6773 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6776 idx2 = _curList.VirtualListSize - 1;
6782 idx3 = (idx1 + idx2) / 2;
6784 SelectListItem(_curList, idx3);
6787 private void GoLast()
6789 if (_curList.VirtualListSize == 0) return;
6791 if (_statuses.SortOrder == SortOrder.Ascending)
6793 SelectListItem(_curList, _curList.VirtualListSize - 1);
6794 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6798 SelectListItem(_curList, 0);
6799 _curList.EnsureVisible(0);
6803 private void MoveTop()
6805 if (_curList.SelectedIndices.Count == 0) return;
6806 int idx = _curList.SelectedIndices[0];
6807 if (_statuses.SortOrder == SortOrder.Ascending)
6809 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6813 _curList.EnsureVisible(0);
6815 _curList.EnsureVisible(idx);
6818 private async Task GoInReplyToPostTree()
6820 if (_curPost == null) return;
6822 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6824 if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6828 var post = await tw.GetStatusApi(false, _curPost.StatusId);
6830 _curPost.InReplyToStatusId = post.InReplyToStatusId;
6831 _curPost.InReplyToUser = post.InReplyToUser;
6832 _curPost.IsReply = post.IsReply;
6833 this.PurgeListViewItemCache();
6834 _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6836 catch (WebApiException ex)
6838 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6842 if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6844 if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6846 replyChains = new Stack<ReplyChain>();
6848 replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6851 string inReplyToTabName;
6852 long inReplyToId = _curPost.InReplyToStatusId.Value;
6853 string inReplyToUser = _curPost.InReplyToUser;
6854 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6856 var inReplyToPosts = from tab in _statuses.Tabs.Values
6857 orderby tab != curTabClass
6858 from post in tab.Posts.Values
6859 where post.StatusId == inReplyToId
6860 let index = tab.IndexOf(post.StatusId)
6862 select new {Tab = tab, Index = index};
6864 var inReplyPost = inReplyToPosts.FirstOrDefault();
6865 if (inReplyPost == null)
6869 await Task.Run(async () =>
6871 var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6872 .ConfigureAwait(false);
6875 _statuses.AddPost(post);
6876 _statuses.DistributePosts();
6879 catch (WebApiException ex)
6881 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6882 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6886 this.RefreshTimeline();
6888 inReplyPost = inReplyToPosts.FirstOrDefault();
6889 if (inReplyPost == null)
6891 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6895 inReplyToTabName = inReplyPost.Tab.TabName;
6896 inReplyToIndex = inReplyPost.Index;
6898 TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6899 DetailsListView listView = (DetailsListView)tabPage.Tag;
6901 if (_curTab != tabPage)
6903 this.ListTab.SelectTab(tabPage);
6906 this.SelectListItem(listView, inReplyToIndex);
6907 listView.EnsureVisible(inReplyToIndex);
6910 private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6912 if (_curPost == null) return;
6914 TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6915 //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6919 if (_curPost.InReplyToStatusId != null)
6921 var posts = from t in _statuses.Tabs
6922 from p in t.Value.Posts
6923 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6924 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6926 orderby isForward ? indexOf : indexOf * -1
6927 orderby t.Value != curTabClass
6928 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6931 var postList = posts.ToList();
6932 for (int i = postList.Count - 1; i >= 0; i--)
6935 if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6937 postList.RemoveAt(index);
6940 var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6941 if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6942 if (post == null) post = postList.First();
6943 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6944 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6945 SelectListItem(listView, post.Index);
6946 listView.EnsureVisible(post.Index);
6948 catch (InvalidOperationException)
6956 if (replyChains == null || replyChains.Count < 1)
6958 var posts = from t in _statuses.Tabs
6959 from p in t.Value.Posts
6960 where p.Value.InReplyToStatusId == _curPost.StatusId
6961 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6964 orderby t.Value != curTabClass
6965 select new {Tab = t.Value, Index = indexOf};
6968 var post = posts.First();
6969 this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6970 DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6971 SelectListItem(listView, post.Index);
6972 listView.EnsureVisible(post.Index);
6974 catch (InvalidOperationException)
6981 ReplyChain chainHead = replyChains.Pop();
6982 if (chainHead.InReplyToId == _curPost.StatusId)
6984 int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6993 ListTab.SelectTab(chainHead.OriginalTab);
6999 SelectListItem(_curList, idx);
7000 _curList.EnsureVisible(idx);
7006 this.GoBackInReplyToPostTree(parallel);
7012 private void GoBackSelectPostChain()
7014 if (this.selectPostChains.Count > 1)
7023 this.selectPostChains.Pop();
7024 var tabPostPair = this.selectPostChains.Peek();
7026 if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue; //該当タブが存在しないので無視
7028 if (tabPostPair.Item2 != null)
7030 idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7031 if (idx == -1) continue; //該当ポストが存在しないので無視
7034 tp = tabPostPair.Item1;
7036 this.selectPostChains.Pop();
7038 catch (InvalidOperationException)
7044 while (this.selectPostChains.Count > 1);
7049 //履歴が残り1つであればクリアしておく
7050 if (this.selectPostChains.Count == 1)
7051 this.selectPostChains.Clear();
7055 DetailsListView lst = (DetailsListView)tp.Tag;
7056 this.ListTab.SelectedTab = tp;
7059 SelectListItem(lst, idx);
7060 lst.EnsureVisible(idx);
7066 private void PushSelectPostChain()
7068 int count = this.selectPostChains.Count;
7071 var p = this.selectPostChains.Peek();
7072 if (p.Item1 == this._curTab)
7074 if (p.Item2 == this._curPost) return; //最新の履歴と同一
7075 if (p.Item2 == null) this.selectPostChains.Pop(); //置き換えるため削除
7078 if (count >= 2500) TrimPostChain();
7079 this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7082 private void TrimPostChain()
7084 if (this.selectPostChains.Count <= 2000) return;
7085 var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7086 for (int i = 0; i < 2000; i++)
7088 p.Push(this.selectPostChains.Pop());
7090 this.selectPostChains.Clear();
7091 for (int i = 0; i < 2000; i++)
7093 this.selectPostChains.Push(p.Pop());
7097 private bool GoStatus(long statusId)
7099 if (statusId == 0) return false;
7100 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7102 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7104 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7105 ListTab.SelectedIndex = tabidx;
7106 SelectListItem(_curList, idx);
7107 _curList.EnsureVisible(idx);
7114 private bool GoDirectMessage(long statusId)
7116 if (statusId == 0) return false;
7117 for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7119 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7121 int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7122 ListTab.SelectedIndex = tabidx;
7123 SelectListItem(_curList, idx);
7124 _curList.EnsureVisible(idx);
7131 private void MyList_MouseClick(object sender, MouseEventArgs e)
7133 _anchorFlag = false;
7136 private void StatusText_Enter(object sender, EventArgs e)
7138 // フォーカスの戻り先を StatusText に設定
7139 this.Tag = StatusText;
7140 StatusText.BackColor = _clInputBackcolor;
7143 public Color InputBackColor
7145 get { return _clInputBackcolor; }
7146 set { _clInputBackcolor = value; }
7149 private void StatusText_Leave(object sender, EventArgs e)
7151 // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7152 if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7153 StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7156 private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7159 if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7162 e.SuppressKeyPress = true;
7165 this.StatusText_TextChanged(null, null);
7167 if (asyncTask != null)
7171 private void SaveConfigsAll(bool ifModified)
7175 SaveConfigsCommon();
7182 if (ModifySettingCommon) SaveConfigsCommon();
7183 if (ModifySettingLocal) SaveConfigsLocal();
7184 if (ModifySettingAtId) SaveConfigsAtId();
7188 private void SaveConfigsAtId()
7190 if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7192 ModifySettingAtId = false;
7193 SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7194 SettingManager.SaveAtIdList();
7197 private void SaveConfigsCommon()
7199 if (_ignoreConfigSave) return;
7201 ModifySettingCommon = false;
7204 SettingManager.Common.UserName = tw.Username;
7205 SettingManager.Common.UserId = tw.UserId;
7206 SettingManager.Common.Token = tw.AccessToken;
7207 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7209 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7210 IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7212 SettingManager.Common.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7215 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7216 switch (_statuses.SortMode)
7218 case ComparerMode.Nickname: //ニックネーム
7219 SettingManager.Common.SortColumn = 1;
7221 case ComparerMode.Data: //本文
7222 SettingManager.Common.SortColumn = 2;
7224 case ComparerMode.Id: //時刻=発言Id
7225 SettingManager.Common.SortColumn = 3;
7227 case ComparerMode.Name: //名前
7228 SettingManager.Common.SortColumn = 4;
7230 case ComparerMode.Source: //Source
7231 SettingManager.Common.SortColumn = 7;
7235 SettingManager.Common.HashTags = HashMgr.HashHistories;
7236 if (HashMgr.IsPermanent)
7238 SettingManager.Common.HashSelected = HashMgr.UseHash;
7242 SettingManager.Common.HashSelected = "";
7244 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7245 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7246 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7247 if (ToolStripFocusLockMenuItem != null &&
7248 ToolStripFocusLockMenuItem.IsDisposed == false)
7250 SettingManager.Common.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7252 SettingManager.Common.TrackWord = tw.TrackWord;
7253 SettingManager.Common.AllAtReply = tw.AllAtReply;
7254 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7255 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7257 SettingManager.SaveCommon();
7261 private void SaveConfigsLocal()
7263 if (_ignoreConfigSave) return;
7266 ModifySettingLocal = false;
7267 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7268 SettingManager.Local.FormSize = _mySize;
7269 SettingManager.Local.FormLocation = _myLoc;
7270 SettingManager.Local.SplitterDistance = _mySpDis;
7271 SettingManager.Local.PreviewDistance = _mySpDis3;
7272 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7273 SettingManager.Local.StatusTextHeight = _mySpDis2;
7275 SettingManager.Local.FontUnread = _fntUnread;
7276 SettingManager.Local.ColorUnread = _clUnread;
7277 SettingManager.Local.FontRead = _fntReaded;
7278 SettingManager.Local.ColorRead = _clReaded;
7279 SettingManager.Local.FontDetail = _fntDetail;
7280 SettingManager.Local.ColorDetail = _clDetail;
7281 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7282 SettingManager.Local.ColorDetailLink = _clDetailLink;
7283 SettingManager.Local.ColorFav = _clFav;
7284 SettingManager.Local.ColorOWL = _clOWL;
7285 SettingManager.Local.ColorRetweet = _clRetweet;
7286 SettingManager.Local.ColorSelf = _clSelf;
7287 SettingManager.Local.ColorAtSelf = _clAtSelf;
7288 SettingManager.Local.ColorTarget = _clTarget;
7289 SettingManager.Local.ColorAtTarget = _clAtTarget;
7290 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7291 SettingManager.Local.ColorAtTo = _clAtTo;
7292 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7293 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7294 SettingManager.Local.ColorInputFont = _clInputFont;
7295 SettingManager.Local.FontInputFont = _fntInputFont;
7297 if (_ignoreConfigSave) return;
7298 SettingManager.SaveLocal();
7302 private void SaveConfigsTabs()
7304 var tabSettingList = new List<SettingTabs.SettingTabItem>();
7306 var tabs = this.ListTab.TabPages.Cast<TabPage>()
7307 .Select(x => this._statuses.Tabs[x.Text])
7308 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7310 foreach (var tab in tabs)
7312 if (!tab.IsPermanentTabType)
7315 var tabSetting = new SettingTabs.SettingTabItem
7317 TabName = tab.TabName,
7318 TabType = tab.TabType,
7319 UnreadManage = tab.UnreadManage,
7320 Protected = tab.Protected,
7321 Notify = tab.Notify,
7322 SoundFile = tab.SoundFile,
7325 var filterTab = tab as FilterTabModel;
7326 if (filterTab != null)
7327 tabSetting.FilterArray = filterTab.FilterArray;
7329 var userTab = tab as UserTimelineTabModel;
7330 if (userTab != null)
7331 tabSetting.User = userTab.ScreenName;
7333 var searchTab = tab as PublicSearchTabModel;
7334 if (searchTab != null)
7336 tabSetting.SearchWords = searchTab.SearchWords;
7337 tabSetting.SearchLang = searchTab.SearchLang;
7340 var listTab = tab as ListTimelineTabModel;
7341 if (listTab != null)
7342 tabSetting.ListInfo = listTab.ListInfo;
7344 tabSettingList.Add(tabSetting);
7347 SettingManager.Tabs.Tabs = tabSettingList;
7348 SettingManager.SaveTabs();
7351 private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7354 var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7355 if (ret != DialogResult.OK)
7358 var match = Twitter.StatusUrlRegex.Match(inputText);
7361 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7362 Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7368 var statusId = long.Parse(match.Groups["StatusId"].Value);
7369 await this.OpenRelatedTab(statusId);
7371 catch (TabException ex)
7373 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7377 private void SaveLogMenuItem_Click(object sender, EventArgs e)
7379 DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7380 Properties.Resources.SaveLogMenuItem_ClickText2,
7381 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7382 if (rslt == DialogResult.Cancel) return;
7384 SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7385 SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7386 SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7387 SaveFileDialog1.FilterIndex = 0;
7388 SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7389 SaveFileDialog1.RestoreDirectory = true;
7391 if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7393 if (!SaveFileDialog1.ValidateNames) return;
7394 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7396 if (rslt == DialogResult.Yes)
7399 for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7401 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402 string protect = "";
7403 if (post.IsProtect) protect = "Protect";
7404 sw.WriteLine(post.Nickname + "\t" +
7405 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7406 post.CreatedAt + "\t" +
7407 post.ScreenName + "\t" +
7408 post.StatusId + "\t" +
7409 post.ImageUrl + "\t" +
7410 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7416 foreach (int idx in _curList.SelectedIndices)
7418 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7419 string protect = "";
7420 if (post.IsProtect) protect = "Protect";
7421 sw.WriteLine(post.Nickname + "\t" +
7422 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7423 post.CreatedAt + "\t" +
7424 post.ScreenName + "\t" +
7425 post.StatusId + "\t" +
7426 post.ImageUrl + "\t" +
7427 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7433 this.TopMost = SettingManager.Common.AlwaysTop;
7436 public bool TabRename(string origTabName, out string newTabName)
7440 using (InputTabName inputName = new InputTabName())
7442 inputName.TabName = origTabName;
7443 inputName.ShowDialog();
7444 if (inputName.DialogResult == DialogResult.Cancel) return false;
7445 newTabName = inputName.TabName;
7447 this.TopMost = SettingManager.Common.AlwaysTop;
7448 if (!string.IsNullOrEmpty(newTabName))
7451 for (int i = 0; i < ListTab.TabCount; i++)
7453 if (ListTab.TabPages[i].Text == newTabName)
7455 string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7456 MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7461 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7462 .FirstOrDefault(x => x.Text == origTabName);
7465 if (tabPage != null)
7466 tabPage.Text = newTabName;
7468 _statuses.RenameTab(origTabName, newTabName);
7470 SaveConfigsCommon();
7472 _rclickTabName = newTabName;
7481 private void ListTab_MouseClick(object sender, MouseEventArgs e)
7483 if (e.Button == MouseButtons.Middle)
7485 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7487 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7489 this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7490 this.SaveConfigsTabs();
7497 private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7500 TabRename(this.ListTab.SelectedTab.Text, out _);
7503 private void ListTab_MouseDown(object sender, MouseEventArgs e)
7505 if (SettingManager.Common.TabMouseLock) return;
7506 if (e.Button == MouseButtons.Left)
7508 for (int i = 0; i < ListTab.TabPages.Count; i++)
7510 if (this.ListTab.GetTabRect(i).Contains(e.Location))
7513 _tabMouseDownPoint = e.Location;
7524 private void ListTab_DragEnter(object sender, DragEventArgs e)
7526 if (e.Data.GetDataPresent(typeof(TabPage)))
7527 e.Effect = DragDropEffects.Move;
7529 e.Effect = DragDropEffects.None;
7532 private void ListTab_DragDrop(object sender, DragEventArgs e)
7534 if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7539 Point cpos = new Point(e.X, e.Y);
7540 Point spos = ListTab.PointToClient(cpos);
7542 for (i = 0; i < ListTab.TabPages.Count; i++)
7544 Rectangle rect = ListTab.GetTabRect(i);
7545 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7546 rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7548 tn = ListTab.TabPages[i].Text;
7549 if (spos.X <= (rect.Left + rect.Right) / 2)
7558 //タブのないところにドロップ->最後尾へ移動
7559 if (string.IsNullOrEmpty(tn))
7561 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7563 i = ListTab.TabPages.Count - 1;
7566 TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7567 if (tp.Text == tn) return;
7569 ReOrderTab(tp.Text, tn, bef);
7572 public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7574 var baseIndex = this.GetTabPageIndex(baseTabText);
7575 if (baseIndex == -1)
7578 var targetIndex = this.GetTabPageIndex(targetTabText);
7579 if (targetIndex == -1)
7582 using (ControlTransaction.Layout(this.ListTab))
7584 var mTp = this.ListTab.TabPages[targetIndex];
7585 this.ListTab.TabPages.Remove(mTp);
7587 if (targetIndex < baseIndex)
7590 if (isBeforeBaseTab)
7591 ListTab.TabPages.Insert(baseIndex, mTp);
7593 ListTab.TabPages.Insert(baseIndex + 1, mTp);
7599 private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7601 //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7602 //isReply:true=@,false=DM
7603 if (!StatusText.Enabled) return;
7604 if (_curList == null) return;
7605 if (_curTab == null) return;
7606 if (!this.ExistCurrentPost) return;
7608 // 複数あてリプライはReplyではなく通常ポスト
7609 //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7610 //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7611 //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7613 if (_curList.SelectedIndices.Count > 0)
7616 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7619 if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7622 StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7623 StatusText.SelectionStart = StatusText.Text.Length;
7625 this.inReplyTo = null;
7628 if (string.IsNullOrEmpty(StatusText.Text))
7632 // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7633 StatusText.Text = "@" + _curPost.ScreenName + " ";
7635 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7636 var inReplyToScreenName = this._curPost.ScreenName;
7637 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7645 //1件選んでEnter or DoubleClick
7646 if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7648 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7651 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7652 var inReplyToScreenName = this._curPost.ScreenName;
7653 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7657 if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7660 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7663 StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7664 this.inReplyTo = null;
7669 StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7670 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7671 var inReplyToScreenName = this._curPost.ScreenName;
7672 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7679 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7680 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7681 this.inReplyTo = null;
7686 //1件選んでCtrl-Rの場合(返信先操作せず)
7687 int sidx = StatusText.SelectionStart;
7688 string id = "@" + _curPost.ScreenName + " ";
7691 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7696 StatusText.Text = StatusText.Text.Insert(sidx, id);
7698 //if (StatusText.Text.StartsWith("@"))
7701 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7702 // sidx += 5 + _curPost.ScreenName.Length;
7707 // StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7708 // sidx += 3 + _curPost.ScreenName.Length;
7710 StatusText.SelectionStart = sidx;
7713 //_reply_to_name = null;
7721 if (!isAuto && !isReply) return;
7723 //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7727 //Enter or DoubleClick
7729 string sTxt = StatusText.Text;
7730 if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7733 this.inReplyTo = null;
7735 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7737 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7738 if (!sTxt.Contains("@" + post.ScreenName + " "))
7740 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7741 //sTxt = "@" + post.ScreenName + " " + sTxt;
7744 StatusText.Text = sTxt;
7749 if (_curList.SelectedIndices.Count > 1)
7754 int sidx = StatusText.SelectionStart;
7755 for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7757 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7758 if (!ids.Contains("@" + post.ScreenName + " ") &&
7759 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7761 ids += "@" + post.ScreenName + " ";
7765 foreach (string nm in post.ReplyToList)
7767 if (!ids.Contains("@" + nm + " ") &&
7768 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7770 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7772 ids += "@" + m.Result("${id}") + " ";
7774 ids += "@" + nm + " ";
7779 if (ids.Length == 0) return;
7780 if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7782 StatusText.Text = ". " + StatusText.Text;
7784 this.inReplyTo = null;
7788 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7793 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7795 //if (StatusText.Text.StartsWith("@"))
7797 // StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7798 // sidx += 2 + ids.Length;
7802 // StatusText.Text = StatusText.Text.Insert(sidx, ids);
7803 // sidx += 1 + ids.Length;
7805 StatusText.SelectionStart = sidx;
7811 //1件のみ選択のC-S-r(返信元付加する可能性あり)
7814 int sidx = StatusText.SelectionStart;
7815 PostClass post = _curPost;
7816 if (!ids.Contains("@" + post.ScreenName + " ") &&
7817 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7819 ids += "@" + post.ScreenName + " ";
7821 foreach (string nm in post.ReplyToList)
7823 if (!ids.Contains("@" + nm + " ") &&
7824 !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7826 Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7828 ids += "@" + m.Result("${id}") + " ";
7830 ids += "@" + nm + " ";
7833 if (!string.IsNullOrEmpty(post.RetweetedBy))
7835 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7836 !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7838 ids += "@" + post.RetweetedBy + " ";
7841 if (ids.Length == 0) return;
7842 if (string.IsNullOrEmpty(StatusText.Text))
7845 StatusText.Text = ids;
7846 StatusText.SelectionStart = ids.Length;
7849 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7850 var inReplyToScreenName = this._curPost.ScreenName;
7851 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7857 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7862 StatusText.Text = StatusText.Text.Insert(sidx, ids);
7864 StatusText.SelectionStart = sidx;
7870 StatusText.SelectionStart = StatusText.Text.Length;
7875 private void ListTab_MouseUp(object sender, MouseEventArgs e)
7880 private static int iconCnt = 0;
7881 private static int blinkCnt = 0;
7882 private static bool blink = false;
7883 private static bool idle = false;
7885 private async Task RefreshTasktrayIcon()
7888 await this.Colorize();
7890 if (!TimerRefreshIcon.Enabled) return;
7891 //Static usCheckCnt As int = 0
7893 //Static iconDlListTopItem As ListViewItem = null
7895 //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7896 // ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7898 // ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7900 //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7906 //if (usCheckCnt > 300) //1min
7909 // if (!this.IsReceivedUserStream)
7911 // TraceOut("ReconnectUserStream");
7912 // tw.ReconnectUserStream();
7916 var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7918 if (iconCnt >= this.NIconRefresh.Length)
7926 SaveConfigsAll(true);
7931 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7933 _myStatusError = false;
7937 TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7938 if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7940 if (blinkCnt > 0) return;
7942 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7944 NotifyIcon1.Icon = ReplyIcon;
7948 NotifyIcon1.Icon = ReplyIconBlink;
7956 //優先度:エラー→オフライン→アイドル
7960 NotifyIcon1.Icon = NIconAtRed;
7963 if (_myStatusOnline)
7965 NotifyIcon1.Icon = NIconAt;
7969 NotifyIcon1.Icon = NIconAtSmoke;
7973 private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7976 await this.RefreshTasktrayIcon();
7979 private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7981 //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7982 if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7984 if (ListTab != null && ListTab.SelectedTab != null)
7985 _rclickTabName = ListTab.SelectedTab.Text;
7990 if (_statuses == null) return;
7991 if (_statuses.Tabs == null) return;
7994 if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out tb))
7997 NotifyDispMenuItem.Checked = tb.Notify;
7998 this.NotifyTbMenuItem.Checked = tb.Notify;
8000 soundfileListup = true;
8001 SoundFileComboBox.Items.Clear();
8002 this.SoundFileTbComboBox.Items.Clear();
8003 SoundFileComboBox.Items.Add("");
8004 this.SoundFileTbComboBox.Items.Add("");
8005 DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8006 if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8008 oDir = oDir.GetDirectories("Sounds")[0];
8010 foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8012 SoundFileComboBox.Items.Add(oFile.Name);
8013 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8015 int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8016 if (idx == -1) idx = 0;
8017 SoundFileComboBox.SelectedIndex = idx;
8018 this.SoundFileTbComboBox.SelectedIndex = idx;
8019 soundfileListup = false;
8020 UreadManageMenuItem.Checked = tb.UnreadManage;
8021 this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8023 TabMenuControl(_rclickTabName);
8026 private void TabMenuControl(string tabName)
8028 var tabInfo = _statuses.GetTabByName(tabName);
8030 this.FilterEditMenuItem.Enabled = true;
8031 this.EditRuleTbMenuItem.Enabled = true;
8033 if (tabInfo.IsDefaultTabType)
8035 this.ProtectTabMenuItem.Enabled = false;
8036 this.ProtectTbMenuItem.Enabled = false;
8040 this.ProtectTabMenuItem.Enabled = true;
8041 this.ProtectTbMenuItem.Enabled = true;
8044 if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8046 this.ProtectTabMenuItem.Checked = true;
8047 this.ProtectTbMenuItem.Checked = true;
8048 this.DeleteTabMenuItem.Enabled = false;
8049 this.DeleteTbMenuItem.Enabled = false;
8053 this.ProtectTabMenuItem.Checked = false;
8054 this.ProtectTbMenuItem.Checked = false;
8055 this.DeleteTabMenuItem.Enabled = true;
8056 this.DeleteTbMenuItem.Enabled = true;
8060 private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8062 var checkState = ((ToolStripMenuItem)sender).Checked;
8065 this.ProtectTbMenuItem.Checked = checkState;
8066 this.ProtectTabMenuItem.Checked = checkState;
8069 this.DeleteTabMenuItem.Enabled = !checkState;
8070 this.DeleteTbMenuItem.Enabled = !checkState;
8072 if (string.IsNullOrEmpty(_rclickTabName)) return;
8073 _statuses.Tabs[_rclickTabName].Protected = checkState;
8078 private void UreadManageMenuItem_Click(object sender, EventArgs e)
8080 UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8081 this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8083 if (string.IsNullOrEmpty(_rclickTabName)) return;
8084 ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8089 public void ChangeTabUnreadManage(string tabName, bool isManage)
8091 var idx = this.GetTabPageIndex(tabName);
8095 _statuses.Tabs[tabName].UnreadManage = isManage;
8096 if (SettingManager.Common.TabIconDisp)
8098 if (_statuses.Tabs[tabName].UnreadCount > 0)
8099 ListTab.TabPages[idx].ImageIndex = 0;
8101 ListTab.TabPages[idx].ImageIndex = -1;
8104 if (_curTab.Text == tabName)
8106 this.PurgeListViewItemCache();
8110 SetMainWindowTitle();
8111 SetStatusLabelUrl();
8112 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8115 private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8117 NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8118 this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8120 if (string.IsNullOrEmpty(_rclickTabName)) return;
8122 _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8127 private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8129 if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8131 _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8136 private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8138 if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8140 RemoveSpecifiedTab(_rclickTabName, true);
8144 private void FilterEditMenuItem_Click(object sender, EventArgs e)
8146 if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8148 using (var fltDialog = new FilterDialog())
8150 fltDialog.Owner = this;
8151 fltDialog.SetCurrent(_rclickTabName);
8152 fltDialog.ShowDialog(this);
8154 this.TopMost = SettingManager.Common.AlwaysTop;
8156 this.ApplyPostFilters();
8160 private void AddTabMenuItem_Click(object sender, EventArgs e)
8162 string tabName = null;
8163 MyCommon.TabUsageType tabUsage;
8164 using (InputTabName inputName = new InputTabName())
8166 inputName.TabName = _statuses.MakeTabName("MyTab");
8167 inputName.IsShowUsage = true;
8168 inputName.ShowDialog();
8169 if (inputName.DialogResult == DialogResult.Cancel) return;
8170 tabName = inputName.TabName;
8171 tabUsage = inputName.Usage;
8173 this.TopMost = SettingManager.Common.AlwaysTop;
8174 if (!string.IsNullOrEmpty(tabName))
8177 ListElement list = null;
8178 if (tabUsage == MyCommon.TabUsageType.Lists)
8180 using (ListAvailable listAvail = new ListAvailable())
8182 if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8183 if (listAvail.SelectedList == null) return;
8184 list = listAvail.SelectedList;
8191 case MyCommon.TabUsageType.UserDefined:
8192 tab = new FilterTabModel(tabName);
8194 case MyCommon.TabUsageType.PublicSearch:
8195 tab = new PublicSearchTabModel(tabName);
8197 case MyCommon.TabUsageType.Lists:
8198 tab = new ListTimelineTabModel(tabName, list);
8204 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8206 string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8207 MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8213 if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8215 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8216 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8218 if (tabUsage == MyCommon.TabUsageType.Lists)
8220 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8221 var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8222 this.GetListTimelineAsync(listTab);
8228 private void TabMenuItem_Click(object sender, EventArgs e)
8230 using (var fltDialog = new FilterDialog())
8232 fltDialog.Owner = this;
8235 foreach (int idx in _curList.SelectedIndices)
8239 if (!SelectTab(out tabName)) return;
8241 fltDialog.SetCurrent(tabName);
8242 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8244 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8248 fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8250 fltDialog.ShowDialog(this);
8251 this.TopMost = SettingManager.Common.AlwaysTop;
8255 this.ApplyPostFilters();
8257 if (this.ListTab.SelectedTab != null &&
8258 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8260 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8264 protected override bool ProcessDialogKey(Keys keyData)
8266 //TextBox1でEnterを押してもビープ音が鳴らないようにする
8267 if ((keyData & Keys.KeyCode) == Keys.Enter)
8269 if (StatusText.Focused)
8271 bool _NewLine = false;
8274 if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8276 if (StatusText.Multiline)
8278 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8280 if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8284 if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8288 else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8290 if (StatusText.Multiline)
8292 if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8294 if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8298 if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8304 if (StatusText.Multiline)
8306 if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8308 if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8309 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8313 if (((keyData & Keys.Shift) == Keys.Shift) ||
8314 (((keyData & Keys.Control) != Keys.Control) &&
8315 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8321 int pos1 = StatusText.SelectionStart;
8322 if (StatusText.SelectionLength > 0)
8324 StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength); //選択状態文字列削除
8326 StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine); //改行挿入
8327 StatusText.SelectionStart = pos1 + Environment.NewLine.Length; //カーソルを改行の次の文字へ移動
8332 PostButton_Click(null, null);
8336 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8337 (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8338 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8340 this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8345 return base.ProcessDialogKey(keyData);
8348 private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8350 MakeReplyOrDirectStatus(false, true, true);
8353 private void IDRuleMenuItem_Click(object sender, EventArgs e)
8356 if (_curList.SelectedIndices.Count == 0) return;
8358 var tab = this._statuses.Tabs[this._curTab.Text];
8359 var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8360 .Select(x => tab[x])
8361 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8364 this.AddFilterRuleByScreenName(screenNameArray);
8366 if (screenNameArray.Length != 0)
8368 List<string> atids = new List<string>();
8369 foreach (var screenName in screenNameArray)
8371 atids.Add("@" + screenName);
8373 int cnt = AtIdSupl.ItemCount;
8374 AtIdSupl.AddRangeItem(atids.ToArray());
8375 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8379 private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8381 if (this._curList.SelectedIndices.Count == 0)
8384 var tab = this._statuses.Tabs[this._curTab.Text];
8385 var sourceArray = this._curList.SelectedIndices.Cast<int>()
8386 .Select(x => tab[x].Source).ToArray();
8388 this.AddFilterRuleBySource(sourceArray);
8391 public void AddFilterRuleByScreenName(params string[] screenNameArray)
8395 if (!SelectTab(out tabName)) return;
8397 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8401 if (tab.TabType != MyCommon.TabUsageType.Mute)
8403 this.MoveOrCopy(out mv, out mk);
8407 // ミュートタブでは常に MoveMatches を true にする
8412 foreach (var screenName in screenNameArray)
8414 tab.AddFilter(new PostFilterRule
8416 FilterName = screenName,
8417 UseNameField = true,
8421 FilterByUrl = false,
8425 this.ApplyPostFilters();
8429 public void AddFilterRuleBySource(params string[] sourceArray)
8431 // タブ選択ダイアログを表示(or追加)
8433 if (!this.SelectTab(out tabName))
8436 var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8440 if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8442 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8443 this.MoveOrCopy(out mv, out mk);
8447 // ミュートタブでは常に MoveMatches を true にする
8452 // 振り分けルールに追加するSource
8453 foreach (var source in sourceArray)
8455 filterTab.AddFilter(new PostFilterRule
8457 FilterSource = source,
8461 FilterByUrl = false,
8465 this.ApplyPostFilters();
8466 this.SaveConfigsTabs();
8469 private bool SelectTab(out string tabName)
8476 using (var dialog = new TabsDialog(_statuses))
8478 if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8480 var selectedTab = dialog.SelectedTab;
8481 tabName = selectedTab == null ? null : selectedTab.TabName;
8484 ListTab.SelectedTab.Focus();
8486 if (tabName == null)
8488 using (InputTabName inputName = new InputTabName())
8490 inputName.TabName = _statuses.MakeTabName("MyTab");
8491 inputName.ShowDialog();
8492 if (inputName.DialogResult == DialogResult.Cancel) return false;
8493 tabName = inputName.TabName;
8495 this.TopMost = SettingManager.Common.AlwaysTop;
8496 if (!string.IsNullOrEmpty(tabName))
8498 var tab = new FilterTabModel(tabName);
8499 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8501 string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8502 MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8520 private void MoveOrCopy(out bool move, out bool mark)
8524 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8525 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8533 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8534 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8544 private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8549 private void CopyURLMenuItem_Click(object sender, EventArgs e)
8554 private void SelectAllMenuItem_Click(object sender, EventArgs e)
8556 if (StatusText.Focused)
8559 StatusText.SelectAll();
8563 // ListView上でのCtrl+A
8564 NativeMethods.SelectAllItems(this._curList);
8568 private void MoveMiddle()
8574 if (_curList.SelectedIndices.Count == 0) return;
8576 int idx = _curList.SelectedIndices[0];
8578 _item = _curList.GetItemAt(0, 25);
8584 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8586 idx2 = _curList.VirtualListSize - 1;
8590 idx -= Math.Abs(idx1 - idx2) / 2;
8591 if (idx < 0) idx = 0;
8593 _curList.EnsureVisible(_curList.VirtualListSize - 1);
8594 _curList.EnsureVisible(idx);
8597 private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8599 var linkElements = this.tweetDetailsView.GetLinkElements();
8601 if (linkElements.Length > 0)
8603 UrlDialog.ClearUrl();
8605 string openUrlStr = "";
8607 if (linkElements.Length == 1)
8609 // ツイートに含まれる URL が 1 つのみの場合
8610 // => OpenURL ダイアログを表示せずにリンクを開く
8615 urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8617 catch (ArgumentException)
8626 if (string.IsNullOrEmpty(urlStr)) return;
8627 openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8629 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8630 await this.OpenUriAsync(new Uri(openUrlStr));
8634 // ツイートに含まれる URL が複数ある場合
8635 // => OpenURL を表示しユーザーが選択したリンクを開く
8637 foreach (var linkElm in linkElements)
8640 string linkText = "";
8644 urlStr = linkElm.GetAttribute("title");
8645 href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8646 if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8647 linkText = linkElm.InnerText;
8649 catch (ArgumentException)
8658 if (string.IsNullOrEmpty(urlStr)) continue;
8659 UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8663 if (UrlDialog.ShowDialog() == DialogResult.OK)
8665 openUrlStr = UrlDialog.SelectedUrl;
8667 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8668 await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8675 this.TopMost = SettingManager.Common.AlwaysTop;
8680 private void ClearTabMenuItem_Click(object sender, EventArgs e)
8682 if (string.IsNullOrEmpty(_rclickTabName)) return;
8683 ClearTab(_rclickTabName, true);
8686 private void ClearTab(string tabName, bool showWarning)
8690 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8691 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8697 _statuses.ClearTabIds(tabName);
8698 if (ListTab.SelectedTab.Text == tabName)
8701 _anchorFlag = false;
8702 this.PurgeListViewItemCache();
8706 foreach (TabPage tb in ListTab.TabPages)
8708 if (tb.Text == tabName)
8710 ((DetailsListView)tb.Tag).VirtualListSize = 0;
8715 if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8717 SetMainWindowTitle();
8718 SetStatusLabelUrl();
8721 private static long followers = 0;
8723 private void SetMainWindowTitle()
8726 StringBuilder ttl = new StringBuilder(256);
8729 if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8730 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8731 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8732 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8734 foreach (var tab in _statuses.Tabs.Values)
8736 ur += tab.UnreadCount;
8741 if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8742 ttl.Append(Application.ProductName);
8744 switch (SettingManager.Common.DispLatestPost)
8746 case MyCommon.DispTitleEnum.Ver:
8747 ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8749 case MyCommon.DispTitleEnum.Post:
8750 if (_history != null && _history.Count > 1)
8751 ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8753 case MyCommon.DispTitleEnum.UnreadRepCount:
8754 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8756 case MyCommon.DispTitleEnum.UnreadAllCount:
8757 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8759 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8760 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8762 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8763 ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8765 case MyCommon.DispTitleEnum.OwnStatus:
8766 if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8767 ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8773 this.Text = ttl.ToString();
8775 catch (AccessViolationException)
8777 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8781 private string GetStatusLabelText()
8784 //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8785 if (_statuses == null) return "";
8786 TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8787 TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8788 if (tbRep == null || tbDm == null) return "";
8789 int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8794 StringBuilder slbl = new StringBuilder(256);
8797 foreach (var tab in _statuses.Tabs.Values)
8799 ur += tab.UnreadCount;
8801 if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8803 tur = tab.UnreadCount;
8814 UnreadAtCounter = urat;
8816 var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8818 slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8819 if (SettingManager.Common.TimelinePeriod == 0)
8821 slbl.Append(Properties.Resources.SetStatusLabelText2);
8825 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8827 return slbl.ToString();
8830 private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8834 if (this.InvokeRequired && !this.IsDisposed)
8836 await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8840 var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8841 SetApiStatusLabel(endpointName);
8844 catch (ObjectDisposedException)
8848 catch (InvalidOperationException)
8854 private void SetApiStatusLabel(string endpointName = null)
8856 if (_curTab == null)
8858 this.toolStripApiGauge.ApiEndpoint = null;
8862 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8864 if (endpointName == null)
8869 case MyCommon.TabUsageType.Home:
8870 case MyCommon.TabUsageType.UserDefined:
8871 endpointName = "/statuses/home_timeline";
8874 case MyCommon.TabUsageType.Mentions:
8875 endpointName = "/statuses/mentions_timeline";
8878 case MyCommon.TabUsageType.Favorites:
8879 endpointName = "/favorites/list";
8882 case MyCommon.TabUsageType.DirectMessage:
8883 endpointName = "/direct_messages";
8886 case MyCommon.TabUsageType.UserTimeline:
8887 endpointName = "/statuses/user_timeline";
8890 case MyCommon.TabUsageType.Lists:
8891 endpointName = "/lists/statuses";
8894 case MyCommon.TabUsageType.PublicSearch:
8895 endpointName = "/search/tweets";
8898 case MyCommon.TabUsageType.Related:
8899 endpointName = "/statuses/show/:id";
8906 this.toolStripApiGauge.ApiEndpoint = endpointName;
8910 // 表示中のタブに関連する endpoint であれば更新
8913 switch (endpointName)
8915 case "/statuses/home_timeline":
8916 update = tabType == MyCommon.TabUsageType.Home ||
8917 tabType == MyCommon.TabUsageType.UserDefined;
8920 case "/statuses/mentions_timeline":
8921 update = tabType == MyCommon.TabUsageType.Mentions;
8924 case "/favorites/list":
8925 update = tabType == MyCommon.TabUsageType.Favorites;
8928 case "/direct_messages:":
8929 update = tabType == MyCommon.TabUsageType.DirectMessage;
8932 case "/statuses/user_timeline":
8933 update = tabType == MyCommon.TabUsageType.UserTimeline;
8936 case "/lists/statuses":
8937 update = tabType == MyCommon.TabUsageType.Lists;
8940 case "/search/tweets":
8941 update = tabType == MyCommon.TabUsageType.PublicSearch;
8944 case "/statuses/show/:id":
8945 update = tabType == MyCommon.TabUsageType.Related;
8954 this.toolStripApiGauge.ApiEndpoint = endpointName;
8960 private void SetStatusLabelUrl()
8962 StatusLabelUrl.Text = GetStatusLabelText();
8965 public void SetStatusLabel(string text)
8967 StatusLabel.Text = text;
8970 private void SetNotifyIconText()
8972 var ur = new StringBuilder(64);
8974 // タスクトレイアイコンのツールチップテキスト書き換え
8976 ur.Remove(0, ur.Length);
8977 if (SettingManager.Common.DispUsername)
8979 ur.Append(tw.Username);
8982 ur.Append(Application.ProductName);
8984 ur.Append("(Debug Build)");
8986 if (UnreadCounter != -1 && UnreadAtCounter != -1)
8989 ur.Append(UnreadCounter);
8991 ur.Append(UnreadAtCounter);
8994 NotifyIcon1.Text = ur.ToString();
8997 internal void CheckReplyTo(string StatusText)
9001 m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9003 foreach (Match hm in m)
9005 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9007 hstr += "#" + hm.Result("$3") + " ";
9008 HashSupl.AddItem("#" + hm.Result("$3"));
9011 if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9013 hstr += HashMgr.UseHash;
9015 if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9017 // 本当にリプライ先指定すべきかどうかの判定
9018 m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9020 if (SettingManager.Common.UseAtIdSupplement)
9022 int bCnt = AtIdSupl.ItemCount;
9023 foreach (Match mid in m)
9025 AtIdSupl.AddItem(mid.Result("${id}"));
9027 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9030 // リプライ先ステータスIDの指定がない場合は指定しない
9031 if (this.inReplyTo == null)
9035 // 次の条件を満たす場合に in_reply_to_status_id 指定
9036 // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9037 // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9038 // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9042 var inReplyToScreenName = this.inReplyTo.Item2;
9043 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9045 if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9049 foreach (Match mid in m)
9051 if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9056 this.inReplyTo = null;
9059 private void TweenMain_Resize(object sender, EventArgs e)
9061 if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9063 this.Visible = false;
9065 if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9067 // 現在の DPI と設定保存時の DPI との比を取得する
9068 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9070 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9071 //_mySize = this.ClientSize; //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9072 this.DesktopLocation = SettingManager.Local.FormLocation;
9073 //_myLoc = this.DesktopLocation; //位置保持(最小化・最大化されたまま終了した場合の対応用)
9076 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9077 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9078 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9080 this.SplitContainer1.SplitterDistance = splitterDistance;
9084 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9085 if (StatusText.Multiline)
9087 var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9088 int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9089 if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9091 SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9093 StatusText.Height = statusTextHeight;
9097 if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9099 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9103 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9104 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9106 this.SplitContainer3.SplitterDistance = previewDistance;
9109 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9110 this.SplitContainer3.Panel2Collapsed = true;
9112 _initialLayout = false;
9114 if (this.WindowState != FormWindowState.Minimized)
9116 _formWindowState = this.WindowState;
9120 private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9122 PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9123 this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9124 if (PlaySoundMenuItem.Checked)
9126 SettingManager.Common.PlaySound = true;
9130 SettingManager.Common.PlaySound = false;
9132 ModifySettingCommon = true;
9135 private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9137 if (this._initialLayout)
9140 int splitterDistance;
9141 switch (this.WindowState)
9143 case FormWindowState.Normal:
9144 splitterDistance = this.SplitContainer1.SplitterDistance;
9146 case FormWindowState.Maximized:
9147 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9148 var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9149 splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9150 splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9156 this._mySpDis = splitterDistance;
9157 this.ModifySettingLocal = true;
9160 private async Task doRepliedStatusOpen()
9162 if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9164 if (MyCommon.IsKeyDown(Keys.Shift))
9166 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9169 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9171 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9172 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9176 foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9178 if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9179 PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9180 MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname} ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9183 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9188 private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9190 await this.doRepliedStatusOpen();
9193 private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9195 var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9196 if (multiline != this.StatusText.Multiline)
9198 this.StatusText.Multiline = multiline;
9199 MultiLineMenuItem.Checked = multiline;
9200 ModifySettingLocal = true;
9204 private void StatusText_MultilineChanged(object sender, EventArgs e)
9206 if (this.StatusText.Multiline)
9207 this.StatusText.ScrollBars = ScrollBars.Vertical;
9209 this.StatusText.ScrollBars = ScrollBars.None;
9211 ModifySettingLocal = true;
9214 private void MultiLineMenuItem_Click(object sender, EventArgs e)
9217 StatusText.Multiline = MultiLineMenuItem.Checked;
9218 SettingManager.Local.StatusMultiline = MultiLineMenuItem.Checked;
9219 if (MultiLineMenuItem.Checked)
9221 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9222 SplitContainer2.SplitterDistance = 0;
9224 SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9228 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9230 ModifySettingLocal = true;
9233 private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9235 //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9236 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9238 //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9239 //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9240 //Appendix A. Collected ABNF for URI
9241 //http://www.ietf.org/rfc/rfc3986.txt
9245 const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9247 if (StatusText.SelectionLength > 0)
9249 string tmp = StatusText.SelectedText;
9250 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9251 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9253 // 文字列が選択されている場合はその文字列について処理
9255 //nico.ms使用、nicovideoにマッチしたら変換
9256 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9258 result = nicoms.Shorten(tmp);
9260 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9262 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9265 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9266 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9267 result = resultUri.AbsoluteUri;
9269 catch (WebApiException e)
9271 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9274 catch (UriFormatException e)
9276 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9285 if (!string.IsNullOrEmpty(result))
9287 urlUndo undotmp = new urlUndo();
9289 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9290 var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9291 if (origUrlIndex == -1)
9294 StatusText.Select(origUrlIndex, tmp.Length);
9295 StatusText.SelectedText = result;
9298 undotmp.Before = tmp;
9299 undotmp.After = result;
9301 if (urlUndoBuffer == null)
9303 urlUndoBuffer = new List<urlUndo>();
9304 UrlUndoToolStripMenuItem.Enabled = true;
9307 urlUndoBuffer.Add(undotmp);
9313 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9314 @"(?<url>(?<protocol>https?://)" +
9315 @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9316 @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9317 @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9318 // 正規表現にマッチしたURL文字列をtinyurl化
9319 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9321 if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9322 string tmp = mt.Result("${url}");
9323 if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9324 urlUndo undotmp = new urlUndo();
9327 StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9329 //nico.ms使用、nicovideoにマッチしたら変換
9330 if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9332 result = nicoms.Shorten(tmp);
9334 else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9336 //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9339 var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9340 var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9341 result = resultUri.AbsoluteUri;
9343 catch (HttpRequestException e)
9345 // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9346 // のように長いので「:」が含まれていればそれ以降のみを抽出する
9347 var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9349 this.StatusLabel.Text = Converter_Type + ":" + message;
9352 catch (WebApiException e)
9354 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9357 catch (UriFormatException e)
9359 this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9368 if (!string.IsNullOrEmpty(result))
9370 // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9371 var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9372 if (origUrlIndex == -1)
9375 StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9376 StatusText.SelectedText = result;
9378 undotmp.Before = mt.Result("${url}");
9379 undotmp.After = result;
9381 if (urlUndoBuffer == null)
9383 urlUndoBuffer = new List<urlUndo>();
9384 UrlUndoToolStripMenuItem.Enabled = true;
9387 urlUndoBuffer.Add(undotmp);
9395 private void doUrlUndo()
9397 if (urlUndoBuffer != null)
9399 string tmp = StatusText.Text;
9400 foreach (urlUndo data in urlUndoBuffer)
9402 tmp = tmp.Replace(data.After, data.Before);
9404 StatusText.Text = tmp;
9405 urlUndoBuffer = null;
9406 UrlUndoToolStripMenuItem.Enabled = false;
9407 StatusText.SelectionStart = 0;
9408 StatusText.SelectionLength = 0;
9412 private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9414 await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9417 private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9419 await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9422 private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9424 await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9427 private async void UxnuMenuItem_Click(object sender, EventArgs e)
9429 await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9432 private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9434 if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9436 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9437 Random rnd = new Random();
9438 // 前回使用した短縮URLサービス以外を選択する
9441 svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9443 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9444 await UrlConvertAsync(svc);
9448 private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9453 private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9455 this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9456 this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9457 SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9458 ModifySettingCommon = true;
9461 private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9463 ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9464 this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9465 SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9466 ModifySettingCommon = true;
9469 private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9471 // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9472 MenuStrip1.Tag = new Object();
9473 MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9476 private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9478 if (this.Tag != null) // 設定された戻り先へ遷移
9480 if (this.Tag == this.ListTab.SelectedTab)
9481 ((Control)this.ListTab.SelectedTab.Tag).Select();
9483 ((Control)this.Tag).Select();
9485 else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9487 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9489 this.Tag = ListTab.SelectedTab.Tag;
9490 ((Control)this.Tag).Select();
9493 // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9494 MenuStrip1.Tag = null;
9497 private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9499 DetailsListView lst = (DetailsListView)sender;
9500 if (SettingManager.Local == null) return;
9504 SettingManager.Local.Width1 = lst.Columns[0].Width;
9505 SettingManager.Local.Width3 = lst.Columns[1].Width;
9509 int[] darr = new int[lst.Columns.Count];
9510 for (int i = 0; i < lst.Columns.Count; i++)
9512 darr[lst.Columns[i].DisplayIndex] = i;
9514 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9516 for (int i = 0; i < lst.Columns.Count; i++)
9521 SettingManager.Local.DisplayIndex1 = i;
9524 SettingManager.Local.DisplayIndex2 = i;
9527 SettingManager.Local.DisplayIndex3 = i;
9530 SettingManager.Local.DisplayIndex4 = i;
9533 SettingManager.Local.DisplayIndex5 = i;
9536 SettingManager.Local.DisplayIndex6 = i;
9539 SettingManager.Local.DisplayIndex7 = i;
9542 SettingManager.Local.DisplayIndex8 = i;
9546 SettingManager.Local.Width1 = lst.Columns[0].Width;
9547 SettingManager.Local.Width2 = lst.Columns[1].Width;
9548 SettingManager.Local.Width3 = lst.Columns[2].Width;
9549 SettingManager.Local.Width4 = lst.Columns[3].Width;
9550 SettingManager.Local.Width5 = lst.Columns[4].Width;
9551 SettingManager.Local.Width6 = lst.Columns[5].Width;
9552 SettingManager.Local.Width7 = lst.Columns[6].Width;
9553 SettingManager.Local.Width8 = lst.Columns[7].Width;
9555 ModifySettingLocal = true;
9556 _isColumnChanged = true;
9559 private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9561 DetailsListView lst = (DetailsListView)sender;
9562 if (SettingManager.Local == null) return;
9565 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9567 SettingManager.Local.Width1 = lst.Columns[0].Width;
9568 ModifySettingLocal = true;
9569 _isColumnChanged = true;
9571 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9573 SettingManager.Local.Width3 = lst.Columns[1].Width;
9574 ModifySettingLocal = true;
9575 _isColumnChanged = true;
9580 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9582 SettingManager.Local.Width1 = lst.Columns[0].Width;
9583 ModifySettingLocal = true;
9584 _isColumnChanged = true;
9586 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9588 SettingManager.Local.Width2 = lst.Columns[1].Width;
9589 ModifySettingLocal = true;
9590 _isColumnChanged = true;
9592 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9594 SettingManager.Local.Width3 = lst.Columns[2].Width;
9595 ModifySettingLocal = true;
9596 _isColumnChanged = true;
9598 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9600 SettingManager.Local.Width4 = lst.Columns[3].Width;
9601 ModifySettingLocal = true;
9602 _isColumnChanged = true;
9604 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9606 SettingManager.Local.Width5 = lst.Columns[4].Width;
9607 ModifySettingLocal = true;
9608 _isColumnChanged = true;
9610 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9612 SettingManager.Local.Width6 = lst.Columns[5].Width;
9613 ModifySettingLocal = true;
9614 _isColumnChanged = true;
9616 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9618 SettingManager.Local.Width7 = lst.Columns[6].Width;
9619 ModifySettingLocal = true;
9620 _isColumnChanged = true;
9622 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9624 SettingManager.Local.Width8 = lst.Columns[7].Width;
9625 ModifySettingLocal = true;
9626 _isColumnChanged = true;
9629 // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9632 // SaveConfigsLocal();
9636 private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9638 if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9639 ModifySettingLocal = true;
9642 private void TweenMain_DragDrop(object sender, DragEventArgs e)
9644 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9646 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9648 SelectMedia_DragDrop(e);
9651 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9653 var url = GetUrlFromDataObject(e.Data);
9656 if (url.Item2 == null)
9657 appendText = url.Item1;
9659 appendText = url.Item2 + " " + url.Item1;
9661 if (this.StatusText.TextLength == 0)
9662 this.StatusText.Text = appendText;
9664 this.StatusText.Text += " " + appendText;
9666 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9668 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9670 this.StatusText.Text += text;
9672 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9674 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9675 if (data != null) StatusText.Text += data;
9680 /// IDataObject から URL とタイトルの対を取得します
9683 /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9685 /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9686 /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9687 internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
9689 if (data.GetDataPresent("text/x-moz-url"))
9691 // Firefox, Google Chrome で利用可能
9692 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9694 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9696 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9697 if (lines.Length < 2)
9698 throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9700 return new Tuple<string, string>(lines[0], lines[1]);
9703 else if (data.GetDataPresent("IESiteModeToUrl"))
9705 // Internet Exproler 用
9706 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9708 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9710 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9711 if (lines.Length < 2)
9712 throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9714 return new Tuple<string, string>(lines[0], lines[1]);
9717 else if (data.GetDataPresent("UniformResourceLocatorW"))
9721 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9723 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9724 return new Tuple<string, string>(url, null);
9728 throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9731 private void TweenMain_DragEnter(object sender, DragEventArgs e)
9733 if (e.Data.GetDataPresent(DataFormats.FileDrop))
9735 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9737 SelectMedia_DragEnter(e);
9741 else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9743 e.Effect = DragDropEffects.Copy;
9746 else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9748 e.Effect = DragDropEffects.Copy;
9751 else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9753 e.Effect = DragDropEffects.Copy;
9757 e.Effect = DragDropEffects.None;
9760 private void TweenMain_DragOver(object sender, DragEventArgs e)
9764 public bool IsNetworkAvailable()
9767 nw = MyCommon.IsNetworkAvailable();
9768 _myStatusOnline = nw;
9772 public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9774 var uriStr = uri.AbsoluteUri;
9776 // OpenTween 内部で使用する URL
9777 if (uri.Authority == "opentween")
9779 await this.OpenInternalUriAsync(uri);
9783 // ハッシュタグを含む Twitter 検索
9784 if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9787 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9788 var pos = unescapedQuery.IndexOf('#');
9789 if (pos == -1) return;
9791 var hash = unescapedQuery.Substring(pos);
9792 this.HashSupl.AddItem(hash);
9793 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9794 this.AddNewTabForSearch(hash);
9799 // フラグが立っている場合は設定と逆の動作をする
9800 if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9801 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9803 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9804 if (userUriMatch.Success)
9806 var screenName = userUriMatch.Groups["ScreenName"].Value;
9807 if (this.IsTwitterId(screenName))
9809 this.AddNewTabForUserTimeline(screenName);
9816 await this.OpenUriInBrowserAsync(uriStr);
9820 /// OpenTween 内部の機能を呼び出すための URL を開きます
9822 private async Task OpenInternalUriAsync(Uri uri)
9824 // ツイートを開く (//opentween/status/:status_id)
9825 var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9828 var statusId = long.Parse(match.Groups[1].Value);
9829 await this.OpenRelatedTab(statusId);
9834 public Task OpenUriInBrowserAsync(string UriString)
9836 return Task.Run(() =>
9838 string myPath = UriString;
9842 var configBrowserPath = SettingManager.Local.BrowserPath;
9843 if (!string.IsNullOrEmpty(configBrowserPath))
9845 if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9847 int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9848 string browserPath = configBrowserPath.Substring(1, sep - 1);
9850 if (sep < configBrowserPath.Length - 1)
9852 arg = configBrowserPath.Substring(sep + 1);
9854 myPath = arg + " " + myPath;
9855 System.Diagnostics.Process.Start(browserPath, myPath);
9859 System.Diagnostics.Process.Start(configBrowserPath, myPath);
9864 System.Diagnostics.Process.Start(myPath);
9869 //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9874 private void ListTabSelect(TabPage _tab)
9878 this.PurgeListViewItemCache();
9881 _curList = (DetailsListView)_tab.Tag;
9883 if (_curList.SelectedIndices.Count > 0)
9885 _curItemIndex = _curList.SelectedIndices[0];
9886 _curPost = GetCurTabPost(_curItemIndex);
9895 _anchorFlag = false;
9899 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9903 for (int i = 0; i < _curList.Columns.Count; i++)
9905 ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9910 private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9912 ListTabSelect(e.TabPage);
9915 private void SelectListItem(DetailsListView LView, int Index)
9918 Rectangle bnd = new Rectangle();
9920 var item = LView.FocusedItem;
9929 LView.SelectedIndices.Clear();
9931 while (LView.SelectedIndices.Count > 0);
9932 item = LView.Items[Index];
9933 item.Selected = true;
9934 item.Focused = true;
9936 if (flg) LView.Invalidate(bnd);
9939 private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9942 Rectangle bnd = new Rectangle();
9944 var item = LView.FocusedItem;
9955 LView.SelectedIndices.Clear();
9957 while (LView.SelectedIndices.Count > 0);
9958 LView.SelectItems(Index);
9960 if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9962 LView.SelectionMark = selectionMarkIndex;
9964 if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9966 LView.Items[focusedIndex].Focused = true;
9968 else if (Index != null && Index.Length != 0)
9970 LView.Items[Index.Last()].Focused = true;
9973 if (flg) LView.Invalidate(bnd);
9976 private void StartUserStream()
9978 tw.NewPostFromStream += tw_NewPostFromStream;
9979 tw.UserStreamStarted += tw_UserStreamStarted;
9980 tw.UserStreamStopped += tw_UserStreamStopped;
9981 tw.PostDeleted += tw_PostDeleted;
9982 tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9984 this.RefreshUserStreamsMenu();
9986 if (SettingManager.Common.UserstreamStartup)
9987 tw.StartUserStream();
9990 private async void TweenMain_Shown(object sender, EventArgs e)
9992 NotifyIcon1.Visible = true;
9994 if (this.IsNetworkAvailable())
9998 var loadTasks = new List<Task>
10000 this.RefreshMuteUserIdsAsync(),
10001 this.RefreshBlockIdsAsync(),
10002 this.RefreshNoRetweetIdsAsync(),
10003 this.RefreshTwitterConfigurationAsync(),
10004 this.GetHomeTimelineAsync(),
10005 this.GetReplyAsync(),
10006 this.GetDirectMessagesAsync(),
10007 this.GetPublicSearchAllAsync(),
10008 this.GetUserTimelineAllAsync(),
10009 this.GetListTimelineAllAsync(),
10012 if (SettingManager.Common.StartupFollowers)
10013 loadTasks.Add(this.RefreshFollowerIdsAsync());
10015 if (SettingManager.Common.GetFav)
10016 loadTasks.Add(this.GetFavoritesAsync());
10018 var allTasks = Task.WhenAll(loadTasks);
10023 var timeout = Task.Delay(5000);
10024 if (await Task.WhenAny(allTasks, timeout) != timeout)
10028 if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10030 if (MyCommon._endingFlag)
10034 if (MyCommon._endingFlag) return;
10036 if (ApplicationSettings.VersionInfoUrl != null)
10038 //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10039 if (SettingManager.Common.StartupVersion)
10040 await this.CheckNewVersion(true);
10044 // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10045 this.VerUpMenuItem.Enabled = false;
10046 this.VerUpMenuItem.Available = false;
10047 this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10050 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10051 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10053 MessageBox.Show(Properties.Resources.ReAuthorizeText);
10054 SettingStripMenuItem_Click(null, null);
10058 var reloadTasks = new List<Task>();
10060 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10061 reloadTasks.Add(this.RefreshFollowerIdsAsync());
10063 if (!tw.GetNoRetweetSuccess)
10064 reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10066 if (this.tw.Configuration.PhotoSizeLimit == 0)
10067 reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10069 await Task.WhenAll(reloadTasks);
10074 TimerTimeline.Enabled = true;
10077 private async Task doGetFollowersMenu()
10079 await this.RefreshFollowerIdsAsync();
10080 await this.DispSelectedPost(true);
10083 private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10085 await this.doGetFollowersMenu();
10088 private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10090 doReTweetUnofficial();
10093 private async Task doReTweetOfficial(bool isConfirm)
10096 if (this.ExistCurrentPost)
10098 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10100 if (this._curPost.IsProtect)
10101 MessageBox.Show("Protected.");
10103 _DoFavRetweetFlags = false;
10106 if (_curList.SelectedIndices.Count > 15)
10108 MessageBox.Show(Properties.Resources.RetweetLimitText);
10109 _DoFavRetweetFlags = false;
10112 else if (_curList.SelectedIndices.Count > 1)
10114 string QuestionText = Properties.Resources.RetweetQuestion2;
10115 if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10116 switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10118 case DialogResult.Cancel:
10119 case DialogResult.No:
10120 _DoFavRetweetFlags = false;
10126 if (!SettingManager.Common.RetweetNoConfirm)
10128 string Questiontext = Properties.Resources.RetweetQuestion1;
10129 if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10130 if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10132 _DoFavRetweetFlags = false;
10138 var statusIds = new List<long>();
10139 foreach (int idx in _curList.SelectedIndices)
10141 PostClass post = GetCurTabPost(idx);
10142 if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10143 statusIds.Add(post.StatusId);
10146 await this.RetweetAsync(statusIds);
10150 private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10152 await this.doReTweetOfficial(true);
10155 private async Task FavoritesRetweetOfficial()
10157 if (!this.ExistCurrentPost) return;
10158 _DoFavRetweetFlags = true;
10159 var retweetTask = this.doReTweetOfficial(true);
10160 if (_DoFavRetweetFlags)
10162 _DoFavRetweetFlags = false;
10163 var favoriteTask = this.FavoriteChange(true, false);
10165 await Task.WhenAll(retweetTask, favoriteTask);
10173 private async Task FavoritesRetweetUnofficial()
10175 if (this.ExistCurrentPost && !_curPost.IsDm)
10177 _DoFavRetweetFlags = true;
10178 var favoriteTask = this.FavoriteChange(true);
10179 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10181 _DoFavRetweetFlags = false;
10182 doReTweetUnofficial();
10185 await favoriteTask;
10190 /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10192 /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10193 /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10194 /// <returns>復元されたツイート本文</returns>
10195 internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10197 // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10200 statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10202 statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10204 statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10208 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10210 statusHtml = statusHtml.Replace("<br>", " ");
10212 // は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10213 // 現状では半角スペースの代用として を使用しているため U+0020 に置換します
10214 statusHtml = statusHtml.Replace(" ", " ");
10216 return WebUtility.HtmlDecode(statusHtml);
10219 private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10221 this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10223 if (_curPost != null)
10224 await this.DispSelectedPost(true);
10227 private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10229 if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10230 DebugModeToolStripMenuItem.Visible = true;
10232 DebugModeToolStripMenuItem.Visible = false;
10235 private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
10237 SettingManager.Common.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
10240 private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10242 ToolStripMenuItemUrlAutoShorten.Checked = SettingManager.Common.UrlConvertAuto;
10245 private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10247 if (TraceOutToolStripMenuItem.Checked)
10248 MyCommon.TraceFlag = true;
10250 MyCommon.TraceFlag = false;
10253 private void TweenMain_Deactivate(object sender, EventArgs e)
10255 //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10256 this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10259 private void TabRenameMenuItem_Click(object sender, EventArgs e)
10261 if (string.IsNullOrEmpty(_rclickTabName)) return;
10264 TabRename(_rclickTabName, out _);
10267 private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10269 await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10272 private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10274 await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10277 private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10279 TwitterApiStatus apiStatus;
10281 using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10283 var cancellationToken = dialog.EnableCancellation();
10287 var task = this.tw.GetInfoApi();
10288 apiStatus = await dialog.WaitForAsync(this, task);
10290 catch (WebApiException)
10295 if (cancellationToken.IsCancellationRequested)
10298 if (apiStatus == null)
10300 MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10305 using (var apiDlg = new ApiInfoDialog())
10307 apiDlg.ShowDialog(this);
10311 private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10313 var id = _curPost?.ScreenName ?? "";
10315 await this.FollowCommand(id);
10318 internal async Task FollowCommand(string id)
10320 using (var inputName = new InputTabName())
10322 inputName.FormTitle = "Follow";
10323 inputName.FormDescription = Properties.Resources.FRMessage1;
10324 inputName.TabName = id;
10326 if (inputName.ShowDialog(this) != DialogResult.OK)
10328 if (string.IsNullOrWhiteSpace(inputName.TabName))
10331 id = inputName.TabName.Trim();
10334 using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10338 var task = this.twitterApi.FriendshipsCreate(id);
10339 await dialog.WaitForAsync(this, task);
10341 catch (WebApiException ex)
10343 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10348 MessageBox.Show(Properties.Resources.FRMessage3);
10351 private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10353 var id = _curPost?.ScreenName ?? "";
10355 await this.RemoveCommand(id, false);
10358 internal async Task RemoveCommand(string id, bool skipInput)
10362 using (var inputName = new InputTabName())
10364 inputName.FormTitle = "Unfollow";
10365 inputName.FormDescription = Properties.Resources.FRMessage1;
10366 inputName.TabName = id;
10368 if (inputName.ShowDialog(this) != DialogResult.OK)
10370 if (string.IsNullOrWhiteSpace(inputName.TabName))
10373 id = inputName.TabName.Trim();
10377 using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10381 var task = this.twitterApi.FriendshipsDestroy(id);
10382 await dialog.WaitForAsync(this, task);
10384 catch (WebApiException ex)
10386 MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10391 MessageBox.Show(Properties.Resources.FRMessage3);
10394 private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10396 var id = _curPost?.ScreenName ?? "";
10398 await this.ShowFriendship(id);
10401 internal async Task ShowFriendship(string id)
10403 using (var inputName = new InputTabName())
10405 inputName.FormTitle = "Show Friendships";
10406 inputName.FormDescription = Properties.Resources.FRMessage1;
10407 inputName.TabName = id;
10409 if (inputName.ShowDialog(this) != DialogResult.OK)
10411 if (string.IsNullOrWhiteSpace(inputName.TabName))
10414 id = inputName.TabName.Trim();
10417 bool isFollowing, isFollowed;
10419 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10421 var cancellationToken = dialog.EnableCancellation();
10425 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10426 var friendship = await dialog.WaitForAsync(this, task);
10428 isFollowing = friendship.Relationship.Source.Following;
10429 isFollowed = friendship.Relationship.Source.FollowedBy;
10431 catch (WebApiException ex)
10433 if (!cancellationToken.IsCancellationRequested)
10434 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10438 if (cancellationToken.IsCancellationRequested)
10442 string result = "";
10445 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10449 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10453 result += Properties.Resources.GetFriendshipInfo3;
10457 result += Properties.Resources.GetFriendshipInfo4;
10459 result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10460 MessageBox.Show(result);
10463 internal async Task ShowFriendship(string[] ids)
10465 foreach (string id in ids)
10467 bool isFollowing, isFollowed;
10469 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10471 var cancellationToken = dialog.EnableCancellation();
10475 var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10476 var friendship = await dialog.WaitForAsync(this, task);
10478 isFollowing = friendship.Relationship.Source.Following;
10479 isFollowed = friendship.Relationship.Source.FollowedBy;
10481 catch (WebApiException ex)
10483 if (!cancellationToken.IsCancellationRequested)
10484 MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10488 if (cancellationToken.IsCancellationRequested)
10492 string result = "";
10498 ff += Properties.Resources.GetFriendshipInfo1;
10502 ff += Properties.Resources.GetFriendshipInfo2;
10505 ff += System.Environment.NewLine + " ";
10508 ff += Properties.Resources.GetFriendshipInfo3;
10512 ff += Properties.Resources.GetFriendshipInfo4;
10514 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10517 if (MessageBox.Show(
10518 Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10519 MessageBoxButtons.YesNo,
10520 MessageBoxIcon.Question,
10521 MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10523 await this.RemoveCommand(id, true);
10528 MessageBox.Show(result);
10533 private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10535 await this.doShowUserStatus(tw.Username, false);
10536 //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10538 // doShowUserStatus(tw.Username, false);
10542 // MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10547 // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10548 // URLから切り出した文字列を渡す
10550 public bool IsTwitterId(string name)
10552 if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10553 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10555 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10558 private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
10560 ModifySettingCommon = true;
10563 private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10565 ModifySettingCommon = true;
10568 private void doQuoteOfficial()
10570 if (this.ExistCurrentPost)
10572 if (_curPost.IsDm ||
10573 !StatusText.Enabled) return;
10575 if (_curPost.IsProtect)
10577 MessageBox.Show("Protected.");
10581 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
10583 this.inReplyTo = null;
10585 StatusText.SelectionStart = 0;
10586 StatusText.Focus();
10590 private void doReTweetUnofficial()
10593 if (this.ExistCurrentPost)
10595 if (_curPost.IsDm || !StatusText.Enabled)
10598 if (_curPost.IsProtect)
10600 MessageBox.Show("Protected.");
10603 string rtdata = _curPost.Text;
10604 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10606 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
10608 // 投稿時に in_reply_to_status_id を付加する
10609 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10610 var inReplyToScreenName = this._curPost.ScreenName;
10611 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10613 StatusText.SelectionStart = 0;
10614 StatusText.Focus();
10618 private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10623 private void SearchButton_Click(object sender, EventArgs e)
10626 Control pnl = ((Control)sender).Parent;
10627 if (pnl == null) return;
10628 string tbName = pnl.Parent.Text;
10629 var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10630 ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10631 ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10632 cmb.Text = cmb.Text.Trim();
10633 // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10634 bool Quote = false;
10635 StringBuilder buf = new StringBuilder();
10636 char[] c = cmb.Text.ToCharArray();
10637 for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10639 if (cnt > cmb.Text.Length - 4)
10641 buf.Append(cmb.Text.Substring(cnt));
10650 if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10652 buf.Append(" OR ");
10657 buf.Append(c[cnt]);
10659 cmb.Text = buf.ToString();
10661 var listView = (DetailsListView)pnl.Parent.Tag;
10663 var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10665 tb.SearchWords = cmb.Text;
10666 tb.SearchLang = cmbLang.Text;
10667 if (string.IsNullOrEmpty(cmb.Text))
10675 int idx = cmb.Items.IndexOf(tb.SearchWords);
10676 if (idx > -1) cmb.Items.RemoveAt(idx);
10677 cmb.Items.Insert(0, tb.SearchWords);
10678 cmb.Text = tb.SearchWords;
10680 this.PurgeListViewItemCache();
10681 listView.VirtualListSize = 0;
10682 _statuses.ClearTabIds(tbName);
10683 SaveConfigsTabs(); //検索条件の保存
10686 this.GetPublicSearchAsync(tb);
10690 private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10693 await this.DoRefreshMore();
10697 /// 指定されたタブのListTabにおける位置を返します
10700 /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10702 public int GetTabPageIndex(string tabName)
10705 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10707 if (tabPage.Text == tabName)
10716 private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10718 if (_statuses.RemovedTab.Count == 0)
10720 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10725 DetailsListView listView = null;
10727 TabModel tb = _statuses.RemovedTab.Pop();
10728 if (tb.TabType == MyCommon.TabUsageType.Related)
10730 var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10731 if (relatedTab != null)
10733 // 関連発言なら既存のタブを置き換える
10734 tb.TabName = relatedTab.TabName;
10735 this.ClearTab(tb.TabName, false);
10736 _statuses.Tabs[tb.TabName] = tb;
10738 for (int i = 0; i < ListTab.TabPages.Count; i++)
10740 var tabPage = ListTab.TabPages[i];
10741 if (tb.TabName == tabPage.Text)
10743 listView = (DetailsListView)tabPage.Tag;
10744 ListTab.SelectedIndex = i;
10751 const string TabName = "Related Tweets";
10752 string renamed = TabName;
10753 for (int i = 2; i <= 100; i++)
10755 if (!_statuses.ContainsTab(renamed)) break;
10756 renamed = TabName + i;
10758 tb.TabName = renamed;
10760 _statuses.AddTab(tb);
10761 AddNewTab(tb, startup: false);
10763 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10764 listView = (DetailsListView)tabPage.Tag;
10765 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10770 string renamed = tb.TabName;
10771 for (int i = 1; i < int.MaxValue; i++)
10773 if (!_statuses.ContainsTab(renamed)) break;
10774 renamed = tb.TabName + "(" + i + ")";
10776 tb.TabName = renamed;
10778 _statuses.AddTab(tb);
10779 AddNewTab(tb, startup: false);
10781 var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10782 listView = (DetailsListView)tabPage.Tag;
10783 ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10787 if (listView != null)
10789 using (ControlTransaction.Update(listView))
10791 listView.VirtualListSize = tb.AllCount;
10797 private async Task doMoveToRTHome()
10799 if (_curList.SelectedIndices.Count > 0)
10801 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10802 if (post.RetweetedId != null)
10804 await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10809 private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10811 await this.doMoveToRTHome();
10814 private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10816 var screenName = this._curPost?.ScreenName;
10817 if (screenName != null)
10818 this.ListManageUserContext(screenName);
10821 public void ListManageUserContext(string screenName)
10823 using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10825 listSelectForm.ShowDialog(this);
10829 private void SearchControls_Enter(object sender, EventArgs e)
10831 Control pnl = (Control)sender;
10832 foreach (Control ctl in pnl.Controls)
10834 ctl.TabStop = true;
10838 private void SearchControls_Leave(object sender, EventArgs e)
10840 Control pnl = (Control)sender;
10841 foreach (Control ctl in pnl.Controls)
10843 ctl.TabStop = false;
10847 private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10849 if (ListTab.SelectedTab != null)
10851 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10852 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10856 private void StatusLabel_DoubleClick(object sender, EventArgs e)
10858 MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10861 private void HashManageMenuItem_Click(object sender, EventArgs e)
10863 DialogResult rslt = DialogResult.Cancel;
10866 rslt = HashMgr.ShowDialog();
10872 this.TopMost = SettingManager.Common.AlwaysTop;
10873 if (rslt == DialogResult.Cancel) return;
10874 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10876 HashStripSplitButton.Text = HashMgr.UseHash;
10877 HashToggleMenuItem.Checked = true;
10878 HashToggleToolStripMenuItem.Checked = true;
10882 HashStripSplitButton.Text = "#[-]";
10883 HashToggleMenuItem.Checked = false;
10884 HashToggleToolStripMenuItem.Checked = false;
10886 //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10888 // int sidx = StatusText.SelectionStart;
10889 // string hash = HashMgr.UseHash + " ";
10892 // if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10893 // hash = " " + hash;
10895 // StatusText.Text = StatusText.Text.Insert(sidx, hash);
10896 // sidx += hash.Length;
10897 // StatusText.SelectionStart = sidx;
10898 // StatusText.Focus();
10900 ModifySettingCommon = true;
10901 this.StatusText_TextChanged(null, null);
10904 private void HashToggleMenuItem_Click(object sender, EventArgs e)
10906 HashMgr.ToggleHash();
10907 if (!string.IsNullOrEmpty(HashMgr.UseHash))
10909 HashStripSplitButton.Text = HashMgr.UseHash;
10910 HashToggleMenuItem.Checked = true;
10911 HashToggleToolStripMenuItem.Checked = true;
10915 HashStripSplitButton.Text = "#[-]";
10916 HashToggleMenuItem.Checked = false;
10917 HashToggleToolStripMenuItem.Checked = false;
10919 ModifySettingCommon = true;
10920 this.StatusText_TextChanged(null, null);
10923 private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10925 HashToggleMenuItem_Click(null, null);
10928 public void SetPermanentHashtag(string hashtag)
10930 HashMgr.SetPermanentHash("#" + hashtag);
10931 HashStripSplitButton.Text = HashMgr.UseHash;
10932 HashToggleMenuItem.Checked = true;
10933 HashToggleToolStripMenuItem.Checked = true;
10935 ModifySettingCommon = true;
10938 private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10940 if (ListTab.SelectedTab == null) return;
10941 if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10942 if (!this.ExistCurrentPost)
10944 this.ReplyOpMenuItem.Enabled = false;
10945 this.ReplyAllOpMenuItem.Enabled = false;
10946 this.DmOpMenuItem.Enabled = false;
10947 this.ShowProfMenuItem.Enabled = false;
10948 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10949 this.ListManageMenuItem.Enabled = false;
10950 this.OpenFavOpMenuItem.Enabled = false;
10951 this.CreateTabRuleOpMenuItem.Enabled = false;
10952 this.CreateIdRuleOpMenuItem.Enabled = false;
10953 this.CreateSourceRuleOpMenuItem.Enabled = false;
10954 this.ReadOpMenuItem.Enabled = false;
10955 this.UnreadOpMenuItem.Enabled = false;
10959 this.ReplyOpMenuItem.Enabled = true;
10960 this.ReplyAllOpMenuItem.Enabled = true;
10961 this.DmOpMenuItem.Enabled = true;
10962 this.ShowProfMenuItem.Enabled = true;
10963 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10964 this.ListManageMenuItem.Enabled = true;
10965 this.OpenFavOpMenuItem.Enabled = true;
10966 this.CreateTabRuleOpMenuItem.Enabled = true;
10967 this.CreateIdRuleOpMenuItem.Enabled = true;
10968 this.CreateSourceRuleOpMenuItem.Enabled = true;
10969 this.ReadOpMenuItem.Enabled = true;
10970 this.UnreadOpMenuItem.Enabled = true;
10973 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10975 this.FavOpMenuItem.Enabled = false;
10976 this.UnFavOpMenuItem.Enabled = false;
10977 this.OpenStatusOpMenuItem.Enabled = false;
10978 this.OpenFavotterOpMenuItem.Enabled = false;
10979 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10980 this.RtOpMenuItem.Enabled = false;
10981 this.RtUnOpMenuItem.Enabled = false;
10982 this.QtOpMenuItem.Enabled = false;
10983 this.FavoriteRetweetMenuItem.Enabled = false;
10984 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10988 this.FavOpMenuItem.Enabled = true;
10989 this.UnFavOpMenuItem.Enabled = true;
10990 this.OpenStatusOpMenuItem.Enabled = true;
10991 this.OpenFavotterOpMenuItem.Enabled = true;
10992 this.ShowRelatedStatusesMenuItem2.Enabled = true; //PublicSearchの時問題出るかも
10994 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10996 this.RtOpMenuItem.Enabled = false;
10997 this.RtUnOpMenuItem.Enabled = false;
10998 this.QtOpMenuItem.Enabled = false;
10999 this.FavoriteRetweetMenuItem.Enabled = false;
11000 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11004 this.RtOpMenuItem.Enabled = true;
11005 this.RtUnOpMenuItem.Enabled = true;
11006 this.QtOpMenuItem.Enabled = true;
11007 this.FavoriteRetweetMenuItem.Enabled = true;
11008 this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11012 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11014 this.RefreshPrevOpMenuItem.Enabled = true;
11018 this.RefreshPrevOpMenuItem.Enabled = false;
11020 if (!this.ExistCurrentPost
11021 || _curPost.InReplyToStatusId == null)
11023 OpenRepSourceOpMenuItem.Enabled = false;
11027 OpenRepSourceOpMenuItem.Enabled = true;
11029 if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11031 OpenRterHomeMenuItem.Enabled = false;
11035 OpenRterHomeMenuItem.Enabled = true;
11038 if (this.ExistCurrentPost)
11040 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11044 private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11046 ContextMenuTabProperty_Opening(sender, null);
11049 public Twitter TwitterInstance
11054 private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11056 if (this._initialLayout)
11059 int splitterDistance;
11060 switch (this.WindowState)
11062 case FormWindowState.Normal:
11063 splitterDistance = this.SplitContainer3.SplitterDistance;
11065 case FormWindowState.Maximized:
11066 // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11067 var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11068 splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11069 splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11075 this._mySpDis3 = splitterDistance;
11076 this.ModifySettingLocal = true;
11079 private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11081 if (_statuses.RemovedTab.Count == 0)
11083 UndoRemoveTabMenuItem.Enabled = false;
11087 UndoRemoveTabMenuItem.Enabled = true;
11089 if (ListTab.SelectedTab != null)
11091 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11092 PublicSearchQueryMenuItem.Enabled = true;
11094 PublicSearchQueryMenuItem.Enabled = false;
11098 PublicSearchQueryMenuItem.Enabled = false;
11100 if (!this.ExistCurrentPost)
11102 this.CopySTOTMenuItem.Enabled = false;
11103 this.CopyURLMenuItem.Enabled = false;
11104 this.CopyUserIdStripMenuItem.Enabled = false;
11108 this.CopySTOTMenuItem.Enabled = true;
11109 this.CopyURLMenuItem.Enabled = true;
11110 this.CopyUserIdStripMenuItem.Enabled = true;
11111 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11112 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11116 private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11118 SetNotifyIconText();
11121 private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11123 var id = _curPost?.ScreenName ?? "";
11125 await this.ShowUserStatus(id);
11128 private async Task doShowUserStatus(string id, bool ShowInputDialog)
11130 TwitterUser user = null;
11132 if (ShowInputDialog)
11134 using (var inputName = new InputTabName())
11136 inputName.FormTitle = "Show UserStatus";
11137 inputName.FormDescription = Properties.Resources.FRMessage1;
11138 inputName.TabName = id;
11140 if (inputName.ShowDialog(this) != DialogResult.OK)
11142 if (string.IsNullOrWhiteSpace(inputName.TabName))
11145 id = inputName.TabName.Trim();
11149 using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11151 var cancellationToken = dialog.EnableCancellation();
11155 var task = this.twitterApi.UsersShow(id);
11156 user = await dialog.WaitForAsync(this, task);
11158 catch (WebApiException ex)
11160 if (!cancellationToken.IsCancellationRequested)
11161 MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11165 if (cancellationToken.IsCancellationRequested)
11169 await this.doShowUserStatus(user);
11172 private async Task doShowUserStatus(TwitterUser user)
11174 using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11176 var showUserTask = userDialog.ShowUserAsync(user);
11177 userDialog.ShowDialog(this);
11180 this.BringToFront();
11182 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11183 await showUserTask;
11187 internal Task ShowUserStatus(string id, bool ShowInputDialog)
11189 return this.doShowUserStatus(id, ShowInputDialog);
11192 internal Task ShowUserStatus(string id)
11194 return this.doShowUserStatus(id, true);
11197 private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11199 if (_curPost != null)
11201 await this.ShowUserStatus(_curPost.ScreenName, false);
11205 private async void RtCountMenuItem_Click(object sender, EventArgs e)
11207 if (!this.ExistCurrentPost)
11210 var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11211 TwitterStatus status;
11213 using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11215 var cancellationToken = dialog.EnableCancellation();
11219 var task = this.twitterApi.StatusesShow(statusId);
11220 status = await dialog.WaitForAsync(this, task);
11222 catch (WebApiException ex)
11224 if (!cancellationToken.IsCancellationRequested)
11225 MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11229 if (cancellationToken.IsCancellationRequested)
11233 MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11236 private HookGlobalHotkey _hookGlobalHotkey;
11239 _hookGlobalHotkey = new HookGlobalHotkey(this);
11241 // この呼び出しは、Windows フォーム デザイナで必要です。
11242 InitializeComponent();
11244 // InitializeComponent() 呼び出しの後で初期化を追加します。
11246 if (!this.DesignMode)
11248 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11249 this.StatusText.Dock = DockStyle.Fill;
11252 this.tweetDetailsView.Owner = this;
11254 this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11255 this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11256 this.gh.NotifyClicked += GrowlHelper_Callback;
11258 // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11259 this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11261 this.ImageSelector.Visible = false;
11262 this.ImageSelector.Enabled = false;
11263 this.ImageSelector.FilePickDialog = OpenFileDialog1;
11265 this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11267 this.ReplaceAppName();
11268 this.InitializeShortcuts();
11271 private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11273 if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11276 this.Visible = false;
11278 else if (Form.ActiveForm == null)
11280 this.Visible = true;
11281 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11283 this.BringToFront();
11284 this.StatusText.Focus();
11288 private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11290 this.MultiLineMenuItem.PerformClick();
11293 public PostClass CurPost
11295 get { return _curPost; }
11299 private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11301 if (ImageSelector.Visible)
11302 ImageSelector.EndSelection();
11304 ImageSelector.BeginSelection();
11307 private void SelectMedia_DragEnter(DragEventArgs e)
11309 if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11311 e.Effect = DragDropEffects.Copy;
11314 e.Effect = DragDropEffects.None;
11317 private void SelectMedia_DragDrop(DragEventArgs e)
11320 this.BringToFront();
11321 ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11322 StatusText.Focus();
11325 private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11327 TimelinePanel.Visible = false;
11328 TimelinePanel.Enabled = false;
11331 private void ImageSelector_EndSelecting(object sender, EventArgs e)
11333 TimelinePanel.Visible = true;
11334 TimelinePanel.Enabled = true;
11335 ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11338 private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11340 this.AllowDrop = false;
11343 private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11345 this.AllowDrop = true;
11348 private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11350 if (ImageSelector.Visible)
11352 ModifySettingCommon = true;
11353 SaveConfigsAll(true);
11355 this.StatusText_TextChanged(null, null);
11359 private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11361 this.StatusText_TextChanged(null, null);
11365 /// StatusTextでCtrl+Vが押下された時の処理
11367 private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11371 if (Clipboard.ContainsText())
11373 // clipboardにテキストがある場合は貼り付け処理
11374 this.StatusText.Paste(Clipboard.GetText());
11376 else if (Clipboard.ContainsImage())
11379 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11380 Properties.Resources.PostPictureWarn4,
11381 MessageBoxButtons.OKCancel,
11382 MessageBoxIcon.Question,
11383 MessageBoxDefaultButton.Button2)
11384 == DialogResult.OK)
11386 // clipboardから画像を取得
11387 using (var image = Clipboard.GetImage())
11389 this.ImageSelector.BeginSelection(image);
11394 catch (ExternalException ex)
11396 MessageBox.Show(ex.Message);
11401 private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11403 using (ListManage form = new ListManage(tw))
11405 form.ShowDialog(this);
11409 public bool ModifySettingCommon { get; set; }
11410 public bool ModifySettingLocal { get; set; }
11411 public bool ModifySettingAtId { get; set; }
11413 private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11415 if (this.ExistCurrentPost && !_curPost.IsDm)
11416 RtCountMenuItem.Enabled = true;
11418 RtCountMenuItem.Enabled = false;
11420 //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11421 // TinyUrlConvertToolStripMenuItem.Enabled = false;
11423 // TinyUrlConvertToolStripMenuItem.Enabled = true;
11426 private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11431 private void CopyUserId()
11433 if (_curPost == null) return;
11434 string clstr = _curPost.ScreenName;
11437 Clipboard.SetDataObject(clstr, false, 5, 100);
11439 catch (Exception ex)
11441 MessageBox.Show(ex.Message);
11445 private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11447 if (this.ExistCurrentPost && !_curPost.IsDm)
11451 await this.OpenRelatedTab(this._curPost);
11453 catch (TabException ex)
11455 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11461 /// 指定されたツイートに対する関連発言タブを開きます
11463 /// <param name="statusId">表示するツイートのID</param>
11464 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11465 private async Task OpenRelatedTab(long statusId)
11467 var post = this._statuses[statusId];
11472 post = await this.tw.GetStatusApi(false, statusId);
11474 catch (WebApiException ex)
11476 this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11481 await this.OpenRelatedTab(post);
11485 /// 指定されたツイートに対する関連発言タブを開きます
11487 /// <param name="post">表示する対象となるツイート</param>
11488 /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11489 private async Task OpenRelatedTab(PostClass post)
11491 var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11492 if (tabRelated != null)
11494 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11497 var tabName = this._statuses.MakeTabName("Related Tweets");
11499 tabRelated = new RelatedPostsTabModel(tabName, post);
11500 tabRelated.UnreadManage = false;
11501 tabRelated.Notify = false;
11503 this._statuses.AddTab(tabRelated);
11504 this.AddNewTab(tabRelated, startup: false);
11507 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11509 tabPage = this.ListTab.TabPages[i];
11510 if (tabName == tabPage.Text)
11512 this.ListTab.SelectedIndex = i;
11517 await this.GetRelatedTweetsAsync(tabRelated);
11519 tabPage = this.ListTab.TabPages.Cast<TabPage>()
11520 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11522 if (tabPage != null)
11524 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11526 var listView = (DetailsListView)tabPage.Tag;
11527 var targetPost = tabRelated.TargetPost;
11528 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11530 if (index != -1 && index < listView.Items.Count)
11532 listView.SelectedIndices.Add(index);
11533 listView.Items[index].Focused = true;
11538 private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11540 StringBuilder buf = new StringBuilder();
11541 //buf.AppendFormat("キャッシュメモリ容量 : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11542 //buf.AppendFormat("物理メモリ使用割合 : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11543 buf.AppendFormat("キャッシュエントリ保持数 : {0}" + Environment.NewLine, IconCache.CacheCount);
11544 buf.AppendFormat("キャッシュエントリ破棄数 : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11545 MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11548 private void tw_UserIdChanged()
11550 this.ModifySettingCommon = true;
11553 #region "Userstream"
11554 private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11558 if (InvokeRequired && !IsDisposed)
11560 await this.InvokeAsync(async () =>
11562 this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11563 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11565 this.PurgeListViewItemCache();
11566 ((DetailsListView)_curTab.Tag).Update();
11567 if (_curPost != null && _curPost.StatusId == e.StatusId)
11568 await this.DispSelectedPost(true);
11574 catch (ObjectDisposedException)
11578 catch (InvalidOperationException)
11584 private int userStreamsRefreshing = 0;
11586 private async void tw_NewPostFromStream(object sender, EventArgs e)
11588 if (SettingManager.Common.ReadOldPosts)
11590 _statuses.SetReadHomeTab(); //新着時未読クリア
11593 this._statuses.DistributePosts();
11595 if (SettingManager.Common.UserstreamPeriod > 0) return;
11597 // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11598 if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11602 await this.InvokeAsync(() => this.RefreshTimeline())
11603 .ConfigureAwait(false);
11607 Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11612 private async void tw_UserStreamStarted(object sender, EventArgs e)
11616 if (InvokeRequired && !IsDisposed)
11618 await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11622 catch (ObjectDisposedException)
11626 catch (InvalidOperationException)
11631 this.RefreshUserStreamsMenu();
11632 this.MenuItemUserStream.Enabled = true;
11634 StatusLabel.Text = "UserStream Started.";
11637 private async void tw_UserStreamStopped(object sender, EventArgs e)
11641 if (InvokeRequired && !IsDisposed)
11643 await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11647 catch (ObjectDisposedException)
11651 catch (InvalidOperationException)
11656 this.RefreshUserStreamsMenu();
11657 this.MenuItemUserStream.Enabled = true;
11659 StatusLabel.Text = "UserStream Stopped.";
11662 private void RefreshUserStreamsMenu()
11664 if (this.tw.UserStreamActive)
11666 this.MenuItemUserStream.Text = "&UserStream ▶";
11667 this.StopToolStripMenuItem.Text = "&Stop";
11671 this.MenuItemUserStream.Text = "&UserStream ■";
11672 this.StopToolStripMenuItem.Text = "&Start";
11676 private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11680 if (InvokeRequired && !IsDisposed)
11682 await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11686 catch (ObjectDisposedException)
11690 catch (InvalidOperationException)
11694 var ev = e.EventData;
11695 StatusLabel.Text = "Event: " + ev.Event;
11696 //if (ev.Event == "favorite")
11698 // NotifyFavorite(ev);
11701 if (ev.Event == "favorite" || ev.Event == "unfavorite")
11703 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11705 this.PurgeListViewItemCache();
11706 ((DetailsListView)_curTab.Tag).Update();
11708 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11710 var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11711 favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11716 private void NotifyEvent(Twitter.FormattedEvent ev)
11719 if (BalloonRequired(ev))
11721 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11722 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11723 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11724 StringBuilder title = new StringBuilder();
11725 if (SettingManager.Common.DispUsername)
11727 title.Append(tw.Username);
11728 title.Append(" - ");
11734 title.Append(Application.ProductName);
11735 title.Append(" [");
11736 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11737 title.Append("] by ");
11738 if (!string.IsNullOrEmpty(ev.Username))
11740 title.Append(ev.Username);
11744 //title.Append("");
11747 if (!string.IsNullOrEmpty(ev.Target))
11749 //NotifyIcon1.BalloonTipText = ev.Target;
11754 //NotifyIcon1.BalloonTipText = " ";
11757 //NotifyIcon1.ShowBalloonTip(500);
11758 if (SettingManager.Common.IsUseNotifyGrowl)
11760 gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11761 ev.Id.ToString(), title.ToString(), text);
11765 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11766 NotifyIcon1.BalloonTipTitle = title.ToString();
11767 NotifyIcon1.BalloonTipText = text;
11768 NotifyIcon1.ShowBalloonTip(500);
11773 string snd = SettingManager.Common.EventSoundFile;
11774 if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11776 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11780 string dir = Application.StartupPath;
11781 if (Directory.Exists(Path.Combine(dir, "Sounds")))
11783 dir = Path.Combine(dir, "Sounds");
11785 using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11797 private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11799 MenuItemUserStream.Enabled = false;
11800 if (StopRefreshAllMenuItem.Checked)
11802 StopRefreshAllMenuItem.Checked = false;
11805 if (this.tw.UserStreamActive)
11807 tw.StopUserStream();
11811 tw.StartUserStream();
11815 private static string inputTrack = "";
11817 private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11819 if (TrackToolStripMenuItem.Checked)
11821 using (InputTabName inputForm = new InputTabName())
11823 inputForm.TabName = inputTrack;
11824 inputForm.FormTitle = "Input track word";
11825 inputForm.FormDescription = "Track word";
11826 if (inputForm.ShowDialog() != DialogResult.OK)
11828 TrackToolStripMenuItem.Checked = false;
11831 inputTrack = inputForm.TabName.Trim();
11833 if (!inputTrack.Equals(tw.TrackWord))
11835 tw.TrackWord = inputTrack;
11836 this.ModifySettingCommon = true;
11837 TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11838 tw.ReconnectUserStream();
11844 tw.ReconnectUserStream();
11846 this.ModifySettingCommon = true;
11849 private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11851 tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11852 this.ModifySettingCommon = true;
11853 tw.ReconnectUserStream();
11856 private void EventViewerMenuItem_Click(object sender, EventArgs e)
11858 if (evtDialog == null || evtDialog.IsDisposed)
11861 evtDialog = new EventViewerDialog();
11862 evtDialog.Owner = this;
11864 Point pos = evtDialog.Location;
11865 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11866 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11867 evtDialog.Location = pos;
11869 evtDialog.EventSource = tw.StoredEvent;
11870 if (!evtDialog.Visible)
11872 evtDialog.Show(this);
11876 evtDialog.Activate();
11878 this.TopMost = SettingManager.Common.AlwaysTop;
11882 private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11884 MyCommon._endingFlag = true;
11888 Application.Restart();
11892 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11896 private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11898 if (!string.IsNullOrEmpty(tw.Username))
11899 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11902 private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11904 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11907 private bool ExistCurrentPost
11911 if (_curPost == null) return false;
11912 if (_curPost.IsDeleted) return false;
11917 private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11919 ShowUserTimeline();
11922 private string GetUserIdFromCurPostOrInput(string caption)
11924 var id = _curPost?.ScreenName ?? "";
11926 using (InputTabName inputName = new InputTabName())
11928 inputName.FormTitle = caption;
11929 inputName.FormDescription = Properties.Resources.FRMessage1;
11930 inputName.TabName = id;
11931 if (inputName.ShowDialog() == DialogResult.OK &&
11932 !string.IsNullOrEmpty(inputName.TabName.Trim()))
11934 id = inputName.TabName.Trim();
11944 private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11946 string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11947 if (!string.IsNullOrEmpty(id))
11949 AddNewTabForUserTimeline(id);
11953 private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11955 string id = GetUserIdFromCurPostOrInput("Show Favstar");
11956 if (!string.IsNullOrEmpty(id))
11958 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11962 private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11964 if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11967 private void TimelineRefreshEnableChange(bool isEnable)
11971 tw.StartUserStream();
11975 tw.StopUserStream();
11977 TimerTimeline.Enabled = isEnable;
11980 private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11982 TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11985 private async Task OpenUserAppointUrl()
11987 if (SettingManager.Common.UserAppointUrl != null)
11989 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11991 if (_curPost != null)
11993 string xUrl = SettingManager.Common.UserAppointUrl;
11994 xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
11996 var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
11997 xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11999 await this.OpenUriInBrowserAsync(xUrl);
12004 await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12009 private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12011 await this.OpenUserAppointUrl();
12014 private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12016 if (Form.ActiveForm == null)
12018 await this.InvokeAsync(() =>
12020 this.Visible = true;
12021 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12023 this.BringToFront();
12024 if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12026 if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12030 if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12036 private void ReplaceAppName()
12038 MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12039 AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12042 private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12044 this.SplitContainer3.Panel2Collapsed = false;
12047 private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12049 await this.OpenThumbnailPicture(e.Thumbnail);
12052 private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12054 await this.OpenUriInBrowserAsync(e.ImageUrl);
12057 private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12059 var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12061 await this.OpenUriInBrowserAsync(url);
12064 private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12066 await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12069 private void PostButton_KeyDown(object sender, KeyEventArgs e)
12071 if (e.KeyCode == Keys.Space)
12073 this.JumpUnreadMenuItem_Click(null, null);
12075 e.SuppressKeyPress = true;
12079 private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12081 this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12082 this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12083 this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12084 this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12085 this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12087 this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12090 private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12092 ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12095 private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12097 ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12100 private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12102 ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12105 private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12107 ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12110 private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12112 ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12115 private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12117 if (SettingManager.Common.IconSize == iconSize) return;
12119 var oldIconCol = _iconCol;
12121 SettingManager.Common.IconSize = iconSize;
12122 ApplyListViewIconSize(iconSize);
12124 if (_iconCol != oldIconCol)
12126 foreach (TabPage tp in ListTab.TabPages)
12128 ResetColumns((DetailsListView)tp.Tag);
12132 _curList?.Refresh();
12134 ModifySettingCommon = true;
12137 private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12139 var state = this.LockListSortOrderToolStripMenuItem.Checked;
12140 if (SettingManager.Common.SortOrderLock == state) return;
12142 SettingManager.Common.SortOrderLock = state;
12144 ModifySettingCommon = true;
12147 private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12149 if (!string.IsNullOrEmpty(e.StatusText))
12151 this.StatusLabelUrl.Text = e.StatusText;
12155 this.SetStatusLabelUrl();